View.java revision b03b434089cf2106c467b2827a65e5c589c91d01
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     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add only accessibility focusable Views.
1012     *
1013     * @hide
1014     */
1015    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1016
1017    /**
1018     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1019     * item.
1020     */
1021    public static final int FOCUS_BACKWARD = 0x00000001;
1022
1023    /**
1024     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1025     * item.
1026     */
1027    public static final int FOCUS_FORWARD = 0x00000002;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus to the left.
1031     */
1032    public static final int FOCUS_LEFT = 0x00000011;
1033
1034    /**
1035     * Use with {@link #focusSearch(int)}. Move focus up.
1036     */
1037    public static final int FOCUS_UP = 0x00000021;
1038
1039    /**
1040     * Use with {@link #focusSearch(int)}. Move focus to the right.
1041     */
1042    public static final int FOCUS_RIGHT = 0x00000042;
1043
1044    /**
1045     * Use with {@link #focusSearch(int)}. Move focus down.
1046     */
1047    public static final int FOCUS_DOWN = 0x00000082;
1048
1049    // Accessibility focus directions.
1050
1051    /**
1052     * The accessibility focus which is the current user position when
1053     * interacting with the accessibility framework.
1054     */
1055    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1056
1057    /**
1058     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1059     */
1060    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1061
1062    /**
1063     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1064     */
1065    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1066
1067    /**
1068     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1069     */
1070    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1071
1072    /**
1073     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1074     */
1075    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1076
1077    /**
1078     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1079     */
1080    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1081
1082    /**
1083     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1084     */
1085    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1086
1087    /**
1088     * Bits of {@link #getMeasuredWidthAndState()} and
1089     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1090     */
1091    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1092
1093    /**
1094     * Bits of {@link #getMeasuredWidthAndState()} and
1095     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1096     */
1097    public static final int MEASURED_STATE_MASK = 0xff000000;
1098
1099    /**
1100     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1101     * for functions that combine both width and height into a single int,
1102     * such as {@link #getMeasuredState()} and the childState argument of
1103     * {@link #resolveSizeAndState(int, int, int)}.
1104     */
1105    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1106
1107    /**
1108     * Bit of {@link #getMeasuredWidthAndState()} and
1109     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1110     * is smaller that the space the view would like to have.
1111     */
1112    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1113
1114    /**
1115     * Base View state sets
1116     */
1117    // Singles
1118    /**
1119     * Indicates the view has no states set. States are used with
1120     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1121     * view depending on its state.
1122     *
1123     * @see android.graphics.drawable.Drawable
1124     * @see #getDrawableState()
1125     */
1126    protected static final int[] EMPTY_STATE_SET;
1127    /**
1128     * Indicates the view is enabled. States are used with
1129     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1130     * view depending on its state.
1131     *
1132     * @see android.graphics.drawable.Drawable
1133     * @see #getDrawableState()
1134     */
1135    protected static final int[] ENABLED_STATE_SET;
1136    /**
1137     * Indicates the view is focused. States are used with
1138     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1139     * view depending on its state.
1140     *
1141     * @see android.graphics.drawable.Drawable
1142     * @see #getDrawableState()
1143     */
1144    protected static final int[] FOCUSED_STATE_SET;
1145    /**
1146     * Indicates the view is selected. States are used with
1147     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1148     * view depending on its state.
1149     *
1150     * @see android.graphics.drawable.Drawable
1151     * @see #getDrawableState()
1152     */
1153    protected static final int[] SELECTED_STATE_SET;
1154    /**
1155     * Indicates the view is pressed. States are used with
1156     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1157     * view depending on its state.
1158     *
1159     * @see android.graphics.drawable.Drawable
1160     * @see #getDrawableState()
1161     * @hide
1162     */
1163    protected static final int[] PRESSED_STATE_SET;
1164    /**
1165     * Indicates the view's window has focus. States are used with
1166     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1167     * view depending on its state.
1168     *
1169     * @see android.graphics.drawable.Drawable
1170     * @see #getDrawableState()
1171     */
1172    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1173    // Doubles
1174    /**
1175     * Indicates the view is enabled and has the focus.
1176     *
1177     * @see #ENABLED_STATE_SET
1178     * @see #FOCUSED_STATE_SET
1179     */
1180    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1181    /**
1182     * Indicates the view is enabled and selected.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #SELECTED_STATE_SET
1186     */
1187    protected static final int[] ENABLED_SELECTED_STATE_SET;
1188    /**
1189     * Indicates the view is enabled and that its window has focus.
1190     *
1191     * @see #ENABLED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is focused and selected.
1197     *
1198     * @see #FOCUSED_STATE_SET
1199     * @see #SELECTED_STATE_SET
1200     */
1201    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1202    /**
1203     * Indicates the view has the focus and that its window has the focus.
1204     *
1205     * @see #FOCUSED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is selected and that its window has the focus.
1211     *
1212     * @see #SELECTED_STATE_SET
1213     * @see #WINDOW_FOCUSED_STATE_SET
1214     */
1215    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1216    // Triples
1217    /**
1218     * Indicates the view is enabled, focused and selected.
1219     *
1220     * @see #ENABLED_STATE_SET
1221     * @see #FOCUSED_STATE_SET
1222     * @see #SELECTED_STATE_SET
1223     */
1224    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1225    /**
1226     * Indicates the view is enabled, focused and its window has the focus.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #FOCUSED_STATE_SET
1230     * @see #WINDOW_FOCUSED_STATE_SET
1231     */
1232    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1233    /**
1234     * Indicates the view is enabled, selected and its window has the focus.
1235     *
1236     * @see #ENABLED_STATE_SET
1237     * @see #SELECTED_STATE_SET
1238     * @see #WINDOW_FOCUSED_STATE_SET
1239     */
1240    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1241    /**
1242     * Indicates the view is focused, selected and its window has the focus.
1243     *
1244     * @see #FOCUSED_STATE_SET
1245     * @see #SELECTED_STATE_SET
1246     * @see #WINDOW_FOCUSED_STATE_SET
1247     */
1248    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1249    /**
1250     * Indicates the view is enabled, focused, selected and its window
1251     * has the focus.
1252     *
1253     * @see #ENABLED_STATE_SET
1254     * @see #FOCUSED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is pressed and its window has the focus.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #WINDOW_FOCUSED_STATE_SET
1264     */
1265    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1266    /**
1267     * Indicates the view is pressed and selected.
1268     *
1269     * @see #PRESSED_STATE_SET
1270     * @see #SELECTED_STATE_SET
1271     */
1272    protected static final int[] PRESSED_SELECTED_STATE_SET;
1273    /**
1274     * Indicates the view is pressed, selected and its window has the focus.
1275     *
1276     * @see #PRESSED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     * @see #WINDOW_FOCUSED_STATE_SET
1279     */
1280    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1281    /**
1282     * Indicates the view is pressed and focused.
1283     *
1284     * @see #PRESSED_STATE_SET
1285     * @see #FOCUSED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, focused and its window has the focus.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #FOCUSED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, focused and selected.
1298     *
1299     * @see #PRESSED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #FOCUSED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed, focused, selected and its window has the focus.
1306     *
1307     * @see #PRESSED_STATE_SET
1308     * @see #FOCUSED_STATE_SET
1309     * @see #SELECTED_STATE_SET
1310     * @see #WINDOW_FOCUSED_STATE_SET
1311     */
1312    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1313    /**
1314     * Indicates the view is pressed and enabled.
1315     *
1316     * @see #PRESSED_STATE_SET
1317     * @see #ENABLED_STATE_SET
1318     */
1319    protected static final int[] PRESSED_ENABLED_STATE_SET;
1320    /**
1321     * Indicates the view is pressed, enabled and its window has the focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled and selected.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     */
1335    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1336    /**
1337     * Indicates the view is pressed, enabled, selected and its window has the
1338     * focus.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #ENABLED_STATE_SET
1342     * @see #SELECTED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed, enabled and focused.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #ENABLED_STATE_SET
1351     * @see #FOCUSED_STATE_SET
1352     */
1353    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1354    /**
1355     * Indicates the view is pressed, enabled, focused and its window has the
1356     * focus.
1357     *
1358     * @see #PRESSED_STATE_SET
1359     * @see #ENABLED_STATE_SET
1360     * @see #FOCUSED_STATE_SET
1361     * @see #WINDOW_FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled, focused and selected.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     * @see #SELECTED_STATE_SET
1370     * @see #FOCUSED_STATE_SET
1371     */
1372    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1373    /**
1374     * Indicates the view is pressed, enabled, focused, selected and its window
1375     * has the focus.
1376     *
1377     * @see #PRESSED_STATE_SET
1378     * @see #ENABLED_STATE_SET
1379     * @see #SELECTED_STATE_SET
1380     * @see #FOCUSED_STATE_SET
1381     * @see #WINDOW_FOCUSED_STATE_SET
1382     */
1383    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1384
1385    /**
1386     * The order here is very important to {@link #getDrawableState()}
1387     */
1388    private static final int[][] VIEW_STATE_SETS;
1389
1390    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1391    static final int VIEW_STATE_SELECTED = 1 << 1;
1392    static final int VIEW_STATE_FOCUSED = 1 << 2;
1393    static final int VIEW_STATE_ENABLED = 1 << 3;
1394    static final int VIEW_STATE_PRESSED = 1 << 4;
1395    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1396    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1397    static final int VIEW_STATE_HOVERED = 1 << 7;
1398    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1399    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1400
1401    static final int[] VIEW_STATE_IDS = new int[] {
1402        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1403        R.attr.state_selected,          VIEW_STATE_SELECTED,
1404        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1405        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1406        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1407        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1408        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1409        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1410        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1411        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1412    };
1413
1414    static {
1415        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1416            throw new IllegalStateException(
1417                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1418        }
1419        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1420        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1421            int viewState = R.styleable.ViewDrawableStates[i];
1422            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1423                if (VIEW_STATE_IDS[j] == viewState) {
1424                    orderedIds[i * 2] = viewState;
1425                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1426                }
1427            }
1428        }
1429        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1430        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1431        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1432            int numBits = Integer.bitCount(i);
1433            int[] set = new int[numBits];
1434            int pos = 0;
1435            for (int j = 0; j < orderedIds.length; j += 2) {
1436                if ((i & orderedIds[j+1]) != 0) {
1437                    set[pos++] = orderedIds[j];
1438                }
1439            }
1440            VIEW_STATE_SETS[i] = set;
1441        }
1442
1443        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1444        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1445        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1446        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1448        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1449        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1451        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1453        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1455                | VIEW_STATE_FOCUSED];
1456        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1457        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1459        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1461        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1463                | VIEW_STATE_ENABLED];
1464        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1466        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_ENABLED];
1469        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED];
1472        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1474                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1475
1476        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1477        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1479        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1481        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1482                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1483                | VIEW_STATE_PRESSED];
1484        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1485                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1486        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1488                | VIEW_STATE_PRESSED];
1489        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1491                | VIEW_STATE_PRESSED];
1492        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1494                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1495        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1497        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1499                | VIEW_STATE_PRESSED];
1500        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1502                | VIEW_STATE_PRESSED];
1503        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1505                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1506        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1508                | VIEW_STATE_PRESSED];
1509        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1510                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1511                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1512        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1514                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1515        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1517                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1518                | VIEW_STATE_PRESSED];
1519    }
1520
1521    /**
1522     * Accessibility event types that are dispatched for text population.
1523     */
1524    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1525            AccessibilityEvent.TYPE_VIEW_CLICKED
1526            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1527            | AccessibilityEvent.TYPE_VIEW_SELECTED
1528            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1529            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1530            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1531            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1532            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1533            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1534            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1535            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1536
1537    /**
1538     * Temporary Rect currently for use in setBackground().  This will probably
1539     * be extended in the future to hold our own class with more than just
1540     * a Rect. :)
1541     */
1542    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1543
1544    /**
1545     * Map used to store views' tags.
1546     */
1547    private SparseArray<Object> mKeyedTags;
1548
1549    /**
1550     * The next available accessiiblity id.
1551     */
1552    private static int sNextAccessibilityViewId;
1553
1554    /**
1555     * The animation currently associated with this view.
1556     * @hide
1557     */
1558    protected Animation mCurrentAnimation = null;
1559
1560    /**
1561     * Width as measured during measure pass.
1562     * {@hide}
1563     */
1564    @ViewDebug.ExportedProperty(category = "measurement")
1565    int mMeasuredWidth;
1566
1567    /**
1568     * Height as measured during measure pass.
1569     * {@hide}
1570     */
1571    @ViewDebug.ExportedProperty(category = "measurement")
1572    int mMeasuredHeight;
1573
1574    /**
1575     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1576     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1577     * its display list. This flag, used only when hw accelerated, allows us to clear the
1578     * flag while retaining this information until it's needed (at getDisplayList() time and
1579     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1580     *
1581     * {@hide}
1582     */
1583    boolean mRecreateDisplayList = false;
1584
1585    /**
1586     * The view's identifier.
1587     * {@hide}
1588     *
1589     * @see #setId(int)
1590     * @see #getId()
1591     */
1592    @ViewDebug.ExportedProperty(resolveId = true)
1593    int mID = NO_ID;
1594
1595    /**
1596     * The stable ID of this view for accessibility purposes.
1597     */
1598    int mAccessibilityViewId = NO_ID;
1599
1600    /**
1601     * @hide
1602     */
1603    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1604
1605    /**
1606     * The view's tag.
1607     * {@hide}
1608     *
1609     * @see #setTag(Object)
1610     * @see #getTag()
1611     */
1612    protected Object mTag;
1613
1614    // for mPrivateFlags:
1615    /** {@hide} */
1616    static final int WANTS_FOCUS                    = 0x00000001;
1617    /** {@hide} */
1618    static final int FOCUSED                        = 0x00000002;
1619    /** {@hide} */
1620    static final int SELECTED                       = 0x00000004;
1621    /** {@hide} */
1622    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1623    /** {@hide} */
1624    static final int HAS_BOUNDS                     = 0x00000010;
1625    /** {@hide} */
1626    static final int DRAWN                          = 0x00000020;
1627    /**
1628     * When this flag is set, this view is running an animation on behalf of its
1629     * children and should therefore not cancel invalidate requests, even if they
1630     * lie outside of this view's bounds.
1631     *
1632     * {@hide}
1633     */
1634    static final int DRAW_ANIMATION                 = 0x00000040;
1635    /** {@hide} */
1636    static final int SKIP_DRAW                      = 0x00000080;
1637    /** {@hide} */
1638    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1639    /** {@hide} */
1640    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1641    /** {@hide} */
1642    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1643    /** {@hide} */
1644    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1645    /** {@hide} */
1646    static final int FORCE_LAYOUT                   = 0x00001000;
1647    /** {@hide} */
1648    static final int LAYOUT_REQUIRED                = 0x00002000;
1649
1650    private static final int PRESSED                = 0x00004000;
1651
1652    /** {@hide} */
1653    static final int DRAWING_CACHE_VALID            = 0x00008000;
1654    /**
1655     * Flag used to indicate that this view should be drawn once more (and only once
1656     * more) after its animation has completed.
1657     * {@hide}
1658     */
1659    static final int ANIMATION_STARTED              = 0x00010000;
1660
1661    private static final int SAVE_STATE_CALLED      = 0x00020000;
1662
1663    /**
1664     * Indicates that the View returned true when onSetAlpha() was called and that
1665     * the alpha must be restored.
1666     * {@hide}
1667     */
1668    static final int ALPHA_SET                      = 0x00040000;
1669
1670    /**
1671     * Set by {@link #setScrollContainer(boolean)}.
1672     */
1673    static final int SCROLL_CONTAINER               = 0x00080000;
1674
1675    /**
1676     * Set by {@link #setScrollContainer(boolean)}.
1677     */
1678    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1679
1680    /**
1681     * View flag indicating whether this view was invalidated (fully or partially.)
1682     *
1683     * @hide
1684     */
1685    static final int DIRTY                          = 0x00200000;
1686
1687    /**
1688     * View flag indicating whether this view was invalidated by an opaque
1689     * invalidate request.
1690     *
1691     * @hide
1692     */
1693    static final int DIRTY_OPAQUE                   = 0x00400000;
1694
1695    /**
1696     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1697     *
1698     * @hide
1699     */
1700    static final int DIRTY_MASK                     = 0x00600000;
1701
1702    /**
1703     * Indicates whether the background is opaque.
1704     *
1705     * @hide
1706     */
1707    static final int OPAQUE_BACKGROUND              = 0x00800000;
1708
1709    /**
1710     * Indicates whether the scrollbars are opaque.
1711     *
1712     * @hide
1713     */
1714    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1715
1716    /**
1717     * Indicates whether the view is opaque.
1718     *
1719     * @hide
1720     */
1721    static final int OPAQUE_MASK                    = 0x01800000;
1722
1723    /**
1724     * Indicates a prepressed state;
1725     * the short time between ACTION_DOWN and recognizing
1726     * a 'real' press. Prepressed is used to recognize quick taps
1727     * even when they are shorter than ViewConfiguration.getTapTimeout().
1728     *
1729     * @hide
1730     */
1731    private static final int PREPRESSED             = 0x02000000;
1732
1733    /**
1734     * Indicates whether the view is temporarily detached.
1735     *
1736     * @hide
1737     */
1738    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1739
1740    /**
1741     * Indicates that we should awaken scroll bars once attached
1742     *
1743     * @hide
1744     */
1745    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1746
1747    /**
1748     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1749     * @hide
1750     */
1751    private static final int HOVERED              = 0x10000000;
1752
1753    /**
1754     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1755     * for transform operations
1756     *
1757     * @hide
1758     */
1759    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1760
1761    /** {@hide} */
1762    static final int ACTIVATED                    = 0x40000000;
1763
1764    /**
1765     * Indicates that this view was specifically invalidated, not just dirtied because some
1766     * child view was invalidated. The flag is used to determine when we need to recreate
1767     * a view's display list (as opposed to just returning a reference to its existing
1768     * display list).
1769     *
1770     * @hide
1771     */
1772    static final int INVALIDATED                  = 0x80000000;
1773
1774    /* Masks for mPrivateFlags2 */
1775
1776    /**
1777     * Indicates that this view has reported that it can accept the current drag's content.
1778     * Cleared when the drag operation concludes.
1779     * @hide
1780     */
1781    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1782
1783    /**
1784     * Indicates that this view is currently directly under the drag location in a
1785     * drag-and-drop operation involving content that it can accept.  Cleared when
1786     * the drag exits the view, or when the drag operation concludes.
1787     * @hide
1788     */
1789    static final int DRAG_HOVERED                 = 0x00000002;
1790
1791    /**
1792     * Horizontal layout direction of this view is from Left to Right.
1793     * Use with {@link #setLayoutDirection}.
1794     */
1795    public static final int LAYOUT_DIRECTION_LTR = 0;
1796
1797    /**
1798     * Horizontal layout direction of this view is from Right to Left.
1799     * Use with {@link #setLayoutDirection}.
1800     */
1801    public static final int LAYOUT_DIRECTION_RTL = 1;
1802
1803    /**
1804     * Horizontal layout direction of this view is inherited from its parent.
1805     * Use with {@link #setLayoutDirection}.
1806     */
1807    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1808
1809    /**
1810     * Horizontal layout direction of this view is from deduced from the default language
1811     * script for the locale. Use with {@link #setLayoutDirection}.
1812     */
1813    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1814
1815    /**
1816     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1817     * @hide
1818     */
1819    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1820
1821    /**
1822     * Mask for use with private flags indicating bits used for horizontal layout direction.
1823     * @hide
1824     */
1825    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1826
1827    /**
1828     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1829     * right-to-left direction.
1830     * @hide
1831     */
1832    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1833
1834    /**
1835     * Indicates whether the view horizontal layout direction has been resolved.
1836     * @hide
1837     */
1838    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1839
1840    /**
1841     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1842     * @hide
1843     */
1844    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1845
1846    /*
1847     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1848     * flag value.
1849     * @hide
1850     */
1851    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1852            LAYOUT_DIRECTION_LTR,
1853            LAYOUT_DIRECTION_RTL,
1854            LAYOUT_DIRECTION_INHERIT,
1855            LAYOUT_DIRECTION_LOCALE
1856    };
1857
1858    /**
1859     * Default horizontal layout direction.
1860     * @hide
1861     */
1862    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1863
1864    /**
1865     * Indicates that the view is tracking some sort of transient state
1866     * that the app should not need to be aware of, but that the framework
1867     * should take special care to preserve.
1868     *
1869     * @hide
1870     */
1871    static final int HAS_TRANSIENT_STATE = 0x00000100;
1872
1873
1874    /**
1875     * Text direction is inherited thru {@link ViewGroup}
1876     */
1877    public static final int TEXT_DIRECTION_INHERIT = 0;
1878
1879    /**
1880     * Text direction is using "first strong algorithm". The first strong directional character
1881     * determines the paragraph direction. If there is no strong directional character, the
1882     * paragraph direction is the view's resolved layout direction.
1883     */
1884    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1885
1886    /**
1887     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1888     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1889     * If there are neither, the paragraph direction is the view's resolved layout direction.
1890     */
1891    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1892
1893    /**
1894     * Text direction is forced to LTR.
1895     */
1896    public static final int TEXT_DIRECTION_LTR = 3;
1897
1898    /**
1899     * Text direction is forced to RTL.
1900     */
1901    public static final int TEXT_DIRECTION_RTL = 4;
1902
1903    /**
1904     * Text direction is coming from the system Locale.
1905     */
1906    public static final int TEXT_DIRECTION_LOCALE = 5;
1907
1908    /**
1909     * Default text direction is inherited
1910     */
1911    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1912
1913    /**
1914     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1915     * @hide
1916     */
1917    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1918
1919    /**
1920     * Mask for use with private flags indicating bits used for text direction.
1921     * @hide
1922     */
1923    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1924
1925    /**
1926     * Array of text direction flags for mapping attribute "textDirection" to correct
1927     * flag value.
1928     * @hide
1929     */
1930    private static final int[] TEXT_DIRECTION_FLAGS = {
1931            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1932            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1933            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1934            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1935            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1936            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1937    };
1938
1939    /**
1940     * Indicates whether the view text direction has been resolved.
1941     * @hide
1942     */
1943    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1944
1945    /**
1946     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1947     * @hide
1948     */
1949    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1950
1951    /**
1952     * Mask for use with private flags indicating bits used for resolved text direction.
1953     * @hide
1954     */
1955    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1956
1957    /**
1958     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1959     * @hide
1960     */
1961    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1962            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1963
1964    /*
1965     * Default text alignment. The text alignment of this View is inherited from its parent.
1966     * Use with {@link #setTextAlignment(int)}
1967     */
1968    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1969
1970    /**
1971     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1972     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1973     *
1974     * Use with {@link #setTextAlignment(int)}
1975     */
1976    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1977
1978    /**
1979     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1980     *
1981     * Use with {@link #setTextAlignment(int)}
1982     */
1983    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1984
1985    /**
1986     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1987     *
1988     * Use with {@link #setTextAlignment(int)}
1989     */
1990    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1991
1992    /**
1993     * Center the paragraph, e.g. ALIGN_CENTER.
1994     *
1995     * Use with {@link #setTextAlignment(int)}
1996     */
1997    public static final int TEXT_ALIGNMENT_CENTER = 4;
1998
1999    /**
2000     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2001     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2002     *
2003     * Use with {@link #setTextAlignment(int)}
2004     */
2005    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2006
2007    /**
2008     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2009     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2010     *
2011     * Use with {@link #setTextAlignment(int)}
2012     */
2013    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2014
2015    /**
2016     * Default text alignment is inherited
2017     */
2018    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2019
2020    /**
2021      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2022      * @hide
2023      */
2024    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2025
2026    /**
2027      * Mask for use with private flags indicating bits used for text alignment.
2028      * @hide
2029      */
2030    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2031
2032    /**
2033     * Array of text direction flags for mapping attribute "textAlignment" to correct
2034     * flag value.
2035     * @hide
2036     */
2037    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2038            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2039            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2040            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2041            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2042            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2043            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2044            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2045    };
2046
2047    /**
2048     * Indicates whether the view text alignment has been resolved.
2049     * @hide
2050     */
2051    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2052
2053    /**
2054     * Bit shift to get the resolved text alignment.
2055     * @hide
2056     */
2057    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2058
2059    /**
2060     * Mask for use with private flags indicating bits used for text alignment.
2061     * @hide
2062     */
2063    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2064
2065    /**
2066     * Indicates whether if the view text alignment has been resolved to gravity
2067     */
2068    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2069            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2070
2071    // Accessiblity constants for mPrivateFlags2
2072
2073    /**
2074     * Shift for the bits in {@link #mPrivateFlags2} related to the
2075     * "importantForAccessibility" attribute.
2076     */
2077    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2078
2079    /**
2080     * Automatically determine whether a view is important for accessibility.
2081     */
2082    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2083
2084    /**
2085     * The view is important for accessibility.
2086     */
2087    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2088
2089    /**
2090     * The view is not important for accessibility.
2091     */
2092    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2093
2094    /**
2095     * The default whether the view is important for accessiblity.
2096     */
2097    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2098
2099    /**
2100     * Mask for obtainig the bits which specify how to determine
2101     * whether a view is important for accessibility.
2102     */
2103    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2104        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2105        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2106
2107    /**
2108     * Flag indicating whether a view has accessibility focus.
2109     */
2110    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2111
2112    /**
2113     * Flag indicating whether a view state for accessibility has changed.
2114     */
2115    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2116
2117    /**
2118     * Flag indicating that view has an animation set on it. This is used to track whether an
2119     * animation is cleared between successive frames, in order to tell the associated
2120     * DisplayList to clear its animation matrix.
2121     */
2122    static final int VIEW_IS_ANIMATING_TRANSFORM = 0x10000000;
2123
2124    /**
2125     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2126     * is used to check whether later changes to the view's transform should invalidate the
2127     * view to force the quickReject test to run again.
2128     */
2129    static final int VIEW_QUICK_REJECTED = 0x20000000;
2130
2131    // Accessiblity constants for mPrivateFlags2
2132
2133    /**
2134     * Shift for the bits in {@link #mPrivateFlags2} related to the
2135     * "accessibilityFocusable" attribute.
2136     */
2137    static final int ACCESSIBILITY_FOCUSABLE_SHIFT = 30;
2138
2139    /**
2140     * The system determines whether the view can take accessibility focus - default (recommended).
2141     * <p>
2142     * Such a view is consideted by the focus search if it is:
2143     * <ul>
2144     * <li>
2145     * Important for accessibility and actionable (clickable, long clickable, focusable)
2146     * </li>
2147     * <li>
2148     * Important for accessibility, not actionable (clickable, long clickable, focusable),
2149     * and does not have an actionable predecessor.
2150     * </li>
2151     * </ul>
2152     * An accessibility srvice can request putting accessibility focus on such a view.
2153     * </p>
2154     *
2155     * @hide
2156     */
2157    public static final int ACCESSIBILITY_FOCUSABLE_AUTO = 0x00000000;
2158
2159    /**
2160     * The view can take accessibility focus.
2161     * <p>
2162     * A view that can take accessibility focus is always considered during focus
2163     * search and an accessibility service can request putting accessibility focus
2164     * on it.
2165     * </p>
2166     *
2167     * @hide
2168     */
2169    public static final int ACCESSIBILITY_FOCUSABLE_YES = 0x00000001;
2170
2171    /**
2172     * The view can not take accessibility focus.
2173     * <p>
2174     * A view that can not take accessibility focus is never considered during focus
2175     * search and an accessibility service can not request putting accessibility focus
2176     * on it.
2177     * </p>
2178     *
2179     * @hide
2180     */
2181    public static final int ACCESSIBILITY_FOCUSABLE_NO = 0x00000002;
2182
2183    /**
2184     * The default whether the view is accessiblity focusable.
2185     */
2186    static final int ACCESSIBILITY_FOCUSABLE_DEFAULT = ACCESSIBILITY_FOCUSABLE_AUTO;
2187
2188    /**
2189     * Mask for obtainig the bits which specifies how to determine
2190     * whether a view is accessibility focusable.
2191     */
2192    static final int ACCESSIBILITY_FOCUSABLE_MASK = (ACCESSIBILITY_FOCUSABLE_AUTO
2193        | ACCESSIBILITY_FOCUSABLE_YES | ACCESSIBILITY_FOCUSABLE_NO)
2194        << ACCESSIBILITY_FOCUSABLE_SHIFT;
2195
2196
2197    /* End of masks for mPrivateFlags2 */
2198
2199    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2200
2201    /**
2202     * Always allow a user to over-scroll this view, provided it is a
2203     * view that can scroll.
2204     *
2205     * @see #getOverScrollMode()
2206     * @see #setOverScrollMode(int)
2207     */
2208    public static final int OVER_SCROLL_ALWAYS = 0;
2209
2210    /**
2211     * Allow a user to over-scroll this view only if the content is large
2212     * enough to meaningfully scroll, provided it is a view that can scroll.
2213     *
2214     * @see #getOverScrollMode()
2215     * @see #setOverScrollMode(int)
2216     */
2217    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2218
2219    /**
2220     * Never allow a user to over-scroll this view.
2221     *
2222     * @see #getOverScrollMode()
2223     * @see #setOverScrollMode(int)
2224     */
2225    public static final int OVER_SCROLL_NEVER = 2;
2226
2227    /**
2228     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2229     * requested the system UI (status bar) to be visible (the default).
2230     *
2231     * @see #setSystemUiVisibility(int)
2232     */
2233    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2234
2235    /**
2236     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2237     * system UI to enter an unobtrusive "low profile" mode.
2238     *
2239     * <p>This is for use in games, book readers, video players, or any other
2240     * "immersive" application where the usual system chrome is deemed too distracting.
2241     *
2242     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2243     *
2244     * @see #setSystemUiVisibility(int)
2245     */
2246    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2247
2248    /**
2249     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2250     * system navigation be temporarily hidden.
2251     *
2252     * <p>This is an even less obtrusive state than that called for by
2253     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2254     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2255     * those to disappear. This is useful (in conjunction with the
2256     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2257     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2258     * window flags) for displaying content using every last pixel on the display.
2259     *
2260     * <p>There is a limitation: because navigation controls are so important, the least user
2261     * interaction will cause them to reappear immediately.  When this happens, both
2262     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2263     * so that both elements reappear at the same time.
2264     *
2265     * @see #setSystemUiVisibility(int)
2266     */
2267    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2268
2269    /**
2270     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2271     * into the normal fullscreen mode so that its content can take over the screen
2272     * while still allowing the user to interact with the application.
2273     *
2274     * <p>This has the same visual effect as
2275     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2276     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2277     * meaning that non-critical screen decorations (such as the status bar) will be
2278     * hidden while the user is in the View's window, focusing the experience on
2279     * that content.  Unlike the window flag, if you are using ActionBar in
2280     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2281     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2282     * hide the action bar.
2283     *
2284     * <p>This approach to going fullscreen is best used over the window flag when
2285     * it is a transient state -- that is, the application does this at certain
2286     * points in its user interaction where it wants to allow the user to focus
2287     * on content, but not as a continuous state.  For situations where the application
2288     * would like to simply stay full screen the entire time (such as a game that
2289     * wants to take over the screen), the
2290     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2291     * is usually a better approach.  The state set here will be removed by the system
2292     * in various situations (such as the user moving to another application) like
2293     * the other system UI states.
2294     *
2295     * <p>When using this flag, the application should provide some easy facility
2296     * for the user to go out of it.  A common example would be in an e-book
2297     * reader, where tapping on the screen brings back whatever screen and UI
2298     * decorations that had been hidden while the user was immersed in reading
2299     * the book.
2300     *
2301     * @see #setSystemUiVisibility(int)
2302     */
2303    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2304
2305    /**
2306     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2307     * flags, we would like a stable view of the content insets given to
2308     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2309     * will always represent the worst case that the application can expect
2310     * as a continuous state.  In the stock Android UI this is the space for
2311     * the system bar, nav bar, and status bar, but not more transient elements
2312     * such as an input method.
2313     *
2314     * The stable layout your UI sees is based on the system UI modes you can
2315     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2316     * then you will get a stable layout for changes of the
2317     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2318     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2319     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2320     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2321     * with a stable layout.  (Note that you should avoid using
2322     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2323     *
2324     * If you have set the window flag {@ WindowManager.LayoutParams#FLAG_FULLSCREEN}
2325     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2326     * then a hidden status bar will be considered a "stable" state for purposes
2327     * here.  This allows your UI to continually hide the status bar, while still
2328     * using the system UI flags to hide the action bar while still retaining
2329     * a stable layout.  Note that changing the window fullscreen flag will never
2330     * provide a stable layout for a clean transition.
2331     *
2332     * <p>If you are using ActionBar in
2333     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2334     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2335     * insets it adds to those given to the application.
2336     */
2337    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2338
2339    /**
2340     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2341     * to be layed out as if it has requested
2342     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2343     * allows it to avoid artifacts when switching in and out of that mode, at
2344     * the expense that some of its user interface may be covered by screen
2345     * decorations when they are shown.  You can perform layout of your inner
2346     * UI elements to account for the navagation system UI through the
2347     * {@link #fitSystemWindows(Rect)} method.
2348     */
2349    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2350
2351    /**
2352     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2353     * to be layed out as if it has requested
2354     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2355     * allows it to avoid artifacts when switching in and out of that mode, at
2356     * the expense that some of its user interface may be covered by screen
2357     * decorations when they are shown.  You can perform layout of your inner
2358     * UI elements to account for non-fullscreen system UI through the
2359     * {@link #fitSystemWindows(Rect)} method.
2360     */
2361    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2362
2363    /**
2364     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2365     */
2366    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2367
2368    /**
2369     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2370     */
2371    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2372
2373    /**
2374     * @hide
2375     *
2376     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2377     * out of the public fields to keep the undefined bits out of the developer's way.
2378     *
2379     * Flag to make the status bar not expandable.  Unless you also
2380     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2381     */
2382    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2383
2384    /**
2385     * @hide
2386     *
2387     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2388     * out of the public fields to keep the undefined bits out of the developer's way.
2389     *
2390     * Flag to hide notification icons and scrolling ticker text.
2391     */
2392    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2393
2394    /**
2395     * @hide
2396     *
2397     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2398     * out of the public fields to keep the undefined bits out of the developer's way.
2399     *
2400     * Flag to disable incoming notification alerts.  This will not block
2401     * icons, but it will block sound, vibrating and other visual or aural notifications.
2402     */
2403    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2404
2405    /**
2406     * @hide
2407     *
2408     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2409     * out of the public fields to keep the undefined bits out of the developer's way.
2410     *
2411     * Flag to hide only the scrolling ticker.  Note that
2412     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2413     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2414     */
2415    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2416
2417    /**
2418     * @hide
2419     *
2420     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2421     * out of the public fields to keep the undefined bits out of the developer's way.
2422     *
2423     * Flag to hide the center system info area.
2424     */
2425    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2426
2427    /**
2428     * @hide
2429     *
2430     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2431     * out of the public fields to keep the undefined bits out of the developer's way.
2432     *
2433     * Flag to hide only the home button.  Don't use this
2434     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2435     */
2436    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2437
2438    /**
2439     * @hide
2440     *
2441     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2442     * out of the public fields to keep the undefined bits out of the developer's way.
2443     *
2444     * Flag to hide only the back button. Don't use this
2445     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2446     */
2447    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2448
2449    /**
2450     * @hide
2451     *
2452     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2453     * out of the public fields to keep the undefined bits out of the developer's way.
2454     *
2455     * Flag to hide only the clock.  You might use this if your activity has
2456     * its own clock making the status bar's clock redundant.
2457     */
2458    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2459
2460    /**
2461     * @hide
2462     *
2463     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2464     * out of the public fields to keep the undefined bits out of the developer's way.
2465     *
2466     * Flag to hide only the recent apps button. Don't use this
2467     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2468     */
2469    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2470
2471    /**
2472     * @hide
2473     */
2474    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2475
2476    /**
2477     * These are the system UI flags that can be cleared by events outside
2478     * of an application.  Currently this is just the ability to tap on the
2479     * screen while hiding the navigation bar to have it return.
2480     * @hide
2481     */
2482    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2483            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2484            | SYSTEM_UI_FLAG_FULLSCREEN;
2485
2486    /**
2487     * Flags that can impact the layout in relation to system UI.
2488     */
2489    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2490            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2491            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2492
2493    /**
2494     * Find views that render the specified text.
2495     *
2496     * @see #findViewsWithText(ArrayList, CharSequence, int)
2497     */
2498    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2499
2500    /**
2501     * Find find views that contain the specified content description.
2502     *
2503     * @see #findViewsWithText(ArrayList, CharSequence, int)
2504     */
2505    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2506
2507    /**
2508     * Find views that contain {@link AccessibilityNodeProvider}. Such
2509     * a View is a root of virtual view hierarchy and may contain the searched
2510     * text. If this flag is set Views with providers are automatically
2511     * added and it is a responsibility of the client to call the APIs of
2512     * the provider to determine whether the virtual tree rooted at this View
2513     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2514     * represeting the virtual views with this text.
2515     *
2516     * @see #findViewsWithText(ArrayList, CharSequence, int)
2517     *
2518     * @hide
2519     */
2520    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2521
2522    /**
2523     * The undefined cursor position.
2524     */
2525    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2526
2527    /**
2528     * Indicates that the screen has changed state and is now off.
2529     *
2530     * @see #onScreenStateChanged(int)
2531     */
2532    public static final int SCREEN_STATE_OFF = 0x0;
2533
2534    /**
2535     * Indicates that the screen has changed state and is now on.
2536     *
2537     * @see #onScreenStateChanged(int)
2538     */
2539    public static final int SCREEN_STATE_ON = 0x1;
2540
2541    /**
2542     * Controls the over-scroll mode for this view.
2543     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2544     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2545     * and {@link #OVER_SCROLL_NEVER}.
2546     */
2547    private int mOverScrollMode;
2548
2549    /**
2550     * The parent this view is attached to.
2551     * {@hide}
2552     *
2553     * @see #getParent()
2554     */
2555    protected ViewParent mParent;
2556
2557    /**
2558     * {@hide}
2559     */
2560    AttachInfo mAttachInfo;
2561
2562    /**
2563     * {@hide}
2564     */
2565    @ViewDebug.ExportedProperty(flagMapping = {
2566        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2567                name = "FORCE_LAYOUT"),
2568        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2569                name = "LAYOUT_REQUIRED"),
2570        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2571            name = "DRAWING_CACHE_INVALID", outputIf = false),
2572        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2573        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2574        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2575        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2576    })
2577    int mPrivateFlags;
2578    int mPrivateFlags2;
2579
2580    /**
2581     * This view's request for the visibility of the status bar.
2582     * @hide
2583     */
2584    @ViewDebug.ExportedProperty(flagMapping = {
2585        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2586                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2587                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2588        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2589                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2590                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2591        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2592                                equals = SYSTEM_UI_FLAG_VISIBLE,
2593                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2594    })
2595    int mSystemUiVisibility;
2596
2597    /**
2598     * Reference count for transient state.
2599     * @see #setHasTransientState(boolean)
2600     */
2601    int mTransientStateCount = 0;
2602
2603    /**
2604     * Count of how many windows this view has been attached to.
2605     */
2606    int mWindowAttachCount;
2607
2608    /**
2609     * The layout parameters associated with this view and used by the parent
2610     * {@link android.view.ViewGroup} to determine how this view should be
2611     * laid out.
2612     * {@hide}
2613     */
2614    protected ViewGroup.LayoutParams mLayoutParams;
2615
2616    /**
2617     * The view flags hold various views states.
2618     * {@hide}
2619     */
2620    @ViewDebug.ExportedProperty
2621    int mViewFlags;
2622
2623    static class TransformationInfo {
2624        /**
2625         * The transform matrix for the View. This transform is calculated internally
2626         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2627         * is used by default. Do *not* use this variable directly; instead call
2628         * getMatrix(), which will automatically recalculate the matrix if necessary
2629         * to get the correct matrix based on the latest rotation and scale properties.
2630         */
2631        private final Matrix mMatrix = new Matrix();
2632
2633        /**
2634         * The transform matrix for the View. This transform is calculated internally
2635         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2636         * is used by default. Do *not* use this variable directly; instead call
2637         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2638         * to get the correct matrix based on the latest rotation and scale properties.
2639         */
2640        private Matrix mInverseMatrix;
2641
2642        /**
2643         * An internal variable that tracks whether we need to recalculate the
2644         * transform matrix, based on whether the rotation or scaleX/Y properties
2645         * have changed since the matrix was last calculated.
2646         */
2647        boolean mMatrixDirty = false;
2648
2649        /**
2650         * An internal variable that tracks whether we need to recalculate the
2651         * transform matrix, based on whether the rotation or scaleX/Y properties
2652         * have changed since the matrix was last calculated.
2653         */
2654        private boolean mInverseMatrixDirty = true;
2655
2656        /**
2657         * A variable that tracks whether we need to recalculate the
2658         * transform matrix, based on whether the rotation or scaleX/Y properties
2659         * have changed since the matrix was last calculated. This variable
2660         * is only valid after a call to updateMatrix() or to a function that
2661         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2662         */
2663        private boolean mMatrixIsIdentity = true;
2664
2665        /**
2666         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2667         */
2668        private Camera mCamera = null;
2669
2670        /**
2671         * This matrix is used when computing the matrix for 3D rotations.
2672         */
2673        private Matrix matrix3D = null;
2674
2675        /**
2676         * These prev values are used to recalculate a centered pivot point when necessary. The
2677         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2678         * set), so thes values are only used then as well.
2679         */
2680        private int mPrevWidth = -1;
2681        private int mPrevHeight = -1;
2682
2683        /**
2684         * The degrees rotation around the vertical axis through the pivot point.
2685         */
2686        @ViewDebug.ExportedProperty
2687        float mRotationY = 0f;
2688
2689        /**
2690         * The degrees rotation around the horizontal axis through the pivot point.
2691         */
2692        @ViewDebug.ExportedProperty
2693        float mRotationX = 0f;
2694
2695        /**
2696         * The degrees rotation around the pivot point.
2697         */
2698        @ViewDebug.ExportedProperty
2699        float mRotation = 0f;
2700
2701        /**
2702         * The amount of translation of the object away from its left property (post-layout).
2703         */
2704        @ViewDebug.ExportedProperty
2705        float mTranslationX = 0f;
2706
2707        /**
2708         * The amount of translation of the object away from its top property (post-layout).
2709         */
2710        @ViewDebug.ExportedProperty
2711        float mTranslationY = 0f;
2712
2713        /**
2714         * The amount of scale in the x direction around the pivot point. A
2715         * value of 1 means no scaling is applied.
2716         */
2717        @ViewDebug.ExportedProperty
2718        float mScaleX = 1f;
2719
2720        /**
2721         * The amount of scale in the y direction around the pivot point. A
2722         * value of 1 means no scaling is applied.
2723         */
2724        @ViewDebug.ExportedProperty
2725        float mScaleY = 1f;
2726
2727        /**
2728         * The x location of the point around which the view is rotated and scaled.
2729         */
2730        @ViewDebug.ExportedProperty
2731        float mPivotX = 0f;
2732
2733        /**
2734         * The y location of the point around which the view is rotated and scaled.
2735         */
2736        @ViewDebug.ExportedProperty
2737        float mPivotY = 0f;
2738
2739        /**
2740         * The opacity of the View. This is a value from 0 to 1, where 0 means
2741         * completely transparent and 1 means completely opaque.
2742         */
2743        @ViewDebug.ExportedProperty
2744        float mAlpha = 1f;
2745    }
2746
2747    TransformationInfo mTransformationInfo;
2748
2749    private boolean mLastIsOpaque;
2750
2751    /**
2752     * Convenience value to check for float values that are close enough to zero to be considered
2753     * zero.
2754     */
2755    private static final float NONZERO_EPSILON = .001f;
2756
2757    /**
2758     * The distance in pixels from the left edge of this view's parent
2759     * to the left edge of this view.
2760     * {@hide}
2761     */
2762    @ViewDebug.ExportedProperty(category = "layout")
2763    protected int mLeft;
2764    /**
2765     * The distance in pixels from the left edge of this view's parent
2766     * to the right edge of this view.
2767     * {@hide}
2768     */
2769    @ViewDebug.ExportedProperty(category = "layout")
2770    protected int mRight;
2771    /**
2772     * The distance in pixels from the top edge of this view's parent
2773     * to the top edge of this view.
2774     * {@hide}
2775     */
2776    @ViewDebug.ExportedProperty(category = "layout")
2777    protected int mTop;
2778    /**
2779     * The distance in pixels from the top edge of this view's parent
2780     * to the bottom edge of this view.
2781     * {@hide}
2782     */
2783    @ViewDebug.ExportedProperty(category = "layout")
2784    protected int mBottom;
2785
2786    /**
2787     * The offset, in pixels, by which the content of this view is scrolled
2788     * horizontally.
2789     * {@hide}
2790     */
2791    @ViewDebug.ExportedProperty(category = "scrolling")
2792    protected int mScrollX;
2793    /**
2794     * The offset, in pixels, by which the content of this view is scrolled
2795     * vertically.
2796     * {@hide}
2797     */
2798    @ViewDebug.ExportedProperty(category = "scrolling")
2799    protected int mScrollY;
2800
2801    /**
2802     * The left padding in pixels, that is the distance in pixels between the
2803     * left edge of this view and the left edge of its content.
2804     * {@hide}
2805     */
2806    @ViewDebug.ExportedProperty(category = "padding")
2807    protected int mPaddingLeft;
2808    /**
2809     * The right padding in pixels, that is the distance in pixels between the
2810     * right edge of this view and the right edge of its content.
2811     * {@hide}
2812     */
2813    @ViewDebug.ExportedProperty(category = "padding")
2814    protected int mPaddingRight;
2815    /**
2816     * The top padding in pixels, that is the distance in pixels between the
2817     * top edge of this view and the top edge of its content.
2818     * {@hide}
2819     */
2820    @ViewDebug.ExportedProperty(category = "padding")
2821    protected int mPaddingTop;
2822    /**
2823     * The bottom padding in pixels, that is the distance in pixels between the
2824     * bottom edge of this view and the bottom edge of its content.
2825     * {@hide}
2826     */
2827    @ViewDebug.ExportedProperty(category = "padding")
2828    protected int mPaddingBottom;
2829
2830    /**
2831     * The layout insets in pixels, that is the distance in pixels between the
2832     * visible edges of this view its bounds.
2833     */
2834    private Insets mLayoutInsets;
2835
2836    /**
2837     * Briefly describes the view and is primarily used for accessibility support.
2838     */
2839    private CharSequence mContentDescription;
2840
2841    /**
2842     * Cache the paddingRight set by the user to append to the scrollbar's size.
2843     *
2844     * @hide
2845     */
2846    @ViewDebug.ExportedProperty(category = "padding")
2847    protected int mUserPaddingRight;
2848
2849    /**
2850     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2851     *
2852     * @hide
2853     */
2854    @ViewDebug.ExportedProperty(category = "padding")
2855    protected int mUserPaddingBottom;
2856
2857    /**
2858     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2859     *
2860     * @hide
2861     */
2862    @ViewDebug.ExportedProperty(category = "padding")
2863    protected int mUserPaddingLeft;
2864
2865    /**
2866     * Cache if the user padding is relative.
2867     *
2868     */
2869    @ViewDebug.ExportedProperty(category = "padding")
2870    boolean mUserPaddingRelative;
2871
2872    /**
2873     * Cache the paddingStart set by the user to append to the scrollbar's size.
2874     *
2875     */
2876    @ViewDebug.ExportedProperty(category = "padding")
2877    int mUserPaddingStart;
2878
2879    /**
2880     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2881     *
2882     */
2883    @ViewDebug.ExportedProperty(category = "padding")
2884    int mUserPaddingEnd;
2885
2886    /**
2887     * @hide
2888     */
2889    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2890    /**
2891     * @hide
2892     */
2893    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2894
2895    private Drawable mBackground;
2896
2897    private int mBackgroundResource;
2898    private boolean mBackgroundSizeChanged;
2899
2900    static class ListenerInfo {
2901        /**
2902         * Listener used to dispatch focus change events.
2903         * This field should be made private, so it is hidden from the SDK.
2904         * {@hide}
2905         */
2906        protected OnFocusChangeListener mOnFocusChangeListener;
2907
2908        /**
2909         * Listeners for layout change events.
2910         */
2911        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2912
2913        /**
2914         * Listeners for attach events.
2915         */
2916        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2917
2918        /**
2919         * Listener used to dispatch click events.
2920         * This field should be made private, so it is hidden from the SDK.
2921         * {@hide}
2922         */
2923        public OnClickListener mOnClickListener;
2924
2925        /**
2926         * Listener used to dispatch long click events.
2927         * This field should be made private, so it is hidden from the SDK.
2928         * {@hide}
2929         */
2930        protected OnLongClickListener mOnLongClickListener;
2931
2932        /**
2933         * Listener used to build the context menu.
2934         * This field should be made private, so it is hidden from the SDK.
2935         * {@hide}
2936         */
2937        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2938
2939        private OnKeyListener mOnKeyListener;
2940
2941        private OnTouchListener mOnTouchListener;
2942
2943        private OnHoverListener mOnHoverListener;
2944
2945        private OnGenericMotionListener mOnGenericMotionListener;
2946
2947        private OnDragListener mOnDragListener;
2948
2949        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2950    }
2951
2952    ListenerInfo mListenerInfo;
2953
2954    /**
2955     * The application environment this view lives in.
2956     * This field should be made private, so it is hidden from the SDK.
2957     * {@hide}
2958     */
2959    protected Context mContext;
2960
2961    private final Resources mResources;
2962
2963    private ScrollabilityCache mScrollCache;
2964
2965    private int[] mDrawableState = null;
2966
2967    /**
2968     * Set to true when drawing cache is enabled and cannot be created.
2969     *
2970     * @hide
2971     */
2972    public boolean mCachingFailed;
2973
2974    private Bitmap mDrawingCache;
2975    private Bitmap mUnscaledDrawingCache;
2976    private HardwareLayer mHardwareLayer;
2977    DisplayList mDisplayList;
2978
2979    /**
2980     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2981     * the user may specify which view to go to next.
2982     */
2983    private int mNextFocusLeftId = View.NO_ID;
2984
2985    /**
2986     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2987     * the user may specify which view to go to next.
2988     */
2989    private int mNextFocusRightId = View.NO_ID;
2990
2991    /**
2992     * When this view has focus and the next focus is {@link #FOCUS_UP},
2993     * the user may specify which view to go to next.
2994     */
2995    private int mNextFocusUpId = View.NO_ID;
2996
2997    /**
2998     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2999     * the user may specify which view to go to next.
3000     */
3001    private int mNextFocusDownId = View.NO_ID;
3002
3003    /**
3004     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3005     * the user may specify which view to go to next.
3006     */
3007    int mNextFocusForwardId = View.NO_ID;
3008
3009    private CheckForLongPress mPendingCheckForLongPress;
3010    private CheckForTap mPendingCheckForTap = null;
3011    private PerformClick mPerformClick;
3012    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3013
3014    private UnsetPressedState mUnsetPressedState;
3015
3016    /**
3017     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3018     * up event while a long press is invoked as soon as the long press duration is reached, so
3019     * a long press could be performed before the tap is checked, in which case the tap's action
3020     * should not be invoked.
3021     */
3022    private boolean mHasPerformedLongPress;
3023
3024    /**
3025     * The minimum height of the view. We'll try our best to have the height
3026     * of this view to at least this amount.
3027     */
3028    @ViewDebug.ExportedProperty(category = "measurement")
3029    private int mMinHeight;
3030
3031    /**
3032     * The minimum width of the view. We'll try our best to have the width
3033     * of this view to at least this amount.
3034     */
3035    @ViewDebug.ExportedProperty(category = "measurement")
3036    private int mMinWidth;
3037
3038    /**
3039     * The delegate to handle touch events that are physically in this view
3040     * but should be handled by another view.
3041     */
3042    private TouchDelegate mTouchDelegate = null;
3043
3044    /**
3045     * Solid color to use as a background when creating the drawing cache. Enables
3046     * the cache to use 16 bit bitmaps instead of 32 bit.
3047     */
3048    private int mDrawingCacheBackgroundColor = 0;
3049
3050    /**
3051     * Special tree observer used when mAttachInfo is null.
3052     */
3053    private ViewTreeObserver mFloatingTreeObserver;
3054
3055    /**
3056     * Cache the touch slop from the context that created the view.
3057     */
3058    private int mTouchSlop;
3059
3060    /**
3061     * Object that handles automatic animation of view properties.
3062     */
3063    private ViewPropertyAnimator mAnimator = null;
3064
3065    /**
3066     * Flag indicating that a drag can cross window boundaries.  When
3067     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3068     * with this flag set, all visible applications will be able to participate
3069     * in the drag operation and receive the dragged content.
3070     *
3071     * @hide
3072     */
3073    public static final int DRAG_FLAG_GLOBAL = 1;
3074
3075    /**
3076     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3077     */
3078    private float mVerticalScrollFactor;
3079
3080    /**
3081     * Position of the vertical scroll bar.
3082     */
3083    private int mVerticalScrollbarPosition;
3084
3085    /**
3086     * Position the scroll bar at the default position as determined by the system.
3087     */
3088    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3089
3090    /**
3091     * Position the scroll bar along the left edge.
3092     */
3093    public static final int SCROLLBAR_POSITION_LEFT = 1;
3094
3095    /**
3096     * Position the scroll bar along the right edge.
3097     */
3098    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3099
3100    /**
3101     * Indicates that the view does not have a layer.
3102     *
3103     * @see #getLayerType()
3104     * @see #setLayerType(int, android.graphics.Paint)
3105     * @see #LAYER_TYPE_SOFTWARE
3106     * @see #LAYER_TYPE_HARDWARE
3107     */
3108    public static final int LAYER_TYPE_NONE = 0;
3109
3110    /**
3111     * <p>Indicates that the view has a software layer. A software layer is backed
3112     * by a bitmap and causes the view to be rendered using Android's software
3113     * rendering pipeline, even if hardware acceleration is enabled.</p>
3114     *
3115     * <p>Software layers have various usages:</p>
3116     * <p>When the application is not using hardware acceleration, a software layer
3117     * is useful to apply a specific color filter and/or blending mode and/or
3118     * translucency to a view and all its children.</p>
3119     * <p>When the application is using hardware acceleration, a software layer
3120     * is useful to render drawing primitives not supported by the hardware
3121     * accelerated pipeline. It can also be used to cache a complex view tree
3122     * into a texture and reduce the complexity of drawing operations. For instance,
3123     * when animating a complex view tree with a translation, a software layer can
3124     * be used to render the view tree only once.</p>
3125     * <p>Software layers should be avoided when the affected view tree updates
3126     * often. Every update will require to re-render the software layer, which can
3127     * potentially be slow (particularly when hardware acceleration is turned on
3128     * since the layer will have to be uploaded into a hardware texture after every
3129     * update.)</p>
3130     *
3131     * @see #getLayerType()
3132     * @see #setLayerType(int, android.graphics.Paint)
3133     * @see #LAYER_TYPE_NONE
3134     * @see #LAYER_TYPE_HARDWARE
3135     */
3136    public static final int LAYER_TYPE_SOFTWARE = 1;
3137
3138    /**
3139     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3140     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3141     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3142     * rendering pipeline, but only if hardware acceleration is turned on for the
3143     * view hierarchy. When hardware acceleration is turned off, hardware layers
3144     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3145     *
3146     * <p>A hardware layer is useful to apply a specific color filter and/or
3147     * blending mode and/or translucency to a view and all its children.</p>
3148     * <p>A hardware layer can be used to cache a complex view tree into a
3149     * texture and reduce the complexity of drawing operations. For instance,
3150     * when animating a complex view tree with a translation, a hardware layer can
3151     * be used to render the view tree only once.</p>
3152     * <p>A hardware layer can also be used to increase the rendering quality when
3153     * rotation transformations are applied on a view. It can also be used to
3154     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3155     *
3156     * @see #getLayerType()
3157     * @see #setLayerType(int, android.graphics.Paint)
3158     * @see #LAYER_TYPE_NONE
3159     * @see #LAYER_TYPE_SOFTWARE
3160     */
3161    public static final int LAYER_TYPE_HARDWARE = 2;
3162
3163    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3164            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3165            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3166            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3167    })
3168    int mLayerType = LAYER_TYPE_NONE;
3169    Paint mLayerPaint;
3170    Rect mLocalDirtyRect;
3171
3172    /**
3173     * Set to true when the view is sending hover accessibility events because it
3174     * is the innermost hovered view.
3175     */
3176    private boolean mSendingHoverAccessibilityEvents;
3177
3178    /**
3179     * Simple constructor to use when creating a view from code.
3180     *
3181     * @param context The Context the view is running in, through which it can
3182     *        access the current theme, resources, etc.
3183     */
3184    public View(Context context) {
3185        mContext = context;
3186        mResources = context != null ? context.getResources() : null;
3187        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3188        // Set layout and text direction defaults
3189        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3190                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3191                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3192                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT) |
3193                (ACCESSIBILITY_FOCUSABLE_DEFAULT << ACCESSIBILITY_FOCUSABLE_SHIFT);
3194        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3195        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3196        mUserPaddingStart = -1;
3197        mUserPaddingEnd = -1;
3198        mUserPaddingRelative = false;
3199    }
3200
3201    /**
3202     * Delegate for injecting accessiblity functionality.
3203     */
3204    AccessibilityDelegate mAccessibilityDelegate;
3205
3206    /**
3207     * Consistency verifier for debugging purposes.
3208     * @hide
3209     */
3210    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3211            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3212                    new InputEventConsistencyVerifier(this, 0) : null;
3213
3214    /**
3215     * Constructor that is called when inflating a view from XML. This is called
3216     * when a view is being constructed from an XML file, supplying attributes
3217     * that were specified in the XML file. This version uses a default style of
3218     * 0, so the only attribute values applied are those in the Context's Theme
3219     * and the given AttributeSet.
3220     *
3221     * <p>
3222     * The method onFinishInflate() will be called after all children have been
3223     * added.
3224     *
3225     * @param context The Context the view is running in, through which it can
3226     *        access the current theme, resources, etc.
3227     * @param attrs The attributes of the XML tag that is inflating the view.
3228     * @see #View(Context, AttributeSet, int)
3229     */
3230    public View(Context context, AttributeSet attrs) {
3231        this(context, attrs, 0);
3232    }
3233
3234    /**
3235     * Perform inflation from XML and apply a class-specific base style. This
3236     * constructor of View allows subclasses to use their own base style when
3237     * they are inflating. For example, a Button class's constructor would call
3238     * this version of the super class constructor and supply
3239     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3240     * the theme's button style to modify all of the base view attributes (in
3241     * particular its background) as well as the Button class's attributes.
3242     *
3243     * @param context The Context the view is running in, through which it can
3244     *        access the current theme, resources, etc.
3245     * @param attrs The attributes of the XML tag that is inflating the view.
3246     * @param defStyle The default style to apply to this view. If 0, no style
3247     *        will be applied (beyond what is included in the theme). This may
3248     *        either be an attribute resource, whose value will be retrieved
3249     *        from the current theme, or an explicit style resource.
3250     * @see #View(Context, AttributeSet)
3251     */
3252    public View(Context context, AttributeSet attrs, int defStyle) {
3253        this(context);
3254
3255        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3256                defStyle, 0);
3257
3258        Drawable background = null;
3259
3260        int leftPadding = -1;
3261        int topPadding = -1;
3262        int rightPadding = -1;
3263        int bottomPadding = -1;
3264        int startPadding = -1;
3265        int endPadding = -1;
3266
3267        int padding = -1;
3268
3269        int viewFlagValues = 0;
3270        int viewFlagMasks = 0;
3271
3272        boolean setScrollContainer = false;
3273
3274        int x = 0;
3275        int y = 0;
3276
3277        float tx = 0;
3278        float ty = 0;
3279        float rotation = 0;
3280        float rotationX = 0;
3281        float rotationY = 0;
3282        float sx = 1f;
3283        float sy = 1f;
3284        boolean transformSet = false;
3285
3286        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3287
3288        int overScrollMode = mOverScrollMode;
3289        final int N = a.getIndexCount();
3290        for (int i = 0; i < N; i++) {
3291            int attr = a.getIndex(i);
3292            switch (attr) {
3293                case com.android.internal.R.styleable.View_background:
3294                    background = a.getDrawable(attr);
3295                    break;
3296                case com.android.internal.R.styleable.View_padding:
3297                    padding = a.getDimensionPixelSize(attr, -1);
3298                    break;
3299                 case com.android.internal.R.styleable.View_paddingLeft:
3300                    leftPadding = a.getDimensionPixelSize(attr, -1);
3301                    break;
3302                case com.android.internal.R.styleable.View_paddingTop:
3303                    topPadding = a.getDimensionPixelSize(attr, -1);
3304                    break;
3305                case com.android.internal.R.styleable.View_paddingRight:
3306                    rightPadding = a.getDimensionPixelSize(attr, -1);
3307                    break;
3308                case com.android.internal.R.styleable.View_paddingBottom:
3309                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3310                    break;
3311                case com.android.internal.R.styleable.View_paddingStart:
3312                    startPadding = a.getDimensionPixelSize(attr, -1);
3313                    break;
3314                case com.android.internal.R.styleable.View_paddingEnd:
3315                    endPadding = a.getDimensionPixelSize(attr, -1);
3316                    break;
3317                case com.android.internal.R.styleable.View_scrollX:
3318                    x = a.getDimensionPixelOffset(attr, 0);
3319                    break;
3320                case com.android.internal.R.styleable.View_scrollY:
3321                    y = a.getDimensionPixelOffset(attr, 0);
3322                    break;
3323                case com.android.internal.R.styleable.View_alpha:
3324                    setAlpha(a.getFloat(attr, 1f));
3325                    break;
3326                case com.android.internal.R.styleable.View_transformPivotX:
3327                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3328                    break;
3329                case com.android.internal.R.styleable.View_transformPivotY:
3330                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3331                    break;
3332                case com.android.internal.R.styleable.View_translationX:
3333                    tx = a.getDimensionPixelOffset(attr, 0);
3334                    transformSet = true;
3335                    break;
3336                case com.android.internal.R.styleable.View_translationY:
3337                    ty = a.getDimensionPixelOffset(attr, 0);
3338                    transformSet = true;
3339                    break;
3340                case com.android.internal.R.styleable.View_rotation:
3341                    rotation = a.getFloat(attr, 0);
3342                    transformSet = true;
3343                    break;
3344                case com.android.internal.R.styleable.View_rotationX:
3345                    rotationX = a.getFloat(attr, 0);
3346                    transformSet = true;
3347                    break;
3348                case com.android.internal.R.styleable.View_rotationY:
3349                    rotationY = a.getFloat(attr, 0);
3350                    transformSet = true;
3351                    break;
3352                case com.android.internal.R.styleable.View_scaleX:
3353                    sx = a.getFloat(attr, 1f);
3354                    transformSet = true;
3355                    break;
3356                case com.android.internal.R.styleable.View_scaleY:
3357                    sy = a.getFloat(attr, 1f);
3358                    transformSet = true;
3359                    break;
3360                case com.android.internal.R.styleable.View_id:
3361                    mID = a.getResourceId(attr, NO_ID);
3362                    break;
3363                case com.android.internal.R.styleable.View_tag:
3364                    mTag = a.getText(attr);
3365                    break;
3366                case com.android.internal.R.styleable.View_fitsSystemWindows:
3367                    if (a.getBoolean(attr, false)) {
3368                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3369                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3370                    }
3371                    break;
3372                case com.android.internal.R.styleable.View_focusable:
3373                    if (a.getBoolean(attr, false)) {
3374                        viewFlagValues |= FOCUSABLE;
3375                        viewFlagMasks |= FOCUSABLE_MASK;
3376                    }
3377                    break;
3378                case com.android.internal.R.styleable.View_focusableInTouchMode:
3379                    if (a.getBoolean(attr, false)) {
3380                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3381                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3382                    }
3383                    break;
3384                case com.android.internal.R.styleable.View_clickable:
3385                    if (a.getBoolean(attr, false)) {
3386                        viewFlagValues |= CLICKABLE;
3387                        viewFlagMasks |= CLICKABLE;
3388                    }
3389                    break;
3390                case com.android.internal.R.styleable.View_longClickable:
3391                    if (a.getBoolean(attr, false)) {
3392                        viewFlagValues |= LONG_CLICKABLE;
3393                        viewFlagMasks |= LONG_CLICKABLE;
3394                    }
3395                    break;
3396                case com.android.internal.R.styleable.View_saveEnabled:
3397                    if (!a.getBoolean(attr, true)) {
3398                        viewFlagValues |= SAVE_DISABLED;
3399                        viewFlagMasks |= SAVE_DISABLED_MASK;
3400                    }
3401                    break;
3402                case com.android.internal.R.styleable.View_duplicateParentState:
3403                    if (a.getBoolean(attr, false)) {
3404                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3405                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3406                    }
3407                    break;
3408                case com.android.internal.R.styleable.View_visibility:
3409                    final int visibility = a.getInt(attr, 0);
3410                    if (visibility != 0) {
3411                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3412                        viewFlagMasks |= VISIBILITY_MASK;
3413                    }
3414                    break;
3415                case com.android.internal.R.styleable.View_layoutDirection:
3416                    // Clear any layout direction flags (included resolved bits) already set
3417                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3418                    // Set the layout direction flags depending on the value of the attribute
3419                    final int layoutDirection = a.getInt(attr, -1);
3420                    final int value = (layoutDirection != -1) ?
3421                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3422                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3423                    break;
3424                case com.android.internal.R.styleable.View_drawingCacheQuality:
3425                    final int cacheQuality = a.getInt(attr, 0);
3426                    if (cacheQuality != 0) {
3427                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3428                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3429                    }
3430                    break;
3431                case com.android.internal.R.styleable.View_contentDescription:
3432                    mContentDescription = a.getString(attr);
3433                    break;
3434                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3435                    if (!a.getBoolean(attr, true)) {
3436                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3437                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3438                    }
3439                    break;
3440                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3441                    if (!a.getBoolean(attr, true)) {
3442                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3443                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3444                    }
3445                    break;
3446                case R.styleable.View_scrollbars:
3447                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3448                    if (scrollbars != SCROLLBARS_NONE) {
3449                        viewFlagValues |= scrollbars;
3450                        viewFlagMasks |= SCROLLBARS_MASK;
3451                        initializeScrollbars(a);
3452                    }
3453                    break;
3454                //noinspection deprecation
3455                case R.styleable.View_fadingEdge:
3456                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3457                        // Ignore the attribute starting with ICS
3458                        break;
3459                    }
3460                    // With builds < ICS, fall through and apply fading edges
3461                case R.styleable.View_requiresFadingEdge:
3462                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3463                    if (fadingEdge != FADING_EDGE_NONE) {
3464                        viewFlagValues |= fadingEdge;
3465                        viewFlagMasks |= FADING_EDGE_MASK;
3466                        initializeFadingEdge(a);
3467                    }
3468                    break;
3469                case R.styleable.View_scrollbarStyle:
3470                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3471                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3472                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3473                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3474                    }
3475                    break;
3476                case R.styleable.View_isScrollContainer:
3477                    setScrollContainer = true;
3478                    if (a.getBoolean(attr, false)) {
3479                        setScrollContainer(true);
3480                    }
3481                    break;
3482                case com.android.internal.R.styleable.View_keepScreenOn:
3483                    if (a.getBoolean(attr, false)) {
3484                        viewFlagValues |= KEEP_SCREEN_ON;
3485                        viewFlagMasks |= KEEP_SCREEN_ON;
3486                    }
3487                    break;
3488                case R.styleable.View_filterTouchesWhenObscured:
3489                    if (a.getBoolean(attr, false)) {
3490                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3491                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3492                    }
3493                    break;
3494                case R.styleable.View_nextFocusLeft:
3495                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3496                    break;
3497                case R.styleable.View_nextFocusRight:
3498                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3499                    break;
3500                case R.styleable.View_nextFocusUp:
3501                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3502                    break;
3503                case R.styleable.View_nextFocusDown:
3504                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3505                    break;
3506                case R.styleable.View_nextFocusForward:
3507                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3508                    break;
3509                case R.styleable.View_minWidth:
3510                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3511                    break;
3512                case R.styleable.View_minHeight:
3513                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3514                    break;
3515                case R.styleable.View_onClick:
3516                    if (context.isRestricted()) {
3517                        throw new IllegalStateException("The android:onClick attribute cannot "
3518                                + "be used within a restricted context");
3519                    }
3520
3521                    final String handlerName = a.getString(attr);
3522                    if (handlerName != null) {
3523                        setOnClickListener(new OnClickListener() {
3524                            private Method mHandler;
3525
3526                            public void onClick(View v) {
3527                                if (mHandler == null) {
3528                                    try {
3529                                        mHandler = getContext().getClass().getMethod(handlerName,
3530                                                View.class);
3531                                    } catch (NoSuchMethodException e) {
3532                                        int id = getId();
3533                                        String idText = id == NO_ID ? "" : " with id '"
3534                                                + getContext().getResources().getResourceEntryName(
3535                                                    id) + "'";
3536                                        throw new IllegalStateException("Could not find a method " +
3537                                                handlerName + "(View) in the activity "
3538                                                + getContext().getClass() + " for onClick handler"
3539                                                + " on view " + View.this.getClass() + idText, e);
3540                                    }
3541                                }
3542
3543                                try {
3544                                    mHandler.invoke(getContext(), View.this);
3545                                } catch (IllegalAccessException e) {
3546                                    throw new IllegalStateException("Could not execute non "
3547                                            + "public method of the activity", e);
3548                                } catch (InvocationTargetException e) {
3549                                    throw new IllegalStateException("Could not execute "
3550                                            + "method of the activity", e);
3551                                }
3552                            }
3553                        });
3554                    }
3555                    break;
3556                case R.styleable.View_overScrollMode:
3557                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3558                    break;
3559                case R.styleable.View_verticalScrollbarPosition:
3560                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3561                    break;
3562                case R.styleable.View_layerType:
3563                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3564                    break;
3565                case R.styleable.View_textDirection:
3566                    // Clear any text direction flag already set
3567                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3568                    // Set the text direction flags depending on the value of the attribute
3569                    final int textDirection = a.getInt(attr, -1);
3570                    if (textDirection != -1) {
3571                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3572                    }
3573                    break;
3574                case R.styleable.View_textAlignment:
3575                    // Clear any text alignment flag already set
3576                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3577                    // Set the text alignment flag depending on the value of the attribute
3578                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3579                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3580                    break;
3581                case R.styleable.View_importantForAccessibility:
3582                    setImportantForAccessibility(a.getInt(attr,
3583                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3584            }
3585        }
3586
3587        a.recycle();
3588
3589        setOverScrollMode(overScrollMode);
3590
3591        if (background != null) {
3592            setBackground(background);
3593        }
3594
3595        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3596        // layout direction). Those cached values will be used later during padding resolution.
3597        mUserPaddingStart = startPadding;
3598        mUserPaddingEnd = endPadding;
3599
3600        updateUserPaddingRelative();
3601
3602        if (padding >= 0) {
3603            leftPadding = padding;
3604            topPadding = padding;
3605            rightPadding = padding;
3606            bottomPadding = padding;
3607        }
3608
3609        // If the user specified the padding (either with android:padding or
3610        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3611        // use the default padding or the padding from the background drawable
3612        // (stored at this point in mPadding*)
3613        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3614                topPadding >= 0 ? topPadding : mPaddingTop,
3615                rightPadding >= 0 ? rightPadding : mPaddingRight,
3616                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3617
3618        if (viewFlagMasks != 0) {
3619            setFlags(viewFlagValues, viewFlagMasks);
3620        }
3621
3622        // Needs to be called after mViewFlags is set
3623        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3624            recomputePadding();
3625        }
3626
3627        if (x != 0 || y != 0) {
3628            scrollTo(x, y);
3629        }
3630
3631        if (transformSet) {
3632            setTranslationX(tx);
3633            setTranslationY(ty);
3634            setRotation(rotation);
3635            setRotationX(rotationX);
3636            setRotationY(rotationY);
3637            setScaleX(sx);
3638            setScaleY(sy);
3639        }
3640
3641        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3642            setScrollContainer(true);
3643        }
3644
3645        computeOpaqueFlags();
3646    }
3647
3648    private void updateUserPaddingRelative() {
3649        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3650    }
3651
3652    /**
3653     * Non-public constructor for use in testing
3654     */
3655    View() {
3656        mResources = null;
3657    }
3658
3659    /**
3660     * <p>
3661     * Initializes the fading edges from a given set of styled attributes. This
3662     * method should be called by subclasses that need fading edges and when an
3663     * instance of these subclasses is created programmatically rather than
3664     * being inflated from XML. This method is automatically called when the XML
3665     * is inflated.
3666     * </p>
3667     *
3668     * @param a the styled attributes set to initialize the fading edges from
3669     */
3670    protected void initializeFadingEdge(TypedArray a) {
3671        initScrollCache();
3672
3673        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3674                R.styleable.View_fadingEdgeLength,
3675                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3676    }
3677
3678    /**
3679     * Returns the size of the vertical faded edges used to indicate that more
3680     * content in this view is visible.
3681     *
3682     * @return The size in pixels of the vertical faded edge or 0 if vertical
3683     *         faded edges are not enabled for this view.
3684     * @attr ref android.R.styleable#View_fadingEdgeLength
3685     */
3686    public int getVerticalFadingEdgeLength() {
3687        if (isVerticalFadingEdgeEnabled()) {
3688            ScrollabilityCache cache = mScrollCache;
3689            if (cache != null) {
3690                return cache.fadingEdgeLength;
3691            }
3692        }
3693        return 0;
3694    }
3695
3696    /**
3697     * Set the size of the faded edge used to indicate that more content in this
3698     * view is available.  Will not change whether the fading edge is enabled; use
3699     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3700     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3701     * for the vertical or horizontal fading edges.
3702     *
3703     * @param length The size in pixels of the faded edge used to indicate that more
3704     *        content in this view is visible.
3705     */
3706    public void setFadingEdgeLength(int length) {
3707        initScrollCache();
3708        mScrollCache.fadingEdgeLength = length;
3709    }
3710
3711    /**
3712     * Returns the size of the horizontal faded edges used to indicate that more
3713     * content in this view is visible.
3714     *
3715     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3716     *         faded edges are not enabled for this view.
3717     * @attr ref android.R.styleable#View_fadingEdgeLength
3718     */
3719    public int getHorizontalFadingEdgeLength() {
3720        if (isHorizontalFadingEdgeEnabled()) {
3721            ScrollabilityCache cache = mScrollCache;
3722            if (cache != null) {
3723                return cache.fadingEdgeLength;
3724            }
3725        }
3726        return 0;
3727    }
3728
3729    /**
3730     * Returns the width of the vertical scrollbar.
3731     *
3732     * @return The width in pixels of the vertical scrollbar or 0 if there
3733     *         is no vertical scrollbar.
3734     */
3735    public int getVerticalScrollbarWidth() {
3736        ScrollabilityCache cache = mScrollCache;
3737        if (cache != null) {
3738            ScrollBarDrawable scrollBar = cache.scrollBar;
3739            if (scrollBar != null) {
3740                int size = scrollBar.getSize(true);
3741                if (size <= 0) {
3742                    size = cache.scrollBarSize;
3743                }
3744                return size;
3745            }
3746            return 0;
3747        }
3748        return 0;
3749    }
3750
3751    /**
3752     * Returns the height of the horizontal scrollbar.
3753     *
3754     * @return The height in pixels of the horizontal scrollbar or 0 if
3755     *         there is no horizontal scrollbar.
3756     */
3757    protected int getHorizontalScrollbarHeight() {
3758        ScrollabilityCache cache = mScrollCache;
3759        if (cache != null) {
3760            ScrollBarDrawable scrollBar = cache.scrollBar;
3761            if (scrollBar != null) {
3762                int size = scrollBar.getSize(false);
3763                if (size <= 0) {
3764                    size = cache.scrollBarSize;
3765                }
3766                return size;
3767            }
3768            return 0;
3769        }
3770        return 0;
3771    }
3772
3773    /**
3774     * <p>
3775     * Initializes the scrollbars from a given set of styled attributes. This
3776     * method should be called by subclasses that need scrollbars and when an
3777     * instance of these subclasses is created programmatically rather than
3778     * being inflated from XML. This method is automatically called when the XML
3779     * is inflated.
3780     * </p>
3781     *
3782     * @param a the styled attributes set to initialize the scrollbars from
3783     */
3784    protected void initializeScrollbars(TypedArray a) {
3785        initScrollCache();
3786
3787        final ScrollabilityCache scrollabilityCache = mScrollCache;
3788
3789        if (scrollabilityCache.scrollBar == null) {
3790            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3791        }
3792
3793        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3794
3795        if (!fadeScrollbars) {
3796            scrollabilityCache.state = ScrollabilityCache.ON;
3797        }
3798        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3799
3800
3801        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3802                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3803                        .getScrollBarFadeDuration());
3804        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3805                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3806                ViewConfiguration.getScrollDefaultDelay());
3807
3808
3809        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3810                com.android.internal.R.styleable.View_scrollbarSize,
3811                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3812
3813        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3814        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3815
3816        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3817        if (thumb != null) {
3818            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3819        }
3820
3821        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3822                false);
3823        if (alwaysDraw) {
3824            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3825        }
3826
3827        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3828        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3829
3830        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3831        if (thumb != null) {
3832            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3833        }
3834
3835        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3836                false);
3837        if (alwaysDraw) {
3838            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3839        }
3840
3841        // Apply layout direction to the new Drawables if needed
3842        final int layoutDirection = getResolvedLayoutDirection();
3843        if (track != null) {
3844            track.setLayoutDirection(layoutDirection);
3845        }
3846        if (thumb != null) {
3847            thumb.setLayoutDirection(layoutDirection);
3848        }
3849
3850        // Re-apply user/background padding so that scrollbar(s) get added
3851        resolvePadding();
3852    }
3853
3854    /**
3855     * <p>
3856     * Initalizes the scrollability cache if necessary.
3857     * </p>
3858     */
3859    private void initScrollCache() {
3860        if (mScrollCache == null) {
3861            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3862        }
3863    }
3864
3865    private ScrollabilityCache getScrollCache() {
3866        initScrollCache();
3867        return mScrollCache;
3868    }
3869
3870    /**
3871     * Set the position of the vertical scroll bar. Should be one of
3872     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3873     * {@link #SCROLLBAR_POSITION_RIGHT}.
3874     *
3875     * @param position Where the vertical scroll bar should be positioned.
3876     */
3877    public void setVerticalScrollbarPosition(int position) {
3878        if (mVerticalScrollbarPosition != position) {
3879            mVerticalScrollbarPosition = position;
3880            computeOpaqueFlags();
3881            resolvePadding();
3882        }
3883    }
3884
3885    /**
3886     * @return The position where the vertical scroll bar will show, if applicable.
3887     * @see #setVerticalScrollbarPosition(int)
3888     */
3889    public int getVerticalScrollbarPosition() {
3890        return mVerticalScrollbarPosition;
3891    }
3892
3893    ListenerInfo getListenerInfo() {
3894        if (mListenerInfo != null) {
3895            return mListenerInfo;
3896        }
3897        mListenerInfo = new ListenerInfo();
3898        return mListenerInfo;
3899    }
3900
3901    /**
3902     * Register a callback to be invoked when focus of this view changed.
3903     *
3904     * @param l The callback that will run.
3905     */
3906    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3907        getListenerInfo().mOnFocusChangeListener = l;
3908    }
3909
3910    /**
3911     * Add a listener that will be called when the bounds of the view change due to
3912     * layout processing.
3913     *
3914     * @param listener The listener that will be called when layout bounds change.
3915     */
3916    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3917        ListenerInfo li = getListenerInfo();
3918        if (li.mOnLayoutChangeListeners == null) {
3919            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3920        }
3921        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3922            li.mOnLayoutChangeListeners.add(listener);
3923        }
3924    }
3925
3926    /**
3927     * Remove a listener for layout changes.
3928     *
3929     * @param listener The listener for layout bounds change.
3930     */
3931    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3932        ListenerInfo li = mListenerInfo;
3933        if (li == null || li.mOnLayoutChangeListeners == null) {
3934            return;
3935        }
3936        li.mOnLayoutChangeListeners.remove(listener);
3937    }
3938
3939    /**
3940     * Add a listener for attach state changes.
3941     *
3942     * This listener will be called whenever this view is attached or detached
3943     * from a window. Remove the listener using
3944     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3945     *
3946     * @param listener Listener to attach
3947     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3948     */
3949    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3950        ListenerInfo li = getListenerInfo();
3951        if (li.mOnAttachStateChangeListeners == null) {
3952            li.mOnAttachStateChangeListeners
3953                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3954        }
3955        li.mOnAttachStateChangeListeners.add(listener);
3956    }
3957
3958    /**
3959     * Remove a listener for attach state changes. The listener will receive no further
3960     * notification of window attach/detach events.
3961     *
3962     * @param listener Listener to remove
3963     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3964     */
3965    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3966        ListenerInfo li = mListenerInfo;
3967        if (li == null || li.mOnAttachStateChangeListeners == null) {
3968            return;
3969        }
3970        li.mOnAttachStateChangeListeners.remove(listener);
3971    }
3972
3973    /**
3974     * Returns the focus-change callback registered for this view.
3975     *
3976     * @return The callback, or null if one is not registered.
3977     */
3978    public OnFocusChangeListener getOnFocusChangeListener() {
3979        ListenerInfo li = mListenerInfo;
3980        return li != null ? li.mOnFocusChangeListener : null;
3981    }
3982
3983    /**
3984     * Register a callback to be invoked when this view is clicked. If this view is not
3985     * clickable, it becomes clickable.
3986     *
3987     * @param l The callback that will run
3988     *
3989     * @see #setClickable(boolean)
3990     */
3991    public void setOnClickListener(OnClickListener l) {
3992        if (!isClickable()) {
3993            setClickable(true);
3994        }
3995        getListenerInfo().mOnClickListener = l;
3996    }
3997
3998    /**
3999     * Return whether this view has an attached OnClickListener.  Returns
4000     * true if there is a listener, false if there is none.
4001     */
4002    public boolean hasOnClickListeners() {
4003        ListenerInfo li = mListenerInfo;
4004        return (li != null && li.mOnClickListener != null);
4005    }
4006
4007    /**
4008     * Register a callback to be invoked when this view is clicked and held. If this view is not
4009     * long clickable, it becomes long clickable.
4010     *
4011     * @param l The callback that will run
4012     *
4013     * @see #setLongClickable(boolean)
4014     */
4015    public void setOnLongClickListener(OnLongClickListener l) {
4016        if (!isLongClickable()) {
4017            setLongClickable(true);
4018        }
4019        getListenerInfo().mOnLongClickListener = l;
4020    }
4021
4022    /**
4023     * Register a callback to be invoked when the context menu for this view is
4024     * being built. If this view is not long clickable, it becomes long clickable.
4025     *
4026     * @param l The callback that will run
4027     *
4028     */
4029    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4030        if (!isLongClickable()) {
4031            setLongClickable(true);
4032        }
4033        getListenerInfo().mOnCreateContextMenuListener = l;
4034    }
4035
4036    /**
4037     * Call this view's OnClickListener, if it is defined.  Performs all normal
4038     * actions associated with clicking: reporting accessibility event, playing
4039     * a sound, etc.
4040     *
4041     * @return True there was an assigned OnClickListener that was called, false
4042     *         otherwise is returned.
4043     */
4044    public boolean performClick() {
4045        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4046
4047        ListenerInfo li = mListenerInfo;
4048        if (li != null && li.mOnClickListener != null) {
4049            playSoundEffect(SoundEffectConstants.CLICK);
4050            li.mOnClickListener.onClick(this);
4051            return true;
4052        }
4053
4054        return false;
4055    }
4056
4057    /**
4058     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4059     * this only calls the listener, and does not do any associated clicking
4060     * actions like reporting an accessibility event.
4061     *
4062     * @return True there was an assigned OnClickListener that was called, false
4063     *         otherwise is returned.
4064     */
4065    public boolean callOnClick() {
4066        ListenerInfo li = mListenerInfo;
4067        if (li != null && li.mOnClickListener != null) {
4068            li.mOnClickListener.onClick(this);
4069            return true;
4070        }
4071        return false;
4072    }
4073
4074    /**
4075     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4076     * OnLongClickListener did not consume the event.
4077     *
4078     * @return True if one of the above receivers consumed the event, false otherwise.
4079     */
4080    public boolean performLongClick() {
4081        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4082
4083        boolean handled = false;
4084        ListenerInfo li = mListenerInfo;
4085        if (li != null && li.mOnLongClickListener != null) {
4086            handled = li.mOnLongClickListener.onLongClick(View.this);
4087        }
4088        if (!handled) {
4089            handled = showContextMenu();
4090        }
4091        if (handled) {
4092            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4093        }
4094        return handled;
4095    }
4096
4097    /**
4098     * Performs button-related actions during a touch down event.
4099     *
4100     * @param event The event.
4101     * @return True if the down was consumed.
4102     *
4103     * @hide
4104     */
4105    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4106        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4107            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4108                return true;
4109            }
4110        }
4111        return false;
4112    }
4113
4114    /**
4115     * Bring up the context menu for this view.
4116     *
4117     * @return Whether a context menu was displayed.
4118     */
4119    public boolean showContextMenu() {
4120        return getParent().showContextMenuForChild(this);
4121    }
4122
4123    /**
4124     * Bring up the context menu for this view, referring to the item under the specified point.
4125     *
4126     * @param x The referenced x coordinate.
4127     * @param y The referenced y coordinate.
4128     * @param metaState The keyboard modifiers that were pressed.
4129     * @return Whether a context menu was displayed.
4130     *
4131     * @hide
4132     */
4133    public boolean showContextMenu(float x, float y, int metaState) {
4134        return showContextMenu();
4135    }
4136
4137    /**
4138     * Start an action mode.
4139     *
4140     * @param callback Callback that will control the lifecycle of the action mode
4141     * @return The new action mode if it is started, null otherwise
4142     *
4143     * @see ActionMode
4144     */
4145    public ActionMode startActionMode(ActionMode.Callback callback) {
4146        ViewParent parent = getParent();
4147        if (parent == null) return null;
4148        return parent.startActionModeForChild(this, callback);
4149    }
4150
4151    /**
4152     * Register a callback to be invoked when a hardware key is pressed in this view.
4153     * Key presses in software input methods will generally not trigger the methods of
4154     * this listener.
4155     * @param l the key listener to attach to this view
4156     */
4157    public void setOnKeyListener(OnKeyListener l) {
4158        getListenerInfo().mOnKeyListener = l;
4159    }
4160
4161    /**
4162     * Register a callback to be invoked when a touch event is sent to this view.
4163     * @param l the touch listener to attach to this view
4164     */
4165    public void setOnTouchListener(OnTouchListener l) {
4166        getListenerInfo().mOnTouchListener = l;
4167    }
4168
4169    /**
4170     * Register a callback to be invoked when a generic motion event is sent to this view.
4171     * @param l the generic motion listener to attach to this view
4172     */
4173    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4174        getListenerInfo().mOnGenericMotionListener = l;
4175    }
4176
4177    /**
4178     * Register a callback to be invoked when a hover event is sent to this view.
4179     * @param l the hover listener to attach to this view
4180     */
4181    public void setOnHoverListener(OnHoverListener l) {
4182        getListenerInfo().mOnHoverListener = l;
4183    }
4184
4185    /**
4186     * Register a drag event listener callback object for this View. The parameter is
4187     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4188     * View, the system calls the
4189     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4190     * @param l An implementation of {@link android.view.View.OnDragListener}.
4191     */
4192    public void setOnDragListener(OnDragListener l) {
4193        getListenerInfo().mOnDragListener = l;
4194    }
4195
4196    /**
4197     * Give this view focus. This will cause
4198     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4199     *
4200     * Note: this does not check whether this {@link View} should get focus, it just
4201     * gives it focus no matter what.  It should only be called internally by framework
4202     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4203     *
4204     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4205     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4206     *        focus moved when requestFocus() is called. It may not always
4207     *        apply, in which case use the default View.FOCUS_DOWN.
4208     * @param previouslyFocusedRect The rectangle of the view that had focus
4209     *        prior in this View's coordinate system.
4210     */
4211    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4212        if (DBG) {
4213            System.out.println(this + " requestFocus()");
4214        }
4215
4216        if ((mPrivateFlags & FOCUSED) == 0) {
4217            mPrivateFlags |= FOCUSED;
4218
4219            if (mParent != null) {
4220                mParent.requestChildFocus(this, this);
4221            }
4222
4223            onFocusChanged(true, direction, previouslyFocusedRect);
4224            refreshDrawableState();
4225
4226            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4227                notifyAccessibilityStateChanged();
4228            }
4229        }
4230    }
4231
4232    /**
4233     * Request that a rectangle of this view be visible on the screen,
4234     * scrolling if necessary just enough.
4235     *
4236     * <p>A View should call this if it maintains some notion of which part
4237     * of its content is interesting.  For example, a text editing view
4238     * should call this when its cursor moves.
4239     *
4240     * @param rectangle The rectangle.
4241     * @return Whether any parent scrolled.
4242     */
4243    public boolean requestRectangleOnScreen(Rect rectangle) {
4244        return requestRectangleOnScreen(rectangle, false);
4245    }
4246
4247    /**
4248     * Request that a rectangle of this view be visible on the screen,
4249     * scrolling if necessary just enough.
4250     *
4251     * <p>A View should call this if it maintains some notion of which part
4252     * of its content is interesting.  For example, a text editing view
4253     * should call this when its cursor moves.
4254     *
4255     * <p>When <code>immediate</code> is set to true, scrolling will not be
4256     * animated.
4257     *
4258     * @param rectangle The rectangle.
4259     * @param immediate True to forbid animated scrolling, false otherwise
4260     * @return Whether any parent scrolled.
4261     */
4262    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4263        View child = this;
4264        ViewParent parent = mParent;
4265        boolean scrolled = false;
4266        while (parent != null) {
4267            scrolled |= parent.requestChildRectangleOnScreen(child,
4268                    rectangle, immediate);
4269
4270            // offset rect so next call has the rectangle in the
4271            // coordinate system of its direct child.
4272            rectangle.offset(child.getLeft(), child.getTop());
4273            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4274
4275            if (!(parent instanceof View)) {
4276                break;
4277            }
4278
4279            child = (View) parent;
4280            parent = child.getParent();
4281        }
4282        return scrolled;
4283    }
4284
4285    /**
4286     * Called when this view wants to give up focus. If focus is cleared
4287     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4288     * <p>
4289     * <strong>Note:</strong> When a View clears focus the framework is trying
4290     * to give focus to the first focusable View from the top. Hence, if this
4291     * View is the first from the top that can take focus, then all callbacks
4292     * related to clearing focus will be invoked after wich the framework will
4293     * give focus to this view.
4294     * </p>
4295     */
4296    public void clearFocus() {
4297        if (DBG) {
4298            System.out.println(this + " clearFocus()");
4299        }
4300
4301        if ((mPrivateFlags & FOCUSED) != 0) {
4302            mPrivateFlags &= ~FOCUSED;
4303
4304            if (mParent != null) {
4305                mParent.clearChildFocus(this);
4306            }
4307
4308            onFocusChanged(false, 0, null);
4309
4310            refreshDrawableState();
4311
4312            ensureInputFocusOnFirstFocusable();
4313
4314            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4315                notifyAccessibilityStateChanged();
4316            }
4317        }
4318    }
4319
4320    void ensureInputFocusOnFirstFocusable() {
4321        View root = getRootView();
4322        if (root != null) {
4323            root.requestFocus();
4324        }
4325    }
4326
4327    /**
4328     * Called internally by the view system when a new view is getting focus.
4329     * This is what clears the old focus.
4330     */
4331    void unFocus() {
4332        if (DBG) {
4333            System.out.println(this + " unFocus()");
4334        }
4335
4336        if ((mPrivateFlags & FOCUSED) != 0) {
4337            mPrivateFlags &= ~FOCUSED;
4338
4339            onFocusChanged(false, 0, null);
4340            refreshDrawableState();
4341
4342            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4343                notifyAccessibilityStateChanged();
4344            }
4345        }
4346    }
4347
4348    /**
4349     * Returns true if this view has focus iteself, or is the ancestor of the
4350     * view that has focus.
4351     *
4352     * @return True if this view has or contains focus, false otherwise.
4353     */
4354    @ViewDebug.ExportedProperty(category = "focus")
4355    public boolean hasFocus() {
4356        return (mPrivateFlags & FOCUSED) != 0;
4357    }
4358
4359    /**
4360     * Returns true if this view is focusable or if it contains a reachable View
4361     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4362     * is a View whose parents do not block descendants focus.
4363     *
4364     * Only {@link #VISIBLE} views are considered focusable.
4365     *
4366     * @return True if the view is focusable or if the view contains a focusable
4367     *         View, false otherwise.
4368     *
4369     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4370     */
4371    public boolean hasFocusable() {
4372        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4373    }
4374
4375    /**
4376     * Called by the view system when the focus state of this view changes.
4377     * When the focus change event is caused by directional navigation, direction
4378     * and previouslyFocusedRect provide insight into where the focus is coming from.
4379     * When overriding, be sure to call up through to the super class so that
4380     * the standard focus handling will occur.
4381     *
4382     * @param gainFocus True if the View has focus; false otherwise.
4383     * @param direction The direction focus has moved when requestFocus()
4384     *                  is called to give this view focus. Values are
4385     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4386     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4387     *                  It may not always apply, in which case use the default.
4388     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4389     *        system, of the previously focused view.  If applicable, this will be
4390     *        passed in as finer grained information about where the focus is coming
4391     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4392     */
4393    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4394        if (gainFocus) {
4395            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4396                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4397            }
4398        }
4399
4400        InputMethodManager imm = InputMethodManager.peekInstance();
4401        if (!gainFocus) {
4402            if (isPressed()) {
4403                setPressed(false);
4404            }
4405            if (imm != null && mAttachInfo != null
4406                    && mAttachInfo.mHasWindowFocus) {
4407                imm.focusOut(this);
4408            }
4409            onFocusLost();
4410        } else if (imm != null && mAttachInfo != null
4411                && mAttachInfo.mHasWindowFocus) {
4412            imm.focusIn(this);
4413        }
4414
4415        invalidate(true);
4416        ListenerInfo li = mListenerInfo;
4417        if (li != null && li.mOnFocusChangeListener != null) {
4418            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4419        }
4420
4421        if (mAttachInfo != null) {
4422            mAttachInfo.mKeyDispatchState.reset(this);
4423        }
4424    }
4425
4426    /**
4427     * Sends an accessibility event of the given type. If accessiiblity is
4428     * not enabled this method has no effect. The default implementation calls
4429     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4430     * to populate information about the event source (this View), then calls
4431     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4432     * populate the text content of the event source including its descendants,
4433     * and last calls
4434     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4435     * on its parent to resuest sending of the event to interested parties.
4436     * <p>
4437     * If an {@link AccessibilityDelegate} has been specified via calling
4438     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4439     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4440     * responsible for handling this call.
4441     * </p>
4442     *
4443     * @param eventType The type of the event to send, as defined by several types from
4444     * {@link android.view.accessibility.AccessibilityEvent}, such as
4445     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4446     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4447     *
4448     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4449     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4450     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4451     * @see AccessibilityDelegate
4452     */
4453    public void sendAccessibilityEvent(int eventType) {
4454        if (mAccessibilityDelegate != null) {
4455            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4456        } else {
4457            sendAccessibilityEventInternal(eventType);
4458        }
4459    }
4460
4461    /**
4462     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4463     * {@link AccessibilityEvent} to make an announcement which is related to some
4464     * sort of a context change for which none of the events representing UI transitions
4465     * is a good fit. For example, announcing a new page in a book. If accessibility
4466     * is not enabled this method does nothing.
4467     *
4468     * @param text The announcement text.
4469     */
4470    public void announceForAccessibility(CharSequence text) {
4471        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4472            AccessibilityEvent event = AccessibilityEvent.obtain(
4473                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4474            event.getText().add(text);
4475            sendAccessibilityEventUnchecked(event);
4476        }
4477    }
4478
4479    /**
4480     * @see #sendAccessibilityEvent(int)
4481     *
4482     * Note: Called from the default {@link AccessibilityDelegate}.
4483     */
4484    void sendAccessibilityEventInternal(int eventType) {
4485        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4486            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4487        }
4488    }
4489
4490    /**
4491     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4492     * takes as an argument an empty {@link AccessibilityEvent} and does not
4493     * perform a check whether accessibility is enabled.
4494     * <p>
4495     * If an {@link AccessibilityDelegate} has been specified via calling
4496     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4497     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4498     * is responsible for handling this call.
4499     * </p>
4500     *
4501     * @param event The event to send.
4502     *
4503     * @see #sendAccessibilityEvent(int)
4504     */
4505    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4506        if (mAccessibilityDelegate != null) {
4507            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4508        } else {
4509            sendAccessibilityEventUncheckedInternal(event);
4510        }
4511    }
4512
4513    /**
4514     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4515     *
4516     * Note: Called from the default {@link AccessibilityDelegate}.
4517     */
4518    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4519        if (!isShown()) {
4520            return;
4521        }
4522        onInitializeAccessibilityEvent(event);
4523        // Only a subset of accessibility events populates text content.
4524        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4525            dispatchPopulateAccessibilityEvent(event);
4526        }
4527        // Intercept accessibility focus events fired by virtual nodes to keep
4528        // track of accessibility focus position in such nodes.
4529        final int eventType = event.getEventType();
4530        switch (eventType) {
4531            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4532                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4533                        event.getSourceNodeId());
4534                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4535                    ViewRootImpl viewRootImpl = getViewRootImpl();
4536                    if (viewRootImpl != null) {
4537                        viewRootImpl.setAccessibilityFocusedHost(this);
4538                    }
4539                }
4540            } break;
4541            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4542                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4543                        event.getSourceNodeId());
4544                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4545                    ViewRootImpl viewRootImpl = getViewRootImpl();
4546                    if (viewRootImpl != null) {
4547                        viewRootImpl.setAccessibilityFocusedHost(null);
4548                    }
4549                }
4550            } break;
4551        }
4552        // In the beginning we called #isShown(), so we know that getParent() is not null.
4553        getParent().requestSendAccessibilityEvent(this, event);
4554    }
4555
4556    /**
4557     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4558     * to its children for adding their text content to the event. Note that the
4559     * event text is populated in a separate dispatch path since we add to the
4560     * event not only the text of the source but also the text of all its descendants.
4561     * A typical implementation will call
4562     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4563     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4564     * on each child. Override this method if custom population of the event text
4565     * content is required.
4566     * <p>
4567     * If an {@link AccessibilityDelegate} has been specified via calling
4568     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4569     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4570     * is responsible for handling this call.
4571     * </p>
4572     * <p>
4573     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4574     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4575     * </p>
4576     *
4577     * @param event The event.
4578     *
4579     * @return True if the event population was completed.
4580     */
4581    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4582        if (mAccessibilityDelegate != null) {
4583            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4584        } else {
4585            return dispatchPopulateAccessibilityEventInternal(event);
4586        }
4587    }
4588
4589    /**
4590     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4591     *
4592     * Note: Called from the default {@link AccessibilityDelegate}.
4593     */
4594    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4595        onPopulateAccessibilityEvent(event);
4596        return false;
4597    }
4598
4599    /**
4600     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4601     * giving a chance to this View to populate the accessibility event with its
4602     * text content. While this method is free to modify event
4603     * attributes other than text content, doing so should normally be performed in
4604     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4605     * <p>
4606     * Example: Adding formatted date string to an accessibility event in addition
4607     *          to the text added by the super implementation:
4608     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4609     *     super.onPopulateAccessibilityEvent(event);
4610     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4611     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4612     *         mCurrentDate.getTimeInMillis(), flags);
4613     *     event.getText().add(selectedDateUtterance);
4614     * }</pre>
4615     * <p>
4616     * If an {@link AccessibilityDelegate} has been specified via calling
4617     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4618     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4619     * is responsible for handling this call.
4620     * </p>
4621     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4622     * information to the event, in case the default implementation has basic information to add.
4623     * </p>
4624     *
4625     * @param event The accessibility event which to populate.
4626     *
4627     * @see #sendAccessibilityEvent(int)
4628     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4629     */
4630    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4631        if (mAccessibilityDelegate != null) {
4632            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4633        } else {
4634            onPopulateAccessibilityEventInternal(event);
4635        }
4636    }
4637
4638    /**
4639     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4640     *
4641     * Note: Called from the default {@link AccessibilityDelegate}.
4642     */
4643    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4644
4645    }
4646
4647    /**
4648     * Initializes an {@link AccessibilityEvent} with information about
4649     * this View which is the event source. In other words, the source of
4650     * an accessibility event is the view whose state change triggered firing
4651     * the event.
4652     * <p>
4653     * Example: Setting the password property of an event in addition
4654     *          to properties set by the super implementation:
4655     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4656     *     super.onInitializeAccessibilityEvent(event);
4657     *     event.setPassword(true);
4658     * }</pre>
4659     * <p>
4660     * If an {@link AccessibilityDelegate} has been specified via calling
4661     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4662     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4663     * is responsible for handling this call.
4664     * </p>
4665     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4666     * information to the event, in case the default implementation has basic information to add.
4667     * </p>
4668     * @param event The event to initialize.
4669     *
4670     * @see #sendAccessibilityEvent(int)
4671     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4672     */
4673    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4674        if (mAccessibilityDelegate != null) {
4675            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4676        } else {
4677            onInitializeAccessibilityEventInternal(event);
4678        }
4679    }
4680
4681    /**
4682     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4683     *
4684     * Note: Called from the default {@link AccessibilityDelegate}.
4685     */
4686    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4687        event.setSource(this);
4688        event.setClassName(View.class.getName());
4689        event.setPackageName(getContext().getPackageName());
4690        event.setEnabled(isEnabled());
4691        event.setContentDescription(mContentDescription);
4692
4693        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4694            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4695            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4696                    FOCUSABLES_ALL);
4697            event.setItemCount(focusablesTempList.size());
4698            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4699            focusablesTempList.clear();
4700        }
4701    }
4702
4703    /**
4704     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4705     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4706     * This method is responsible for obtaining an accessibility node info from a
4707     * pool of reusable instances and calling
4708     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4709     * initialize the former.
4710     * <p>
4711     * Note: The client is responsible for recycling the obtained instance by calling
4712     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4713     * </p>
4714     *
4715     * @return A populated {@link AccessibilityNodeInfo}.
4716     *
4717     * @see AccessibilityNodeInfo
4718     */
4719    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4720        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4721        if (provider != null) {
4722            return provider.createAccessibilityNodeInfo(View.NO_ID);
4723        } else {
4724            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4725            onInitializeAccessibilityNodeInfo(info);
4726            return info;
4727        }
4728    }
4729
4730    /**
4731     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4732     * The base implementation sets:
4733     * <ul>
4734     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4735     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4736     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4737     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4738     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4739     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4740     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4741     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4742     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4743     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4744     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4745     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4746     * </ul>
4747     * <p>
4748     * Subclasses should override this method, call the super implementation,
4749     * and set additional attributes.
4750     * </p>
4751     * <p>
4752     * If an {@link AccessibilityDelegate} has been specified via calling
4753     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4754     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4755     * is responsible for handling this call.
4756     * </p>
4757     *
4758     * @param info The instance to initialize.
4759     */
4760    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4761        if (mAccessibilityDelegate != null) {
4762            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4763        } else {
4764            onInitializeAccessibilityNodeInfoInternal(info);
4765        }
4766    }
4767
4768    /**
4769     * Gets the location of this view in screen coordintates.
4770     *
4771     * @param outRect The output location
4772     */
4773    private void getBoundsOnScreen(Rect outRect) {
4774        if (mAttachInfo == null) {
4775            return;
4776        }
4777
4778        RectF position = mAttachInfo.mTmpTransformRect;
4779        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4780
4781        if (!hasIdentityMatrix()) {
4782            getMatrix().mapRect(position);
4783        }
4784
4785        position.offset(mLeft, mTop);
4786
4787        ViewParent parent = mParent;
4788        while (parent instanceof View) {
4789            View parentView = (View) parent;
4790
4791            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4792
4793            if (!parentView.hasIdentityMatrix()) {
4794                parentView.getMatrix().mapRect(position);
4795            }
4796
4797            position.offset(parentView.mLeft, parentView.mTop);
4798
4799            parent = parentView.mParent;
4800        }
4801
4802        if (parent instanceof ViewRootImpl) {
4803            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4804            position.offset(0, -viewRootImpl.mCurScrollY);
4805        }
4806
4807        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4808
4809        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4810                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4811    }
4812
4813    /**
4814     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4815     *
4816     * Note: Called from the default {@link AccessibilityDelegate}.
4817     */
4818    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4819        Rect bounds = mAttachInfo.mTmpInvalRect;
4820        getDrawingRect(bounds);
4821        info.setBoundsInParent(bounds);
4822
4823        getBoundsOnScreen(bounds);
4824        info.setBoundsInScreen(bounds);
4825
4826        ViewParent parent = getParentForAccessibility();
4827        if (parent instanceof View) {
4828            info.setParent((View) parent);
4829        }
4830
4831        info.setVisibleToUser(isVisibleToUser());
4832
4833        info.setPackageName(mContext.getPackageName());
4834        info.setClassName(View.class.getName());
4835        info.setContentDescription(getContentDescription());
4836
4837        info.setEnabled(isEnabled());
4838        info.setClickable(isClickable());
4839        info.setFocusable(isFocusable());
4840        info.setFocused(isFocused());
4841        info.setAccessibilityFocused(isAccessibilityFocused());
4842        info.setSelected(isSelected());
4843        info.setLongClickable(isLongClickable());
4844
4845        // TODO: These make sense only if we are in an AdapterView but all
4846        // views can be selected. Maybe from accessiiblity perspective
4847        // we should report as selectable view in an AdapterView.
4848        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4849        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4850
4851        if (isFocusable()) {
4852            if (isFocused()) {
4853                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4854            } else {
4855                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4856            }
4857        }
4858
4859        if (!isAccessibilityFocused()) {
4860            final int mode = getAccessibilityFocusable();
4861            if (mode == ACCESSIBILITY_FOCUSABLE_YES || mode == ACCESSIBILITY_FOCUSABLE_AUTO) {
4862                info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4863            }
4864        } else {
4865            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4866        }
4867
4868        if (isClickable() && isEnabled()) {
4869            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4870        }
4871
4872        if (isLongClickable() && isEnabled()) {
4873            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4874        }
4875
4876        if (mContentDescription != null && mContentDescription.length() > 0) {
4877            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4878            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4879            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4880                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4881                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4882        }
4883    }
4884
4885    /**
4886     * Computes whether this view is visible to the user. Such a view is
4887     * attached, visible, all its predecessors are visible, it is not clipped
4888     * entirely by its predecessors, and has an alpha greater than zero.
4889     *
4890     * @return Whether the view is visible on the screen.
4891     *
4892     * @hide
4893     */
4894    protected boolean isVisibleToUser() {
4895        return isVisibleToUser(null);
4896    }
4897
4898    /**
4899     * Computes whether the given portion of this view is visible to the user. Such a view is
4900     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4901     * the specified portion is not clipped entirely by its predecessors.
4902     *
4903     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4904     *                    <code>null</code>, and the entire view will be tested in this case.
4905     *                    When <code>true</code> is returned by the function, the actual visible
4906     *                    region will be stored in this parameter; that is, if boundInView is fully
4907     *                    contained within the view, no modification will be made, otherwise regions
4908     *                    outside of the visible area of the view will be clipped.
4909     *
4910     * @return Whether the specified portion of the view is visible on the screen.
4911     *
4912     * @hide
4913     */
4914    protected boolean isVisibleToUser(Rect boundInView) {
4915        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4916        Point offset = mAttachInfo.mPoint;
4917        // The first two checks are made also made by isShown() which
4918        // however traverses the tree up to the parent to catch that.
4919        // Therefore, we do some fail fast check to minimize the up
4920        // tree traversal.
4921        boolean isVisible = mAttachInfo != null
4922            && mAttachInfo.mWindowVisibility == View.VISIBLE
4923            && getAlpha() > 0
4924            && isShown()
4925            && getGlobalVisibleRect(visibleRect, offset);
4926            if (isVisible && boundInView != null) {
4927                visibleRect.offset(-offset.x, -offset.y);
4928                isVisible &= boundInView.intersect(visibleRect);
4929            }
4930            return isVisible;
4931    }
4932
4933    /**
4934     * Sets a delegate for implementing accessibility support via compositon as
4935     * opposed to inheritance. The delegate's primary use is for implementing
4936     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4937     *
4938     * @param delegate The delegate instance.
4939     *
4940     * @see AccessibilityDelegate
4941     */
4942    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4943        mAccessibilityDelegate = delegate;
4944    }
4945
4946    /**
4947     * Gets the provider for managing a virtual view hierarchy rooted at this View
4948     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4949     * that explore the window content.
4950     * <p>
4951     * If this method returns an instance, this instance is responsible for managing
4952     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4953     * View including the one representing the View itself. Similarly the returned
4954     * instance is responsible for performing accessibility actions on any virtual
4955     * view or the root view itself.
4956     * </p>
4957     * <p>
4958     * If an {@link AccessibilityDelegate} has been specified via calling
4959     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4960     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4961     * is responsible for handling this call.
4962     * </p>
4963     *
4964     * @return The provider.
4965     *
4966     * @see AccessibilityNodeProvider
4967     */
4968    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4969        if (mAccessibilityDelegate != null) {
4970            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4971        } else {
4972            return null;
4973        }
4974    }
4975
4976    /**
4977     * Gets the unique identifier of this view on the screen for accessibility purposes.
4978     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4979     *
4980     * @return The view accessibility id.
4981     *
4982     * @hide
4983     */
4984    public int getAccessibilityViewId() {
4985        if (mAccessibilityViewId == NO_ID) {
4986            mAccessibilityViewId = sNextAccessibilityViewId++;
4987        }
4988        return mAccessibilityViewId;
4989    }
4990
4991    /**
4992     * Gets the unique identifier of the window in which this View reseides.
4993     *
4994     * @return The window accessibility id.
4995     *
4996     * @hide
4997     */
4998    public int getAccessibilityWindowId() {
4999        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5000    }
5001
5002    /**
5003     * Gets the {@link View} description. It briefly describes the view and is
5004     * primarily used for accessibility support. Set this property to enable
5005     * better accessibility support for your application. This is especially
5006     * true for views that do not have textual representation (For example,
5007     * ImageButton).
5008     *
5009     * @return The content description.
5010     *
5011     * @attr ref android.R.styleable#View_contentDescription
5012     */
5013    @ViewDebug.ExportedProperty(category = "accessibility")
5014    public CharSequence getContentDescription() {
5015        return mContentDescription;
5016    }
5017
5018    /**
5019     * Sets the {@link View} description. It briefly describes the view and is
5020     * primarily used for accessibility support. Set this property to enable
5021     * better accessibility support for your application. This is especially
5022     * true for views that do not have textual representation (For example,
5023     * ImageButton).
5024     *
5025     * @param contentDescription The content description.
5026     *
5027     * @attr ref android.R.styleable#View_contentDescription
5028     */
5029    @RemotableViewMethod
5030    public void setContentDescription(CharSequence contentDescription) {
5031        mContentDescription = contentDescription;
5032    }
5033
5034    /**
5035     * Invoked whenever this view loses focus, either by losing window focus or by losing
5036     * focus within its window. This method can be used to clear any state tied to the
5037     * focus. For instance, if a button is held pressed with the trackball and the window
5038     * loses focus, this method can be used to cancel the press.
5039     *
5040     * Subclasses of View overriding this method should always call super.onFocusLost().
5041     *
5042     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5043     * @see #onWindowFocusChanged(boolean)
5044     *
5045     * @hide pending API council approval
5046     */
5047    protected void onFocusLost() {
5048        resetPressedState();
5049    }
5050
5051    private void resetPressedState() {
5052        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5053            return;
5054        }
5055
5056        if (isPressed()) {
5057            setPressed(false);
5058
5059            if (!mHasPerformedLongPress) {
5060                removeLongPressCallback();
5061            }
5062        }
5063    }
5064
5065    /**
5066     * Returns true if this view has focus
5067     *
5068     * @return True if this view has focus, false otherwise.
5069     */
5070    @ViewDebug.ExportedProperty(category = "focus")
5071    public boolean isFocused() {
5072        return (mPrivateFlags & FOCUSED) != 0;
5073    }
5074
5075    /**
5076     * Find the view in the hierarchy rooted at this view that currently has
5077     * focus.
5078     *
5079     * @return The view that currently has focus, or null if no focused view can
5080     *         be found.
5081     */
5082    public View findFocus() {
5083        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
5084    }
5085
5086    /**
5087     * Indicates whether this view is one of the set of scrollable containers in
5088     * its window.
5089     *
5090     * @return whether this view is one of the set of scrollable containers in
5091     * its window
5092     *
5093     * @attr ref android.R.styleable#View_isScrollContainer
5094     */
5095    public boolean isScrollContainer() {
5096        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5097    }
5098
5099    /**
5100     * Change whether this view is one of the set of scrollable containers in
5101     * its window.  This will be used to determine whether the window can
5102     * resize or must pan when a soft input area is open -- scrollable
5103     * containers allow the window to use resize mode since the container
5104     * will appropriately shrink.
5105     *
5106     * @attr ref android.R.styleable#View_isScrollContainer
5107     */
5108    public void setScrollContainer(boolean isScrollContainer) {
5109        if (isScrollContainer) {
5110            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5111                mAttachInfo.mScrollContainers.add(this);
5112                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5113            }
5114            mPrivateFlags |= SCROLL_CONTAINER;
5115        } else {
5116            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5117                mAttachInfo.mScrollContainers.remove(this);
5118            }
5119            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5120        }
5121    }
5122
5123    /**
5124     * Returns the quality of the drawing cache.
5125     *
5126     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5127     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5128     *
5129     * @see #setDrawingCacheQuality(int)
5130     * @see #setDrawingCacheEnabled(boolean)
5131     * @see #isDrawingCacheEnabled()
5132     *
5133     * @attr ref android.R.styleable#View_drawingCacheQuality
5134     */
5135    public int getDrawingCacheQuality() {
5136        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5137    }
5138
5139    /**
5140     * Set the drawing cache quality of this view. This value is used only when the
5141     * drawing cache is enabled
5142     *
5143     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5144     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5145     *
5146     * @see #getDrawingCacheQuality()
5147     * @see #setDrawingCacheEnabled(boolean)
5148     * @see #isDrawingCacheEnabled()
5149     *
5150     * @attr ref android.R.styleable#View_drawingCacheQuality
5151     */
5152    public void setDrawingCacheQuality(int quality) {
5153        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5154    }
5155
5156    /**
5157     * Returns whether the screen should remain on, corresponding to the current
5158     * value of {@link #KEEP_SCREEN_ON}.
5159     *
5160     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5161     *
5162     * @see #setKeepScreenOn(boolean)
5163     *
5164     * @attr ref android.R.styleable#View_keepScreenOn
5165     */
5166    public boolean getKeepScreenOn() {
5167        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5168    }
5169
5170    /**
5171     * Controls whether the screen should remain on, modifying the
5172     * value of {@link #KEEP_SCREEN_ON}.
5173     *
5174     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5175     *
5176     * @see #getKeepScreenOn()
5177     *
5178     * @attr ref android.R.styleable#View_keepScreenOn
5179     */
5180    public void setKeepScreenOn(boolean keepScreenOn) {
5181        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5182    }
5183
5184    /**
5185     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5186     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5187     *
5188     * @attr ref android.R.styleable#View_nextFocusLeft
5189     */
5190    public int getNextFocusLeftId() {
5191        return mNextFocusLeftId;
5192    }
5193
5194    /**
5195     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5196     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5197     * decide automatically.
5198     *
5199     * @attr ref android.R.styleable#View_nextFocusLeft
5200     */
5201    public void setNextFocusLeftId(int nextFocusLeftId) {
5202        mNextFocusLeftId = nextFocusLeftId;
5203    }
5204
5205    /**
5206     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5207     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5208     *
5209     * @attr ref android.R.styleable#View_nextFocusRight
5210     */
5211    public int getNextFocusRightId() {
5212        return mNextFocusRightId;
5213    }
5214
5215    /**
5216     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5217     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5218     * decide automatically.
5219     *
5220     * @attr ref android.R.styleable#View_nextFocusRight
5221     */
5222    public void setNextFocusRightId(int nextFocusRightId) {
5223        mNextFocusRightId = nextFocusRightId;
5224    }
5225
5226    /**
5227     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5228     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5229     *
5230     * @attr ref android.R.styleable#View_nextFocusUp
5231     */
5232    public int getNextFocusUpId() {
5233        return mNextFocusUpId;
5234    }
5235
5236    /**
5237     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5238     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5239     * decide automatically.
5240     *
5241     * @attr ref android.R.styleable#View_nextFocusUp
5242     */
5243    public void setNextFocusUpId(int nextFocusUpId) {
5244        mNextFocusUpId = nextFocusUpId;
5245    }
5246
5247    /**
5248     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5249     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5250     *
5251     * @attr ref android.R.styleable#View_nextFocusDown
5252     */
5253    public int getNextFocusDownId() {
5254        return mNextFocusDownId;
5255    }
5256
5257    /**
5258     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5259     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5260     * decide automatically.
5261     *
5262     * @attr ref android.R.styleable#View_nextFocusDown
5263     */
5264    public void setNextFocusDownId(int nextFocusDownId) {
5265        mNextFocusDownId = nextFocusDownId;
5266    }
5267
5268    /**
5269     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5270     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5271     *
5272     * @attr ref android.R.styleable#View_nextFocusForward
5273     */
5274    public int getNextFocusForwardId() {
5275        return mNextFocusForwardId;
5276    }
5277
5278    /**
5279     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5280     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5281     * decide automatically.
5282     *
5283     * @attr ref android.R.styleable#View_nextFocusForward
5284     */
5285    public void setNextFocusForwardId(int nextFocusForwardId) {
5286        mNextFocusForwardId = nextFocusForwardId;
5287    }
5288
5289    /**
5290     * Returns the visibility of this view and all of its ancestors
5291     *
5292     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5293     */
5294    public boolean isShown() {
5295        View current = this;
5296        //noinspection ConstantConditions
5297        do {
5298            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5299                return false;
5300            }
5301            ViewParent parent = current.mParent;
5302            if (parent == null) {
5303                return false; // We are not attached to the view root
5304            }
5305            if (!(parent instanceof View)) {
5306                return true;
5307            }
5308            current = (View) parent;
5309        } while (current != null);
5310
5311        return false;
5312    }
5313
5314    /**
5315     * Called by the view hierarchy when the content insets for a window have
5316     * changed, to allow it to adjust its content to fit within those windows.
5317     * The content insets tell you the space that the status bar, input method,
5318     * and other system windows infringe on the application's window.
5319     *
5320     * <p>You do not normally need to deal with this function, since the default
5321     * window decoration given to applications takes care of applying it to the
5322     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5323     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5324     * and your content can be placed under those system elements.  You can then
5325     * use this method within your view hierarchy if you have parts of your UI
5326     * which you would like to ensure are not being covered.
5327     *
5328     * <p>The default implementation of this method simply applies the content
5329     * inset's to the view's padding, consuming that content (modifying the
5330     * insets to be 0), and returning true.  This behavior is off by default, but can
5331     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5332     *
5333     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5334     * insets object is propagated down the hierarchy, so any changes made to it will
5335     * be seen by all following views (including potentially ones above in
5336     * the hierarchy since this is a depth-first traversal).  The first view
5337     * that returns true will abort the entire traversal.
5338     *
5339     * <p>The default implementation works well for a situation where it is
5340     * used with a container that covers the entire window, allowing it to
5341     * apply the appropriate insets to its content on all edges.  If you need
5342     * a more complicated layout (such as two different views fitting system
5343     * windows, one on the top of the window, and one on the bottom),
5344     * you can override the method and handle the insets however you would like.
5345     * Note that the insets provided by the framework are always relative to the
5346     * far edges of the window, not accounting for the location of the called view
5347     * within that window.  (In fact when this method is called you do not yet know
5348     * where the layout will place the view, as it is done before layout happens.)
5349     *
5350     * <p>Note: unlike many View methods, there is no dispatch phase to this
5351     * call.  If you are overriding it in a ViewGroup and want to allow the
5352     * call to continue to your children, you must be sure to call the super
5353     * implementation.
5354     *
5355     * <p>Here is a sample layout that makes use of fitting system windows
5356     * to have controls for a video view placed inside of the window decorations
5357     * that it hides and shows.  This can be used with code like the second
5358     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5359     *
5360     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5361     *
5362     * @param insets Current content insets of the window.  Prior to
5363     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5364     * the insets or else you and Android will be unhappy.
5365     *
5366     * @return Return true if this view applied the insets and it should not
5367     * continue propagating further down the hierarchy, false otherwise.
5368     * @see #getFitsSystemWindows()
5369     * @see #setFitsSystemWindows()
5370     * @see #setSystemUiVisibility(int)
5371     */
5372    protected boolean fitSystemWindows(Rect insets) {
5373        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5374            mUserPaddingStart = -1;
5375            mUserPaddingEnd = -1;
5376            mUserPaddingRelative = false;
5377            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5378                    || mAttachInfo == null
5379                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5380                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5381                return true;
5382            } else {
5383                internalSetPadding(0, 0, 0, 0);
5384                return false;
5385            }
5386        }
5387        return false;
5388    }
5389
5390    /**
5391     * Sets whether or not this view should account for system screen decorations
5392     * such as the status bar and inset its content; that is, controlling whether
5393     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5394     * executed.  See that method for more details.
5395     *
5396     * <p>Note that if you are providing your own implementation of
5397     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5398     * flag to true -- your implementation will be overriding the default
5399     * implementation that checks this flag.
5400     *
5401     * @param fitSystemWindows If true, then the default implementation of
5402     * {@link #fitSystemWindows(Rect)} will be executed.
5403     *
5404     * @attr ref android.R.styleable#View_fitsSystemWindows
5405     * @see #getFitsSystemWindows()
5406     * @see #fitSystemWindows(Rect)
5407     * @see #setSystemUiVisibility(int)
5408     */
5409    public void setFitsSystemWindows(boolean fitSystemWindows) {
5410        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5411    }
5412
5413    /**
5414     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5415     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5416     * will be executed.
5417     *
5418     * @return Returns true if the default implementation of
5419     * {@link #fitSystemWindows(Rect)} will be executed.
5420     *
5421     * @attr ref android.R.styleable#View_fitsSystemWindows
5422     * @see #setFitsSystemWindows()
5423     * @see #fitSystemWindows(Rect)
5424     * @see #setSystemUiVisibility(int)
5425     */
5426    public boolean getFitsSystemWindows() {
5427        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5428    }
5429
5430    /** @hide */
5431    public boolean fitsSystemWindows() {
5432        return getFitsSystemWindows();
5433    }
5434
5435    /**
5436     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5437     */
5438    public void requestFitSystemWindows() {
5439        if (mParent != null) {
5440            mParent.requestFitSystemWindows();
5441        }
5442    }
5443
5444    /**
5445     * For use by PhoneWindow to make its own system window fitting optional.
5446     * @hide
5447     */
5448    public void makeOptionalFitsSystemWindows() {
5449        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5450    }
5451
5452    /**
5453     * Returns the visibility status for this view.
5454     *
5455     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5456     * @attr ref android.R.styleable#View_visibility
5457     */
5458    @ViewDebug.ExportedProperty(mapping = {
5459        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5460        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5461        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5462    })
5463    public int getVisibility() {
5464        return mViewFlags & VISIBILITY_MASK;
5465    }
5466
5467    /**
5468     * Set the enabled state of this view.
5469     *
5470     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5471     * @attr ref android.R.styleable#View_visibility
5472     */
5473    @RemotableViewMethod
5474    public void setVisibility(int visibility) {
5475        setFlags(visibility, VISIBILITY_MASK);
5476        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5477    }
5478
5479    /**
5480     * Returns the enabled status for this view. The interpretation of the
5481     * enabled state varies by subclass.
5482     *
5483     * @return True if this view is enabled, false otherwise.
5484     */
5485    @ViewDebug.ExportedProperty
5486    public boolean isEnabled() {
5487        return (mViewFlags & ENABLED_MASK) == ENABLED;
5488    }
5489
5490    /**
5491     * Set the enabled state of this view. The interpretation of the enabled
5492     * state varies by subclass.
5493     *
5494     * @param enabled True if this view is enabled, false otherwise.
5495     */
5496    @RemotableViewMethod
5497    public void setEnabled(boolean enabled) {
5498        if (enabled == isEnabled()) return;
5499
5500        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5501
5502        /*
5503         * The View most likely has to change its appearance, so refresh
5504         * the drawable state.
5505         */
5506        refreshDrawableState();
5507
5508        // Invalidate too, since the default behavior for views is to be
5509        // be drawn at 50% alpha rather than to change the drawable.
5510        invalidate(true);
5511    }
5512
5513    /**
5514     * Set whether this view can receive the focus.
5515     *
5516     * Setting this to false will also ensure that this view is not focusable
5517     * in touch mode.
5518     *
5519     * @param focusable If true, this view can receive the focus.
5520     *
5521     * @see #setFocusableInTouchMode(boolean)
5522     * @attr ref android.R.styleable#View_focusable
5523     */
5524    public void setFocusable(boolean focusable) {
5525        if (!focusable) {
5526            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5527        }
5528        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5529    }
5530
5531    /**
5532     * Set whether this view can receive focus while in touch mode.
5533     *
5534     * Setting this to true will also ensure that this view is focusable.
5535     *
5536     * @param focusableInTouchMode If true, this view can receive the focus while
5537     *   in touch mode.
5538     *
5539     * @see #setFocusable(boolean)
5540     * @attr ref android.R.styleable#View_focusableInTouchMode
5541     */
5542    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5543        // Focusable in touch mode should always be set before the focusable flag
5544        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5545        // which, in touch mode, will not successfully request focus on this view
5546        // because the focusable in touch mode flag is not set
5547        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5548        if (focusableInTouchMode) {
5549            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5550        }
5551    }
5552
5553    /**
5554     * Set whether this view should have sound effects enabled for events such as
5555     * clicking and touching.
5556     *
5557     * <p>You may wish to disable sound effects for a view if you already play sounds,
5558     * for instance, a dial key that plays dtmf tones.
5559     *
5560     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5561     * @see #isSoundEffectsEnabled()
5562     * @see #playSoundEffect(int)
5563     * @attr ref android.R.styleable#View_soundEffectsEnabled
5564     */
5565    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5566        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5567    }
5568
5569    /**
5570     * @return whether this view should have sound effects enabled for events such as
5571     *     clicking and touching.
5572     *
5573     * @see #setSoundEffectsEnabled(boolean)
5574     * @see #playSoundEffect(int)
5575     * @attr ref android.R.styleable#View_soundEffectsEnabled
5576     */
5577    @ViewDebug.ExportedProperty
5578    public boolean isSoundEffectsEnabled() {
5579        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5580    }
5581
5582    /**
5583     * Set whether this view should have haptic feedback for events such as
5584     * long presses.
5585     *
5586     * <p>You may wish to disable haptic feedback if your view already controls
5587     * its own haptic feedback.
5588     *
5589     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5590     * @see #isHapticFeedbackEnabled()
5591     * @see #performHapticFeedback(int)
5592     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5593     */
5594    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5595        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5596    }
5597
5598    /**
5599     * @return whether this view should have haptic feedback enabled for events
5600     * long presses.
5601     *
5602     * @see #setHapticFeedbackEnabled(boolean)
5603     * @see #performHapticFeedback(int)
5604     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5605     */
5606    @ViewDebug.ExportedProperty
5607    public boolean isHapticFeedbackEnabled() {
5608        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5609    }
5610
5611    /**
5612     * Returns the layout direction for this view.
5613     *
5614     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5615     *   {@link #LAYOUT_DIRECTION_RTL},
5616     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5617     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5618     * @attr ref android.R.styleable#View_layoutDirection
5619     */
5620    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5621        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5622        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5623        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5624        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5625    })
5626    public int getLayoutDirection() {
5627        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5628    }
5629
5630    /**
5631     * Set the layout direction for this view. This will propagate a reset of layout direction
5632     * resolution to the view's children and resolve layout direction for this view.
5633     *
5634     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5635     *   {@link #LAYOUT_DIRECTION_RTL},
5636     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5637     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5638     *
5639     * @attr ref android.R.styleable#View_layoutDirection
5640     */
5641    @RemotableViewMethod
5642    public void setLayoutDirection(int layoutDirection) {
5643        if (getLayoutDirection() != layoutDirection) {
5644            // Reset the current layout direction and the resolved one
5645            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5646            resetResolvedLayoutDirection();
5647            // Set the new layout direction (filtered) and ask for a layout pass
5648            mPrivateFlags2 |=
5649                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5650            requestLayout();
5651        }
5652    }
5653
5654    /**
5655     * Returns the resolved layout direction for this view.
5656     *
5657     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5658     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5659     */
5660    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5661        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5662        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5663    })
5664    public int getResolvedLayoutDirection() {
5665        // The layout diretion will be resolved only if needed
5666        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5667            resolveLayoutDirection();
5668        }
5669        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5670                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5671    }
5672
5673    /**
5674     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5675     * layout attribute and/or the inherited value from the parent
5676     *
5677     * @return true if the layout is right-to-left.
5678     */
5679    @ViewDebug.ExportedProperty(category = "layout")
5680    public boolean isLayoutRtl() {
5681        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5682    }
5683
5684    /**
5685     * Indicates whether the view is currently tracking transient state that the
5686     * app should not need to concern itself with saving and restoring, but that
5687     * the framework should take special note to preserve when possible.
5688     *
5689     * <p>A view with transient state cannot be trivially rebound from an external
5690     * data source, such as an adapter binding item views in a list. This may be
5691     * because the view is performing an animation, tracking user selection
5692     * of content, or similar.</p>
5693     *
5694     * @return true if the view has transient state
5695     */
5696    @ViewDebug.ExportedProperty(category = "layout")
5697    public boolean hasTransientState() {
5698        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5699    }
5700
5701    /**
5702     * Set whether this view is currently tracking transient state that the
5703     * framework should attempt to preserve when possible. This flag is reference counted,
5704     * so every call to setHasTransientState(true) should be paired with a later call
5705     * to setHasTransientState(false).
5706     *
5707     * <p>A view with transient state cannot be trivially rebound from an external
5708     * data source, such as an adapter binding item views in a list. This may be
5709     * because the view is performing an animation, tracking user selection
5710     * of content, or similar.</p>
5711     *
5712     * @param hasTransientState true if this view has transient state
5713     */
5714    public void setHasTransientState(boolean hasTransientState) {
5715        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5716                mTransientStateCount - 1;
5717        if (mTransientStateCount < 0) {
5718            mTransientStateCount = 0;
5719            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5720                    "unmatched pair of setHasTransientState calls");
5721        }
5722        if ((hasTransientState && mTransientStateCount == 1) ||
5723                (!hasTransientState && mTransientStateCount == 0)) {
5724            // update flag if we've just incremented up from 0 or decremented down to 0
5725            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5726                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5727            if (mParent != null) {
5728                try {
5729                    mParent.childHasTransientStateChanged(this, hasTransientState);
5730                } catch (AbstractMethodError e) {
5731                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5732                            " does not fully implement ViewParent", e);
5733                }
5734            }
5735        }
5736    }
5737
5738    /**
5739     * If this view doesn't do any drawing on its own, set this flag to
5740     * allow further optimizations. By default, this flag is not set on
5741     * View, but could be set on some View subclasses such as ViewGroup.
5742     *
5743     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5744     * you should clear this flag.
5745     *
5746     * @param willNotDraw whether or not this View draw on its own
5747     */
5748    public void setWillNotDraw(boolean willNotDraw) {
5749        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5750    }
5751
5752    /**
5753     * Returns whether or not this View draws on its own.
5754     *
5755     * @return true if this view has nothing to draw, false otherwise
5756     */
5757    @ViewDebug.ExportedProperty(category = "drawing")
5758    public boolean willNotDraw() {
5759        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5760    }
5761
5762    /**
5763     * When a View's drawing cache is enabled, drawing is redirected to an
5764     * offscreen bitmap. Some views, like an ImageView, must be able to
5765     * bypass this mechanism if they already draw a single bitmap, to avoid
5766     * unnecessary usage of the memory.
5767     *
5768     * @param willNotCacheDrawing true if this view does not cache its
5769     *        drawing, false otherwise
5770     */
5771    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5772        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5773    }
5774
5775    /**
5776     * Returns whether or not this View can cache its drawing or not.
5777     *
5778     * @return true if this view does not cache its drawing, false otherwise
5779     */
5780    @ViewDebug.ExportedProperty(category = "drawing")
5781    public boolean willNotCacheDrawing() {
5782        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5783    }
5784
5785    /**
5786     * Indicates whether this view reacts to click events or not.
5787     *
5788     * @return true if the view is clickable, false otherwise
5789     *
5790     * @see #setClickable(boolean)
5791     * @attr ref android.R.styleable#View_clickable
5792     */
5793    @ViewDebug.ExportedProperty
5794    public boolean isClickable() {
5795        return (mViewFlags & CLICKABLE) == CLICKABLE;
5796    }
5797
5798    /**
5799     * Enables or disables click events for this view. When a view
5800     * is clickable it will change its state to "pressed" on every click.
5801     * Subclasses should set the view clickable to visually react to
5802     * user's clicks.
5803     *
5804     * @param clickable true to make the view clickable, false otherwise
5805     *
5806     * @see #isClickable()
5807     * @attr ref android.R.styleable#View_clickable
5808     */
5809    public void setClickable(boolean clickable) {
5810        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5811    }
5812
5813    /**
5814     * Indicates whether this view reacts to long click events or not.
5815     *
5816     * @return true if the view is long clickable, false otherwise
5817     *
5818     * @see #setLongClickable(boolean)
5819     * @attr ref android.R.styleable#View_longClickable
5820     */
5821    public boolean isLongClickable() {
5822        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5823    }
5824
5825    /**
5826     * Enables or disables long click events for this view. When a view is long
5827     * clickable it reacts to the user holding down the button for a longer
5828     * duration than a tap. This event can either launch the listener or a
5829     * context menu.
5830     *
5831     * @param longClickable true to make the view long clickable, false otherwise
5832     * @see #isLongClickable()
5833     * @attr ref android.R.styleable#View_longClickable
5834     */
5835    public void setLongClickable(boolean longClickable) {
5836        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5837    }
5838
5839    /**
5840     * Sets the pressed state for this view.
5841     *
5842     * @see #isClickable()
5843     * @see #setClickable(boolean)
5844     *
5845     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5846     *        the View's internal state from a previously set "pressed" state.
5847     */
5848    public void setPressed(boolean pressed) {
5849        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5850
5851        if (pressed) {
5852            mPrivateFlags |= PRESSED;
5853        } else {
5854            mPrivateFlags &= ~PRESSED;
5855        }
5856
5857        if (needsRefresh) {
5858            refreshDrawableState();
5859        }
5860        dispatchSetPressed(pressed);
5861    }
5862
5863    /**
5864     * Dispatch setPressed to all of this View's children.
5865     *
5866     * @see #setPressed(boolean)
5867     *
5868     * @param pressed The new pressed state
5869     */
5870    protected void dispatchSetPressed(boolean pressed) {
5871    }
5872
5873    /**
5874     * Indicates whether the view is currently in pressed state. Unless
5875     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5876     * the pressed state.
5877     *
5878     * @see #setPressed(boolean)
5879     * @see #isClickable()
5880     * @see #setClickable(boolean)
5881     *
5882     * @return true if the view is currently pressed, false otherwise
5883     */
5884    public boolean isPressed() {
5885        return (mPrivateFlags & PRESSED) == PRESSED;
5886    }
5887
5888    /**
5889     * Indicates whether this view will save its state (that is,
5890     * whether its {@link #onSaveInstanceState} method will be called).
5891     *
5892     * @return Returns true if the view state saving is enabled, else false.
5893     *
5894     * @see #setSaveEnabled(boolean)
5895     * @attr ref android.R.styleable#View_saveEnabled
5896     */
5897    public boolean isSaveEnabled() {
5898        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5899    }
5900
5901    /**
5902     * Controls whether the saving of this view's state is
5903     * enabled (that is, whether its {@link #onSaveInstanceState} method
5904     * will be called).  Note that even if freezing is enabled, the
5905     * view still must have an id assigned to it (via {@link #setId(int)})
5906     * for its state to be saved.  This flag can only disable the
5907     * saving of this view; any child views may still have their state saved.
5908     *
5909     * @param enabled Set to false to <em>disable</em> state saving, or true
5910     * (the default) to allow it.
5911     *
5912     * @see #isSaveEnabled()
5913     * @see #setId(int)
5914     * @see #onSaveInstanceState()
5915     * @attr ref android.R.styleable#View_saveEnabled
5916     */
5917    public void setSaveEnabled(boolean enabled) {
5918        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5919    }
5920
5921    /**
5922     * Gets whether the framework should discard touches when the view's
5923     * window is obscured by another visible window.
5924     * Refer to the {@link View} security documentation for more details.
5925     *
5926     * @return True if touch filtering is enabled.
5927     *
5928     * @see #setFilterTouchesWhenObscured(boolean)
5929     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5930     */
5931    @ViewDebug.ExportedProperty
5932    public boolean getFilterTouchesWhenObscured() {
5933        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5934    }
5935
5936    /**
5937     * Sets whether the framework should discard touches when the view's
5938     * window is obscured by another visible window.
5939     * Refer to the {@link View} security documentation for more details.
5940     *
5941     * @param enabled True if touch filtering should be enabled.
5942     *
5943     * @see #getFilterTouchesWhenObscured
5944     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5945     */
5946    public void setFilterTouchesWhenObscured(boolean enabled) {
5947        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5948                FILTER_TOUCHES_WHEN_OBSCURED);
5949    }
5950
5951    /**
5952     * Indicates whether the entire hierarchy under this view will save its
5953     * state when a state saving traversal occurs from its parent.  The default
5954     * is true; if false, these views will not be saved unless
5955     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5956     *
5957     * @return Returns true if the view state saving from parent is enabled, else false.
5958     *
5959     * @see #setSaveFromParentEnabled(boolean)
5960     */
5961    public boolean isSaveFromParentEnabled() {
5962        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5963    }
5964
5965    /**
5966     * Controls whether the entire hierarchy under this view will save its
5967     * state when a state saving traversal occurs from its parent.  The default
5968     * is true; if false, these views will not be saved unless
5969     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5970     *
5971     * @param enabled Set to false to <em>disable</em> state saving, or true
5972     * (the default) to allow it.
5973     *
5974     * @see #isSaveFromParentEnabled()
5975     * @see #setId(int)
5976     * @see #onSaveInstanceState()
5977     */
5978    public void setSaveFromParentEnabled(boolean enabled) {
5979        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5980    }
5981
5982
5983    /**
5984     * Returns whether this View is able to take focus.
5985     *
5986     * @return True if this view can take focus, or false otherwise.
5987     * @attr ref android.R.styleable#View_focusable
5988     */
5989    @ViewDebug.ExportedProperty(category = "focus")
5990    public final boolean isFocusable() {
5991        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5992    }
5993
5994    /**
5995     * When a view is focusable, it may not want to take focus when in touch mode.
5996     * For example, a button would like focus when the user is navigating via a D-pad
5997     * so that the user can click on it, but once the user starts touching the screen,
5998     * the button shouldn't take focus
5999     * @return Whether the view is focusable in touch mode.
6000     * @attr ref android.R.styleable#View_focusableInTouchMode
6001     */
6002    @ViewDebug.ExportedProperty
6003    public final boolean isFocusableInTouchMode() {
6004        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6005    }
6006
6007    /**
6008     * Find the nearest view in the specified direction that can take focus.
6009     * This does not actually give focus to that view.
6010     *
6011     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6012     *
6013     * @return The nearest focusable in the specified direction, or null if none
6014     *         can be found.
6015     */
6016    public View focusSearch(int direction) {
6017        if (mParent != null) {
6018            return mParent.focusSearch(this, direction);
6019        } else {
6020            return null;
6021        }
6022    }
6023
6024    /**
6025     * This method is the last chance for the focused view and its ancestors to
6026     * respond to an arrow key. This is called when the focused view did not
6027     * consume the key internally, nor could the view system find a new view in
6028     * the requested direction to give focus to.
6029     *
6030     * @param focused The currently focused view.
6031     * @param direction The direction focus wants to move. One of FOCUS_UP,
6032     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6033     * @return True if the this view consumed this unhandled move.
6034     */
6035    public boolean dispatchUnhandledMove(View focused, int direction) {
6036        return false;
6037    }
6038
6039    /**
6040     * If a user manually specified the next view id for a particular direction,
6041     * use the root to look up the view.
6042     * @param root The root view of the hierarchy containing this view.
6043     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6044     * or FOCUS_BACKWARD.
6045     * @return The user specified next view, or null if there is none.
6046     */
6047    View findUserSetNextFocus(View root, int direction) {
6048        switch (direction) {
6049            case FOCUS_LEFT:
6050                if (mNextFocusLeftId == View.NO_ID) return null;
6051                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6052            case FOCUS_RIGHT:
6053                if (mNextFocusRightId == View.NO_ID) return null;
6054                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6055            case FOCUS_UP:
6056                if (mNextFocusUpId == View.NO_ID) return null;
6057                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6058            case FOCUS_DOWN:
6059                if (mNextFocusDownId == View.NO_ID) return null;
6060                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6061            case FOCUS_FORWARD:
6062                if (mNextFocusForwardId == View.NO_ID) return null;
6063                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6064            case FOCUS_BACKWARD: {
6065                if (mID == View.NO_ID) return null;
6066                final int id = mID;
6067                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6068                    @Override
6069                    public boolean apply(View t) {
6070                        return t.mNextFocusForwardId == id;
6071                    }
6072                });
6073            }
6074        }
6075        return null;
6076    }
6077
6078    private View findViewInsideOutShouldExist(View root, final int childViewId) {
6079        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6080            @Override
6081            public boolean apply(View t) {
6082                return t.mID == childViewId;
6083            }
6084        });
6085
6086        if (result == null) {
6087            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
6088                    + "by user for id " + childViewId);
6089        }
6090        return result;
6091    }
6092
6093    /**
6094     * Find and return all focusable views that are descendants of this view,
6095     * possibly including this view if it is focusable itself.
6096     *
6097     * @param direction The direction of the focus
6098     * @return A list of focusable views
6099     */
6100    public ArrayList<View> getFocusables(int direction) {
6101        ArrayList<View> result = new ArrayList<View>(24);
6102        addFocusables(result, direction);
6103        return result;
6104    }
6105
6106    /**
6107     * Add any focusable views that are descendants of this view (possibly
6108     * including this view if it is focusable itself) to views.  If we are in touch mode,
6109     * only add views that are also focusable in touch mode.
6110     *
6111     * @param views Focusable views found so far
6112     * @param direction The direction of the focus
6113     */
6114    public void addFocusables(ArrayList<View> views, int direction) {
6115        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6116    }
6117
6118    /**
6119     * Adds any focusable views that are descendants of this view (possibly
6120     * including this view if it is focusable itself) to views. This method
6121     * adds all focusable views regardless if we are in touch mode or
6122     * only views focusable in touch mode if we are in touch mode or
6123     * only views that can take accessibility focus if accessibility is enabeld
6124     * depending on the focusable mode paramater.
6125     *
6126     * @param views Focusable views found so far or null if all we are interested is
6127     *        the number of focusables.
6128     * @param direction The direction of the focus.
6129     * @param focusableMode The type of focusables to be added.
6130     *
6131     * @see #FOCUSABLES_ALL
6132     * @see #FOCUSABLES_TOUCH_MODE
6133     */
6134    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6135        if (views == null) {
6136            return;
6137        }
6138        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
6139            if (isAccessibilityFocusable()) {
6140                views.add(this);
6141                return;
6142            }
6143        }
6144        if (!isFocusable()) {
6145            return;
6146        }
6147        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6148                && isInTouchMode() && !isFocusableInTouchMode()) {
6149            return;
6150        }
6151        views.add(this);
6152    }
6153
6154    /**
6155     * Finds the Views that contain given text. The containment is case insensitive.
6156     * The search is performed by either the text that the View renders or the content
6157     * description that describes the view for accessibility purposes and the view does
6158     * not render or both. Clients can specify how the search is to be performed via
6159     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6160     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6161     *
6162     * @param outViews The output list of matching Views.
6163     * @param searched The text to match against.
6164     *
6165     * @see #FIND_VIEWS_WITH_TEXT
6166     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6167     * @see #setContentDescription(CharSequence)
6168     */
6169    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6170        if (getAccessibilityNodeProvider() != null) {
6171            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6172                outViews.add(this);
6173            }
6174        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6175                && (searched != null && searched.length() > 0)
6176                && (mContentDescription != null && mContentDescription.length() > 0)) {
6177            String searchedLowerCase = searched.toString().toLowerCase();
6178            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6179            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6180                outViews.add(this);
6181            }
6182        }
6183    }
6184
6185    /**
6186     * Find and return all touchable views that are descendants of this view,
6187     * possibly including this view if it is touchable itself.
6188     *
6189     * @return A list of touchable views
6190     */
6191    public ArrayList<View> getTouchables() {
6192        ArrayList<View> result = new ArrayList<View>();
6193        addTouchables(result);
6194        return result;
6195    }
6196
6197    /**
6198     * Add any touchable views that are descendants of this view (possibly
6199     * including this view if it is touchable itself) to views.
6200     *
6201     * @param views Touchable views found so far
6202     */
6203    public void addTouchables(ArrayList<View> views) {
6204        final int viewFlags = mViewFlags;
6205
6206        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6207                && (viewFlags & ENABLED_MASK) == ENABLED) {
6208            views.add(this);
6209        }
6210    }
6211
6212    /**
6213     * Returns whether this View is accessibility focused.
6214     *
6215     * @return True if this View is accessibility focused.
6216     */
6217    boolean isAccessibilityFocused() {
6218        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6219    }
6220
6221    /**
6222     * Call this to try to give accessibility focus to this view.
6223     *
6224     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6225     * returns false or the view is no visible or the view already has accessibility
6226     * focus.
6227     *
6228     * See also {@link #focusSearch(int)}, which is what you call to say that you
6229     * have focus, and you want your parent to look for the next one.
6230     *
6231     * @return Whether this view actually took accessibility focus.
6232     *
6233     * @hide
6234     */
6235    public boolean requestAccessibilityFocus() {
6236        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6237        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6238            return false;
6239        }
6240        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6241            return false;
6242        }
6243        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6244            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6245            ViewRootImpl viewRootImpl = getViewRootImpl();
6246            if (viewRootImpl != null) {
6247                viewRootImpl.setAccessibilityFocusedHost(this);
6248            }
6249            invalidate();
6250            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6251            notifyAccessibilityStateChanged();
6252            return true;
6253        }
6254        return false;
6255    }
6256
6257    /**
6258     * Call this to try to clear accessibility focus of this view.
6259     *
6260     * See also {@link #focusSearch(int)}, which is what you call to say that you
6261     * have focus, and you want your parent to look for the next one.
6262     *
6263     * @hide
6264     */
6265    public void clearAccessibilityFocus() {
6266        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6267            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6268            invalidate();
6269            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6270            notifyAccessibilityStateChanged();
6271            // Clear the text navigation state.
6272            setAccessibilityCursorPosition(ACCESSIBILITY_CURSOR_POSITION_UNDEFINED);
6273        }
6274        // Clear the global reference of accessibility focus if this
6275        // view or any of its descendants had accessibility focus.
6276        ViewRootImpl viewRootImpl = getViewRootImpl();
6277        if (viewRootImpl != null) {
6278            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6279            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6280                viewRootImpl.setAccessibilityFocusedHost(null);
6281            }
6282        }
6283    }
6284
6285    private void requestAccessibilityFocusFromHover() {
6286        if (includeForAccessibility() && isActionableForAccessibility()) {
6287            requestAccessibilityFocus();
6288            requestFocusNoSearch(View.FOCUS_DOWN, null);
6289        } else {
6290            if (mParent != null) {
6291                View nextFocus = mParent.findViewToTakeAccessibilityFocusFromHover(this, this);
6292                if (nextFocus != null) {
6293                    nextFocus.requestAccessibilityFocus();
6294                    nextFocus.requestFocusNoSearch(View.FOCUS_DOWN, null);
6295                }
6296            }
6297        }
6298    }
6299
6300    /**
6301     * @hide
6302     */
6303    public boolean canTakeAccessibilityFocusFromHover() {
6304        if (includeForAccessibility() && isActionableForAccessibility()) {
6305            return true;
6306        }
6307        if (mParent != null) {
6308            return (mParent.findViewToTakeAccessibilityFocusFromHover(this, this) == this);
6309        }
6310        return false;
6311    }
6312
6313    /**
6314     * Clears accessibility focus without calling any callback methods
6315     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6316     * is used for clearing accessibility focus when giving this focus to
6317     * another view.
6318     */
6319    void clearAccessibilityFocusNoCallbacks() {
6320        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6321            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6322            setAccessibilityCursorPosition(ACCESSIBILITY_CURSOR_POSITION_UNDEFINED);
6323            invalidate();
6324        }
6325    }
6326
6327    /**
6328     * Call this to try to give focus to a specific view or to one of its
6329     * descendants.
6330     *
6331     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6332     * false), or if it is focusable and it is not focusable in touch mode
6333     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6334     *
6335     * See also {@link #focusSearch(int)}, which is what you call to say that you
6336     * have focus, and you want your parent to look for the next one.
6337     *
6338     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6339     * {@link #FOCUS_DOWN} and <code>null</code>.
6340     *
6341     * @return Whether this view or one of its descendants actually took focus.
6342     */
6343    public final boolean requestFocus() {
6344        return requestFocus(View.FOCUS_DOWN);
6345    }
6346
6347    /**
6348     * Call this to try to give focus to a specific view or to one of its
6349     * descendants and give it a hint about what direction focus is heading.
6350     *
6351     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6352     * false), or if it is focusable and it is not focusable in touch mode
6353     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6354     *
6355     * See also {@link #focusSearch(int)}, which is what you call to say that you
6356     * have focus, and you want your parent to look for the next one.
6357     *
6358     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6359     * <code>null</code> set for the previously focused rectangle.
6360     *
6361     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6362     * @return Whether this view or one of its descendants actually took focus.
6363     */
6364    public final boolean requestFocus(int direction) {
6365        return requestFocus(direction, null);
6366    }
6367
6368    /**
6369     * Call this to try to give focus to a specific view or to one of its descendants
6370     * and give it hints about the direction and a specific rectangle that the focus
6371     * is coming from.  The rectangle can help give larger views a finer grained hint
6372     * about where focus is coming from, and therefore, where to show selection, or
6373     * forward focus change internally.
6374     *
6375     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6376     * false), or if it is focusable and it is not focusable in touch mode
6377     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6378     *
6379     * A View will not take focus if it is not visible.
6380     *
6381     * A View will not take focus if one of its parents has
6382     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6383     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6384     *
6385     * See also {@link #focusSearch(int)}, which is what you call to say that you
6386     * have focus, and you want your parent to look for the next one.
6387     *
6388     * You may wish to override this method if your custom {@link View} has an internal
6389     * {@link View} that it wishes to forward the request to.
6390     *
6391     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6392     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6393     *        to give a finer grained hint about where focus is coming from.  May be null
6394     *        if there is no hint.
6395     * @return Whether this view or one of its descendants actually took focus.
6396     */
6397    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6398        return requestFocusNoSearch(direction, previouslyFocusedRect);
6399    }
6400
6401    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6402        // need to be focusable
6403        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6404                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6405            return false;
6406        }
6407
6408        // need to be focusable in touch mode if in touch mode
6409        if (isInTouchMode() &&
6410            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6411               return false;
6412        }
6413
6414        // need to not have any parents blocking us
6415        if (hasAncestorThatBlocksDescendantFocus()) {
6416            return false;
6417        }
6418
6419        handleFocusGainInternal(direction, previouslyFocusedRect);
6420        return true;
6421    }
6422
6423    /**
6424     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6425     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6426     * touch mode to request focus when they are touched.
6427     *
6428     * @return Whether this view or one of its descendants actually took focus.
6429     *
6430     * @see #isInTouchMode()
6431     *
6432     */
6433    public final boolean requestFocusFromTouch() {
6434        // Leave touch mode if we need to
6435        if (isInTouchMode()) {
6436            ViewRootImpl viewRoot = getViewRootImpl();
6437            if (viewRoot != null) {
6438                viewRoot.ensureTouchMode(false);
6439            }
6440        }
6441        return requestFocus(View.FOCUS_DOWN);
6442    }
6443
6444    /**
6445     * @return Whether any ancestor of this view blocks descendant focus.
6446     */
6447    private boolean hasAncestorThatBlocksDescendantFocus() {
6448        ViewParent ancestor = mParent;
6449        while (ancestor instanceof ViewGroup) {
6450            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6451            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6452                return true;
6453            } else {
6454                ancestor = vgAncestor.getParent();
6455            }
6456        }
6457        return false;
6458    }
6459
6460    /**
6461     * Gets the mode for determining whether this View is important for accessibility
6462     * which is if it fires accessibility events and if it is reported to
6463     * accessibility services that query the screen.
6464     *
6465     * @return The mode for determining whether a View is important for accessibility.
6466     *
6467     * @attr ref android.R.styleable#View_importantForAccessibility
6468     *
6469     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6470     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6471     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6472     */
6473    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6474            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6475            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6476            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6477        })
6478    public int getImportantForAccessibility() {
6479        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6480                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6481    }
6482
6483    /**
6484     * Sets how to determine whether this view is important for accessibility
6485     * which is if it fires accessibility events and if it is reported to
6486     * accessibility services that query the screen.
6487     *
6488     * @param mode How to determine whether this view is important for accessibility.
6489     *
6490     * @attr ref android.R.styleable#View_importantForAccessibility
6491     *
6492     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6493     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6494     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6495     */
6496    public void setImportantForAccessibility(int mode) {
6497        if (mode != getImportantForAccessibility()) {
6498            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6499            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6500                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6501            notifyAccessibilityStateChanged();
6502        }
6503    }
6504
6505    /**
6506     * Gets whether this view should be exposed for accessibility.
6507     *
6508     * @return Whether the view is exposed for accessibility.
6509     *
6510     * @hide
6511     */
6512    public boolean isImportantForAccessibility() {
6513        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6514                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6515        switch (mode) {
6516            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6517                return true;
6518            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6519                return false;
6520            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6521                return isActionableForAccessibility() || hasListenersForAccessibility();
6522            default:
6523                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6524                        + mode);
6525        }
6526    }
6527
6528    /**
6529     * Gets the mode for determining whether this View can take accessibility focus.
6530     *
6531     * @return The mode for determining whether a View can take accessibility focus.
6532     *
6533     * @attr ref android.R.styleable#View_accessibilityFocusable
6534     *
6535     * @see #ACCESSIBILITY_FOCUSABLE_YES
6536     * @see #ACCESSIBILITY_FOCUSABLE_NO
6537     * @see #ACCESSIBILITY_FOCUSABLE_AUTO
6538     *
6539     * @hide
6540     */
6541    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6542            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_AUTO, to = "auto"),
6543            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_YES, to = "yes"),
6544            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_NO, to = "no")
6545        })
6546    public int getAccessibilityFocusable() {
6547        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK) >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
6548    }
6549
6550    /**
6551     * Sets how to determine whether this view can take accessibility focus.
6552     *
6553     * @param mode How to determine whether this view can take accessibility focus.
6554     *
6555     * @attr ref android.R.styleable#View_accessibilityFocusable
6556     *
6557     * @see #ACCESSIBILITY_FOCUSABLE_YES
6558     * @see #ACCESSIBILITY_FOCUSABLE_NO
6559     * @see #ACCESSIBILITY_FOCUSABLE_AUTO
6560     *
6561     * @hide
6562     */
6563    public void setAccessibilityFocusable(int mode) {
6564        if (mode != getAccessibilityFocusable()) {
6565            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSABLE_MASK;
6566            mPrivateFlags2 |= (mode << ACCESSIBILITY_FOCUSABLE_SHIFT)
6567                    & ACCESSIBILITY_FOCUSABLE_MASK;
6568            notifyAccessibilityStateChanged();
6569        }
6570    }
6571
6572    /**
6573     * Gets whether this view can take accessibility focus.
6574     *
6575     * @return Whether the view can take accessibility focus.
6576     *
6577     * @hide
6578     */
6579    public boolean isAccessibilityFocusable() {
6580        final int mode = (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK)
6581                >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
6582        switch (mode) {
6583            case ACCESSIBILITY_FOCUSABLE_YES:
6584                return true;
6585            case ACCESSIBILITY_FOCUSABLE_NO:
6586                return false;
6587            case ACCESSIBILITY_FOCUSABLE_AUTO:
6588                return canTakeAccessibilityFocusFromHover()
6589                        || getAccessibilityNodeProvider() != null;
6590            default:
6591                throw new IllegalArgumentException("Unknow accessibility focusable mode: " + mode);
6592        }
6593    }
6594
6595    /**
6596     * Gets the parent for accessibility purposes. Note that the parent for
6597     * accessibility is not necessary the immediate parent. It is the first
6598     * predecessor that is important for accessibility.
6599     *
6600     * @return The parent for accessibility purposes.
6601     */
6602    public ViewParent getParentForAccessibility() {
6603        if (mParent instanceof View) {
6604            View parentView = (View) mParent;
6605            if (parentView.includeForAccessibility()) {
6606                return mParent;
6607            } else {
6608                return mParent.getParentForAccessibility();
6609            }
6610        }
6611        return null;
6612    }
6613
6614    /**
6615     * Adds the children of a given View for accessibility. Since some Views are
6616     * not important for accessibility the children for accessibility are not
6617     * necessarily direct children of the riew, rather they are the first level of
6618     * descendants important for accessibility.
6619     *
6620     * @param children The list of children for accessibility.
6621     */
6622    public void addChildrenForAccessibility(ArrayList<View> children) {
6623        if (includeForAccessibility()) {
6624            children.add(this);
6625        }
6626    }
6627
6628    /**
6629     * Whether to regard this view for accessibility. A view is regarded for
6630     * accessibility if it is important for accessibility or the querying
6631     * accessibility service has explicitly requested that view not
6632     * important for accessibility are regarded.
6633     *
6634     * @return Whether to regard the view for accessibility.
6635     *
6636     * @hide
6637     */
6638    public boolean includeForAccessibility() {
6639        if (mAttachInfo != null) {
6640            if (!mAttachInfo.mIncludeNotImportantViews) {
6641                return isImportantForAccessibility();
6642            }
6643            return true;
6644        }
6645        return false;
6646    }
6647
6648    /**
6649     * Returns whether the View is considered actionable from
6650     * accessibility perspective. Such view are important for
6651     * accessiiblity.
6652     *
6653     * @return True if the view is actionable for accessibility.
6654     *
6655     * @hide
6656     */
6657    public boolean isActionableForAccessibility() {
6658        return (isClickable() || isLongClickable() || isFocusable());
6659    }
6660
6661    /**
6662     * Returns whether the View has registered callbacks wich makes it
6663     * important for accessiiblity.
6664     *
6665     * @return True if the view is actionable for accessibility.
6666     */
6667    private boolean hasListenersForAccessibility() {
6668        ListenerInfo info = getListenerInfo();
6669        return mTouchDelegate != null || info.mOnKeyListener != null
6670                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6671                || info.mOnHoverListener != null || info.mOnDragListener != null;
6672    }
6673
6674    /**
6675     * Notifies accessibility services that some view's important for
6676     * accessibility state has changed. Note that such notifications
6677     * are made at most once every
6678     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6679     * to avoid unnecessary load to the system. Also once a view has
6680     * made a notifucation this method is a NOP until the notification has
6681     * been sent to clients.
6682     *
6683     * @hide
6684     *
6685     * TODO: Makse sure this method is called for any view state change
6686     *       that is interesting for accessilility purposes.
6687     */
6688    public void notifyAccessibilityStateChanged() {
6689        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6690            return;
6691        }
6692        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6693            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6694            if (mParent != null) {
6695                mParent.childAccessibilityStateChanged(this);
6696            }
6697        }
6698    }
6699
6700    /**
6701     * Reset the state indicating the this view has requested clients
6702     * interested in its accessiblity state to be notified.
6703     *
6704     * @hide
6705     */
6706    public void resetAccessibilityStateChanged() {
6707        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6708    }
6709
6710    /**
6711     * Performs the specified accessibility action on the view. For
6712     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6713    * <p>
6714    * If an {@link AccessibilityDelegate} has been specified via calling
6715    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6716    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6717    * is responsible for handling this call.
6718    * </p>
6719     *
6720     * @param action The action to perform.
6721     * @param arguments Optional action arguments.
6722     * @return Whether the action was performed.
6723     */
6724    public boolean performAccessibilityAction(int action, Bundle arguments) {
6725      if (mAccessibilityDelegate != null) {
6726          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6727      } else {
6728          return performAccessibilityActionInternal(action, arguments);
6729      }
6730    }
6731
6732   /**
6733    * @see #performAccessibilityAction(int, Bundle)
6734    *
6735    * Note: Called from the default {@link AccessibilityDelegate}.
6736    */
6737    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6738        switch (action) {
6739            case AccessibilityNodeInfo.ACTION_CLICK: {
6740                if (isClickable()) {
6741                    return performClick();
6742                }
6743            } break;
6744            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6745                if (isLongClickable()) {
6746                    return performLongClick();
6747                }
6748            } break;
6749            case AccessibilityNodeInfo.ACTION_FOCUS: {
6750                if (!hasFocus()) {
6751                    // Get out of touch mode since accessibility
6752                    // wants to move focus around.
6753                    getViewRootImpl().ensureTouchMode(false);
6754                    return requestFocus();
6755                }
6756            } break;
6757            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6758                if (hasFocus()) {
6759                    clearFocus();
6760                    return !isFocused();
6761                }
6762            } break;
6763            case AccessibilityNodeInfo.ACTION_SELECT: {
6764                if (!isSelected()) {
6765                    setSelected(true);
6766                    return isSelected();
6767                }
6768            } break;
6769            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6770                if (isSelected()) {
6771                    setSelected(false);
6772                    return !isSelected();
6773                }
6774            } break;
6775            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6776                final int mode = getAccessibilityFocusable();
6777                if (!isAccessibilityFocused()
6778                        && (mode == ACCESSIBILITY_FOCUSABLE_YES
6779                                || mode == ACCESSIBILITY_FOCUSABLE_AUTO)) {
6780                    return requestAccessibilityFocus();
6781                }
6782            } break;
6783            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6784                if (isAccessibilityFocused()) {
6785                    clearAccessibilityFocus();
6786                    return true;
6787                }
6788            } break;
6789            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6790                if (arguments != null) {
6791                    final int granularity = arguments.getInt(
6792                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6793                    return nextAtGranularity(granularity);
6794                }
6795            } break;
6796            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6797                if (arguments != null) {
6798                    final int granularity = arguments.getInt(
6799                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6800                    return previousAtGranularity(granularity);
6801                }
6802            } break;
6803        }
6804        return false;
6805    }
6806
6807    private boolean nextAtGranularity(int granularity) {
6808        CharSequence text = getIterableTextForAccessibility();
6809        if (text == null || text.length() == 0) {
6810            return false;
6811        }
6812        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6813        if (iterator == null) {
6814            return false;
6815        }
6816        final int current = getAccessibilityCursorPosition();
6817        final int[] range = iterator.following(current);
6818        if (range == null) {
6819            return false;
6820        }
6821        final int start = range[0];
6822        final int end = range[1];
6823        setAccessibilityCursorPosition(end);
6824        sendViewTextTraversedAtGranularityEvent(
6825                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6826                granularity, start, end);
6827        return true;
6828    }
6829
6830    private boolean previousAtGranularity(int granularity) {
6831        CharSequence text = getIterableTextForAccessibility();
6832        if (text == null || text.length() == 0) {
6833            return false;
6834        }
6835        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6836        if (iterator == null) {
6837            return false;
6838        }
6839        int current = getAccessibilityCursorPosition();
6840        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6841            current = text.length();
6842        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6843            // When traversing by character we always put the cursor after the character
6844            // to ease edit and have to compensate before asking the for previous segment.
6845            current--;
6846        }
6847        final int[] range = iterator.preceding(current);
6848        if (range == null) {
6849            return false;
6850        }
6851        final int start = range[0];
6852        final int end = range[1];
6853        // Always put the cursor after the character to ease edit.
6854        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6855            setAccessibilityCursorPosition(end);
6856        } else {
6857            setAccessibilityCursorPosition(start);
6858        }
6859        sendViewTextTraversedAtGranularityEvent(
6860                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6861                granularity, start, end);
6862        return true;
6863    }
6864
6865    /**
6866     * Gets the text reported for accessibility purposes.
6867     *
6868     * @return The accessibility text.
6869     *
6870     * @hide
6871     */
6872    public CharSequence getIterableTextForAccessibility() {
6873        return mContentDescription;
6874    }
6875
6876    /**
6877     * @hide
6878     */
6879    public int getAccessibilityCursorPosition() {
6880        return mAccessibilityCursorPosition;
6881    }
6882
6883    /**
6884     * @hide
6885     */
6886    public void setAccessibilityCursorPosition(int position) {
6887        mAccessibilityCursorPosition = position;
6888    }
6889
6890    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6891            int fromIndex, int toIndex) {
6892        if (mParent == null) {
6893            return;
6894        }
6895        AccessibilityEvent event = AccessibilityEvent.obtain(
6896                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6897        onInitializeAccessibilityEvent(event);
6898        onPopulateAccessibilityEvent(event);
6899        event.setFromIndex(fromIndex);
6900        event.setToIndex(toIndex);
6901        event.setAction(action);
6902        event.setMovementGranularity(granularity);
6903        mParent.requestSendAccessibilityEvent(this, event);
6904    }
6905
6906    /**
6907     * @hide
6908     */
6909    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6910        switch (granularity) {
6911            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6912                CharSequence text = getIterableTextForAccessibility();
6913                if (text != null && text.length() > 0) {
6914                    CharacterTextSegmentIterator iterator =
6915                        CharacterTextSegmentIterator.getInstance(mContext);
6916                    iterator.initialize(text.toString());
6917                    return iterator;
6918                }
6919            } break;
6920            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6921                CharSequence text = getIterableTextForAccessibility();
6922                if (text != null && text.length() > 0) {
6923                    WordTextSegmentIterator iterator =
6924                        WordTextSegmentIterator.getInstance(mContext);
6925                    iterator.initialize(text.toString());
6926                    return iterator;
6927                }
6928            } break;
6929            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6930                CharSequence text = getIterableTextForAccessibility();
6931                if (text != null && text.length() > 0) {
6932                    ParagraphTextSegmentIterator iterator =
6933                        ParagraphTextSegmentIterator.getInstance();
6934                    iterator.initialize(text.toString());
6935                    return iterator;
6936                }
6937            } break;
6938        }
6939        return null;
6940    }
6941
6942    /**
6943     * @hide
6944     */
6945    public void dispatchStartTemporaryDetach() {
6946        clearAccessibilityFocus();
6947        clearDisplayList();
6948
6949        onStartTemporaryDetach();
6950    }
6951
6952    /**
6953     * This is called when a container is going to temporarily detach a child, with
6954     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6955     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6956     * {@link #onDetachedFromWindow()} when the container is done.
6957     */
6958    public void onStartTemporaryDetach() {
6959        removeUnsetPressCallback();
6960        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6961    }
6962
6963    /**
6964     * @hide
6965     */
6966    public void dispatchFinishTemporaryDetach() {
6967        onFinishTemporaryDetach();
6968    }
6969
6970    /**
6971     * Called after {@link #onStartTemporaryDetach} when the container is done
6972     * changing the view.
6973     */
6974    public void onFinishTemporaryDetach() {
6975    }
6976
6977    /**
6978     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6979     * for this view's window.  Returns null if the view is not currently attached
6980     * to the window.  Normally you will not need to use this directly, but
6981     * just use the standard high-level event callbacks like
6982     * {@link #onKeyDown(int, KeyEvent)}.
6983     */
6984    public KeyEvent.DispatcherState getKeyDispatcherState() {
6985        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6986    }
6987
6988    /**
6989     * Dispatch a key event before it is processed by any input method
6990     * associated with the view hierarchy.  This can be used to intercept
6991     * key events in special situations before the IME consumes them; a
6992     * typical example would be handling the BACK key to update the application's
6993     * UI instead of allowing the IME to see it and close itself.
6994     *
6995     * @param event The key event to be dispatched.
6996     * @return True if the event was handled, false otherwise.
6997     */
6998    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6999        return onKeyPreIme(event.getKeyCode(), event);
7000    }
7001
7002    /**
7003     * Dispatch a key event to the next view on the focus path. This path runs
7004     * from the top of the view tree down to the currently focused view. If this
7005     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7006     * the next node down the focus path. This method also fires any key
7007     * listeners.
7008     *
7009     * @param event The key event to be dispatched.
7010     * @return True if the event was handled, false otherwise.
7011     */
7012    public boolean dispatchKeyEvent(KeyEvent event) {
7013        if (mInputEventConsistencyVerifier != null) {
7014            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7015        }
7016
7017        // Give any attached key listener a first crack at the event.
7018        //noinspection SimplifiableIfStatement
7019        ListenerInfo li = mListenerInfo;
7020        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7021                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7022            return true;
7023        }
7024
7025        if (event.dispatch(this, mAttachInfo != null
7026                ? mAttachInfo.mKeyDispatchState : null, this)) {
7027            return true;
7028        }
7029
7030        if (mInputEventConsistencyVerifier != null) {
7031            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7032        }
7033        return false;
7034    }
7035
7036    /**
7037     * Dispatches a key shortcut event.
7038     *
7039     * @param event The key event to be dispatched.
7040     * @return True if the event was handled by the view, false otherwise.
7041     */
7042    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7043        return onKeyShortcut(event.getKeyCode(), event);
7044    }
7045
7046    /**
7047     * Pass the touch screen motion event down to the target view, or this
7048     * view if it is the target.
7049     *
7050     * @param event The motion event to be dispatched.
7051     * @return True if the event was handled by the view, false otherwise.
7052     */
7053    public boolean dispatchTouchEvent(MotionEvent event) {
7054        if (mInputEventConsistencyVerifier != null) {
7055            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7056        }
7057
7058        if (onFilterTouchEventForSecurity(event)) {
7059            //noinspection SimplifiableIfStatement
7060            ListenerInfo li = mListenerInfo;
7061            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7062                    && li.mOnTouchListener.onTouch(this, event)) {
7063                return true;
7064            }
7065
7066            if (onTouchEvent(event)) {
7067                return true;
7068            }
7069        }
7070
7071        if (mInputEventConsistencyVerifier != null) {
7072            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7073        }
7074        return false;
7075    }
7076
7077    /**
7078     * Filter the touch event to apply security policies.
7079     *
7080     * @param event The motion event to be filtered.
7081     * @return True if the event should be dispatched, false if the event should be dropped.
7082     *
7083     * @see #getFilterTouchesWhenObscured
7084     */
7085    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7086        //noinspection RedundantIfStatement
7087        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7088                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7089            // Window is obscured, drop this touch.
7090            return false;
7091        }
7092        return true;
7093    }
7094
7095    /**
7096     * Pass a trackball motion event down to the focused view.
7097     *
7098     * @param event The motion event to be dispatched.
7099     * @return True if the event was handled by the view, false otherwise.
7100     */
7101    public boolean dispatchTrackballEvent(MotionEvent event) {
7102        if (mInputEventConsistencyVerifier != null) {
7103            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7104        }
7105
7106        return onTrackballEvent(event);
7107    }
7108
7109    /**
7110     * Dispatch a generic motion event.
7111     * <p>
7112     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7113     * are delivered to the view under the pointer.  All other generic motion events are
7114     * delivered to the focused view.  Hover events are handled specially and are delivered
7115     * to {@link #onHoverEvent(MotionEvent)}.
7116     * </p>
7117     *
7118     * @param event The motion event to be dispatched.
7119     * @return True if the event was handled by the view, false otherwise.
7120     */
7121    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7122        if (mInputEventConsistencyVerifier != null) {
7123            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7124        }
7125
7126        final int source = event.getSource();
7127        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7128            final int action = event.getAction();
7129            if (action == MotionEvent.ACTION_HOVER_ENTER
7130                    || action == MotionEvent.ACTION_HOVER_MOVE
7131                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7132                if (dispatchHoverEvent(event)) {
7133                    return true;
7134                }
7135            } else if (dispatchGenericPointerEvent(event)) {
7136                return true;
7137            }
7138        } else if (dispatchGenericFocusedEvent(event)) {
7139            return true;
7140        }
7141
7142        if (dispatchGenericMotionEventInternal(event)) {
7143            return true;
7144        }
7145
7146        if (mInputEventConsistencyVerifier != null) {
7147            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7148        }
7149        return false;
7150    }
7151
7152    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7153        //noinspection SimplifiableIfStatement
7154        ListenerInfo li = mListenerInfo;
7155        if (li != null && li.mOnGenericMotionListener != null
7156                && (mViewFlags & ENABLED_MASK) == ENABLED
7157                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7158            return true;
7159        }
7160
7161        if (onGenericMotionEvent(event)) {
7162            return true;
7163        }
7164
7165        if (mInputEventConsistencyVerifier != null) {
7166            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7167        }
7168        return false;
7169    }
7170
7171    /**
7172     * Dispatch a hover event.
7173     * <p>
7174     * Do not call this method directly.
7175     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7176     * </p>
7177     *
7178     * @param event The motion event to be dispatched.
7179     * @return True if the event was handled by the view, false otherwise.
7180     */
7181    protected boolean dispatchHoverEvent(MotionEvent event) {
7182        //noinspection SimplifiableIfStatement
7183        ListenerInfo li = mListenerInfo;
7184        if (li != null && li.mOnHoverListener != null
7185                && (mViewFlags & ENABLED_MASK) == ENABLED
7186                && li.mOnHoverListener.onHover(this, event)) {
7187            return true;
7188        }
7189
7190        return onHoverEvent(event);
7191    }
7192
7193    /**
7194     * Returns true if the view has a child to which it has recently sent
7195     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7196     * it does not have a hovered child, then it must be the innermost hovered view.
7197     * @hide
7198     */
7199    protected boolean hasHoveredChild() {
7200        return false;
7201    }
7202
7203    /**
7204     * Dispatch a generic motion event to the view under the first pointer.
7205     * <p>
7206     * Do not call this method directly.
7207     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7208     * </p>
7209     *
7210     * @param event The motion event to be dispatched.
7211     * @return True if the event was handled by the view, false otherwise.
7212     */
7213    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7214        return false;
7215    }
7216
7217    /**
7218     * Dispatch a generic motion event to the currently focused view.
7219     * <p>
7220     * Do not call this method directly.
7221     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7222     * </p>
7223     *
7224     * @param event The motion event to be dispatched.
7225     * @return True if the event was handled by the view, false otherwise.
7226     */
7227    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7228        return false;
7229    }
7230
7231    /**
7232     * Dispatch a pointer event.
7233     * <p>
7234     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7235     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7236     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7237     * and should not be expected to handle other pointing device features.
7238     * </p>
7239     *
7240     * @param event The motion event to be dispatched.
7241     * @return True if the event was handled by the view, false otherwise.
7242     * @hide
7243     */
7244    public final boolean dispatchPointerEvent(MotionEvent event) {
7245        if (event.isTouchEvent()) {
7246            return dispatchTouchEvent(event);
7247        } else {
7248            return dispatchGenericMotionEvent(event);
7249        }
7250    }
7251
7252    /**
7253     * Called when the window containing this view gains or loses window focus.
7254     * ViewGroups should override to route to their children.
7255     *
7256     * @param hasFocus True if the window containing this view now has focus,
7257     *        false otherwise.
7258     */
7259    public void dispatchWindowFocusChanged(boolean hasFocus) {
7260        onWindowFocusChanged(hasFocus);
7261    }
7262
7263    /**
7264     * Called when the window containing this view gains or loses focus.  Note
7265     * that this is separate from view focus: to receive key events, both
7266     * your view and its window must have focus.  If a window is displayed
7267     * on top of yours that takes input focus, then your own window will lose
7268     * focus but the view focus will remain unchanged.
7269     *
7270     * @param hasWindowFocus True if the window containing this view now has
7271     *        focus, false otherwise.
7272     */
7273    public void onWindowFocusChanged(boolean hasWindowFocus) {
7274        InputMethodManager imm = InputMethodManager.peekInstance();
7275        if (!hasWindowFocus) {
7276            if (isPressed()) {
7277                setPressed(false);
7278            }
7279            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7280                imm.focusOut(this);
7281            }
7282            removeLongPressCallback();
7283            removeTapCallback();
7284            onFocusLost();
7285        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7286            imm.focusIn(this);
7287        }
7288        refreshDrawableState();
7289    }
7290
7291    /**
7292     * Returns true if this view is in a window that currently has window focus.
7293     * Note that this is not the same as the view itself having focus.
7294     *
7295     * @return True if this view is in a window that currently has window focus.
7296     */
7297    public boolean hasWindowFocus() {
7298        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7299    }
7300
7301    /**
7302     * Dispatch a view visibility change down the view hierarchy.
7303     * ViewGroups should override to route to their children.
7304     * @param changedView The view whose visibility changed. Could be 'this' or
7305     * an ancestor view.
7306     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7307     * {@link #INVISIBLE} or {@link #GONE}.
7308     */
7309    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7310        onVisibilityChanged(changedView, visibility);
7311    }
7312
7313    /**
7314     * Called when the visibility of the view or an ancestor of the view is changed.
7315     * @param changedView The view whose visibility changed. Could be 'this' or
7316     * an ancestor view.
7317     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7318     * {@link #INVISIBLE} or {@link #GONE}.
7319     */
7320    protected void onVisibilityChanged(View changedView, int visibility) {
7321        if (visibility == VISIBLE) {
7322            if (mAttachInfo != null) {
7323                initialAwakenScrollBars();
7324            } else {
7325                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7326            }
7327        }
7328    }
7329
7330    /**
7331     * Dispatch a hint about whether this view is displayed. For instance, when
7332     * a View moves out of the screen, it might receives a display hint indicating
7333     * the view is not displayed. Applications should not <em>rely</em> on this hint
7334     * as there is no guarantee that they will receive one.
7335     *
7336     * @param hint A hint about whether or not this view is displayed:
7337     * {@link #VISIBLE} or {@link #INVISIBLE}.
7338     */
7339    public void dispatchDisplayHint(int hint) {
7340        onDisplayHint(hint);
7341    }
7342
7343    /**
7344     * Gives this view a hint about whether is displayed or not. For instance, when
7345     * a View moves out of the screen, it might receives a display hint indicating
7346     * the view is not displayed. Applications should not <em>rely</em> on this hint
7347     * as there is no guarantee that they will receive one.
7348     *
7349     * @param hint A hint about whether or not this view is displayed:
7350     * {@link #VISIBLE} or {@link #INVISIBLE}.
7351     */
7352    protected void onDisplayHint(int hint) {
7353    }
7354
7355    /**
7356     * Dispatch a window visibility change down the view hierarchy.
7357     * ViewGroups should override to route to their children.
7358     *
7359     * @param visibility The new visibility of the window.
7360     *
7361     * @see #onWindowVisibilityChanged(int)
7362     */
7363    public void dispatchWindowVisibilityChanged(int visibility) {
7364        onWindowVisibilityChanged(visibility);
7365    }
7366
7367    /**
7368     * Called when the window containing has change its visibility
7369     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7370     * that this tells you whether or not your window is being made visible
7371     * to the window manager; this does <em>not</em> tell you whether or not
7372     * your window is obscured by other windows on the screen, even if it
7373     * is itself visible.
7374     *
7375     * @param visibility The new visibility of the window.
7376     */
7377    protected void onWindowVisibilityChanged(int visibility) {
7378        if (visibility == VISIBLE) {
7379            initialAwakenScrollBars();
7380        }
7381    }
7382
7383    /**
7384     * Returns the current visibility of the window this view is attached to
7385     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7386     *
7387     * @return Returns the current visibility of the view's window.
7388     */
7389    public int getWindowVisibility() {
7390        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7391    }
7392
7393    /**
7394     * Retrieve the overall visible display size in which the window this view is
7395     * attached to has been positioned in.  This takes into account screen
7396     * decorations above the window, for both cases where the window itself
7397     * is being position inside of them or the window is being placed under
7398     * then and covered insets are used for the window to position its content
7399     * inside.  In effect, this tells you the available area where content can
7400     * be placed and remain visible to users.
7401     *
7402     * <p>This function requires an IPC back to the window manager to retrieve
7403     * the requested information, so should not be used in performance critical
7404     * code like drawing.
7405     *
7406     * @param outRect Filled in with the visible display frame.  If the view
7407     * is not attached to a window, this is simply the raw display size.
7408     */
7409    public void getWindowVisibleDisplayFrame(Rect outRect) {
7410        if (mAttachInfo != null) {
7411            try {
7412                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7413            } catch (RemoteException e) {
7414                return;
7415            }
7416            // XXX This is really broken, and probably all needs to be done
7417            // in the window manager, and we need to know more about whether
7418            // we want the area behind or in front of the IME.
7419            final Rect insets = mAttachInfo.mVisibleInsets;
7420            outRect.left += insets.left;
7421            outRect.top += insets.top;
7422            outRect.right -= insets.right;
7423            outRect.bottom -= insets.bottom;
7424            return;
7425        }
7426        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7427        d.getRectSize(outRect);
7428    }
7429
7430    /**
7431     * Dispatch a notification about a resource configuration change down
7432     * the view hierarchy.
7433     * ViewGroups should override to route to their children.
7434     *
7435     * @param newConfig The new resource configuration.
7436     *
7437     * @see #onConfigurationChanged(android.content.res.Configuration)
7438     */
7439    public void dispatchConfigurationChanged(Configuration newConfig) {
7440        onConfigurationChanged(newConfig);
7441    }
7442
7443    /**
7444     * Called when the current configuration of the resources being used
7445     * by the application have changed.  You can use this to decide when
7446     * to reload resources that can changed based on orientation and other
7447     * configuration characterstics.  You only need to use this if you are
7448     * not relying on the normal {@link android.app.Activity} mechanism of
7449     * recreating the activity instance upon a configuration change.
7450     *
7451     * @param newConfig The new resource configuration.
7452     */
7453    protected void onConfigurationChanged(Configuration newConfig) {
7454    }
7455
7456    /**
7457     * Private function to aggregate all per-view attributes in to the view
7458     * root.
7459     */
7460    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7461        performCollectViewAttributes(attachInfo, visibility);
7462    }
7463
7464    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7465        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7466            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7467                attachInfo.mKeepScreenOn = true;
7468            }
7469            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7470            ListenerInfo li = mListenerInfo;
7471            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7472                attachInfo.mHasSystemUiListeners = true;
7473            }
7474        }
7475    }
7476
7477    void needGlobalAttributesUpdate(boolean force) {
7478        final AttachInfo ai = mAttachInfo;
7479        if (ai != null) {
7480            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7481                    || ai.mHasSystemUiListeners) {
7482                ai.mRecomputeGlobalAttributes = true;
7483            }
7484        }
7485    }
7486
7487    /**
7488     * Returns whether the device is currently in touch mode.  Touch mode is entered
7489     * once the user begins interacting with the device by touch, and affects various
7490     * things like whether focus is always visible to the user.
7491     *
7492     * @return Whether the device is in touch mode.
7493     */
7494    @ViewDebug.ExportedProperty
7495    public boolean isInTouchMode() {
7496        if (mAttachInfo != null) {
7497            return mAttachInfo.mInTouchMode;
7498        } else {
7499            return ViewRootImpl.isInTouchMode();
7500        }
7501    }
7502
7503    /**
7504     * Returns the context the view is running in, through which it can
7505     * access the current theme, resources, etc.
7506     *
7507     * @return The view's Context.
7508     */
7509    @ViewDebug.CapturedViewProperty
7510    public final Context getContext() {
7511        return mContext;
7512    }
7513
7514    /**
7515     * Handle a key event before it is processed by any input method
7516     * associated with the view hierarchy.  This can be used to intercept
7517     * key events in special situations before the IME consumes them; a
7518     * typical example would be handling the BACK key to update the application's
7519     * UI instead of allowing the IME to see it and close itself.
7520     *
7521     * @param keyCode The value in event.getKeyCode().
7522     * @param event Description of the key event.
7523     * @return If you handled the event, return true. If you want to allow the
7524     *         event to be handled by the next receiver, return false.
7525     */
7526    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7527        return false;
7528    }
7529
7530    /**
7531     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7532     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7533     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7534     * is released, if the view is enabled and clickable.
7535     *
7536     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7537     * although some may elect to do so in some situations. Do not rely on this to
7538     * catch software key presses.
7539     *
7540     * @param keyCode A key code that represents the button pressed, from
7541     *                {@link android.view.KeyEvent}.
7542     * @param event   The KeyEvent object that defines the button action.
7543     */
7544    public boolean onKeyDown(int keyCode, KeyEvent event) {
7545        boolean result = false;
7546
7547        switch (keyCode) {
7548            case KeyEvent.KEYCODE_DPAD_CENTER:
7549            case KeyEvent.KEYCODE_ENTER: {
7550                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7551                    return true;
7552                }
7553                // Long clickable items don't necessarily have to be clickable
7554                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7555                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7556                        (event.getRepeatCount() == 0)) {
7557                    setPressed(true);
7558                    checkForLongClick(0);
7559                    return true;
7560                }
7561                break;
7562            }
7563        }
7564        return result;
7565    }
7566
7567    /**
7568     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7569     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7570     * the event).
7571     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7572     * although some may elect to do so in some situations. Do not rely on this to
7573     * catch software key presses.
7574     */
7575    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7576        return false;
7577    }
7578
7579    /**
7580     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7581     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7582     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7583     * {@link KeyEvent#KEYCODE_ENTER} is released.
7584     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7585     * although some may elect to do so in some situations. Do not rely on this to
7586     * catch software key presses.
7587     *
7588     * @param keyCode A key code that represents the button pressed, from
7589     *                {@link android.view.KeyEvent}.
7590     * @param event   The KeyEvent object that defines the button action.
7591     */
7592    public boolean onKeyUp(int keyCode, KeyEvent event) {
7593        boolean result = false;
7594
7595        switch (keyCode) {
7596            case KeyEvent.KEYCODE_DPAD_CENTER:
7597            case KeyEvent.KEYCODE_ENTER: {
7598                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7599                    return true;
7600                }
7601                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7602                    setPressed(false);
7603
7604                    if (!mHasPerformedLongPress) {
7605                        // This is a tap, so remove the longpress check
7606                        removeLongPressCallback();
7607
7608                        result = performClick();
7609                    }
7610                }
7611                break;
7612            }
7613        }
7614        return result;
7615    }
7616
7617    /**
7618     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7619     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7620     * the event).
7621     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7622     * although some may elect to do so in some situations. Do not rely on this to
7623     * catch software key presses.
7624     *
7625     * @param keyCode     A key code that represents the button pressed, from
7626     *                    {@link android.view.KeyEvent}.
7627     * @param repeatCount The number of times the action was made.
7628     * @param event       The KeyEvent object that defines the button action.
7629     */
7630    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7631        return false;
7632    }
7633
7634    /**
7635     * Called on the focused view when a key shortcut event is not handled.
7636     * Override this method to implement local key shortcuts for the View.
7637     * Key shortcuts can also be implemented by setting the
7638     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7639     *
7640     * @param keyCode The value in event.getKeyCode().
7641     * @param event Description of the key event.
7642     * @return If you handled the event, return true. If you want to allow the
7643     *         event to be handled by the next receiver, return false.
7644     */
7645    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7646        return false;
7647    }
7648
7649    /**
7650     * Check whether the called view is a text editor, in which case it
7651     * would make sense to automatically display a soft input window for
7652     * it.  Subclasses should override this if they implement
7653     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7654     * a call on that method would return a non-null InputConnection, and
7655     * they are really a first-class editor that the user would normally
7656     * start typing on when the go into a window containing your view.
7657     *
7658     * <p>The default implementation always returns false.  This does
7659     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7660     * will not be called or the user can not otherwise perform edits on your
7661     * view; it is just a hint to the system that this is not the primary
7662     * purpose of this view.
7663     *
7664     * @return Returns true if this view is a text editor, else false.
7665     */
7666    public boolean onCheckIsTextEditor() {
7667        return false;
7668    }
7669
7670    /**
7671     * Create a new InputConnection for an InputMethod to interact
7672     * with the view.  The default implementation returns null, since it doesn't
7673     * support input methods.  You can override this to implement such support.
7674     * This is only needed for views that take focus and text input.
7675     *
7676     * <p>When implementing this, you probably also want to implement
7677     * {@link #onCheckIsTextEditor()} to indicate you will return a
7678     * non-null InputConnection.
7679     *
7680     * @param outAttrs Fill in with attribute information about the connection.
7681     */
7682    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7683        return null;
7684    }
7685
7686    /**
7687     * Called by the {@link android.view.inputmethod.InputMethodManager}
7688     * when a view who is not the current
7689     * input connection target is trying to make a call on the manager.  The
7690     * default implementation returns false; you can override this to return
7691     * true for certain views if you are performing InputConnection proxying
7692     * to them.
7693     * @param view The View that is making the InputMethodManager call.
7694     * @return Return true to allow the call, false to reject.
7695     */
7696    public boolean checkInputConnectionProxy(View view) {
7697        return false;
7698    }
7699
7700    /**
7701     * Show the context menu for this view. It is not safe to hold on to the
7702     * menu after returning from this method.
7703     *
7704     * You should normally not overload this method. Overload
7705     * {@link #onCreateContextMenu(ContextMenu)} or define an
7706     * {@link OnCreateContextMenuListener} to add items to the context menu.
7707     *
7708     * @param menu The context menu to populate
7709     */
7710    public void createContextMenu(ContextMenu menu) {
7711        ContextMenuInfo menuInfo = getContextMenuInfo();
7712
7713        // Sets the current menu info so all items added to menu will have
7714        // my extra info set.
7715        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7716
7717        onCreateContextMenu(menu);
7718        ListenerInfo li = mListenerInfo;
7719        if (li != null && li.mOnCreateContextMenuListener != null) {
7720            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7721        }
7722
7723        // Clear the extra information so subsequent items that aren't mine don't
7724        // have my extra info.
7725        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7726
7727        if (mParent != null) {
7728            mParent.createContextMenu(menu);
7729        }
7730    }
7731
7732    /**
7733     * Views should implement this if they have extra information to associate
7734     * with the context menu. The return result is supplied as a parameter to
7735     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7736     * callback.
7737     *
7738     * @return Extra information about the item for which the context menu
7739     *         should be shown. This information will vary across different
7740     *         subclasses of View.
7741     */
7742    protected ContextMenuInfo getContextMenuInfo() {
7743        return null;
7744    }
7745
7746    /**
7747     * Views should implement this if the view itself is going to add items to
7748     * the context menu.
7749     *
7750     * @param menu the context menu to populate
7751     */
7752    protected void onCreateContextMenu(ContextMenu menu) {
7753    }
7754
7755    /**
7756     * Implement this method to handle trackball motion events.  The
7757     * <em>relative</em> movement of the trackball since the last event
7758     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7759     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7760     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7761     * they will often be fractional values, representing the more fine-grained
7762     * movement information available from a trackball).
7763     *
7764     * @param event The motion event.
7765     * @return True if the event was handled, false otherwise.
7766     */
7767    public boolean onTrackballEvent(MotionEvent event) {
7768        return false;
7769    }
7770
7771    /**
7772     * Implement this method to handle generic motion events.
7773     * <p>
7774     * Generic motion events describe joystick movements, mouse hovers, track pad
7775     * touches, scroll wheel movements and other input events.  The
7776     * {@link MotionEvent#getSource() source} of the motion event specifies
7777     * the class of input that was received.  Implementations of this method
7778     * must examine the bits in the source before processing the event.
7779     * The following code example shows how this is done.
7780     * </p><p>
7781     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7782     * are delivered to the view under the pointer.  All other generic motion events are
7783     * delivered to the focused view.
7784     * </p>
7785     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7786     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7787     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7788     *             // process the joystick movement...
7789     *             return true;
7790     *         }
7791     *     }
7792     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7793     *         switch (event.getAction()) {
7794     *             case MotionEvent.ACTION_HOVER_MOVE:
7795     *                 // process the mouse hover movement...
7796     *                 return true;
7797     *             case MotionEvent.ACTION_SCROLL:
7798     *                 // process the scroll wheel movement...
7799     *                 return true;
7800     *         }
7801     *     }
7802     *     return super.onGenericMotionEvent(event);
7803     * }</pre>
7804     *
7805     * @param event The generic motion event being processed.
7806     * @return True if the event was handled, false otherwise.
7807     */
7808    public boolean onGenericMotionEvent(MotionEvent event) {
7809        return false;
7810    }
7811
7812    /**
7813     * Implement this method to handle hover events.
7814     * <p>
7815     * This method is called whenever a pointer is hovering into, over, or out of the
7816     * bounds of a view and the view is not currently being touched.
7817     * Hover events are represented as pointer events with action
7818     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7819     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7820     * </p>
7821     * <ul>
7822     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7823     * when the pointer enters the bounds of the view.</li>
7824     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7825     * when the pointer has already entered the bounds of the view and has moved.</li>
7826     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7827     * when the pointer has exited the bounds of the view or when the pointer is
7828     * about to go down due to a button click, tap, or similar user action that
7829     * causes the view to be touched.</li>
7830     * </ul>
7831     * <p>
7832     * The view should implement this method to return true to indicate that it is
7833     * handling the hover event, such as by changing its drawable state.
7834     * </p><p>
7835     * The default implementation calls {@link #setHovered} to update the hovered state
7836     * of the view when a hover enter or hover exit event is received, if the view
7837     * is enabled and is clickable.  The default implementation also sends hover
7838     * accessibility events.
7839     * </p>
7840     *
7841     * @param event The motion event that describes the hover.
7842     * @return True if the view handled the hover event.
7843     *
7844     * @see #isHovered
7845     * @see #setHovered
7846     * @see #onHoverChanged
7847     */
7848    public boolean onHoverEvent(MotionEvent event) {
7849        // The root view may receive hover (or touch) events that are outside the bounds of
7850        // the window.  This code ensures that we only send accessibility events for
7851        // hovers that are actually within the bounds of the root view.
7852        final int action = event.getActionMasked();
7853        if (!mSendingHoverAccessibilityEvents) {
7854            if ((action == MotionEvent.ACTION_HOVER_ENTER
7855                    || action == MotionEvent.ACTION_HOVER_MOVE)
7856                    && !hasHoveredChild()
7857                    && pointInView(event.getX(), event.getY())) {
7858                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7859                mSendingHoverAccessibilityEvents = true;
7860                requestAccessibilityFocusFromHover();
7861            }
7862        } else {
7863            if (action == MotionEvent.ACTION_HOVER_EXIT
7864                    || (action == MotionEvent.ACTION_MOVE
7865                            && !pointInView(event.getX(), event.getY()))) {
7866                mSendingHoverAccessibilityEvents = false;
7867                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7868                // If the window does not have input focus we take away accessibility
7869                // focus as soon as the user stop hovering over the view.
7870                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7871                    getViewRootImpl().setAccessibilityFocusedHost(null);
7872                }
7873            }
7874        }
7875
7876        if (isHoverable()) {
7877            switch (action) {
7878                case MotionEvent.ACTION_HOVER_ENTER:
7879                    setHovered(true);
7880                    break;
7881                case MotionEvent.ACTION_HOVER_EXIT:
7882                    setHovered(false);
7883                    break;
7884            }
7885
7886            // Dispatch the event to onGenericMotionEvent before returning true.
7887            // This is to provide compatibility with existing applications that
7888            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7889            // break because of the new default handling for hoverable views
7890            // in onHoverEvent.
7891            // Note that onGenericMotionEvent will be called by default when
7892            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7893            dispatchGenericMotionEventInternal(event);
7894            return true;
7895        }
7896
7897        return false;
7898    }
7899
7900    /**
7901     * Returns true if the view should handle {@link #onHoverEvent}
7902     * by calling {@link #setHovered} to change its hovered state.
7903     *
7904     * @return True if the view is hoverable.
7905     */
7906    private boolean isHoverable() {
7907        final int viewFlags = mViewFlags;
7908        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7909            return false;
7910        }
7911
7912        return (viewFlags & CLICKABLE) == CLICKABLE
7913                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7914    }
7915
7916    /**
7917     * Returns true if the view is currently hovered.
7918     *
7919     * @return True if the view is currently hovered.
7920     *
7921     * @see #setHovered
7922     * @see #onHoverChanged
7923     */
7924    @ViewDebug.ExportedProperty
7925    public boolean isHovered() {
7926        return (mPrivateFlags & HOVERED) != 0;
7927    }
7928
7929    /**
7930     * Sets whether the view is currently hovered.
7931     * <p>
7932     * Calling this method also changes the drawable state of the view.  This
7933     * enables the view to react to hover by using different drawable resources
7934     * to change its appearance.
7935     * </p><p>
7936     * The {@link #onHoverChanged} method is called when the hovered state changes.
7937     * </p>
7938     *
7939     * @param hovered True if the view is hovered.
7940     *
7941     * @see #isHovered
7942     * @see #onHoverChanged
7943     */
7944    public void setHovered(boolean hovered) {
7945        if (hovered) {
7946            if ((mPrivateFlags & HOVERED) == 0) {
7947                mPrivateFlags |= HOVERED;
7948                refreshDrawableState();
7949                onHoverChanged(true);
7950            }
7951        } else {
7952            if ((mPrivateFlags & HOVERED) != 0) {
7953                mPrivateFlags &= ~HOVERED;
7954                refreshDrawableState();
7955                onHoverChanged(false);
7956            }
7957        }
7958    }
7959
7960    /**
7961     * Implement this method to handle hover state changes.
7962     * <p>
7963     * This method is called whenever the hover state changes as a result of a
7964     * call to {@link #setHovered}.
7965     * </p>
7966     *
7967     * @param hovered The current hover state, as returned by {@link #isHovered}.
7968     *
7969     * @see #isHovered
7970     * @see #setHovered
7971     */
7972    public void onHoverChanged(boolean hovered) {
7973    }
7974
7975    /**
7976     * Implement this method to handle touch screen motion events.
7977     *
7978     * @param event The motion event.
7979     * @return True if the event was handled, false otherwise.
7980     */
7981    public boolean onTouchEvent(MotionEvent event) {
7982        final int viewFlags = mViewFlags;
7983
7984        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7985            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7986                setPressed(false);
7987            }
7988            // A disabled view that is clickable still consumes the touch
7989            // events, it just doesn't respond to them.
7990            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7991                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7992        }
7993
7994        if (mTouchDelegate != null) {
7995            if (mTouchDelegate.onTouchEvent(event)) {
7996                return true;
7997            }
7998        }
7999
8000        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8001                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8002            switch (event.getAction()) {
8003                case MotionEvent.ACTION_UP:
8004                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
8005                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
8006                        // take focus if we don't have it already and we should in
8007                        // touch mode.
8008                        boolean focusTaken = false;
8009                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8010                            focusTaken = requestFocus();
8011                        }
8012
8013                        if (prepressed) {
8014                            // The button is being released before we actually
8015                            // showed it as pressed.  Make it show the pressed
8016                            // state now (before scheduling the click) to ensure
8017                            // the user sees it.
8018                            setPressed(true);
8019                       }
8020
8021                        if (!mHasPerformedLongPress) {
8022                            // This is a tap, so remove the longpress check
8023                            removeLongPressCallback();
8024
8025                            // Only perform take click actions if we were in the pressed state
8026                            if (!focusTaken) {
8027                                // Use a Runnable and post this rather than calling
8028                                // performClick directly. This lets other visual state
8029                                // of the view update before click actions start.
8030                                if (mPerformClick == null) {
8031                                    mPerformClick = new PerformClick();
8032                                }
8033                                if (!post(mPerformClick)) {
8034                                    performClick();
8035                                }
8036                            }
8037                        }
8038
8039                        if (mUnsetPressedState == null) {
8040                            mUnsetPressedState = new UnsetPressedState();
8041                        }
8042
8043                        if (prepressed) {
8044                            postDelayed(mUnsetPressedState,
8045                                    ViewConfiguration.getPressedStateDuration());
8046                        } else if (!post(mUnsetPressedState)) {
8047                            // If the post failed, unpress right now
8048                            mUnsetPressedState.run();
8049                        }
8050                        removeTapCallback();
8051                    }
8052                    break;
8053
8054                case MotionEvent.ACTION_DOWN:
8055                    mHasPerformedLongPress = false;
8056
8057                    if (performButtonActionOnTouchDown(event)) {
8058                        break;
8059                    }
8060
8061                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8062                    boolean isInScrollingContainer = isInScrollingContainer();
8063
8064                    // For views inside a scrolling container, delay the pressed feedback for
8065                    // a short period in case this is a scroll.
8066                    if (isInScrollingContainer) {
8067                        mPrivateFlags |= PREPRESSED;
8068                        if (mPendingCheckForTap == null) {
8069                            mPendingCheckForTap = new CheckForTap();
8070                        }
8071                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8072                    } else {
8073                        // Not inside a scrolling container, so show the feedback right away
8074                        setPressed(true);
8075                        checkForLongClick(0);
8076                    }
8077                    break;
8078
8079                case MotionEvent.ACTION_CANCEL:
8080                    setPressed(false);
8081                    removeTapCallback();
8082                    break;
8083
8084                case MotionEvent.ACTION_MOVE:
8085                    final int x = (int) event.getX();
8086                    final int y = (int) event.getY();
8087
8088                    // Be lenient about moving outside of buttons
8089                    if (!pointInView(x, y, mTouchSlop)) {
8090                        // Outside button
8091                        removeTapCallback();
8092                        if ((mPrivateFlags & PRESSED) != 0) {
8093                            // Remove any future long press/tap checks
8094                            removeLongPressCallback();
8095
8096                            setPressed(false);
8097                        }
8098                    }
8099                    break;
8100            }
8101            return true;
8102        }
8103
8104        return false;
8105    }
8106
8107    /**
8108     * @hide
8109     */
8110    public boolean isInScrollingContainer() {
8111        ViewParent p = getParent();
8112        while (p != null && p instanceof ViewGroup) {
8113            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8114                return true;
8115            }
8116            p = p.getParent();
8117        }
8118        return false;
8119    }
8120
8121    /**
8122     * Remove the longpress detection timer.
8123     */
8124    private void removeLongPressCallback() {
8125        if (mPendingCheckForLongPress != null) {
8126          removeCallbacks(mPendingCheckForLongPress);
8127        }
8128    }
8129
8130    /**
8131     * Remove the pending click action
8132     */
8133    private void removePerformClickCallback() {
8134        if (mPerformClick != null) {
8135            removeCallbacks(mPerformClick);
8136        }
8137    }
8138
8139    /**
8140     * Remove the prepress detection timer.
8141     */
8142    private void removeUnsetPressCallback() {
8143        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
8144            setPressed(false);
8145            removeCallbacks(mUnsetPressedState);
8146        }
8147    }
8148
8149    /**
8150     * Remove the tap detection timer.
8151     */
8152    private void removeTapCallback() {
8153        if (mPendingCheckForTap != null) {
8154            mPrivateFlags &= ~PREPRESSED;
8155            removeCallbacks(mPendingCheckForTap);
8156        }
8157    }
8158
8159    /**
8160     * Cancels a pending long press.  Your subclass can use this if you
8161     * want the context menu to come up if the user presses and holds
8162     * at the same place, but you don't want it to come up if they press
8163     * and then move around enough to cause scrolling.
8164     */
8165    public void cancelLongPress() {
8166        removeLongPressCallback();
8167
8168        /*
8169         * The prepressed state handled by the tap callback is a display
8170         * construct, but the tap callback will post a long press callback
8171         * less its own timeout. Remove it here.
8172         */
8173        removeTapCallback();
8174    }
8175
8176    /**
8177     * Remove the pending callback for sending a
8178     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8179     */
8180    private void removeSendViewScrolledAccessibilityEventCallback() {
8181        if (mSendViewScrolledAccessibilityEvent != null) {
8182            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8183            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8184        }
8185    }
8186
8187    /**
8188     * Sets the TouchDelegate for this View.
8189     */
8190    public void setTouchDelegate(TouchDelegate delegate) {
8191        mTouchDelegate = delegate;
8192    }
8193
8194    /**
8195     * Gets the TouchDelegate for this View.
8196     */
8197    public TouchDelegate getTouchDelegate() {
8198        return mTouchDelegate;
8199    }
8200
8201    /**
8202     * Set flags controlling behavior of this view.
8203     *
8204     * @param flags Constant indicating the value which should be set
8205     * @param mask Constant indicating the bit range that should be changed
8206     */
8207    void setFlags(int flags, int mask) {
8208        int old = mViewFlags;
8209        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8210
8211        int changed = mViewFlags ^ old;
8212        if (changed == 0) {
8213            return;
8214        }
8215        int privateFlags = mPrivateFlags;
8216
8217        /* Check if the FOCUSABLE bit has changed */
8218        if (((changed & FOCUSABLE_MASK) != 0) &&
8219                ((privateFlags & HAS_BOUNDS) !=0)) {
8220            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8221                    && ((privateFlags & FOCUSED) != 0)) {
8222                /* Give up focus if we are no longer focusable */
8223                clearFocus();
8224            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8225                    && ((privateFlags & FOCUSED) == 0)) {
8226                /*
8227                 * Tell the view system that we are now available to take focus
8228                 * if no one else already has it.
8229                 */
8230                if (mParent != null) mParent.focusableViewAvailable(this);
8231            }
8232            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8233                notifyAccessibilityStateChanged();
8234            }
8235        }
8236
8237        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8238            if ((changed & VISIBILITY_MASK) != 0) {
8239                /*
8240                 * If this view is becoming visible, invalidate it in case it changed while
8241                 * it was not visible. Marking it drawn ensures that the invalidation will
8242                 * go through.
8243                 */
8244                mPrivateFlags |= DRAWN;
8245                invalidate(true);
8246
8247                needGlobalAttributesUpdate(true);
8248
8249                // a view becoming visible is worth notifying the parent
8250                // about in case nothing has focus.  even if this specific view
8251                // isn't focusable, it may contain something that is, so let
8252                // the root view try to give this focus if nothing else does.
8253                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8254                    mParent.focusableViewAvailable(this);
8255                }
8256            }
8257        }
8258
8259        /* Check if the GONE bit has changed */
8260        if ((changed & GONE) != 0) {
8261            needGlobalAttributesUpdate(false);
8262            requestLayout();
8263
8264            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8265                if (hasFocus()) clearFocus();
8266                clearAccessibilityFocus();
8267                destroyDrawingCache();
8268                if (mParent instanceof View) {
8269                    // GONE views noop invalidation, so invalidate the parent
8270                    ((View) mParent).invalidate(true);
8271                }
8272                // Mark the view drawn to ensure that it gets invalidated properly the next
8273                // time it is visible and gets invalidated
8274                mPrivateFlags |= DRAWN;
8275            }
8276            if (mAttachInfo != null) {
8277                mAttachInfo.mViewVisibilityChanged = true;
8278            }
8279        }
8280
8281        /* Check if the VISIBLE bit has changed */
8282        if ((changed & INVISIBLE) != 0) {
8283            needGlobalAttributesUpdate(false);
8284            /*
8285             * If this view is becoming invisible, set the DRAWN flag so that
8286             * the next invalidate() will not be skipped.
8287             */
8288            mPrivateFlags |= DRAWN;
8289
8290            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8291                // root view becoming invisible shouldn't clear focus and accessibility focus
8292                if (getRootView() != this) {
8293                    clearFocus();
8294                    clearAccessibilityFocus();
8295                }
8296            }
8297            if (mAttachInfo != null) {
8298                mAttachInfo.mViewVisibilityChanged = true;
8299            }
8300        }
8301
8302        if ((changed & VISIBILITY_MASK) != 0) {
8303            if (mParent instanceof ViewGroup) {
8304                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8305                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8306                ((View) mParent).invalidate(true);
8307            } else if (mParent != null) {
8308                mParent.invalidateChild(this, null);
8309            }
8310            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8311        }
8312
8313        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8314            destroyDrawingCache();
8315        }
8316
8317        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8318            destroyDrawingCache();
8319            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8320            invalidateParentCaches();
8321        }
8322
8323        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8324            destroyDrawingCache();
8325            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8326        }
8327
8328        if ((changed & DRAW_MASK) != 0) {
8329            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8330                if (mBackground != null) {
8331                    mPrivateFlags &= ~SKIP_DRAW;
8332                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8333                } else {
8334                    mPrivateFlags |= SKIP_DRAW;
8335                }
8336            } else {
8337                mPrivateFlags &= ~SKIP_DRAW;
8338            }
8339            requestLayout();
8340            invalidate(true);
8341        }
8342
8343        if ((changed & KEEP_SCREEN_ON) != 0) {
8344            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8345                mParent.recomputeViewAttributes(this);
8346            }
8347        }
8348
8349        if (AccessibilityManager.getInstance(mContext).isEnabled()
8350                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8351                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8352            notifyAccessibilityStateChanged();
8353        }
8354    }
8355
8356    /**
8357     * Change the view's z order in the tree, so it's on top of other sibling
8358     * views
8359     */
8360    public void bringToFront() {
8361        if (mParent != null) {
8362            mParent.bringChildToFront(this);
8363        }
8364    }
8365
8366    /**
8367     * This is called in response to an internal scroll in this view (i.e., the
8368     * view scrolled its own contents). This is typically as a result of
8369     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8370     * called.
8371     *
8372     * @param l Current horizontal scroll origin.
8373     * @param t Current vertical scroll origin.
8374     * @param oldl Previous horizontal scroll origin.
8375     * @param oldt Previous vertical scroll origin.
8376     */
8377    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8378        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8379            postSendViewScrolledAccessibilityEventCallback();
8380        }
8381
8382        mBackgroundSizeChanged = true;
8383
8384        final AttachInfo ai = mAttachInfo;
8385        if (ai != null) {
8386            ai.mViewScrollChanged = true;
8387        }
8388    }
8389
8390    /**
8391     * Interface definition for a callback to be invoked when the layout bounds of a view
8392     * changes due to layout processing.
8393     */
8394    public interface OnLayoutChangeListener {
8395        /**
8396         * Called when the focus state of a view has changed.
8397         *
8398         * @param v The view whose state has changed.
8399         * @param left The new value of the view's left property.
8400         * @param top The new value of the view's top property.
8401         * @param right The new value of the view's right property.
8402         * @param bottom The new value of the view's bottom property.
8403         * @param oldLeft The previous value of the view's left property.
8404         * @param oldTop The previous value of the view's top property.
8405         * @param oldRight The previous value of the view's right property.
8406         * @param oldBottom The previous value of the view's bottom property.
8407         */
8408        void onLayoutChange(View v, int left, int top, int right, int bottom,
8409            int oldLeft, int oldTop, int oldRight, int oldBottom);
8410    }
8411
8412    /**
8413     * This is called during layout when the size of this view has changed. If
8414     * you were just added to the view hierarchy, you're called with the old
8415     * values of 0.
8416     *
8417     * @param w Current width of this view.
8418     * @param h Current height of this view.
8419     * @param oldw Old width of this view.
8420     * @param oldh Old height of this view.
8421     */
8422    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8423    }
8424
8425    /**
8426     * Called by draw to draw the child views. This may be overridden
8427     * by derived classes to gain control just before its children are drawn
8428     * (but after its own view has been drawn).
8429     * @param canvas the canvas on which to draw the view
8430     */
8431    protected void dispatchDraw(Canvas canvas) {
8432
8433    }
8434
8435    /**
8436     * Gets the parent of this view. Note that the parent is a
8437     * ViewParent and not necessarily a View.
8438     *
8439     * @return Parent of this view.
8440     */
8441    public final ViewParent getParent() {
8442        return mParent;
8443    }
8444
8445    /**
8446     * Set the horizontal scrolled position of your view. This will cause a call to
8447     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8448     * invalidated.
8449     * @param value the x position to scroll to
8450     */
8451    public void setScrollX(int value) {
8452        scrollTo(value, mScrollY);
8453    }
8454
8455    /**
8456     * Set the vertical scrolled position of your view. This will cause a call to
8457     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8458     * invalidated.
8459     * @param value the y position to scroll to
8460     */
8461    public void setScrollY(int value) {
8462        scrollTo(mScrollX, value);
8463    }
8464
8465    /**
8466     * Return the scrolled left position of this view. This is the left edge of
8467     * the displayed part of your view. You do not need to draw any pixels
8468     * farther left, since those are outside of the frame of your view on
8469     * screen.
8470     *
8471     * @return The left edge of the displayed part of your view, in pixels.
8472     */
8473    public final int getScrollX() {
8474        return mScrollX;
8475    }
8476
8477    /**
8478     * Return the scrolled top position of this view. This is the top edge of
8479     * the displayed part of your view. You do not need to draw any pixels above
8480     * it, since those are outside of the frame of your view on screen.
8481     *
8482     * @return The top edge of the displayed part of your view, in pixels.
8483     */
8484    public final int getScrollY() {
8485        return mScrollY;
8486    }
8487
8488    /**
8489     * Return the width of the your view.
8490     *
8491     * @return The width of your view, in pixels.
8492     */
8493    @ViewDebug.ExportedProperty(category = "layout")
8494    public final int getWidth() {
8495        return mRight - mLeft;
8496    }
8497
8498    /**
8499     * Return the height of your view.
8500     *
8501     * @return The height of your view, in pixels.
8502     */
8503    @ViewDebug.ExportedProperty(category = "layout")
8504    public final int getHeight() {
8505        return mBottom - mTop;
8506    }
8507
8508    /**
8509     * Return the visible drawing bounds of your view. Fills in the output
8510     * rectangle with the values from getScrollX(), getScrollY(),
8511     * getWidth(), and getHeight().
8512     *
8513     * @param outRect The (scrolled) drawing bounds of the view.
8514     */
8515    public void getDrawingRect(Rect outRect) {
8516        outRect.left = mScrollX;
8517        outRect.top = mScrollY;
8518        outRect.right = mScrollX + (mRight - mLeft);
8519        outRect.bottom = mScrollY + (mBottom - mTop);
8520    }
8521
8522    /**
8523     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8524     * raw width component (that is the result is masked by
8525     * {@link #MEASURED_SIZE_MASK}).
8526     *
8527     * @return The raw measured width of this view.
8528     */
8529    public final int getMeasuredWidth() {
8530        return mMeasuredWidth & MEASURED_SIZE_MASK;
8531    }
8532
8533    /**
8534     * Return the full width measurement information for this view as computed
8535     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8536     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8537     * This should be used during measurement and layout calculations only. Use
8538     * {@link #getWidth()} to see how wide a view is after layout.
8539     *
8540     * @return The measured width of this view as a bit mask.
8541     */
8542    public final int getMeasuredWidthAndState() {
8543        return mMeasuredWidth;
8544    }
8545
8546    /**
8547     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8548     * raw width component (that is the result is masked by
8549     * {@link #MEASURED_SIZE_MASK}).
8550     *
8551     * @return The raw measured height of this view.
8552     */
8553    public final int getMeasuredHeight() {
8554        return mMeasuredHeight & MEASURED_SIZE_MASK;
8555    }
8556
8557    /**
8558     * Return the full height measurement information for this view as computed
8559     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8560     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8561     * This should be used during measurement and layout calculations only. Use
8562     * {@link #getHeight()} to see how wide a view is after layout.
8563     *
8564     * @return The measured width of this view as a bit mask.
8565     */
8566    public final int getMeasuredHeightAndState() {
8567        return mMeasuredHeight;
8568    }
8569
8570    /**
8571     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8572     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8573     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8574     * and the height component is at the shifted bits
8575     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8576     */
8577    public final int getMeasuredState() {
8578        return (mMeasuredWidth&MEASURED_STATE_MASK)
8579                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8580                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8581    }
8582
8583    /**
8584     * The transform matrix of this view, which is calculated based on the current
8585     * roation, scale, and pivot properties.
8586     *
8587     * @see #getRotation()
8588     * @see #getScaleX()
8589     * @see #getScaleY()
8590     * @see #getPivotX()
8591     * @see #getPivotY()
8592     * @return The current transform matrix for the view
8593     */
8594    public Matrix getMatrix() {
8595        if (mTransformationInfo != null) {
8596            updateMatrix();
8597            return mTransformationInfo.mMatrix;
8598        }
8599        return Matrix.IDENTITY_MATRIX;
8600    }
8601
8602    /**
8603     * Utility function to determine if the value is far enough away from zero to be
8604     * considered non-zero.
8605     * @param value A floating point value to check for zero-ness
8606     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8607     */
8608    private static boolean nonzero(float value) {
8609        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8610    }
8611
8612    /**
8613     * Returns true if the transform matrix is the identity matrix.
8614     * Recomputes the matrix if necessary.
8615     *
8616     * @return True if the transform matrix is the identity matrix, false otherwise.
8617     */
8618    final boolean hasIdentityMatrix() {
8619        if (mTransformationInfo != null) {
8620            updateMatrix();
8621            return mTransformationInfo.mMatrixIsIdentity;
8622        }
8623        return true;
8624    }
8625
8626    void ensureTransformationInfo() {
8627        if (mTransformationInfo == null) {
8628            mTransformationInfo = new TransformationInfo();
8629        }
8630    }
8631
8632    /**
8633     * Recomputes the transform matrix if necessary.
8634     */
8635    private void updateMatrix() {
8636        final TransformationInfo info = mTransformationInfo;
8637        if (info == null) {
8638            return;
8639        }
8640        if (info.mMatrixDirty) {
8641            // transform-related properties have changed since the last time someone
8642            // asked for the matrix; recalculate it with the current values
8643
8644            // Figure out if we need to update the pivot point
8645            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8646                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8647                    info.mPrevWidth = mRight - mLeft;
8648                    info.mPrevHeight = mBottom - mTop;
8649                    info.mPivotX = info.mPrevWidth / 2f;
8650                    info.mPivotY = info.mPrevHeight / 2f;
8651                }
8652            }
8653            info.mMatrix.reset();
8654            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8655                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8656                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8657                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8658            } else {
8659                if (info.mCamera == null) {
8660                    info.mCamera = new Camera();
8661                    info.matrix3D = new Matrix();
8662                }
8663                info.mCamera.save();
8664                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8665                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8666                info.mCamera.getMatrix(info.matrix3D);
8667                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8668                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8669                        info.mPivotY + info.mTranslationY);
8670                info.mMatrix.postConcat(info.matrix3D);
8671                info.mCamera.restore();
8672            }
8673            info.mMatrixDirty = false;
8674            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8675            info.mInverseMatrixDirty = true;
8676        }
8677    }
8678
8679    /**
8680     * Utility method to retrieve the inverse of the current mMatrix property.
8681     * We cache the matrix to avoid recalculating it when transform properties
8682     * have not changed.
8683     *
8684     * @return The inverse of the current matrix of this view.
8685     */
8686    final Matrix getInverseMatrix() {
8687        final TransformationInfo info = mTransformationInfo;
8688        if (info != null) {
8689            updateMatrix();
8690            if (info.mInverseMatrixDirty) {
8691                if (info.mInverseMatrix == null) {
8692                    info.mInverseMatrix = new Matrix();
8693                }
8694                info.mMatrix.invert(info.mInverseMatrix);
8695                info.mInverseMatrixDirty = false;
8696            }
8697            return info.mInverseMatrix;
8698        }
8699        return Matrix.IDENTITY_MATRIX;
8700    }
8701
8702    /**
8703     * Gets the distance along the Z axis from the camera to this view.
8704     *
8705     * @see #setCameraDistance(float)
8706     *
8707     * @return The distance along the Z axis.
8708     */
8709    public float getCameraDistance() {
8710        ensureTransformationInfo();
8711        final float dpi = mResources.getDisplayMetrics().densityDpi;
8712        final TransformationInfo info = mTransformationInfo;
8713        if (info.mCamera == null) {
8714            info.mCamera = new Camera();
8715            info.matrix3D = new Matrix();
8716        }
8717        return -(info.mCamera.getLocationZ() * dpi);
8718    }
8719
8720    /**
8721     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8722     * views are drawn) from the camera to this view. The camera's distance
8723     * affects 3D transformations, for instance rotations around the X and Y
8724     * axis. If the rotationX or rotationY properties are changed and this view is
8725     * large (more than half the size of the screen), it is recommended to always
8726     * use a camera distance that's greater than the height (X axis rotation) or
8727     * the width (Y axis rotation) of this view.</p>
8728     *
8729     * <p>The distance of the camera from the view plane can have an affect on the
8730     * perspective distortion of the view when it is rotated around the x or y axis.
8731     * For example, a large distance will result in a large viewing angle, and there
8732     * will not be much perspective distortion of the view as it rotates. A short
8733     * distance may cause much more perspective distortion upon rotation, and can
8734     * also result in some drawing artifacts if the rotated view ends up partially
8735     * behind the camera (which is why the recommendation is to use a distance at
8736     * least as far as the size of the view, if the view is to be rotated.)</p>
8737     *
8738     * <p>The distance is expressed in "depth pixels." The default distance depends
8739     * on the screen density. For instance, on a medium density display, the
8740     * default distance is 1280. On a high density display, the default distance
8741     * is 1920.</p>
8742     *
8743     * <p>If you want to specify a distance that leads to visually consistent
8744     * results across various densities, use the following formula:</p>
8745     * <pre>
8746     * float scale = context.getResources().getDisplayMetrics().density;
8747     * view.setCameraDistance(distance * scale);
8748     * </pre>
8749     *
8750     * <p>The density scale factor of a high density display is 1.5,
8751     * and 1920 = 1280 * 1.5.</p>
8752     *
8753     * @param distance The distance in "depth pixels", if negative the opposite
8754     *        value is used
8755     *
8756     * @see #setRotationX(float)
8757     * @see #setRotationY(float)
8758     */
8759    public void setCameraDistance(float distance) {
8760        invalidateViewProperty(true, false);
8761
8762        ensureTransformationInfo();
8763        final float dpi = mResources.getDisplayMetrics().densityDpi;
8764        final TransformationInfo info = mTransformationInfo;
8765        if (info.mCamera == null) {
8766            info.mCamera = new Camera();
8767            info.matrix3D = new Matrix();
8768        }
8769
8770        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8771        info.mMatrixDirty = true;
8772
8773        invalidateViewProperty(false, false);
8774        if (mDisplayList != null) {
8775            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8776        }
8777        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8778            // View was rejected last time it was drawn by its parent; this may have changed
8779            invalidateParentIfNeeded();
8780        }
8781    }
8782
8783    /**
8784     * The degrees that the view is rotated around the pivot point.
8785     *
8786     * @see #setRotation(float)
8787     * @see #getPivotX()
8788     * @see #getPivotY()
8789     *
8790     * @return The degrees of rotation.
8791     */
8792    @ViewDebug.ExportedProperty(category = "drawing")
8793    public float getRotation() {
8794        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8795    }
8796
8797    /**
8798     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8799     * result in clockwise rotation.
8800     *
8801     * @param rotation The degrees of rotation.
8802     *
8803     * @see #getRotation()
8804     * @see #getPivotX()
8805     * @see #getPivotY()
8806     * @see #setRotationX(float)
8807     * @see #setRotationY(float)
8808     *
8809     * @attr ref android.R.styleable#View_rotation
8810     */
8811    public void setRotation(float rotation) {
8812        ensureTransformationInfo();
8813        final TransformationInfo info = mTransformationInfo;
8814        if (info.mRotation != rotation) {
8815            // Double-invalidation is necessary to capture view's old and new areas
8816            invalidateViewProperty(true, false);
8817            info.mRotation = rotation;
8818            info.mMatrixDirty = true;
8819            invalidateViewProperty(false, true);
8820            if (mDisplayList != null) {
8821                mDisplayList.setRotation(rotation);
8822            }
8823            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8824                // View was rejected last time it was drawn by its parent; this may have changed
8825                invalidateParentIfNeeded();
8826            }
8827        }
8828    }
8829
8830    /**
8831     * The degrees that the view is rotated around the vertical axis through the pivot point.
8832     *
8833     * @see #getPivotX()
8834     * @see #getPivotY()
8835     * @see #setRotationY(float)
8836     *
8837     * @return The degrees of Y rotation.
8838     */
8839    @ViewDebug.ExportedProperty(category = "drawing")
8840    public float getRotationY() {
8841        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8842    }
8843
8844    /**
8845     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8846     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8847     * down the y axis.
8848     *
8849     * When rotating large views, it is recommended to adjust the camera distance
8850     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8851     *
8852     * @param rotationY The degrees of Y rotation.
8853     *
8854     * @see #getRotationY()
8855     * @see #getPivotX()
8856     * @see #getPivotY()
8857     * @see #setRotation(float)
8858     * @see #setRotationX(float)
8859     * @see #setCameraDistance(float)
8860     *
8861     * @attr ref android.R.styleable#View_rotationY
8862     */
8863    public void setRotationY(float rotationY) {
8864        ensureTransformationInfo();
8865        final TransformationInfo info = mTransformationInfo;
8866        if (info.mRotationY != rotationY) {
8867            invalidateViewProperty(true, false);
8868            info.mRotationY = rotationY;
8869            info.mMatrixDirty = true;
8870            invalidateViewProperty(false, true);
8871            if (mDisplayList != null) {
8872                mDisplayList.setRotationY(rotationY);
8873            }
8874            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8875                // View was rejected last time it was drawn by its parent; this may have changed
8876                invalidateParentIfNeeded();
8877            }
8878        }
8879    }
8880
8881    /**
8882     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8883     *
8884     * @see #getPivotX()
8885     * @see #getPivotY()
8886     * @see #setRotationX(float)
8887     *
8888     * @return The degrees of X rotation.
8889     */
8890    @ViewDebug.ExportedProperty(category = "drawing")
8891    public float getRotationX() {
8892        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8893    }
8894
8895    /**
8896     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8897     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8898     * x axis.
8899     *
8900     * When rotating large views, it is recommended to adjust the camera distance
8901     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8902     *
8903     * @param rotationX The degrees of X rotation.
8904     *
8905     * @see #getRotationX()
8906     * @see #getPivotX()
8907     * @see #getPivotY()
8908     * @see #setRotation(float)
8909     * @see #setRotationY(float)
8910     * @see #setCameraDistance(float)
8911     *
8912     * @attr ref android.R.styleable#View_rotationX
8913     */
8914    public void setRotationX(float rotationX) {
8915        ensureTransformationInfo();
8916        final TransformationInfo info = mTransformationInfo;
8917        if (info.mRotationX != rotationX) {
8918            invalidateViewProperty(true, false);
8919            info.mRotationX = rotationX;
8920            info.mMatrixDirty = true;
8921            invalidateViewProperty(false, true);
8922            if (mDisplayList != null) {
8923                mDisplayList.setRotationX(rotationX);
8924            }
8925            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8926                // View was rejected last time it was drawn by its parent; this may have changed
8927                invalidateParentIfNeeded();
8928            }
8929        }
8930    }
8931
8932    /**
8933     * The amount that the view is scaled in x around the pivot point, as a proportion of
8934     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8935     *
8936     * <p>By default, this is 1.0f.
8937     *
8938     * @see #getPivotX()
8939     * @see #getPivotY()
8940     * @return The scaling factor.
8941     */
8942    @ViewDebug.ExportedProperty(category = "drawing")
8943    public float getScaleX() {
8944        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8945    }
8946
8947    /**
8948     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8949     * the view's unscaled width. A value of 1 means that no scaling is applied.
8950     *
8951     * @param scaleX The scaling factor.
8952     * @see #getPivotX()
8953     * @see #getPivotY()
8954     *
8955     * @attr ref android.R.styleable#View_scaleX
8956     */
8957    public void setScaleX(float scaleX) {
8958        ensureTransformationInfo();
8959        final TransformationInfo info = mTransformationInfo;
8960        if (info.mScaleX != scaleX) {
8961            invalidateViewProperty(true, false);
8962            info.mScaleX = scaleX;
8963            info.mMatrixDirty = true;
8964            invalidateViewProperty(false, true);
8965            if (mDisplayList != null) {
8966                mDisplayList.setScaleX(scaleX);
8967            }
8968            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8969                // View was rejected last time it was drawn by its parent; this may have changed
8970                invalidateParentIfNeeded();
8971            }
8972        }
8973    }
8974
8975    /**
8976     * The amount that the view is scaled in y around the pivot point, as a proportion of
8977     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8978     *
8979     * <p>By default, this is 1.0f.
8980     *
8981     * @see #getPivotX()
8982     * @see #getPivotY()
8983     * @return The scaling factor.
8984     */
8985    @ViewDebug.ExportedProperty(category = "drawing")
8986    public float getScaleY() {
8987        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8988    }
8989
8990    /**
8991     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8992     * the view's unscaled width. A value of 1 means that no scaling is applied.
8993     *
8994     * @param scaleY The scaling factor.
8995     * @see #getPivotX()
8996     * @see #getPivotY()
8997     *
8998     * @attr ref android.R.styleable#View_scaleY
8999     */
9000    public void setScaleY(float scaleY) {
9001        ensureTransformationInfo();
9002        final TransformationInfo info = mTransformationInfo;
9003        if (info.mScaleY != scaleY) {
9004            invalidateViewProperty(true, false);
9005            info.mScaleY = scaleY;
9006            info.mMatrixDirty = true;
9007            invalidateViewProperty(false, true);
9008            if (mDisplayList != null) {
9009                mDisplayList.setScaleY(scaleY);
9010            }
9011            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9012                // View was rejected last time it was drawn by its parent; this may have changed
9013                invalidateParentIfNeeded();
9014            }
9015        }
9016    }
9017
9018    /**
9019     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9020     * and {@link #setScaleX(float) scaled}.
9021     *
9022     * @see #getRotation()
9023     * @see #getScaleX()
9024     * @see #getScaleY()
9025     * @see #getPivotY()
9026     * @return The x location of the pivot point.
9027     *
9028     * @attr ref android.R.styleable#View_transformPivotX
9029     */
9030    @ViewDebug.ExportedProperty(category = "drawing")
9031    public float getPivotX() {
9032        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9033    }
9034
9035    /**
9036     * Sets the x location of the point around which the view is
9037     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9038     * By default, the pivot point is centered on the object.
9039     * Setting this property disables this behavior and causes the view to use only the
9040     * explicitly set pivotX and pivotY values.
9041     *
9042     * @param pivotX The x location of the pivot point.
9043     * @see #getRotation()
9044     * @see #getScaleX()
9045     * @see #getScaleY()
9046     * @see #getPivotY()
9047     *
9048     * @attr ref android.R.styleable#View_transformPivotX
9049     */
9050    public void setPivotX(float pivotX) {
9051        ensureTransformationInfo();
9052        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
9053        final TransformationInfo info = mTransformationInfo;
9054        if (info.mPivotX != pivotX) {
9055            invalidateViewProperty(true, false);
9056            info.mPivotX = pivotX;
9057            info.mMatrixDirty = true;
9058            invalidateViewProperty(false, true);
9059            if (mDisplayList != null) {
9060                mDisplayList.setPivotX(pivotX);
9061            }
9062            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9063                // View was rejected last time it was drawn by its parent; this may have changed
9064                invalidateParentIfNeeded();
9065            }
9066        }
9067    }
9068
9069    /**
9070     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9071     * and {@link #setScaleY(float) scaled}.
9072     *
9073     * @see #getRotation()
9074     * @see #getScaleX()
9075     * @see #getScaleY()
9076     * @see #getPivotY()
9077     * @return The y location of the pivot point.
9078     *
9079     * @attr ref android.R.styleable#View_transformPivotY
9080     */
9081    @ViewDebug.ExportedProperty(category = "drawing")
9082    public float getPivotY() {
9083        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9084    }
9085
9086    /**
9087     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9088     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9089     * Setting this property disables this behavior and causes the view to use only the
9090     * explicitly set pivotX and pivotY values.
9091     *
9092     * @param pivotY The y location of the pivot point.
9093     * @see #getRotation()
9094     * @see #getScaleX()
9095     * @see #getScaleY()
9096     * @see #getPivotY()
9097     *
9098     * @attr ref android.R.styleable#View_transformPivotY
9099     */
9100    public void setPivotY(float pivotY) {
9101        ensureTransformationInfo();
9102        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
9103        final TransformationInfo info = mTransformationInfo;
9104        if (info.mPivotY != pivotY) {
9105            invalidateViewProperty(true, false);
9106            info.mPivotY = pivotY;
9107            info.mMatrixDirty = true;
9108            invalidateViewProperty(false, true);
9109            if (mDisplayList != null) {
9110                mDisplayList.setPivotY(pivotY);
9111            }
9112            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9113                // View was rejected last time it was drawn by its parent; this may have changed
9114                invalidateParentIfNeeded();
9115            }
9116        }
9117    }
9118
9119    /**
9120     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9121     * completely transparent and 1 means the view is completely opaque.
9122     *
9123     * <p>By default this is 1.0f.
9124     * @return The opacity of the view.
9125     */
9126    @ViewDebug.ExportedProperty(category = "drawing")
9127    public float getAlpha() {
9128        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9129    }
9130
9131    /**
9132     * Returns whether this View has content which overlaps. This function, intended to be
9133     * overridden by specific View types, is an optimization when alpha is set on a view. If
9134     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9135     * and then composited it into place, which can be expensive. If the view has no overlapping
9136     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9137     * An example of overlapping rendering is a TextView with a background image, such as a
9138     * Button. An example of non-overlapping rendering is a TextView with no background, or
9139     * an ImageView with only the foreground image. The default implementation returns true;
9140     * subclasses should override if they have cases which can be optimized.
9141     *
9142     * @return true if the content in this view might overlap, false otherwise.
9143     */
9144    public boolean hasOverlappingRendering() {
9145        return true;
9146    }
9147
9148    /**
9149     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9150     * completely transparent and 1 means the view is completely opaque.</p>
9151     *
9152     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9153     * responsible for applying the opacity itself. Otherwise, calling this method is
9154     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9155     * setting a hardware layer.</p>
9156     *
9157     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9158     * performance implications. It is generally best to use the alpha property sparingly and
9159     * transiently, as in the case of fading animations.</p>
9160     *
9161     * @param alpha The opacity of the view.
9162     *
9163     * @see #setLayerType(int, android.graphics.Paint)
9164     *
9165     * @attr ref android.R.styleable#View_alpha
9166     */
9167    public void setAlpha(float alpha) {
9168        ensureTransformationInfo();
9169        if (mTransformationInfo.mAlpha != alpha) {
9170            mTransformationInfo.mAlpha = alpha;
9171            if (onSetAlpha((int) (alpha * 255))) {
9172                mPrivateFlags |= ALPHA_SET;
9173                // subclass is handling alpha - don't optimize rendering cache invalidation
9174                invalidateParentCaches();
9175                invalidate(true);
9176            } else {
9177                mPrivateFlags &= ~ALPHA_SET;
9178                invalidateViewProperty(true, false);
9179                if (mDisplayList != null) {
9180                    mDisplayList.setAlpha(alpha);
9181                }
9182            }
9183        }
9184    }
9185
9186    /**
9187     * Faster version of setAlpha() which performs the same steps except there are
9188     * no calls to invalidate(). The caller of this function should perform proper invalidation
9189     * on the parent and this object. The return value indicates whether the subclass handles
9190     * alpha (the return value for onSetAlpha()).
9191     *
9192     * @param alpha The new value for the alpha property
9193     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9194     *         the new value for the alpha property is different from the old value
9195     */
9196    boolean setAlphaNoInvalidation(float alpha) {
9197        ensureTransformationInfo();
9198        if (mTransformationInfo.mAlpha != alpha) {
9199            mTransformationInfo.mAlpha = alpha;
9200            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9201            if (subclassHandlesAlpha) {
9202                mPrivateFlags |= ALPHA_SET;
9203                return true;
9204            } else {
9205                mPrivateFlags &= ~ALPHA_SET;
9206                if (mDisplayList != null) {
9207                    mDisplayList.setAlpha(alpha);
9208                }
9209            }
9210        }
9211        return false;
9212    }
9213
9214    /**
9215     * Top position of this view relative to its parent.
9216     *
9217     * @return The top of this view, in pixels.
9218     */
9219    @ViewDebug.CapturedViewProperty
9220    public final int getTop() {
9221        return mTop;
9222    }
9223
9224    /**
9225     * Sets the top position of this view relative to its parent. This method is meant to be called
9226     * by the layout system and should not generally be called otherwise, because the property
9227     * may be changed at any time by the layout.
9228     *
9229     * @param top The top of this view, in pixels.
9230     */
9231    public final void setTop(int top) {
9232        if (top != mTop) {
9233            updateMatrix();
9234            final boolean matrixIsIdentity = mTransformationInfo == null
9235                    || mTransformationInfo.mMatrixIsIdentity;
9236            if (matrixIsIdentity) {
9237                if (mAttachInfo != null) {
9238                    int minTop;
9239                    int yLoc;
9240                    if (top < mTop) {
9241                        minTop = top;
9242                        yLoc = top - mTop;
9243                    } else {
9244                        minTop = mTop;
9245                        yLoc = 0;
9246                    }
9247                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9248                }
9249            } else {
9250                // Double-invalidation is necessary to capture view's old and new areas
9251                invalidate(true);
9252            }
9253
9254            int width = mRight - mLeft;
9255            int oldHeight = mBottom - mTop;
9256
9257            mTop = top;
9258            if (mDisplayList != null) {
9259                mDisplayList.setTop(mTop);
9260            }
9261
9262            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9263
9264            if (!matrixIsIdentity) {
9265                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9266                    // A change in dimension means an auto-centered pivot point changes, too
9267                    mTransformationInfo.mMatrixDirty = true;
9268                }
9269                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9270                invalidate(true);
9271            }
9272            mBackgroundSizeChanged = true;
9273            invalidateParentIfNeeded();
9274            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9275                // View was rejected last time it was drawn by its parent; this may have changed
9276                invalidateParentIfNeeded();
9277            }
9278        }
9279    }
9280
9281    /**
9282     * Bottom position of this view relative to its parent.
9283     *
9284     * @return The bottom of this view, in pixels.
9285     */
9286    @ViewDebug.CapturedViewProperty
9287    public final int getBottom() {
9288        return mBottom;
9289    }
9290
9291    /**
9292     * True if this view has changed since the last time being drawn.
9293     *
9294     * @return The dirty state of this view.
9295     */
9296    public boolean isDirty() {
9297        return (mPrivateFlags & DIRTY_MASK) != 0;
9298    }
9299
9300    /**
9301     * Sets the bottom position of this view relative to its parent. This method is meant to be
9302     * called by the layout system and should not generally be called otherwise, because the
9303     * property may be changed at any time by the layout.
9304     *
9305     * @param bottom The bottom of this view, in pixels.
9306     */
9307    public final void setBottom(int bottom) {
9308        if (bottom != mBottom) {
9309            updateMatrix();
9310            final boolean matrixIsIdentity = mTransformationInfo == null
9311                    || mTransformationInfo.mMatrixIsIdentity;
9312            if (matrixIsIdentity) {
9313                if (mAttachInfo != null) {
9314                    int maxBottom;
9315                    if (bottom < mBottom) {
9316                        maxBottom = mBottom;
9317                    } else {
9318                        maxBottom = bottom;
9319                    }
9320                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9321                }
9322            } else {
9323                // Double-invalidation is necessary to capture view's old and new areas
9324                invalidate(true);
9325            }
9326
9327            int width = mRight - mLeft;
9328            int oldHeight = mBottom - mTop;
9329
9330            mBottom = bottom;
9331            if (mDisplayList != null) {
9332                mDisplayList.setBottom(mBottom);
9333            }
9334
9335            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9336
9337            if (!matrixIsIdentity) {
9338                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9339                    // A change in dimension means an auto-centered pivot point changes, too
9340                    mTransformationInfo.mMatrixDirty = true;
9341                }
9342                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9343                invalidate(true);
9344            }
9345            mBackgroundSizeChanged = true;
9346            invalidateParentIfNeeded();
9347            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9348                // View was rejected last time it was drawn by its parent; this may have changed
9349                invalidateParentIfNeeded();
9350            }
9351        }
9352    }
9353
9354    /**
9355     * Left position of this view relative to its parent.
9356     *
9357     * @return The left edge of this view, in pixels.
9358     */
9359    @ViewDebug.CapturedViewProperty
9360    public final int getLeft() {
9361        return mLeft;
9362    }
9363
9364    /**
9365     * Sets the left position of this view relative to its parent. This method is meant to be called
9366     * by the layout system and should not generally be called otherwise, because the property
9367     * may be changed at any time by the layout.
9368     *
9369     * @param left The bottom of this view, in pixels.
9370     */
9371    public final void setLeft(int left) {
9372        if (left != mLeft) {
9373            updateMatrix();
9374            final boolean matrixIsIdentity = mTransformationInfo == null
9375                    || mTransformationInfo.mMatrixIsIdentity;
9376            if (matrixIsIdentity) {
9377                if (mAttachInfo != null) {
9378                    int minLeft;
9379                    int xLoc;
9380                    if (left < mLeft) {
9381                        minLeft = left;
9382                        xLoc = left - mLeft;
9383                    } else {
9384                        minLeft = mLeft;
9385                        xLoc = 0;
9386                    }
9387                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9388                }
9389            } else {
9390                // Double-invalidation is necessary to capture view's old and new areas
9391                invalidate(true);
9392            }
9393
9394            int oldWidth = mRight - mLeft;
9395            int height = mBottom - mTop;
9396
9397            mLeft = left;
9398            if (mDisplayList != null) {
9399                mDisplayList.setLeft(left);
9400            }
9401
9402            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9403
9404            if (!matrixIsIdentity) {
9405                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9406                    // A change in dimension means an auto-centered pivot point changes, too
9407                    mTransformationInfo.mMatrixDirty = true;
9408                }
9409                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9410                invalidate(true);
9411            }
9412            mBackgroundSizeChanged = true;
9413            invalidateParentIfNeeded();
9414            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9415                // View was rejected last time it was drawn by its parent; this may have changed
9416                invalidateParentIfNeeded();
9417            }
9418        }
9419    }
9420
9421    /**
9422     * Right position of this view relative to its parent.
9423     *
9424     * @return The right edge of this view, in pixels.
9425     */
9426    @ViewDebug.CapturedViewProperty
9427    public final int getRight() {
9428        return mRight;
9429    }
9430
9431    /**
9432     * Sets the right position of this view relative to its parent. This method is meant to be called
9433     * by the layout system and should not generally be called otherwise, because the property
9434     * may be changed at any time by the layout.
9435     *
9436     * @param right The bottom of this view, in pixels.
9437     */
9438    public final void setRight(int right) {
9439        if (right != mRight) {
9440            updateMatrix();
9441            final boolean matrixIsIdentity = mTransformationInfo == null
9442                    || mTransformationInfo.mMatrixIsIdentity;
9443            if (matrixIsIdentity) {
9444                if (mAttachInfo != null) {
9445                    int maxRight;
9446                    if (right < mRight) {
9447                        maxRight = mRight;
9448                    } else {
9449                        maxRight = right;
9450                    }
9451                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9452                }
9453            } else {
9454                // Double-invalidation is necessary to capture view's old and new areas
9455                invalidate(true);
9456            }
9457
9458            int oldWidth = mRight - mLeft;
9459            int height = mBottom - mTop;
9460
9461            mRight = right;
9462            if (mDisplayList != null) {
9463                mDisplayList.setRight(mRight);
9464            }
9465
9466            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9467
9468            if (!matrixIsIdentity) {
9469                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9470                    // A change in dimension means an auto-centered pivot point changes, too
9471                    mTransformationInfo.mMatrixDirty = true;
9472                }
9473                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9474                invalidate(true);
9475            }
9476            mBackgroundSizeChanged = true;
9477            invalidateParentIfNeeded();
9478            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9479                // View was rejected last time it was drawn by its parent; this may have changed
9480                invalidateParentIfNeeded();
9481            }
9482        }
9483    }
9484
9485    /**
9486     * The visual x position of this view, in pixels. This is equivalent to the
9487     * {@link #setTranslationX(float) translationX} property plus the current
9488     * {@link #getLeft() left} property.
9489     *
9490     * @return The visual x position of this view, in pixels.
9491     */
9492    @ViewDebug.ExportedProperty(category = "drawing")
9493    public float getX() {
9494        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9495    }
9496
9497    /**
9498     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9499     * {@link #setTranslationX(float) translationX} property to be the difference between
9500     * the x value passed in and the current {@link #getLeft() left} property.
9501     *
9502     * @param x The visual x position of this view, in pixels.
9503     */
9504    public void setX(float x) {
9505        setTranslationX(x - mLeft);
9506    }
9507
9508    /**
9509     * The visual y position of this view, in pixels. This is equivalent to the
9510     * {@link #setTranslationY(float) translationY} property plus the current
9511     * {@link #getTop() top} property.
9512     *
9513     * @return The visual y position of this view, in pixels.
9514     */
9515    @ViewDebug.ExportedProperty(category = "drawing")
9516    public float getY() {
9517        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9518    }
9519
9520    /**
9521     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9522     * {@link #setTranslationY(float) translationY} property to be the difference between
9523     * the y value passed in and the current {@link #getTop() top} property.
9524     *
9525     * @param y The visual y position of this view, in pixels.
9526     */
9527    public void setY(float y) {
9528        setTranslationY(y - mTop);
9529    }
9530
9531
9532    /**
9533     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9534     * This position is post-layout, in addition to wherever the object's
9535     * layout placed it.
9536     *
9537     * @return The horizontal position of this view relative to its left position, in pixels.
9538     */
9539    @ViewDebug.ExportedProperty(category = "drawing")
9540    public float getTranslationX() {
9541        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9542    }
9543
9544    /**
9545     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9546     * This effectively positions the object post-layout, in addition to wherever the object's
9547     * layout placed it.
9548     *
9549     * @param translationX The horizontal position of this view relative to its left position,
9550     * in pixels.
9551     *
9552     * @attr ref android.R.styleable#View_translationX
9553     */
9554    public void setTranslationX(float translationX) {
9555        ensureTransformationInfo();
9556        final TransformationInfo info = mTransformationInfo;
9557        if (info.mTranslationX != translationX) {
9558            // Double-invalidation is necessary to capture view's old and new areas
9559            invalidateViewProperty(true, false);
9560            info.mTranslationX = translationX;
9561            info.mMatrixDirty = true;
9562            invalidateViewProperty(false, true);
9563            if (mDisplayList != null) {
9564                mDisplayList.setTranslationX(translationX);
9565            }
9566            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9567                // View was rejected last time it was drawn by its parent; this may have changed
9568                invalidateParentIfNeeded();
9569            }
9570        }
9571    }
9572
9573    /**
9574     * The horizontal location of this view relative to its {@link #getTop() top} position.
9575     * This position is post-layout, in addition to wherever the object's
9576     * layout placed it.
9577     *
9578     * @return The vertical position of this view relative to its top position,
9579     * in pixels.
9580     */
9581    @ViewDebug.ExportedProperty(category = "drawing")
9582    public float getTranslationY() {
9583        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9584    }
9585
9586    /**
9587     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9588     * This effectively positions the object post-layout, in addition to wherever the object's
9589     * layout placed it.
9590     *
9591     * @param translationY The vertical position of this view relative to its top position,
9592     * in pixels.
9593     *
9594     * @attr ref android.R.styleable#View_translationY
9595     */
9596    public void setTranslationY(float translationY) {
9597        ensureTransformationInfo();
9598        final TransformationInfo info = mTransformationInfo;
9599        if (info.mTranslationY != translationY) {
9600            invalidateViewProperty(true, false);
9601            info.mTranslationY = translationY;
9602            info.mMatrixDirty = true;
9603            invalidateViewProperty(false, true);
9604            if (mDisplayList != null) {
9605                mDisplayList.setTranslationY(translationY);
9606            }
9607            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9608                // View was rejected last time it was drawn by its parent; this may have changed
9609                invalidateParentIfNeeded();
9610            }
9611        }
9612    }
9613
9614    /**
9615     * Hit rectangle in parent's coordinates
9616     *
9617     * @param outRect The hit rectangle of the view.
9618     */
9619    public void getHitRect(Rect outRect) {
9620        updateMatrix();
9621        final TransformationInfo info = mTransformationInfo;
9622        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9623            outRect.set(mLeft, mTop, mRight, mBottom);
9624        } else {
9625            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9626            tmpRect.set(-info.mPivotX, -info.mPivotY,
9627                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9628            info.mMatrix.mapRect(tmpRect);
9629            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9630                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9631        }
9632    }
9633
9634    /**
9635     * Determines whether the given point, in local coordinates is inside the view.
9636     */
9637    /*package*/ final boolean pointInView(float localX, float localY) {
9638        return localX >= 0 && localX < (mRight - mLeft)
9639                && localY >= 0 && localY < (mBottom - mTop);
9640    }
9641
9642    /**
9643     * Utility method to determine whether the given point, in local coordinates,
9644     * is inside the view, where the area of the view is expanded by the slop factor.
9645     * This method is called while processing touch-move events to determine if the event
9646     * is still within the view.
9647     */
9648    private boolean pointInView(float localX, float localY, float slop) {
9649        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9650                localY < ((mBottom - mTop) + slop);
9651    }
9652
9653    /**
9654     * When a view has focus and the user navigates away from it, the next view is searched for
9655     * starting from the rectangle filled in by this method.
9656     *
9657     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9658     * of the view.  However, if your view maintains some idea of internal selection,
9659     * such as a cursor, or a selected row or column, you should override this method and
9660     * fill in a more specific rectangle.
9661     *
9662     * @param r The rectangle to fill in, in this view's coordinates.
9663     */
9664    public void getFocusedRect(Rect r) {
9665        getDrawingRect(r);
9666    }
9667
9668    /**
9669     * If some part of this view is not clipped by any of its parents, then
9670     * return that area in r in global (root) coordinates. To convert r to local
9671     * coordinates (without taking possible View rotations into account), offset
9672     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9673     * If the view is completely clipped or translated out, return false.
9674     *
9675     * @param r If true is returned, r holds the global coordinates of the
9676     *        visible portion of this view.
9677     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9678     *        between this view and its root. globalOffet may be null.
9679     * @return true if r is non-empty (i.e. part of the view is visible at the
9680     *         root level.
9681     */
9682    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9683        int width = mRight - mLeft;
9684        int height = mBottom - mTop;
9685        if (width > 0 && height > 0) {
9686            r.set(0, 0, width, height);
9687            if (globalOffset != null) {
9688                globalOffset.set(-mScrollX, -mScrollY);
9689            }
9690            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9691        }
9692        return false;
9693    }
9694
9695    public final boolean getGlobalVisibleRect(Rect r) {
9696        return getGlobalVisibleRect(r, null);
9697    }
9698
9699    public final boolean getLocalVisibleRect(Rect r) {
9700        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9701        if (getGlobalVisibleRect(r, offset)) {
9702            r.offset(-offset.x, -offset.y); // make r local
9703            return true;
9704        }
9705        return false;
9706    }
9707
9708    /**
9709     * Offset this view's vertical location by the specified number of pixels.
9710     *
9711     * @param offset the number of pixels to offset the view by
9712     */
9713    public void offsetTopAndBottom(int offset) {
9714        if (offset != 0) {
9715            updateMatrix();
9716            final boolean matrixIsIdentity = mTransformationInfo == null
9717                    || mTransformationInfo.mMatrixIsIdentity;
9718            if (matrixIsIdentity) {
9719                if (mDisplayList != null) {
9720                    invalidateViewProperty(false, false);
9721                } else {
9722                    final ViewParent p = mParent;
9723                    if (p != null && mAttachInfo != null) {
9724                        final Rect r = mAttachInfo.mTmpInvalRect;
9725                        int minTop;
9726                        int maxBottom;
9727                        int yLoc;
9728                        if (offset < 0) {
9729                            minTop = mTop + offset;
9730                            maxBottom = mBottom;
9731                            yLoc = offset;
9732                        } else {
9733                            minTop = mTop;
9734                            maxBottom = mBottom + offset;
9735                            yLoc = 0;
9736                        }
9737                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9738                        p.invalidateChild(this, r);
9739                    }
9740                }
9741            } else {
9742                invalidateViewProperty(false, false);
9743            }
9744
9745            mTop += offset;
9746            mBottom += offset;
9747            if (mDisplayList != null) {
9748                mDisplayList.offsetTopBottom(offset);
9749                invalidateViewProperty(false, false);
9750            } else {
9751                if (!matrixIsIdentity) {
9752                    invalidateViewProperty(false, true);
9753                }
9754                invalidateParentIfNeeded();
9755            }
9756        }
9757    }
9758
9759    /**
9760     * Offset this view's horizontal location by the specified amount of pixels.
9761     *
9762     * @param offset the numer of pixels to offset the view by
9763     */
9764    public void offsetLeftAndRight(int offset) {
9765        if (offset != 0) {
9766            updateMatrix();
9767            final boolean matrixIsIdentity = mTransformationInfo == null
9768                    || mTransformationInfo.mMatrixIsIdentity;
9769            if (matrixIsIdentity) {
9770                if (mDisplayList != null) {
9771                    invalidateViewProperty(false, false);
9772                } else {
9773                    final ViewParent p = mParent;
9774                    if (p != null && mAttachInfo != null) {
9775                        final Rect r = mAttachInfo.mTmpInvalRect;
9776                        int minLeft;
9777                        int maxRight;
9778                        if (offset < 0) {
9779                            minLeft = mLeft + offset;
9780                            maxRight = mRight;
9781                        } else {
9782                            minLeft = mLeft;
9783                            maxRight = mRight + offset;
9784                        }
9785                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9786                        p.invalidateChild(this, r);
9787                    }
9788                }
9789            } else {
9790                invalidateViewProperty(false, false);
9791            }
9792
9793            mLeft += offset;
9794            mRight += offset;
9795            if (mDisplayList != null) {
9796                mDisplayList.offsetLeftRight(offset);
9797                invalidateViewProperty(false, false);
9798            } else {
9799                if (!matrixIsIdentity) {
9800                    invalidateViewProperty(false, true);
9801                }
9802                invalidateParentIfNeeded();
9803            }
9804        }
9805    }
9806
9807    /**
9808     * Get the LayoutParams associated with this view. All views should have
9809     * layout parameters. These supply parameters to the <i>parent</i> of this
9810     * view specifying how it should be arranged. There are many subclasses of
9811     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9812     * of ViewGroup that are responsible for arranging their children.
9813     *
9814     * This method may return null if this View is not attached to a parent
9815     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9816     * was not invoked successfully. When a View is attached to a parent
9817     * ViewGroup, this method must not return null.
9818     *
9819     * @return The LayoutParams associated with this view, or null if no
9820     *         parameters have been set yet
9821     */
9822    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9823    public ViewGroup.LayoutParams getLayoutParams() {
9824        return mLayoutParams;
9825    }
9826
9827    /**
9828     * Set the layout parameters associated with this view. These supply
9829     * parameters to the <i>parent</i> of this view specifying how it should be
9830     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9831     * correspond to the different subclasses of ViewGroup that are responsible
9832     * for arranging their children.
9833     *
9834     * @param params The layout parameters for this view, cannot be null
9835     */
9836    public void setLayoutParams(ViewGroup.LayoutParams params) {
9837        if (params == null) {
9838            throw new NullPointerException("Layout parameters cannot be null");
9839        }
9840        mLayoutParams = params;
9841        if (mParent instanceof ViewGroup) {
9842            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9843        }
9844        requestLayout();
9845    }
9846
9847    /**
9848     * Set the scrolled position of your view. This will cause a call to
9849     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9850     * invalidated.
9851     * @param x the x position to scroll to
9852     * @param y the y position to scroll to
9853     */
9854    public void scrollTo(int x, int y) {
9855        if (mScrollX != x || mScrollY != y) {
9856            int oldX = mScrollX;
9857            int oldY = mScrollY;
9858            mScrollX = x;
9859            mScrollY = y;
9860            invalidateParentCaches();
9861            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9862            if (!awakenScrollBars()) {
9863                postInvalidateOnAnimation();
9864            }
9865        }
9866    }
9867
9868    /**
9869     * Move the scrolled position of your view. This will cause a call to
9870     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9871     * invalidated.
9872     * @param x the amount of pixels to scroll by horizontally
9873     * @param y the amount of pixels to scroll by vertically
9874     */
9875    public void scrollBy(int x, int y) {
9876        scrollTo(mScrollX + x, mScrollY + y);
9877    }
9878
9879    /**
9880     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9881     * animation to fade the scrollbars out after a default delay. If a subclass
9882     * provides animated scrolling, the start delay should equal the duration
9883     * of the scrolling animation.</p>
9884     *
9885     * <p>The animation starts only if at least one of the scrollbars is
9886     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9887     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9888     * this method returns true, and false otherwise. If the animation is
9889     * started, this method calls {@link #invalidate()}; in that case the
9890     * caller should not call {@link #invalidate()}.</p>
9891     *
9892     * <p>This method should be invoked every time a subclass directly updates
9893     * the scroll parameters.</p>
9894     *
9895     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9896     * and {@link #scrollTo(int, int)}.</p>
9897     *
9898     * @return true if the animation is played, false otherwise
9899     *
9900     * @see #awakenScrollBars(int)
9901     * @see #scrollBy(int, int)
9902     * @see #scrollTo(int, int)
9903     * @see #isHorizontalScrollBarEnabled()
9904     * @see #isVerticalScrollBarEnabled()
9905     * @see #setHorizontalScrollBarEnabled(boolean)
9906     * @see #setVerticalScrollBarEnabled(boolean)
9907     */
9908    protected boolean awakenScrollBars() {
9909        return mScrollCache != null &&
9910                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9911    }
9912
9913    /**
9914     * Trigger the scrollbars to draw.
9915     * This method differs from awakenScrollBars() only in its default duration.
9916     * initialAwakenScrollBars() will show the scroll bars for longer than
9917     * usual to give the user more of a chance to notice them.
9918     *
9919     * @return true if the animation is played, false otherwise.
9920     */
9921    private boolean initialAwakenScrollBars() {
9922        return mScrollCache != null &&
9923                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9924    }
9925
9926    /**
9927     * <p>
9928     * Trigger the scrollbars to draw. When invoked this method starts an
9929     * animation to fade the scrollbars out after a fixed delay. If a subclass
9930     * provides animated scrolling, the start delay should equal the duration of
9931     * the scrolling animation.
9932     * </p>
9933     *
9934     * <p>
9935     * The animation starts only if at least one of the scrollbars is enabled,
9936     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9937     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9938     * this method returns true, and false otherwise. If the animation is
9939     * started, this method calls {@link #invalidate()}; in that case the caller
9940     * should not call {@link #invalidate()}.
9941     * </p>
9942     *
9943     * <p>
9944     * This method should be invoked everytime a subclass directly updates the
9945     * scroll parameters.
9946     * </p>
9947     *
9948     * @param startDelay the delay, in milliseconds, after which the animation
9949     *        should start; when the delay is 0, the animation starts
9950     *        immediately
9951     * @return true if the animation is played, false otherwise
9952     *
9953     * @see #scrollBy(int, int)
9954     * @see #scrollTo(int, int)
9955     * @see #isHorizontalScrollBarEnabled()
9956     * @see #isVerticalScrollBarEnabled()
9957     * @see #setHorizontalScrollBarEnabled(boolean)
9958     * @see #setVerticalScrollBarEnabled(boolean)
9959     */
9960    protected boolean awakenScrollBars(int startDelay) {
9961        return awakenScrollBars(startDelay, true);
9962    }
9963
9964    /**
9965     * <p>
9966     * Trigger the scrollbars to draw. When invoked this method starts an
9967     * animation to fade the scrollbars out after a fixed delay. If a subclass
9968     * provides animated scrolling, the start delay should equal the duration of
9969     * the scrolling animation.
9970     * </p>
9971     *
9972     * <p>
9973     * The animation starts only if at least one of the scrollbars is enabled,
9974     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9975     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9976     * this method returns true, and false otherwise. If the animation is
9977     * started, this method calls {@link #invalidate()} if the invalidate parameter
9978     * is set to true; in that case the caller
9979     * should not call {@link #invalidate()}.
9980     * </p>
9981     *
9982     * <p>
9983     * This method should be invoked everytime a subclass directly updates the
9984     * scroll parameters.
9985     * </p>
9986     *
9987     * @param startDelay the delay, in milliseconds, after which the animation
9988     *        should start; when the delay is 0, the animation starts
9989     *        immediately
9990     *
9991     * @param invalidate Wheter this method should call invalidate
9992     *
9993     * @return true if the animation is played, false otherwise
9994     *
9995     * @see #scrollBy(int, int)
9996     * @see #scrollTo(int, int)
9997     * @see #isHorizontalScrollBarEnabled()
9998     * @see #isVerticalScrollBarEnabled()
9999     * @see #setHorizontalScrollBarEnabled(boolean)
10000     * @see #setVerticalScrollBarEnabled(boolean)
10001     */
10002    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10003        final ScrollabilityCache scrollCache = mScrollCache;
10004
10005        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10006            return false;
10007        }
10008
10009        if (scrollCache.scrollBar == null) {
10010            scrollCache.scrollBar = new ScrollBarDrawable();
10011        }
10012
10013        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10014
10015            if (invalidate) {
10016                // Invalidate to show the scrollbars
10017                postInvalidateOnAnimation();
10018            }
10019
10020            if (scrollCache.state == ScrollabilityCache.OFF) {
10021                // FIXME: this is copied from WindowManagerService.
10022                // We should get this value from the system when it
10023                // is possible to do so.
10024                final int KEY_REPEAT_FIRST_DELAY = 750;
10025                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10026            }
10027
10028            // Tell mScrollCache when we should start fading. This may
10029            // extend the fade start time if one was already scheduled
10030            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10031            scrollCache.fadeStartTime = fadeStartTime;
10032            scrollCache.state = ScrollabilityCache.ON;
10033
10034            // Schedule our fader to run, unscheduling any old ones first
10035            if (mAttachInfo != null) {
10036                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10037                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10038            }
10039
10040            return true;
10041        }
10042
10043        return false;
10044    }
10045
10046    /**
10047     * Do not invalidate views which are not visible and which are not running an animation. They
10048     * will not get drawn and they should not set dirty flags as if they will be drawn
10049     */
10050    private boolean skipInvalidate() {
10051        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10052                (!(mParent instanceof ViewGroup) ||
10053                        !((ViewGroup) mParent).isViewTransitioning(this));
10054    }
10055    /**
10056     * Mark the area defined by dirty as needing to be drawn. If the view is
10057     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10058     * in the future. This must be called from a UI thread. To call from a non-UI
10059     * thread, call {@link #postInvalidate()}.
10060     *
10061     * WARNING: This method is destructive to dirty.
10062     * @param dirty the rectangle representing the bounds of the dirty region
10063     */
10064    public void invalidate(Rect dirty) {
10065        if (skipInvalidate()) {
10066            return;
10067        }
10068        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10069                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
10070                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
10071            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10072            mPrivateFlags |= INVALIDATED;
10073            mPrivateFlags |= DIRTY;
10074            final ViewParent p = mParent;
10075            final AttachInfo ai = mAttachInfo;
10076            //noinspection PointlessBooleanExpression,ConstantConditions
10077            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10078                if (p != null && ai != null && ai.mHardwareAccelerated) {
10079                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10080                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10081                    p.invalidateChild(this, null);
10082                    return;
10083                }
10084            }
10085            if (p != null && ai != null) {
10086                final int scrollX = mScrollX;
10087                final int scrollY = mScrollY;
10088                final Rect r = ai.mTmpInvalRect;
10089                r.set(dirty.left - scrollX, dirty.top - scrollY,
10090                        dirty.right - scrollX, dirty.bottom - scrollY);
10091                mParent.invalidateChild(this, r);
10092            }
10093        }
10094    }
10095
10096    /**
10097     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10098     * The coordinates of the dirty rect are relative to the view.
10099     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10100     * will be called at some point in the future. This must be called from
10101     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10102     * @param l the left position of the dirty region
10103     * @param t the top position of the dirty region
10104     * @param r the right position of the dirty region
10105     * @param b the bottom position of the dirty region
10106     */
10107    public void invalidate(int l, int t, int r, int b) {
10108        if (skipInvalidate()) {
10109            return;
10110        }
10111        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10112                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
10113                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
10114            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10115            mPrivateFlags |= INVALIDATED;
10116            mPrivateFlags |= DIRTY;
10117            final ViewParent p = mParent;
10118            final AttachInfo ai = mAttachInfo;
10119            //noinspection PointlessBooleanExpression,ConstantConditions
10120            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10121                if (p != null && ai != null && ai.mHardwareAccelerated) {
10122                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10123                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10124                    p.invalidateChild(this, null);
10125                    return;
10126                }
10127            }
10128            if (p != null && ai != null && l < r && t < b) {
10129                final int scrollX = mScrollX;
10130                final int scrollY = mScrollY;
10131                final Rect tmpr = ai.mTmpInvalRect;
10132                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10133                p.invalidateChild(this, tmpr);
10134            }
10135        }
10136    }
10137
10138    /**
10139     * Invalidate the whole view. If the view is visible,
10140     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10141     * the future. This must be called from a UI thread. To call from a non-UI thread,
10142     * call {@link #postInvalidate()}.
10143     */
10144    public void invalidate() {
10145        invalidate(true);
10146    }
10147
10148    /**
10149     * This is where the invalidate() work actually happens. A full invalidate()
10150     * causes the drawing cache to be invalidated, but this function can be called with
10151     * invalidateCache set to false to skip that invalidation step for cases that do not
10152     * need it (for example, a component that remains at the same dimensions with the same
10153     * content).
10154     *
10155     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10156     * well. This is usually true for a full invalidate, but may be set to false if the
10157     * View's contents or dimensions have not changed.
10158     */
10159    void invalidate(boolean invalidateCache) {
10160        if (skipInvalidate()) {
10161            return;
10162        }
10163        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10164                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
10165                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
10166            mLastIsOpaque = isOpaque();
10167            mPrivateFlags &= ~DRAWN;
10168            mPrivateFlags |= DIRTY;
10169            if (invalidateCache) {
10170                mPrivateFlags |= INVALIDATED;
10171                mPrivateFlags &= ~DRAWING_CACHE_VALID;
10172            }
10173            final AttachInfo ai = mAttachInfo;
10174            final ViewParent p = mParent;
10175            //noinspection PointlessBooleanExpression,ConstantConditions
10176            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10177                if (p != null && ai != null && ai.mHardwareAccelerated) {
10178                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10179                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10180                    p.invalidateChild(this, null);
10181                    return;
10182                }
10183            }
10184
10185            if (p != null && ai != null) {
10186                final Rect r = ai.mTmpInvalRect;
10187                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10188                // Don't call invalidate -- we don't want to internally scroll
10189                // our own bounds
10190                p.invalidateChild(this, r);
10191            }
10192        }
10193    }
10194
10195    /**
10196     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10197     * set any flags or handle all of the cases handled by the default invalidation methods.
10198     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10199     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10200     * walk up the hierarchy, transforming the dirty rect as necessary.
10201     *
10202     * The method also handles normal invalidation logic if display list properties are not
10203     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10204     * backup approach, to handle these cases used in the various property-setting methods.
10205     *
10206     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10207     * are not being used in this view
10208     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10209     * list properties are not being used in this view
10210     */
10211    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10212        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10213            if (invalidateParent) {
10214                invalidateParentCaches();
10215            }
10216            if (forceRedraw) {
10217                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10218            }
10219            invalidate(false);
10220        } else {
10221            final AttachInfo ai = mAttachInfo;
10222            final ViewParent p = mParent;
10223            if (p != null && ai != null) {
10224                final Rect r = ai.mTmpInvalRect;
10225                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10226                if (mParent instanceof ViewGroup) {
10227                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10228                } else {
10229                    mParent.invalidateChild(this, r);
10230                }
10231            }
10232        }
10233    }
10234
10235    /**
10236     * Utility method to transform a given Rect by the current matrix of this view.
10237     */
10238    void transformRect(final Rect rect) {
10239        if (!getMatrix().isIdentity()) {
10240            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10241            boundingRect.set(rect);
10242            getMatrix().mapRect(boundingRect);
10243            rect.set((int) (boundingRect.left - 0.5f),
10244                    (int) (boundingRect.top - 0.5f),
10245                    (int) (boundingRect.right + 0.5f),
10246                    (int) (boundingRect.bottom + 0.5f));
10247        }
10248    }
10249
10250    /**
10251     * Used to indicate that the parent of this view should clear its caches. This functionality
10252     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10253     * which is necessary when various parent-managed properties of the view change, such as
10254     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10255     * clears the parent caches and does not causes an invalidate event.
10256     *
10257     * @hide
10258     */
10259    protected void invalidateParentCaches() {
10260        if (mParent instanceof View) {
10261            ((View) mParent).mPrivateFlags |= INVALIDATED;
10262        }
10263    }
10264
10265    /**
10266     * Used to indicate that the parent of this view should be invalidated. This functionality
10267     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10268     * which is necessary when various parent-managed properties of the view change, such as
10269     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10270     * an invalidation event to the parent.
10271     *
10272     * @hide
10273     */
10274    protected void invalidateParentIfNeeded() {
10275        if (isHardwareAccelerated() && mParent instanceof View) {
10276            ((View) mParent).invalidate(true);
10277        }
10278    }
10279
10280    /**
10281     * Indicates whether this View is opaque. An opaque View guarantees that it will
10282     * draw all the pixels overlapping its bounds using a fully opaque color.
10283     *
10284     * Subclasses of View should override this method whenever possible to indicate
10285     * whether an instance is opaque. Opaque Views are treated in a special way by
10286     * the View hierarchy, possibly allowing it to perform optimizations during
10287     * invalidate/draw passes.
10288     *
10289     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10290     */
10291    @ViewDebug.ExportedProperty(category = "drawing")
10292    public boolean isOpaque() {
10293        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10294                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10295                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10296    }
10297
10298    /**
10299     * @hide
10300     */
10301    protected void computeOpaqueFlags() {
10302        // Opaque if:
10303        //   - Has a background
10304        //   - Background is opaque
10305        //   - Doesn't have scrollbars or scrollbars are inside overlay
10306
10307        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10308            mPrivateFlags |= OPAQUE_BACKGROUND;
10309        } else {
10310            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10311        }
10312
10313        final int flags = mViewFlags;
10314        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10315                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10316            mPrivateFlags |= OPAQUE_SCROLLBARS;
10317        } else {
10318            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10319        }
10320    }
10321
10322    /**
10323     * @hide
10324     */
10325    protected boolean hasOpaqueScrollbars() {
10326        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10327    }
10328
10329    /**
10330     * @return A handler associated with the thread running the View. This
10331     * handler can be used to pump events in the UI events queue.
10332     */
10333    public Handler getHandler() {
10334        if (mAttachInfo != null) {
10335            return mAttachInfo.mHandler;
10336        }
10337        return null;
10338    }
10339
10340    /**
10341     * Gets the view root associated with the View.
10342     * @return The view root, or null if none.
10343     * @hide
10344     */
10345    public ViewRootImpl getViewRootImpl() {
10346        if (mAttachInfo != null) {
10347            return mAttachInfo.mViewRootImpl;
10348        }
10349        return null;
10350    }
10351
10352    /**
10353     * <p>Causes the Runnable to be added to the message queue.
10354     * The runnable will be run on the user interface thread.</p>
10355     *
10356     * <p>This method can be invoked from outside of the UI thread
10357     * only when this View is attached to a window.</p>
10358     *
10359     * @param action The Runnable that will be executed.
10360     *
10361     * @return Returns true if the Runnable was successfully placed in to the
10362     *         message queue.  Returns false on failure, usually because the
10363     *         looper processing the message queue is exiting.
10364     *
10365     * @see #postDelayed
10366     * @see #removeCallbacks
10367     */
10368    public boolean post(Runnable action) {
10369        final AttachInfo attachInfo = mAttachInfo;
10370        if (attachInfo != null) {
10371            return attachInfo.mHandler.post(action);
10372        }
10373        // Assume that post will succeed later
10374        ViewRootImpl.getRunQueue().post(action);
10375        return true;
10376    }
10377
10378    /**
10379     * <p>Causes the Runnable to be added to the message queue, to be run
10380     * after the specified amount of time elapses.
10381     * The runnable will be run on the user interface thread.</p>
10382     *
10383     * <p>This method can be invoked from outside of the UI thread
10384     * only when this View is attached to a window.</p>
10385     *
10386     * @param action The Runnable that will be executed.
10387     * @param delayMillis The delay (in milliseconds) until the Runnable
10388     *        will be executed.
10389     *
10390     * @return true if the Runnable was successfully placed in to the
10391     *         message queue.  Returns false on failure, usually because the
10392     *         looper processing the message queue is exiting.  Note that a
10393     *         result of true does not mean the Runnable will be processed --
10394     *         if the looper is quit before the delivery time of the message
10395     *         occurs then the message will be dropped.
10396     *
10397     * @see #post
10398     * @see #removeCallbacks
10399     */
10400    public boolean postDelayed(Runnable action, long delayMillis) {
10401        final AttachInfo attachInfo = mAttachInfo;
10402        if (attachInfo != null) {
10403            return attachInfo.mHandler.postDelayed(action, delayMillis);
10404        }
10405        // Assume that post will succeed later
10406        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10407        return true;
10408    }
10409
10410    /**
10411     * <p>Causes the Runnable to execute on the next animation time step.
10412     * The runnable will be run on the user interface thread.</p>
10413     *
10414     * <p>This method can be invoked from outside of the UI thread
10415     * only when this View is attached to a window.</p>
10416     *
10417     * @param action The Runnable that will be executed.
10418     *
10419     * @see #postOnAnimationDelayed
10420     * @see #removeCallbacks
10421     */
10422    public void postOnAnimation(Runnable action) {
10423        final AttachInfo attachInfo = mAttachInfo;
10424        if (attachInfo != null) {
10425            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10426                    Choreographer.CALLBACK_ANIMATION, action, null);
10427        } else {
10428            // Assume that post will succeed later
10429            ViewRootImpl.getRunQueue().post(action);
10430        }
10431    }
10432
10433    /**
10434     * <p>Causes the Runnable to execute on the next animation time step,
10435     * after the specified amount of time elapses.
10436     * The runnable will be run on the user interface thread.</p>
10437     *
10438     * <p>This method can be invoked from outside of the UI thread
10439     * only when this View is attached to a window.</p>
10440     *
10441     * @param action The Runnable that will be executed.
10442     * @param delayMillis The delay (in milliseconds) until the Runnable
10443     *        will be executed.
10444     *
10445     * @see #postOnAnimation
10446     * @see #removeCallbacks
10447     */
10448    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10449        final AttachInfo attachInfo = mAttachInfo;
10450        if (attachInfo != null) {
10451            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10452                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10453        } else {
10454            // Assume that post will succeed later
10455            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10456        }
10457    }
10458
10459    /**
10460     * <p>Removes the specified Runnable from the message queue.</p>
10461     *
10462     * <p>This method can be invoked from outside of the UI thread
10463     * only when this View is attached to a window.</p>
10464     *
10465     * @param action The Runnable to remove from the message handling queue
10466     *
10467     * @return true if this view could ask the Handler to remove the Runnable,
10468     *         false otherwise. When the returned value is true, the Runnable
10469     *         may or may not have been actually removed from the message queue
10470     *         (for instance, if the Runnable was not in the queue already.)
10471     *
10472     * @see #post
10473     * @see #postDelayed
10474     * @see #postOnAnimation
10475     * @see #postOnAnimationDelayed
10476     */
10477    public boolean removeCallbacks(Runnable action) {
10478        if (action != null) {
10479            final AttachInfo attachInfo = mAttachInfo;
10480            if (attachInfo != null) {
10481                attachInfo.mHandler.removeCallbacks(action);
10482                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10483                        Choreographer.CALLBACK_ANIMATION, action, null);
10484            } else {
10485                // Assume that post will succeed later
10486                ViewRootImpl.getRunQueue().removeCallbacks(action);
10487            }
10488        }
10489        return true;
10490    }
10491
10492    /**
10493     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10494     * Use this to invalidate the View from a non-UI thread.</p>
10495     *
10496     * <p>This method can be invoked from outside of the UI thread
10497     * only when this View is attached to a window.</p>
10498     *
10499     * @see #invalidate()
10500     * @see #postInvalidateDelayed(long)
10501     */
10502    public void postInvalidate() {
10503        postInvalidateDelayed(0);
10504    }
10505
10506    /**
10507     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10508     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10509     *
10510     * <p>This method can be invoked from outside of the UI thread
10511     * only when this View is attached to a window.</p>
10512     *
10513     * @param left The left coordinate of the rectangle to invalidate.
10514     * @param top The top coordinate of the rectangle to invalidate.
10515     * @param right The right coordinate of the rectangle to invalidate.
10516     * @param bottom The bottom coordinate of the rectangle to invalidate.
10517     *
10518     * @see #invalidate(int, int, int, int)
10519     * @see #invalidate(Rect)
10520     * @see #postInvalidateDelayed(long, int, int, int, int)
10521     */
10522    public void postInvalidate(int left, int top, int right, int bottom) {
10523        postInvalidateDelayed(0, left, top, right, bottom);
10524    }
10525
10526    /**
10527     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10528     * loop. Waits for the specified amount of time.</p>
10529     *
10530     * <p>This method can be invoked from outside of the UI thread
10531     * only when this View is attached to a window.</p>
10532     *
10533     * @param delayMilliseconds the duration in milliseconds to delay the
10534     *         invalidation by
10535     *
10536     * @see #invalidate()
10537     * @see #postInvalidate()
10538     */
10539    public void postInvalidateDelayed(long delayMilliseconds) {
10540        // We try only with the AttachInfo because there's no point in invalidating
10541        // if we are not attached to our window
10542        final AttachInfo attachInfo = mAttachInfo;
10543        if (attachInfo != null) {
10544            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10545        }
10546    }
10547
10548    /**
10549     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10550     * through the event loop. Waits for the specified amount of time.</p>
10551     *
10552     * <p>This method can be invoked from outside of the UI thread
10553     * only when this View is attached to a window.</p>
10554     *
10555     * @param delayMilliseconds the duration in milliseconds to delay the
10556     *         invalidation by
10557     * @param left The left coordinate of the rectangle to invalidate.
10558     * @param top The top coordinate of the rectangle to invalidate.
10559     * @param right The right coordinate of the rectangle to invalidate.
10560     * @param bottom The bottom coordinate of the rectangle to invalidate.
10561     *
10562     * @see #invalidate(int, int, int, int)
10563     * @see #invalidate(Rect)
10564     * @see #postInvalidate(int, int, int, int)
10565     */
10566    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10567            int right, int bottom) {
10568
10569        // We try only with the AttachInfo because there's no point in invalidating
10570        // if we are not attached to our window
10571        final AttachInfo attachInfo = mAttachInfo;
10572        if (attachInfo != null) {
10573            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10574            info.target = this;
10575            info.left = left;
10576            info.top = top;
10577            info.right = right;
10578            info.bottom = bottom;
10579
10580            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10581        }
10582    }
10583
10584    /**
10585     * <p>Cause an invalidate to happen on the next animation time step, typically the
10586     * next display frame.</p>
10587     *
10588     * <p>This method can be invoked from outside of the UI thread
10589     * only when this View is attached to a window.</p>
10590     *
10591     * @see #invalidate()
10592     */
10593    public void postInvalidateOnAnimation() {
10594        // We try only with the AttachInfo because there's no point in invalidating
10595        // if we are not attached to our window
10596        final AttachInfo attachInfo = mAttachInfo;
10597        if (attachInfo != null) {
10598            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10599        }
10600    }
10601
10602    /**
10603     * <p>Cause an invalidate of the specified area to happen on the next animation
10604     * time step, typically the next display frame.</p>
10605     *
10606     * <p>This method can be invoked from outside of the UI thread
10607     * only when this View is attached to a window.</p>
10608     *
10609     * @param left The left coordinate of the rectangle to invalidate.
10610     * @param top The top coordinate of the rectangle to invalidate.
10611     * @param right The right coordinate of the rectangle to invalidate.
10612     * @param bottom The bottom coordinate of the rectangle to invalidate.
10613     *
10614     * @see #invalidate(int, int, int, int)
10615     * @see #invalidate(Rect)
10616     */
10617    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10618        // We try only with the AttachInfo because there's no point in invalidating
10619        // if we are not attached to our window
10620        final AttachInfo attachInfo = mAttachInfo;
10621        if (attachInfo != null) {
10622            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10623            info.target = this;
10624            info.left = left;
10625            info.top = top;
10626            info.right = right;
10627            info.bottom = bottom;
10628
10629            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10630        }
10631    }
10632
10633    /**
10634     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10635     * This event is sent at most once every
10636     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10637     */
10638    private void postSendViewScrolledAccessibilityEventCallback() {
10639        if (mSendViewScrolledAccessibilityEvent == null) {
10640            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10641        }
10642        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10643            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10644            postDelayed(mSendViewScrolledAccessibilityEvent,
10645                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10646        }
10647    }
10648
10649    /**
10650     * Called by a parent to request that a child update its values for mScrollX
10651     * and mScrollY if necessary. This will typically be done if the child is
10652     * animating a scroll using a {@link android.widget.Scroller Scroller}
10653     * object.
10654     */
10655    public void computeScroll() {
10656    }
10657
10658    /**
10659     * <p>Indicate whether the horizontal edges are faded when the view is
10660     * scrolled horizontally.</p>
10661     *
10662     * @return true if the horizontal edges should are faded on scroll, false
10663     *         otherwise
10664     *
10665     * @see #setHorizontalFadingEdgeEnabled(boolean)
10666     *
10667     * @attr ref android.R.styleable#View_requiresFadingEdge
10668     */
10669    public boolean isHorizontalFadingEdgeEnabled() {
10670        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10671    }
10672
10673    /**
10674     * <p>Define whether the horizontal edges should be faded when this view
10675     * is scrolled horizontally.</p>
10676     *
10677     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10678     *                                    be faded when the view is scrolled
10679     *                                    horizontally
10680     *
10681     * @see #isHorizontalFadingEdgeEnabled()
10682     *
10683     * @attr ref android.R.styleable#View_requiresFadingEdge
10684     */
10685    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10686        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10687            if (horizontalFadingEdgeEnabled) {
10688                initScrollCache();
10689            }
10690
10691            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10692        }
10693    }
10694
10695    /**
10696     * <p>Indicate whether the vertical edges are faded when the view is
10697     * scrolled horizontally.</p>
10698     *
10699     * @return true if the vertical edges should are faded on scroll, false
10700     *         otherwise
10701     *
10702     * @see #setVerticalFadingEdgeEnabled(boolean)
10703     *
10704     * @attr ref android.R.styleable#View_requiresFadingEdge
10705     */
10706    public boolean isVerticalFadingEdgeEnabled() {
10707        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10708    }
10709
10710    /**
10711     * <p>Define whether the vertical edges should be faded when this view
10712     * is scrolled vertically.</p>
10713     *
10714     * @param verticalFadingEdgeEnabled true if the vertical edges should
10715     *                                  be faded when the view is scrolled
10716     *                                  vertically
10717     *
10718     * @see #isVerticalFadingEdgeEnabled()
10719     *
10720     * @attr ref android.R.styleable#View_requiresFadingEdge
10721     */
10722    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10723        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10724            if (verticalFadingEdgeEnabled) {
10725                initScrollCache();
10726            }
10727
10728            mViewFlags ^= FADING_EDGE_VERTICAL;
10729        }
10730    }
10731
10732    /**
10733     * Returns the strength, or intensity, of the top faded edge. The strength is
10734     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10735     * returns 0.0 or 1.0 but no value in between.
10736     *
10737     * Subclasses should override this method to provide a smoother fade transition
10738     * when scrolling occurs.
10739     *
10740     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10741     */
10742    protected float getTopFadingEdgeStrength() {
10743        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10744    }
10745
10746    /**
10747     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10748     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10749     * returns 0.0 or 1.0 but no value in between.
10750     *
10751     * Subclasses should override this method to provide a smoother fade transition
10752     * when scrolling occurs.
10753     *
10754     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10755     */
10756    protected float getBottomFadingEdgeStrength() {
10757        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10758                computeVerticalScrollRange() ? 1.0f : 0.0f;
10759    }
10760
10761    /**
10762     * Returns the strength, or intensity, of the left faded edge. The strength is
10763     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10764     * returns 0.0 or 1.0 but no value in between.
10765     *
10766     * Subclasses should override this method to provide a smoother fade transition
10767     * when scrolling occurs.
10768     *
10769     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10770     */
10771    protected float getLeftFadingEdgeStrength() {
10772        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10773    }
10774
10775    /**
10776     * Returns the strength, or intensity, of the right faded edge. The strength is
10777     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10778     * returns 0.0 or 1.0 but no value in between.
10779     *
10780     * Subclasses should override this method to provide a smoother fade transition
10781     * when scrolling occurs.
10782     *
10783     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10784     */
10785    protected float getRightFadingEdgeStrength() {
10786        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10787                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10788    }
10789
10790    /**
10791     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10792     * scrollbar is not drawn by default.</p>
10793     *
10794     * @return true if the horizontal scrollbar should be painted, false
10795     *         otherwise
10796     *
10797     * @see #setHorizontalScrollBarEnabled(boolean)
10798     */
10799    public boolean isHorizontalScrollBarEnabled() {
10800        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10801    }
10802
10803    /**
10804     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10805     * scrollbar is not drawn by default.</p>
10806     *
10807     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10808     *                                   be painted
10809     *
10810     * @see #isHorizontalScrollBarEnabled()
10811     */
10812    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10813        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10814            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10815            computeOpaqueFlags();
10816            resolvePadding();
10817        }
10818    }
10819
10820    /**
10821     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10822     * scrollbar is not drawn by default.</p>
10823     *
10824     * @return true if the vertical scrollbar should be painted, false
10825     *         otherwise
10826     *
10827     * @see #setVerticalScrollBarEnabled(boolean)
10828     */
10829    public boolean isVerticalScrollBarEnabled() {
10830        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10831    }
10832
10833    /**
10834     * <p>Define whether the vertical scrollbar should be drawn or not. The
10835     * scrollbar is not drawn by default.</p>
10836     *
10837     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10838     *                                 be painted
10839     *
10840     * @see #isVerticalScrollBarEnabled()
10841     */
10842    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10843        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10844            mViewFlags ^= SCROLLBARS_VERTICAL;
10845            computeOpaqueFlags();
10846            resolvePadding();
10847        }
10848    }
10849
10850    /**
10851     * @hide
10852     */
10853    protected void recomputePadding() {
10854        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10855    }
10856
10857    /**
10858     * Define whether scrollbars will fade when the view is not scrolling.
10859     *
10860     * @param fadeScrollbars wheter to enable fading
10861     *
10862     * @attr ref android.R.styleable#View_fadeScrollbars
10863     */
10864    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10865        initScrollCache();
10866        final ScrollabilityCache scrollabilityCache = mScrollCache;
10867        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10868        if (fadeScrollbars) {
10869            scrollabilityCache.state = ScrollabilityCache.OFF;
10870        } else {
10871            scrollabilityCache.state = ScrollabilityCache.ON;
10872        }
10873    }
10874
10875    /**
10876     *
10877     * Returns true if scrollbars will fade when this view is not scrolling
10878     *
10879     * @return true if scrollbar fading is enabled
10880     *
10881     * @attr ref android.R.styleable#View_fadeScrollbars
10882     */
10883    public boolean isScrollbarFadingEnabled() {
10884        return mScrollCache != null && mScrollCache.fadeScrollBars;
10885    }
10886
10887    /**
10888     *
10889     * Returns the delay before scrollbars fade.
10890     *
10891     * @return the delay before scrollbars fade
10892     *
10893     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10894     */
10895    public int getScrollBarDefaultDelayBeforeFade() {
10896        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10897                mScrollCache.scrollBarDefaultDelayBeforeFade;
10898    }
10899
10900    /**
10901     * Define the delay before scrollbars fade.
10902     *
10903     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10904     *
10905     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10906     */
10907    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10908        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10909    }
10910
10911    /**
10912     *
10913     * Returns the scrollbar fade duration.
10914     *
10915     * @return the scrollbar fade duration
10916     *
10917     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10918     */
10919    public int getScrollBarFadeDuration() {
10920        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10921                mScrollCache.scrollBarFadeDuration;
10922    }
10923
10924    /**
10925     * Define the scrollbar fade duration.
10926     *
10927     * @param scrollBarFadeDuration - the scrollbar fade duration
10928     *
10929     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10930     */
10931    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10932        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10933    }
10934
10935    /**
10936     *
10937     * Returns the scrollbar size.
10938     *
10939     * @return the scrollbar size
10940     *
10941     * @attr ref android.R.styleable#View_scrollbarSize
10942     */
10943    public int getScrollBarSize() {
10944        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10945                mScrollCache.scrollBarSize;
10946    }
10947
10948    /**
10949     * Define the scrollbar size.
10950     *
10951     * @param scrollBarSize - the scrollbar size
10952     *
10953     * @attr ref android.R.styleable#View_scrollbarSize
10954     */
10955    public void setScrollBarSize(int scrollBarSize) {
10956        getScrollCache().scrollBarSize = scrollBarSize;
10957    }
10958
10959    /**
10960     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10961     * inset. When inset, they add to the padding of the view. And the scrollbars
10962     * can be drawn inside the padding area or on the edge of the view. For example,
10963     * if a view has a background drawable and you want to draw the scrollbars
10964     * inside the padding specified by the drawable, you can use
10965     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10966     * appear at the edge of the view, ignoring the padding, then you can use
10967     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10968     * @param style the style of the scrollbars. Should be one of
10969     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10970     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10971     * @see #SCROLLBARS_INSIDE_OVERLAY
10972     * @see #SCROLLBARS_INSIDE_INSET
10973     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10974     * @see #SCROLLBARS_OUTSIDE_INSET
10975     *
10976     * @attr ref android.R.styleable#View_scrollbarStyle
10977     */
10978    public void setScrollBarStyle(int style) {
10979        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10980            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10981            computeOpaqueFlags();
10982            resolvePadding();
10983        }
10984    }
10985
10986    /**
10987     * <p>Returns the current scrollbar style.</p>
10988     * @return the current scrollbar style
10989     * @see #SCROLLBARS_INSIDE_OVERLAY
10990     * @see #SCROLLBARS_INSIDE_INSET
10991     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10992     * @see #SCROLLBARS_OUTSIDE_INSET
10993     *
10994     * @attr ref android.R.styleable#View_scrollbarStyle
10995     */
10996    @ViewDebug.ExportedProperty(mapping = {
10997            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10998            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10999            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11000            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11001    })
11002    public int getScrollBarStyle() {
11003        return mViewFlags & SCROLLBARS_STYLE_MASK;
11004    }
11005
11006    /**
11007     * <p>Compute the horizontal range that the horizontal scrollbar
11008     * represents.</p>
11009     *
11010     * <p>The range is expressed in arbitrary units that must be the same as the
11011     * units used by {@link #computeHorizontalScrollExtent()} and
11012     * {@link #computeHorizontalScrollOffset()}.</p>
11013     *
11014     * <p>The default range is the drawing width of this view.</p>
11015     *
11016     * @return the total horizontal range represented by the horizontal
11017     *         scrollbar
11018     *
11019     * @see #computeHorizontalScrollExtent()
11020     * @see #computeHorizontalScrollOffset()
11021     * @see android.widget.ScrollBarDrawable
11022     */
11023    protected int computeHorizontalScrollRange() {
11024        return getWidth();
11025    }
11026
11027    /**
11028     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11029     * within the horizontal range. This value is used to compute the position
11030     * of the thumb within the scrollbar's track.</p>
11031     *
11032     * <p>The range is expressed in arbitrary units that must be the same as the
11033     * units used by {@link #computeHorizontalScrollRange()} and
11034     * {@link #computeHorizontalScrollExtent()}.</p>
11035     *
11036     * <p>The default offset is the scroll offset of this view.</p>
11037     *
11038     * @return the horizontal offset of the scrollbar's thumb
11039     *
11040     * @see #computeHorizontalScrollRange()
11041     * @see #computeHorizontalScrollExtent()
11042     * @see android.widget.ScrollBarDrawable
11043     */
11044    protected int computeHorizontalScrollOffset() {
11045        return mScrollX;
11046    }
11047
11048    /**
11049     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11050     * within the horizontal range. This value is used to compute the length
11051     * of the thumb within the scrollbar's track.</p>
11052     *
11053     * <p>The range is expressed in arbitrary units that must be the same as the
11054     * units used by {@link #computeHorizontalScrollRange()} and
11055     * {@link #computeHorizontalScrollOffset()}.</p>
11056     *
11057     * <p>The default extent is the drawing width of this view.</p>
11058     *
11059     * @return the horizontal extent of the scrollbar's thumb
11060     *
11061     * @see #computeHorizontalScrollRange()
11062     * @see #computeHorizontalScrollOffset()
11063     * @see android.widget.ScrollBarDrawable
11064     */
11065    protected int computeHorizontalScrollExtent() {
11066        return getWidth();
11067    }
11068
11069    /**
11070     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11071     *
11072     * <p>The range is expressed in arbitrary units that must be the same as the
11073     * units used by {@link #computeVerticalScrollExtent()} and
11074     * {@link #computeVerticalScrollOffset()}.</p>
11075     *
11076     * @return the total vertical range represented by the vertical scrollbar
11077     *
11078     * <p>The default range is the drawing height of this view.</p>
11079     *
11080     * @see #computeVerticalScrollExtent()
11081     * @see #computeVerticalScrollOffset()
11082     * @see android.widget.ScrollBarDrawable
11083     */
11084    protected int computeVerticalScrollRange() {
11085        return getHeight();
11086    }
11087
11088    /**
11089     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11090     * within the horizontal range. This value is used to compute the position
11091     * of the thumb within the scrollbar's track.</p>
11092     *
11093     * <p>The range is expressed in arbitrary units that must be the same as the
11094     * units used by {@link #computeVerticalScrollRange()} and
11095     * {@link #computeVerticalScrollExtent()}.</p>
11096     *
11097     * <p>The default offset is the scroll offset of this view.</p>
11098     *
11099     * @return the vertical offset of the scrollbar's thumb
11100     *
11101     * @see #computeVerticalScrollRange()
11102     * @see #computeVerticalScrollExtent()
11103     * @see android.widget.ScrollBarDrawable
11104     */
11105    protected int computeVerticalScrollOffset() {
11106        return mScrollY;
11107    }
11108
11109    /**
11110     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11111     * within the vertical range. This value is used to compute the length
11112     * of the thumb within the scrollbar's track.</p>
11113     *
11114     * <p>The range is expressed in arbitrary units that must be the same as the
11115     * units used by {@link #computeVerticalScrollRange()} and
11116     * {@link #computeVerticalScrollOffset()}.</p>
11117     *
11118     * <p>The default extent is the drawing height of this view.</p>
11119     *
11120     * @return the vertical extent of the scrollbar's thumb
11121     *
11122     * @see #computeVerticalScrollRange()
11123     * @see #computeVerticalScrollOffset()
11124     * @see android.widget.ScrollBarDrawable
11125     */
11126    protected int computeVerticalScrollExtent() {
11127        return getHeight();
11128    }
11129
11130    /**
11131     * Check if this view can be scrolled horizontally in a certain direction.
11132     *
11133     * @param direction Negative to check scrolling left, positive to check scrolling right.
11134     * @return true if this view can be scrolled in the specified direction, false otherwise.
11135     */
11136    public boolean canScrollHorizontally(int direction) {
11137        final int offset = computeHorizontalScrollOffset();
11138        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11139        if (range == 0) return false;
11140        if (direction < 0) {
11141            return offset > 0;
11142        } else {
11143            return offset < range - 1;
11144        }
11145    }
11146
11147    /**
11148     * Check if this view can be scrolled vertically in a certain direction.
11149     *
11150     * @param direction Negative to check scrolling up, positive to check scrolling down.
11151     * @return true if this view can be scrolled in the specified direction, false otherwise.
11152     */
11153    public boolean canScrollVertically(int direction) {
11154        final int offset = computeVerticalScrollOffset();
11155        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11156        if (range == 0) return false;
11157        if (direction < 0) {
11158            return offset > 0;
11159        } else {
11160            return offset < range - 1;
11161        }
11162    }
11163
11164    /**
11165     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11166     * scrollbars are painted only if they have been awakened first.</p>
11167     *
11168     * @param canvas the canvas on which to draw the scrollbars
11169     *
11170     * @see #awakenScrollBars(int)
11171     */
11172    protected final void onDrawScrollBars(Canvas canvas) {
11173        // scrollbars are drawn only when the animation is running
11174        final ScrollabilityCache cache = mScrollCache;
11175        if (cache != null) {
11176
11177            int state = cache.state;
11178
11179            if (state == ScrollabilityCache.OFF) {
11180                return;
11181            }
11182
11183            boolean invalidate = false;
11184
11185            if (state == ScrollabilityCache.FADING) {
11186                // We're fading -- get our fade interpolation
11187                if (cache.interpolatorValues == null) {
11188                    cache.interpolatorValues = new float[1];
11189                }
11190
11191                float[] values = cache.interpolatorValues;
11192
11193                // Stops the animation if we're done
11194                if (cache.scrollBarInterpolator.timeToValues(values) ==
11195                        Interpolator.Result.FREEZE_END) {
11196                    cache.state = ScrollabilityCache.OFF;
11197                } else {
11198                    cache.scrollBar.setAlpha(Math.round(values[0]));
11199                }
11200
11201                // This will make the scroll bars inval themselves after
11202                // drawing. We only want this when we're fading so that
11203                // we prevent excessive redraws
11204                invalidate = true;
11205            } else {
11206                // We're just on -- but we may have been fading before so
11207                // reset alpha
11208                cache.scrollBar.setAlpha(255);
11209            }
11210
11211
11212            final int viewFlags = mViewFlags;
11213
11214            final boolean drawHorizontalScrollBar =
11215                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11216            final boolean drawVerticalScrollBar =
11217                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11218                && !isVerticalScrollBarHidden();
11219
11220            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11221                final int width = mRight - mLeft;
11222                final int height = mBottom - mTop;
11223
11224                final ScrollBarDrawable scrollBar = cache.scrollBar;
11225
11226                final int scrollX = mScrollX;
11227                final int scrollY = mScrollY;
11228                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11229
11230                int left, top, right, bottom;
11231
11232                if (drawHorizontalScrollBar) {
11233                    int size = scrollBar.getSize(false);
11234                    if (size <= 0) {
11235                        size = cache.scrollBarSize;
11236                    }
11237
11238                    scrollBar.setParameters(computeHorizontalScrollRange(),
11239                                            computeHorizontalScrollOffset(),
11240                                            computeHorizontalScrollExtent(), false);
11241                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11242                            getVerticalScrollbarWidth() : 0;
11243                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11244                    left = scrollX + (mPaddingLeft & inside);
11245                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11246                    bottom = top + size;
11247                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11248                    if (invalidate) {
11249                        invalidate(left, top, right, bottom);
11250                    }
11251                }
11252
11253                if (drawVerticalScrollBar) {
11254                    int size = scrollBar.getSize(true);
11255                    if (size <= 0) {
11256                        size = cache.scrollBarSize;
11257                    }
11258
11259                    scrollBar.setParameters(computeVerticalScrollRange(),
11260                                            computeVerticalScrollOffset(),
11261                                            computeVerticalScrollExtent(), true);
11262                    switch (mVerticalScrollbarPosition) {
11263                        default:
11264                        case SCROLLBAR_POSITION_DEFAULT:
11265                        case SCROLLBAR_POSITION_RIGHT:
11266                            left = scrollX + width - size - (mUserPaddingRight & inside);
11267                            break;
11268                        case SCROLLBAR_POSITION_LEFT:
11269                            left = scrollX + (mUserPaddingLeft & inside);
11270                            break;
11271                    }
11272                    top = scrollY + (mPaddingTop & inside);
11273                    right = left + size;
11274                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11275                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11276                    if (invalidate) {
11277                        invalidate(left, top, right, bottom);
11278                    }
11279                }
11280            }
11281        }
11282    }
11283
11284    /**
11285     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11286     * FastScroller is visible.
11287     * @return whether to temporarily hide the vertical scrollbar
11288     * @hide
11289     */
11290    protected boolean isVerticalScrollBarHidden() {
11291        return false;
11292    }
11293
11294    /**
11295     * <p>Draw the horizontal scrollbar if
11296     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11297     *
11298     * @param canvas the canvas on which to draw the scrollbar
11299     * @param scrollBar the scrollbar's drawable
11300     *
11301     * @see #isHorizontalScrollBarEnabled()
11302     * @see #computeHorizontalScrollRange()
11303     * @see #computeHorizontalScrollExtent()
11304     * @see #computeHorizontalScrollOffset()
11305     * @see android.widget.ScrollBarDrawable
11306     * @hide
11307     */
11308    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11309            int l, int t, int r, int b) {
11310        scrollBar.setBounds(l, t, r, b);
11311        scrollBar.draw(canvas);
11312    }
11313
11314    /**
11315     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11316     * returns true.</p>
11317     *
11318     * @param canvas the canvas on which to draw the scrollbar
11319     * @param scrollBar the scrollbar's drawable
11320     *
11321     * @see #isVerticalScrollBarEnabled()
11322     * @see #computeVerticalScrollRange()
11323     * @see #computeVerticalScrollExtent()
11324     * @see #computeVerticalScrollOffset()
11325     * @see android.widget.ScrollBarDrawable
11326     * @hide
11327     */
11328    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11329            int l, int t, int r, int b) {
11330        scrollBar.setBounds(l, t, r, b);
11331        scrollBar.draw(canvas);
11332    }
11333
11334    /**
11335     * Implement this to do your drawing.
11336     *
11337     * @param canvas the canvas on which the background will be drawn
11338     */
11339    protected void onDraw(Canvas canvas) {
11340    }
11341
11342    /*
11343     * Caller is responsible for calling requestLayout if necessary.
11344     * (This allows addViewInLayout to not request a new layout.)
11345     */
11346    void assignParent(ViewParent parent) {
11347        if (mParent == null) {
11348            mParent = parent;
11349        } else if (parent == null) {
11350            mParent = null;
11351        } else {
11352            throw new RuntimeException("view " + this + " being added, but"
11353                    + " it already has a parent");
11354        }
11355    }
11356
11357    /**
11358     * This is called when the view is attached to a window.  At this point it
11359     * has a Surface and will start drawing.  Note that this function is
11360     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11361     * however it may be called any time before the first onDraw -- including
11362     * before or after {@link #onMeasure(int, int)}.
11363     *
11364     * @see #onDetachedFromWindow()
11365     */
11366    protected void onAttachedToWindow() {
11367        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11368            mParent.requestTransparentRegion(this);
11369        }
11370
11371        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11372            initialAwakenScrollBars();
11373            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11374        }
11375
11376        jumpDrawablesToCurrentState();
11377
11378        // Order is important here: LayoutDirection MUST be resolved before Padding
11379        // and TextDirection
11380        resolveLayoutDirection();
11381        resolvePadding();
11382        resolveTextDirection();
11383        resolveTextAlignment();
11384
11385        clearAccessibilityFocus();
11386        if (isFocused()) {
11387            InputMethodManager imm = InputMethodManager.peekInstance();
11388            imm.focusIn(this);
11389        }
11390
11391        if (mAttachInfo != null && mDisplayList != null) {
11392            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11393        }
11394    }
11395
11396    /**
11397     * @see #onScreenStateChanged(int)
11398     */
11399    void dispatchScreenStateChanged(int screenState) {
11400        onScreenStateChanged(screenState);
11401    }
11402
11403    /**
11404     * This method is called whenever the state of the screen this view is
11405     * attached to changes. A state change will usually occurs when the screen
11406     * turns on or off (whether it happens automatically or the user does it
11407     * manually.)
11408     *
11409     * @param screenState The new state of the screen. Can be either
11410     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11411     */
11412    public void onScreenStateChanged(int screenState) {
11413    }
11414
11415    /**
11416     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11417     */
11418    private boolean hasRtlSupport() {
11419        return mContext.getApplicationInfo().hasRtlSupport();
11420    }
11421
11422    /**
11423     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11424     * that the parent directionality can and will be resolved before its children.
11425     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11426     */
11427    public void resolveLayoutDirection() {
11428        // Clear any previous layout direction resolution
11429        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11430
11431        if (hasRtlSupport()) {
11432            // Set resolved depending on layout direction
11433            switch (getLayoutDirection()) {
11434                case LAYOUT_DIRECTION_INHERIT:
11435                    // If this is root view, no need to look at parent's layout dir.
11436                    if (canResolveLayoutDirection()) {
11437                        ViewGroup viewGroup = ((ViewGroup) mParent);
11438
11439                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11440                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11441                        }
11442                    } else {
11443                        // Nothing to do, LTR by default
11444                    }
11445                    break;
11446                case LAYOUT_DIRECTION_RTL:
11447                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11448                    break;
11449                case LAYOUT_DIRECTION_LOCALE:
11450                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11451                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11452                    }
11453                    break;
11454                default:
11455                    // Nothing to do, LTR by default
11456            }
11457        }
11458
11459        // Set to resolved
11460        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11461        onResolvedLayoutDirectionChanged();
11462        // Resolve padding
11463        resolvePadding();
11464    }
11465
11466    /**
11467     * Called when layout direction has been resolved.
11468     *
11469     * The default implementation does nothing.
11470     */
11471    public void onResolvedLayoutDirectionChanged() {
11472    }
11473
11474    /**
11475     * Resolve padding depending on layout direction.
11476     */
11477    public void resolvePadding() {
11478        // If the user specified the absolute padding (either with android:padding or
11479        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11480        // use the default padding or the padding from the background drawable
11481        // (stored at this point in mPadding*)
11482        int resolvedLayoutDirection = getResolvedLayoutDirection();
11483        switch (resolvedLayoutDirection) {
11484            case LAYOUT_DIRECTION_RTL:
11485                // Start user padding override Right user padding. Otherwise, if Right user
11486                // padding is not defined, use the default Right padding. If Right user padding
11487                // is defined, just use it.
11488                if (mUserPaddingStart >= 0) {
11489                    mUserPaddingRight = mUserPaddingStart;
11490                } else if (mUserPaddingRight < 0) {
11491                    mUserPaddingRight = mPaddingRight;
11492                }
11493                if (mUserPaddingEnd >= 0) {
11494                    mUserPaddingLeft = mUserPaddingEnd;
11495                } else if (mUserPaddingLeft < 0) {
11496                    mUserPaddingLeft = mPaddingLeft;
11497                }
11498                break;
11499            case LAYOUT_DIRECTION_LTR:
11500            default:
11501                // Start user padding override Left user padding. Otherwise, if Left user
11502                // padding is not defined, use the default left padding. If Left user padding
11503                // is defined, just use it.
11504                if (mUserPaddingStart >= 0) {
11505                    mUserPaddingLeft = mUserPaddingStart;
11506                } else if (mUserPaddingLeft < 0) {
11507                    mUserPaddingLeft = mPaddingLeft;
11508                }
11509                if (mUserPaddingEnd >= 0) {
11510                    mUserPaddingRight = mUserPaddingEnd;
11511                } else if (mUserPaddingRight < 0) {
11512                    mUserPaddingRight = mPaddingRight;
11513                }
11514        }
11515
11516        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11517
11518        if(isPaddingRelative()) {
11519            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11520        } else {
11521            recomputePadding();
11522        }
11523        onPaddingChanged(resolvedLayoutDirection);
11524    }
11525
11526    /**
11527     * Resolve padding depending on the layout direction. Subclasses that care about
11528     * padding resolution should override this method. The default implementation does
11529     * nothing.
11530     *
11531     * @param layoutDirection the direction of the layout
11532     *
11533     * @see {@link #LAYOUT_DIRECTION_LTR}
11534     * @see {@link #LAYOUT_DIRECTION_RTL}
11535     */
11536    public void onPaddingChanged(int layoutDirection) {
11537    }
11538
11539    /**
11540     * Check if layout direction resolution can be done.
11541     *
11542     * @return true if layout direction resolution can be done otherwise return false.
11543     */
11544    public boolean canResolveLayoutDirection() {
11545        switch (getLayoutDirection()) {
11546            case LAYOUT_DIRECTION_INHERIT:
11547                return (mParent != null) && (mParent instanceof ViewGroup);
11548            default:
11549                return true;
11550        }
11551    }
11552
11553    /**
11554     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11555     * when reset is done.
11556     */
11557    public void resetResolvedLayoutDirection() {
11558        // Reset the current resolved bits
11559        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11560        onResolvedLayoutDirectionReset();
11561        // Reset also the text direction
11562        resetResolvedTextDirection();
11563    }
11564
11565    /**
11566     * Called during reset of resolved layout direction.
11567     *
11568     * Subclasses need to override this method to clear cached information that depends on the
11569     * resolved layout direction, or to inform child views that inherit their layout direction.
11570     *
11571     * The default implementation does nothing.
11572     */
11573    public void onResolvedLayoutDirectionReset() {
11574    }
11575
11576    /**
11577     * Check if a Locale uses an RTL script.
11578     *
11579     * @param locale Locale to check
11580     * @return true if the Locale uses an RTL script.
11581     */
11582    protected static boolean isLayoutDirectionRtl(Locale locale) {
11583        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11584    }
11585
11586    /**
11587     * This is called when the view is detached from a window.  At this point it
11588     * no longer has a surface for drawing.
11589     *
11590     * @see #onAttachedToWindow()
11591     */
11592    protected void onDetachedFromWindow() {
11593        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11594
11595        removeUnsetPressCallback();
11596        removeLongPressCallback();
11597        removePerformClickCallback();
11598        removeSendViewScrolledAccessibilityEventCallback();
11599
11600        destroyDrawingCache();
11601
11602        destroyLayer(false);
11603
11604        if (mAttachInfo != null) {
11605            if (mDisplayList != null) {
11606                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11607            }
11608            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11609        } else {
11610            // Should never happen
11611            clearDisplayList();
11612        }
11613
11614        mCurrentAnimation = null;
11615
11616        resetResolvedLayoutDirection();
11617        resetResolvedTextAlignment();
11618        resetAccessibilityStateChanged();
11619    }
11620
11621    /**
11622     * @return The number of times this view has been attached to a window
11623     */
11624    protected int getWindowAttachCount() {
11625        return mWindowAttachCount;
11626    }
11627
11628    /**
11629     * Retrieve a unique token identifying the window this view is attached to.
11630     * @return Return the window's token for use in
11631     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11632     */
11633    public IBinder getWindowToken() {
11634        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11635    }
11636
11637    /**
11638     * Retrieve a unique token identifying the top-level "real" window of
11639     * the window that this view is attached to.  That is, this is like
11640     * {@link #getWindowToken}, except if the window this view in is a panel
11641     * window (attached to another containing window), then the token of
11642     * the containing window is returned instead.
11643     *
11644     * @return Returns the associated window token, either
11645     * {@link #getWindowToken()} or the containing window's token.
11646     */
11647    public IBinder getApplicationWindowToken() {
11648        AttachInfo ai = mAttachInfo;
11649        if (ai != null) {
11650            IBinder appWindowToken = ai.mPanelParentWindowToken;
11651            if (appWindowToken == null) {
11652                appWindowToken = ai.mWindowToken;
11653            }
11654            return appWindowToken;
11655        }
11656        return null;
11657    }
11658
11659    /**
11660     * Retrieve private session object this view hierarchy is using to
11661     * communicate with the window manager.
11662     * @return the session object to communicate with the window manager
11663     */
11664    /*package*/ IWindowSession getWindowSession() {
11665        return mAttachInfo != null ? mAttachInfo.mSession : null;
11666    }
11667
11668    /**
11669     * @param info the {@link android.view.View.AttachInfo} to associated with
11670     *        this view
11671     */
11672    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11673        //System.out.println("Attached! " + this);
11674        mAttachInfo = info;
11675        mWindowAttachCount++;
11676        // We will need to evaluate the drawable state at least once.
11677        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11678        if (mFloatingTreeObserver != null) {
11679            info.mTreeObserver.merge(mFloatingTreeObserver);
11680            mFloatingTreeObserver = null;
11681        }
11682        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11683            mAttachInfo.mScrollContainers.add(this);
11684            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11685        }
11686        performCollectViewAttributes(mAttachInfo, visibility);
11687        onAttachedToWindow();
11688
11689        ListenerInfo li = mListenerInfo;
11690        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11691                li != null ? li.mOnAttachStateChangeListeners : null;
11692        if (listeners != null && listeners.size() > 0) {
11693            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11694            // perform the dispatching. The iterator is a safe guard against listeners that
11695            // could mutate the list by calling the various add/remove methods. This prevents
11696            // the array from being modified while we iterate it.
11697            for (OnAttachStateChangeListener listener : listeners) {
11698                listener.onViewAttachedToWindow(this);
11699            }
11700        }
11701
11702        int vis = info.mWindowVisibility;
11703        if (vis != GONE) {
11704            onWindowVisibilityChanged(vis);
11705        }
11706        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11707            // If nobody has evaluated the drawable state yet, then do it now.
11708            refreshDrawableState();
11709        }
11710    }
11711
11712    void dispatchDetachedFromWindow() {
11713        AttachInfo info = mAttachInfo;
11714        if (info != null) {
11715            int vis = info.mWindowVisibility;
11716            if (vis != GONE) {
11717                onWindowVisibilityChanged(GONE);
11718            }
11719        }
11720
11721        onDetachedFromWindow();
11722
11723        ListenerInfo li = mListenerInfo;
11724        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11725                li != null ? li.mOnAttachStateChangeListeners : null;
11726        if (listeners != null && listeners.size() > 0) {
11727            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11728            // perform the dispatching. The iterator is a safe guard against listeners that
11729            // could mutate the list by calling the various add/remove methods. This prevents
11730            // the array from being modified while we iterate it.
11731            for (OnAttachStateChangeListener listener : listeners) {
11732                listener.onViewDetachedFromWindow(this);
11733            }
11734        }
11735
11736        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11737            mAttachInfo.mScrollContainers.remove(this);
11738            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11739        }
11740
11741        mAttachInfo = null;
11742    }
11743
11744    /**
11745     * Store this view hierarchy's frozen state into the given container.
11746     *
11747     * @param container The SparseArray in which to save the view's state.
11748     *
11749     * @see #restoreHierarchyState(android.util.SparseArray)
11750     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11751     * @see #onSaveInstanceState()
11752     */
11753    public void saveHierarchyState(SparseArray<Parcelable> container) {
11754        dispatchSaveInstanceState(container);
11755    }
11756
11757    /**
11758     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11759     * this view and its children. May be overridden to modify how freezing happens to a
11760     * view's children; for example, some views may want to not store state for their children.
11761     *
11762     * @param container The SparseArray in which to save the view's state.
11763     *
11764     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11765     * @see #saveHierarchyState(android.util.SparseArray)
11766     * @see #onSaveInstanceState()
11767     */
11768    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11769        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11770            mPrivateFlags &= ~SAVE_STATE_CALLED;
11771            Parcelable state = onSaveInstanceState();
11772            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11773                throw new IllegalStateException(
11774                        "Derived class did not call super.onSaveInstanceState()");
11775            }
11776            if (state != null) {
11777                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11778                // + ": " + state);
11779                container.put(mID, state);
11780            }
11781        }
11782    }
11783
11784    /**
11785     * Hook allowing a view to generate a representation of its internal state
11786     * that can later be used to create a new instance with that same state.
11787     * This state should only contain information that is not persistent or can
11788     * not be reconstructed later. For example, you will never store your
11789     * current position on screen because that will be computed again when a
11790     * new instance of the view is placed in its view hierarchy.
11791     * <p>
11792     * Some examples of things you may store here: the current cursor position
11793     * in a text view (but usually not the text itself since that is stored in a
11794     * content provider or other persistent storage), the currently selected
11795     * item in a list view.
11796     *
11797     * @return Returns a Parcelable object containing the view's current dynamic
11798     *         state, or null if there is nothing interesting to save. The
11799     *         default implementation returns null.
11800     * @see #onRestoreInstanceState(android.os.Parcelable)
11801     * @see #saveHierarchyState(android.util.SparseArray)
11802     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11803     * @see #setSaveEnabled(boolean)
11804     */
11805    protected Parcelable onSaveInstanceState() {
11806        mPrivateFlags |= SAVE_STATE_CALLED;
11807        return BaseSavedState.EMPTY_STATE;
11808    }
11809
11810    /**
11811     * Restore this view hierarchy's frozen state from the given container.
11812     *
11813     * @param container The SparseArray which holds previously frozen states.
11814     *
11815     * @see #saveHierarchyState(android.util.SparseArray)
11816     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11817     * @see #onRestoreInstanceState(android.os.Parcelable)
11818     */
11819    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11820        dispatchRestoreInstanceState(container);
11821    }
11822
11823    /**
11824     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11825     * state for this view and its children. May be overridden to modify how restoring
11826     * happens to a view's children; for example, some views may want to not store state
11827     * for their children.
11828     *
11829     * @param container The SparseArray which holds previously saved state.
11830     *
11831     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11832     * @see #restoreHierarchyState(android.util.SparseArray)
11833     * @see #onRestoreInstanceState(android.os.Parcelable)
11834     */
11835    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11836        if (mID != NO_ID) {
11837            Parcelable state = container.get(mID);
11838            if (state != null) {
11839                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11840                // + ": " + state);
11841                mPrivateFlags &= ~SAVE_STATE_CALLED;
11842                onRestoreInstanceState(state);
11843                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11844                    throw new IllegalStateException(
11845                            "Derived class did not call super.onRestoreInstanceState()");
11846                }
11847            }
11848        }
11849    }
11850
11851    /**
11852     * Hook allowing a view to re-apply a representation of its internal state that had previously
11853     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11854     * null state.
11855     *
11856     * @param state The frozen state that had previously been returned by
11857     *        {@link #onSaveInstanceState}.
11858     *
11859     * @see #onSaveInstanceState()
11860     * @see #restoreHierarchyState(android.util.SparseArray)
11861     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11862     */
11863    protected void onRestoreInstanceState(Parcelable state) {
11864        mPrivateFlags |= SAVE_STATE_CALLED;
11865        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11866            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11867                    + "received " + state.getClass().toString() + " instead. This usually happens "
11868                    + "when two views of different type have the same id in the same hierarchy. "
11869                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11870                    + "other views do not use the same id.");
11871        }
11872    }
11873
11874    /**
11875     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11876     *
11877     * @return the drawing start time in milliseconds
11878     */
11879    public long getDrawingTime() {
11880        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11881    }
11882
11883    /**
11884     * <p>Enables or disables the duplication of the parent's state into this view. When
11885     * duplication is enabled, this view gets its drawable state from its parent rather
11886     * than from its own internal properties.</p>
11887     *
11888     * <p>Note: in the current implementation, setting this property to true after the
11889     * view was added to a ViewGroup might have no effect at all. This property should
11890     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11891     *
11892     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11893     * property is enabled, an exception will be thrown.</p>
11894     *
11895     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11896     * parent, these states should not be affected by this method.</p>
11897     *
11898     * @param enabled True to enable duplication of the parent's drawable state, false
11899     *                to disable it.
11900     *
11901     * @see #getDrawableState()
11902     * @see #isDuplicateParentStateEnabled()
11903     */
11904    public void setDuplicateParentStateEnabled(boolean enabled) {
11905        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11906    }
11907
11908    /**
11909     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11910     *
11911     * @return True if this view's drawable state is duplicated from the parent,
11912     *         false otherwise
11913     *
11914     * @see #getDrawableState()
11915     * @see #setDuplicateParentStateEnabled(boolean)
11916     */
11917    public boolean isDuplicateParentStateEnabled() {
11918        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11919    }
11920
11921    /**
11922     * <p>Specifies the type of layer backing this view. The layer can be
11923     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11924     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11925     *
11926     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11927     * instance that controls how the layer is composed on screen. The following
11928     * properties of the paint are taken into account when composing the layer:</p>
11929     * <ul>
11930     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11931     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11932     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11933     * </ul>
11934     *
11935     * <p>If this view has an alpha value set to < 1.0 by calling
11936     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11937     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11938     * equivalent to setting a hardware layer on this view and providing a paint with
11939     * the desired alpha value.<p>
11940     *
11941     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11942     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11943     * for more information on when and how to use layers.</p>
11944     *
11945     * @param layerType The ype of layer to use with this view, must be one of
11946     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11947     *        {@link #LAYER_TYPE_HARDWARE}
11948     * @param paint The paint used to compose the layer. This argument is optional
11949     *        and can be null. It is ignored when the layer type is
11950     *        {@link #LAYER_TYPE_NONE}
11951     *
11952     * @see #getLayerType()
11953     * @see #LAYER_TYPE_NONE
11954     * @see #LAYER_TYPE_SOFTWARE
11955     * @see #LAYER_TYPE_HARDWARE
11956     * @see #setAlpha(float)
11957     *
11958     * @attr ref android.R.styleable#View_layerType
11959     */
11960    public void setLayerType(int layerType, Paint paint) {
11961        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11962            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11963                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11964        }
11965
11966        if (layerType == mLayerType) {
11967            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11968                mLayerPaint = paint == null ? new Paint() : paint;
11969                invalidateParentCaches();
11970                invalidate(true);
11971            }
11972            return;
11973        }
11974
11975        // Destroy any previous software drawing cache if needed
11976        switch (mLayerType) {
11977            case LAYER_TYPE_HARDWARE:
11978                destroyLayer(false);
11979                // fall through - non-accelerated views may use software layer mechanism instead
11980            case LAYER_TYPE_SOFTWARE:
11981                destroyDrawingCache();
11982                break;
11983            default:
11984                break;
11985        }
11986
11987        mLayerType = layerType;
11988        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11989        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11990        mLocalDirtyRect = layerDisabled ? null : new Rect();
11991
11992        invalidateParentCaches();
11993        invalidate(true);
11994    }
11995
11996    /**
11997     * Indicates whether this view has a static layer. A view with layer type
11998     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11999     * dynamic.
12000     */
12001    boolean hasStaticLayer() {
12002        return true;
12003    }
12004
12005    /**
12006     * Indicates what type of layer is currently associated with this view. By default
12007     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12008     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12009     * for more information on the different types of layers.
12010     *
12011     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12012     *         {@link #LAYER_TYPE_HARDWARE}
12013     *
12014     * @see #setLayerType(int, android.graphics.Paint)
12015     * @see #buildLayer()
12016     * @see #LAYER_TYPE_NONE
12017     * @see #LAYER_TYPE_SOFTWARE
12018     * @see #LAYER_TYPE_HARDWARE
12019     */
12020    public int getLayerType() {
12021        return mLayerType;
12022    }
12023
12024    /**
12025     * Forces this view's layer to be created and this view to be rendered
12026     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12027     * invoking this method will have no effect.
12028     *
12029     * This method can for instance be used to render a view into its layer before
12030     * starting an animation. If this view is complex, rendering into the layer
12031     * before starting the animation will avoid skipping frames.
12032     *
12033     * @throws IllegalStateException If this view is not attached to a window
12034     *
12035     * @see #setLayerType(int, android.graphics.Paint)
12036     */
12037    public void buildLayer() {
12038        if (mLayerType == LAYER_TYPE_NONE) return;
12039
12040        if (mAttachInfo == null) {
12041            throw new IllegalStateException("This view must be attached to a window first");
12042        }
12043
12044        switch (mLayerType) {
12045            case LAYER_TYPE_HARDWARE:
12046                if (mAttachInfo.mHardwareRenderer != null &&
12047                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12048                        mAttachInfo.mHardwareRenderer.validate()) {
12049                    getHardwareLayer();
12050                }
12051                break;
12052            case LAYER_TYPE_SOFTWARE:
12053                buildDrawingCache(true);
12054                break;
12055        }
12056    }
12057
12058    // Make sure the HardwareRenderer.validate() was invoked before calling this method
12059    void flushLayer() {
12060        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
12061            mHardwareLayer.flush();
12062        }
12063    }
12064
12065    /**
12066     * <p>Returns a hardware layer that can be used to draw this view again
12067     * without executing its draw method.</p>
12068     *
12069     * @return A HardwareLayer ready to render, or null if an error occurred.
12070     */
12071    HardwareLayer getHardwareLayer() {
12072        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12073                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12074            return null;
12075        }
12076
12077        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12078
12079        final int width = mRight - mLeft;
12080        final int height = mBottom - mTop;
12081
12082        if (width == 0 || height == 0) {
12083            return null;
12084        }
12085
12086        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12087            if (mHardwareLayer == null) {
12088                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12089                        width, height, isOpaque());
12090                mLocalDirtyRect.set(0, 0, width, height);
12091            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12092                mHardwareLayer.resize(width, height);
12093                mLocalDirtyRect.set(0, 0, width, height);
12094            }
12095
12096            // The layer is not valid if the underlying GPU resources cannot be allocated
12097            if (!mHardwareLayer.isValid()) {
12098                return null;
12099            }
12100
12101            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12102            mLocalDirtyRect.setEmpty();
12103        }
12104
12105        return mHardwareLayer;
12106    }
12107
12108    /**
12109     * Destroys this View's hardware layer if possible.
12110     *
12111     * @return True if the layer was destroyed, false otherwise.
12112     *
12113     * @see #setLayerType(int, android.graphics.Paint)
12114     * @see #LAYER_TYPE_HARDWARE
12115     */
12116    boolean destroyLayer(boolean valid) {
12117        if (mHardwareLayer != null) {
12118            AttachInfo info = mAttachInfo;
12119            if (info != null && info.mHardwareRenderer != null &&
12120                    info.mHardwareRenderer.isEnabled() &&
12121                    (valid || info.mHardwareRenderer.validate())) {
12122                mHardwareLayer.destroy();
12123                mHardwareLayer = null;
12124
12125                invalidate(true);
12126                invalidateParentCaches();
12127            }
12128            return true;
12129        }
12130        return false;
12131    }
12132
12133    /**
12134     * Destroys all hardware rendering resources. This method is invoked
12135     * when the system needs to reclaim resources. Upon execution of this
12136     * method, you should free any OpenGL resources created by the view.
12137     *
12138     * Note: you <strong>must</strong> call
12139     * <code>super.destroyHardwareResources()</code> when overriding
12140     * this method.
12141     *
12142     * @hide
12143     */
12144    protected void destroyHardwareResources() {
12145        destroyLayer(true);
12146    }
12147
12148    /**
12149     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12150     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12151     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12152     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12153     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12154     * null.</p>
12155     *
12156     * <p>Enabling the drawing cache is similar to
12157     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12158     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12159     * drawing cache has no effect on rendering because the system uses a different mechanism
12160     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12161     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12162     * for information on how to enable software and hardware layers.</p>
12163     *
12164     * <p>This API can be used to manually generate
12165     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12166     * {@link #getDrawingCache()}.</p>
12167     *
12168     * @param enabled true to enable the drawing cache, false otherwise
12169     *
12170     * @see #isDrawingCacheEnabled()
12171     * @see #getDrawingCache()
12172     * @see #buildDrawingCache()
12173     * @see #setLayerType(int, android.graphics.Paint)
12174     */
12175    public void setDrawingCacheEnabled(boolean enabled) {
12176        mCachingFailed = false;
12177        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12178    }
12179
12180    /**
12181     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12182     *
12183     * @return true if the drawing cache is enabled
12184     *
12185     * @see #setDrawingCacheEnabled(boolean)
12186     * @see #getDrawingCache()
12187     */
12188    @ViewDebug.ExportedProperty(category = "drawing")
12189    public boolean isDrawingCacheEnabled() {
12190        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12191    }
12192
12193    /**
12194     * Debugging utility which recursively outputs the dirty state of a view and its
12195     * descendants.
12196     *
12197     * @hide
12198     */
12199    @SuppressWarnings({"UnusedDeclaration"})
12200    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12201        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12202                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12203                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12204                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12205        if (clear) {
12206            mPrivateFlags &= clearMask;
12207        }
12208        if (this instanceof ViewGroup) {
12209            ViewGroup parent = (ViewGroup) this;
12210            final int count = parent.getChildCount();
12211            for (int i = 0; i < count; i++) {
12212                final View child = parent.getChildAt(i);
12213                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12214            }
12215        }
12216    }
12217
12218    /**
12219     * This method is used by ViewGroup to cause its children to restore or recreate their
12220     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12221     * to recreate its own display list, which would happen if it went through the normal
12222     * draw/dispatchDraw mechanisms.
12223     *
12224     * @hide
12225     */
12226    protected void dispatchGetDisplayList() {}
12227
12228    /**
12229     * A view that is not attached or hardware accelerated cannot create a display list.
12230     * This method checks these conditions and returns the appropriate result.
12231     *
12232     * @return true if view has the ability to create a display list, false otherwise.
12233     *
12234     * @hide
12235     */
12236    public boolean canHaveDisplayList() {
12237        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12238    }
12239
12240    /**
12241     * @return The HardwareRenderer associated with that view or null if hardware rendering
12242     * is not supported or this this has not been attached to a window.
12243     *
12244     * @hide
12245     */
12246    public HardwareRenderer getHardwareRenderer() {
12247        if (mAttachInfo != null) {
12248            return mAttachInfo.mHardwareRenderer;
12249        }
12250        return null;
12251    }
12252
12253    /**
12254     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12255     * Otherwise, the same display list will be returned (after having been rendered into
12256     * along the way, depending on the invalidation state of the view).
12257     *
12258     * @param displayList The previous version of this displayList, could be null.
12259     * @param isLayer Whether the requester of the display list is a layer. If so,
12260     * the view will avoid creating a layer inside the resulting display list.
12261     * @return A new or reused DisplayList object.
12262     */
12263    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12264        if (!canHaveDisplayList()) {
12265            return null;
12266        }
12267
12268        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12269                displayList == null || !displayList.isValid() ||
12270                (!isLayer && mRecreateDisplayList))) {
12271            // Don't need to recreate the display list, just need to tell our
12272            // children to restore/recreate theirs
12273            if (displayList != null && displayList.isValid() &&
12274                    !isLayer && !mRecreateDisplayList) {
12275                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12276                mPrivateFlags &= ~DIRTY_MASK;
12277                dispatchGetDisplayList();
12278
12279                return displayList;
12280            }
12281
12282            if (!isLayer) {
12283                // If we got here, we're recreating it. Mark it as such to ensure that
12284                // we copy in child display lists into ours in drawChild()
12285                mRecreateDisplayList = true;
12286            }
12287            if (displayList == null) {
12288                final String name = getClass().getSimpleName();
12289                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12290                // If we're creating a new display list, make sure our parent gets invalidated
12291                // since they will need to recreate their display list to account for this
12292                // new child display list.
12293                invalidateParentCaches();
12294            }
12295
12296            boolean caching = false;
12297            final HardwareCanvas canvas = displayList.start();
12298            int width = mRight - mLeft;
12299            int height = mBottom - mTop;
12300
12301            try {
12302                canvas.setViewport(width, height);
12303                // The dirty rect should always be null for a display list
12304                canvas.onPreDraw(null);
12305                int layerType = (
12306                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12307                        getLayerType() : LAYER_TYPE_NONE;
12308                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12309                    if (layerType == LAYER_TYPE_HARDWARE) {
12310                        final HardwareLayer layer = getHardwareLayer();
12311                        if (layer != null && layer.isValid()) {
12312                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12313                        } else {
12314                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12315                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12316                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12317                        }
12318                        caching = true;
12319                    } else {
12320                        buildDrawingCache(true);
12321                        Bitmap cache = getDrawingCache(true);
12322                        if (cache != null) {
12323                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12324                            caching = true;
12325                        }
12326                    }
12327                } else {
12328
12329                    computeScroll();
12330
12331                    canvas.translate(-mScrollX, -mScrollY);
12332                    if (!isLayer) {
12333                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12334                        mPrivateFlags &= ~DIRTY_MASK;
12335                    }
12336
12337                    // Fast path for layouts with no backgrounds
12338                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12339                        dispatchDraw(canvas);
12340                    } else {
12341                        draw(canvas);
12342                    }
12343                }
12344            } finally {
12345                canvas.onPostDraw();
12346
12347                displayList.end();
12348                displayList.setCaching(caching);
12349                if (isLayer) {
12350                    displayList.setLeftTopRightBottom(0, 0, width, height);
12351                } else {
12352                    setDisplayListProperties(displayList);
12353                }
12354            }
12355        } else if (!isLayer) {
12356            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12357            mPrivateFlags &= ~DIRTY_MASK;
12358        }
12359
12360        return displayList;
12361    }
12362
12363    /**
12364     * Get the DisplayList for the HardwareLayer
12365     *
12366     * @param layer The HardwareLayer whose DisplayList we want
12367     * @return A DisplayList fopr the specified HardwareLayer
12368     */
12369    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12370        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12371        layer.setDisplayList(displayList);
12372        return displayList;
12373    }
12374
12375
12376    /**
12377     * <p>Returns a display list that can be used to draw this view again
12378     * without executing its draw method.</p>
12379     *
12380     * @return A DisplayList ready to replay, or null if caching is not enabled.
12381     *
12382     * @hide
12383     */
12384    public DisplayList getDisplayList() {
12385        mDisplayList = getDisplayList(mDisplayList, false);
12386        return mDisplayList;
12387    }
12388
12389    private void clearDisplayList() {
12390        if (mDisplayList != null) {
12391            mDisplayList.invalidate();
12392            mDisplayList.clear();
12393        }
12394    }
12395
12396    /**
12397     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12398     *
12399     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12400     *
12401     * @see #getDrawingCache(boolean)
12402     */
12403    public Bitmap getDrawingCache() {
12404        return getDrawingCache(false);
12405    }
12406
12407    /**
12408     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12409     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12410     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12411     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12412     * request the drawing cache by calling this method and draw it on screen if the
12413     * returned bitmap is not null.</p>
12414     *
12415     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12416     * this method will create a bitmap of the same size as this view. Because this bitmap
12417     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12418     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12419     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12420     * size than the view. This implies that your application must be able to handle this
12421     * size.</p>
12422     *
12423     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12424     *        the current density of the screen when the application is in compatibility
12425     *        mode.
12426     *
12427     * @return A bitmap representing this view or null if cache is disabled.
12428     *
12429     * @see #setDrawingCacheEnabled(boolean)
12430     * @see #isDrawingCacheEnabled()
12431     * @see #buildDrawingCache(boolean)
12432     * @see #destroyDrawingCache()
12433     */
12434    public Bitmap getDrawingCache(boolean autoScale) {
12435        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12436            return null;
12437        }
12438        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12439            buildDrawingCache(autoScale);
12440        }
12441        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12442    }
12443
12444    /**
12445     * <p>Frees the resources used by the drawing cache. If you call
12446     * {@link #buildDrawingCache()} manually without calling
12447     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12448     * should cleanup the cache with this method afterwards.</p>
12449     *
12450     * @see #setDrawingCacheEnabled(boolean)
12451     * @see #buildDrawingCache()
12452     * @see #getDrawingCache()
12453     */
12454    public void destroyDrawingCache() {
12455        if (mDrawingCache != null) {
12456            mDrawingCache.recycle();
12457            mDrawingCache = null;
12458        }
12459        if (mUnscaledDrawingCache != null) {
12460            mUnscaledDrawingCache.recycle();
12461            mUnscaledDrawingCache = null;
12462        }
12463    }
12464
12465    /**
12466     * Setting a solid background color for the drawing cache's bitmaps will improve
12467     * performance and memory usage. Note, though that this should only be used if this
12468     * view will always be drawn on top of a solid color.
12469     *
12470     * @param color The background color to use for the drawing cache's bitmap
12471     *
12472     * @see #setDrawingCacheEnabled(boolean)
12473     * @see #buildDrawingCache()
12474     * @see #getDrawingCache()
12475     */
12476    public void setDrawingCacheBackgroundColor(int color) {
12477        if (color != mDrawingCacheBackgroundColor) {
12478            mDrawingCacheBackgroundColor = color;
12479            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12480        }
12481    }
12482
12483    /**
12484     * @see #setDrawingCacheBackgroundColor(int)
12485     *
12486     * @return The background color to used for the drawing cache's bitmap
12487     */
12488    public int getDrawingCacheBackgroundColor() {
12489        return mDrawingCacheBackgroundColor;
12490    }
12491
12492    /**
12493     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12494     *
12495     * @see #buildDrawingCache(boolean)
12496     */
12497    public void buildDrawingCache() {
12498        buildDrawingCache(false);
12499    }
12500
12501    /**
12502     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12503     *
12504     * <p>If you call {@link #buildDrawingCache()} manually without calling
12505     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12506     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12507     *
12508     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12509     * this method will create a bitmap of the same size as this view. Because this bitmap
12510     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12511     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12512     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12513     * size than the view. This implies that your application must be able to handle this
12514     * size.</p>
12515     *
12516     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12517     * you do not need the drawing cache bitmap, calling this method will increase memory
12518     * usage and cause the view to be rendered in software once, thus negatively impacting
12519     * performance.</p>
12520     *
12521     * @see #getDrawingCache()
12522     * @see #destroyDrawingCache()
12523     */
12524    public void buildDrawingCache(boolean autoScale) {
12525        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12526                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12527            mCachingFailed = false;
12528
12529            int width = mRight - mLeft;
12530            int height = mBottom - mTop;
12531
12532            final AttachInfo attachInfo = mAttachInfo;
12533            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12534
12535            if (autoScale && scalingRequired) {
12536                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12537                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12538            }
12539
12540            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12541            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12542            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12543
12544            if (width <= 0 || height <= 0 ||
12545                     // Projected bitmap size in bytes
12546                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12547                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12548                destroyDrawingCache();
12549                mCachingFailed = true;
12550                return;
12551            }
12552
12553            boolean clear = true;
12554            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12555
12556            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12557                Bitmap.Config quality;
12558                if (!opaque) {
12559                    // Never pick ARGB_4444 because it looks awful
12560                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12561                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12562                        case DRAWING_CACHE_QUALITY_AUTO:
12563                            quality = Bitmap.Config.ARGB_8888;
12564                            break;
12565                        case DRAWING_CACHE_QUALITY_LOW:
12566                            quality = Bitmap.Config.ARGB_8888;
12567                            break;
12568                        case DRAWING_CACHE_QUALITY_HIGH:
12569                            quality = Bitmap.Config.ARGB_8888;
12570                            break;
12571                        default:
12572                            quality = Bitmap.Config.ARGB_8888;
12573                            break;
12574                    }
12575                } else {
12576                    // Optimization for translucent windows
12577                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12578                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12579                }
12580
12581                // Try to cleanup memory
12582                if (bitmap != null) bitmap.recycle();
12583
12584                try {
12585                    bitmap = Bitmap.createBitmap(width, height, quality);
12586                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12587                    if (autoScale) {
12588                        mDrawingCache = bitmap;
12589                    } else {
12590                        mUnscaledDrawingCache = bitmap;
12591                    }
12592                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12593                } catch (OutOfMemoryError e) {
12594                    // If there is not enough memory to create the bitmap cache, just
12595                    // ignore the issue as bitmap caches are not required to draw the
12596                    // view hierarchy
12597                    if (autoScale) {
12598                        mDrawingCache = null;
12599                    } else {
12600                        mUnscaledDrawingCache = null;
12601                    }
12602                    mCachingFailed = true;
12603                    return;
12604                }
12605
12606                clear = drawingCacheBackgroundColor != 0;
12607            }
12608
12609            Canvas canvas;
12610            if (attachInfo != null) {
12611                canvas = attachInfo.mCanvas;
12612                if (canvas == null) {
12613                    canvas = new Canvas();
12614                }
12615                canvas.setBitmap(bitmap);
12616                // Temporarily clobber the cached Canvas in case one of our children
12617                // is also using a drawing cache. Without this, the children would
12618                // steal the canvas by attaching their own bitmap to it and bad, bad
12619                // thing would happen (invisible views, corrupted drawings, etc.)
12620                attachInfo.mCanvas = null;
12621            } else {
12622                // This case should hopefully never or seldom happen
12623                canvas = new Canvas(bitmap);
12624            }
12625
12626            if (clear) {
12627                bitmap.eraseColor(drawingCacheBackgroundColor);
12628            }
12629
12630            computeScroll();
12631            final int restoreCount = canvas.save();
12632
12633            if (autoScale && scalingRequired) {
12634                final float scale = attachInfo.mApplicationScale;
12635                canvas.scale(scale, scale);
12636            }
12637
12638            canvas.translate(-mScrollX, -mScrollY);
12639
12640            mPrivateFlags |= DRAWN;
12641            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12642                    mLayerType != LAYER_TYPE_NONE) {
12643                mPrivateFlags |= DRAWING_CACHE_VALID;
12644            }
12645
12646            // Fast path for layouts with no backgrounds
12647            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12648                mPrivateFlags &= ~DIRTY_MASK;
12649                dispatchDraw(canvas);
12650            } else {
12651                draw(canvas);
12652            }
12653
12654            canvas.restoreToCount(restoreCount);
12655            canvas.setBitmap(null);
12656
12657            if (attachInfo != null) {
12658                // Restore the cached Canvas for our siblings
12659                attachInfo.mCanvas = canvas;
12660            }
12661        }
12662    }
12663
12664    /**
12665     * Create a snapshot of the view into a bitmap.  We should probably make
12666     * some form of this public, but should think about the API.
12667     */
12668    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12669        int width = mRight - mLeft;
12670        int height = mBottom - mTop;
12671
12672        final AttachInfo attachInfo = mAttachInfo;
12673        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12674        width = (int) ((width * scale) + 0.5f);
12675        height = (int) ((height * scale) + 0.5f);
12676
12677        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12678        if (bitmap == null) {
12679            throw new OutOfMemoryError();
12680        }
12681
12682        Resources resources = getResources();
12683        if (resources != null) {
12684            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12685        }
12686
12687        Canvas canvas;
12688        if (attachInfo != null) {
12689            canvas = attachInfo.mCanvas;
12690            if (canvas == null) {
12691                canvas = new Canvas();
12692            }
12693            canvas.setBitmap(bitmap);
12694            // Temporarily clobber the cached Canvas in case one of our children
12695            // is also using a drawing cache. Without this, the children would
12696            // steal the canvas by attaching their own bitmap to it and bad, bad
12697            // things would happen (invisible views, corrupted drawings, etc.)
12698            attachInfo.mCanvas = null;
12699        } else {
12700            // This case should hopefully never or seldom happen
12701            canvas = new Canvas(bitmap);
12702        }
12703
12704        if ((backgroundColor & 0xff000000) != 0) {
12705            bitmap.eraseColor(backgroundColor);
12706        }
12707
12708        computeScroll();
12709        final int restoreCount = canvas.save();
12710        canvas.scale(scale, scale);
12711        canvas.translate(-mScrollX, -mScrollY);
12712
12713        // Temporarily remove the dirty mask
12714        int flags = mPrivateFlags;
12715        mPrivateFlags &= ~DIRTY_MASK;
12716
12717        // Fast path for layouts with no backgrounds
12718        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12719            dispatchDraw(canvas);
12720        } else {
12721            draw(canvas);
12722        }
12723
12724        mPrivateFlags = flags;
12725
12726        canvas.restoreToCount(restoreCount);
12727        canvas.setBitmap(null);
12728
12729        if (attachInfo != null) {
12730            // Restore the cached Canvas for our siblings
12731            attachInfo.mCanvas = canvas;
12732        }
12733
12734        return bitmap;
12735    }
12736
12737    /**
12738     * Indicates whether this View is currently in edit mode. A View is usually
12739     * in edit mode when displayed within a developer tool. For instance, if
12740     * this View is being drawn by a visual user interface builder, this method
12741     * should return true.
12742     *
12743     * Subclasses should check the return value of this method to provide
12744     * different behaviors if their normal behavior might interfere with the
12745     * host environment. For instance: the class spawns a thread in its
12746     * constructor, the drawing code relies on device-specific features, etc.
12747     *
12748     * This method is usually checked in the drawing code of custom widgets.
12749     *
12750     * @return True if this View is in edit mode, false otherwise.
12751     */
12752    public boolean isInEditMode() {
12753        return false;
12754    }
12755
12756    /**
12757     * If the View draws content inside its padding and enables fading edges,
12758     * it needs to support padding offsets. Padding offsets are added to the
12759     * fading edges to extend the length of the fade so that it covers pixels
12760     * drawn inside the padding.
12761     *
12762     * Subclasses of this class should override this method if they need
12763     * to draw content inside the padding.
12764     *
12765     * @return True if padding offset must be applied, false otherwise.
12766     *
12767     * @see #getLeftPaddingOffset()
12768     * @see #getRightPaddingOffset()
12769     * @see #getTopPaddingOffset()
12770     * @see #getBottomPaddingOffset()
12771     *
12772     * @since CURRENT
12773     */
12774    protected boolean isPaddingOffsetRequired() {
12775        return false;
12776    }
12777
12778    /**
12779     * Amount by which to extend the left fading region. Called only when
12780     * {@link #isPaddingOffsetRequired()} returns true.
12781     *
12782     * @return The left padding offset in pixels.
12783     *
12784     * @see #isPaddingOffsetRequired()
12785     *
12786     * @since CURRENT
12787     */
12788    protected int getLeftPaddingOffset() {
12789        return 0;
12790    }
12791
12792    /**
12793     * Amount by which to extend the right fading region. Called only when
12794     * {@link #isPaddingOffsetRequired()} returns true.
12795     *
12796     * @return The right padding offset in pixels.
12797     *
12798     * @see #isPaddingOffsetRequired()
12799     *
12800     * @since CURRENT
12801     */
12802    protected int getRightPaddingOffset() {
12803        return 0;
12804    }
12805
12806    /**
12807     * Amount by which to extend the top fading region. Called only when
12808     * {@link #isPaddingOffsetRequired()} returns true.
12809     *
12810     * @return The top padding offset in pixels.
12811     *
12812     * @see #isPaddingOffsetRequired()
12813     *
12814     * @since CURRENT
12815     */
12816    protected int getTopPaddingOffset() {
12817        return 0;
12818    }
12819
12820    /**
12821     * Amount by which to extend the bottom fading region. Called only when
12822     * {@link #isPaddingOffsetRequired()} returns true.
12823     *
12824     * @return The bottom padding offset in pixels.
12825     *
12826     * @see #isPaddingOffsetRequired()
12827     *
12828     * @since CURRENT
12829     */
12830    protected int getBottomPaddingOffset() {
12831        return 0;
12832    }
12833
12834    /**
12835     * @hide
12836     * @param offsetRequired
12837     */
12838    protected int getFadeTop(boolean offsetRequired) {
12839        int top = mPaddingTop;
12840        if (offsetRequired) top += getTopPaddingOffset();
12841        return top;
12842    }
12843
12844    /**
12845     * @hide
12846     * @param offsetRequired
12847     */
12848    protected int getFadeHeight(boolean offsetRequired) {
12849        int padding = mPaddingTop;
12850        if (offsetRequired) padding += getTopPaddingOffset();
12851        return mBottom - mTop - mPaddingBottom - padding;
12852    }
12853
12854    /**
12855     * <p>Indicates whether this view is attached to a hardware accelerated
12856     * window or not.</p>
12857     *
12858     * <p>Even if this method returns true, it does not mean that every call
12859     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12860     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12861     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12862     * window is hardware accelerated,
12863     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12864     * return false, and this method will return true.</p>
12865     *
12866     * @return True if the view is attached to a window and the window is
12867     *         hardware accelerated; false in any other case.
12868     */
12869    public boolean isHardwareAccelerated() {
12870        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12871    }
12872
12873    /**
12874     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12875     * case of an active Animation being run on the view.
12876     */
12877    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12878            Animation a, boolean scalingRequired) {
12879        Transformation invalidationTransform;
12880        final int flags = parent.mGroupFlags;
12881        final boolean initialized = a.isInitialized();
12882        if (!initialized) {
12883            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12884            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12885            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12886            onAnimationStart();
12887        }
12888
12889        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12890        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12891            if (parent.mInvalidationTransformation == null) {
12892                parent.mInvalidationTransformation = new Transformation();
12893            }
12894            invalidationTransform = parent.mInvalidationTransformation;
12895            a.getTransformation(drawingTime, invalidationTransform, 1f);
12896        } else {
12897            invalidationTransform = parent.mChildTransformation;
12898        }
12899
12900        if (more) {
12901            if (!a.willChangeBounds()) {
12902                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12903                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12904                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12905                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12906                    // The child need to draw an animation, potentially offscreen, so
12907                    // make sure we do not cancel invalidate requests
12908                    parent.mPrivateFlags |= DRAW_ANIMATION;
12909                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12910                }
12911            } else {
12912                if (parent.mInvalidateRegion == null) {
12913                    parent.mInvalidateRegion = new RectF();
12914                }
12915                final RectF region = parent.mInvalidateRegion;
12916                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12917                        invalidationTransform);
12918
12919                // The child need to draw an animation, potentially offscreen, so
12920                // make sure we do not cancel invalidate requests
12921                parent.mPrivateFlags |= DRAW_ANIMATION;
12922
12923                final int left = mLeft + (int) region.left;
12924                final int top = mTop + (int) region.top;
12925                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12926                        top + (int) (region.height() + .5f));
12927            }
12928        }
12929        return more;
12930    }
12931
12932    /**
12933     * This method is called by getDisplayList() when a display list is created or re-rendered.
12934     * It sets or resets the current value of all properties on that display list (resetting is
12935     * necessary when a display list is being re-created, because we need to make sure that
12936     * previously-set transform values
12937     */
12938    void setDisplayListProperties(DisplayList displayList) {
12939        if (displayList != null) {
12940            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12941            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12942            if (mParent instanceof ViewGroup) {
12943                displayList.setClipChildren(
12944                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12945            }
12946            float alpha = 1;
12947            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12948                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12949                ViewGroup parentVG = (ViewGroup) mParent;
12950                final boolean hasTransform =
12951                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12952                if (hasTransform) {
12953                    Transformation transform = parentVG.mChildTransformation;
12954                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12955                    if (transformType != Transformation.TYPE_IDENTITY) {
12956                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12957                            alpha = transform.getAlpha();
12958                        }
12959                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12960                            displayList.setStaticMatrix(transform.getMatrix());
12961                        }
12962                    }
12963                }
12964            }
12965            if (mTransformationInfo != null) {
12966                alpha *= mTransformationInfo.mAlpha;
12967                if (alpha < 1) {
12968                    final int multipliedAlpha = (int) (255 * alpha);
12969                    if (onSetAlpha(multipliedAlpha)) {
12970                        alpha = 1;
12971                    }
12972                }
12973                displayList.setTransformationInfo(alpha,
12974                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12975                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12976                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12977                        mTransformationInfo.mScaleY);
12978                if (mTransformationInfo.mCamera == null) {
12979                    mTransformationInfo.mCamera = new Camera();
12980                    mTransformationInfo.matrix3D = new Matrix();
12981                }
12982                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12983                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12984                    displayList.setPivotX(getPivotX());
12985                    displayList.setPivotY(getPivotY());
12986                }
12987            } else if (alpha < 1) {
12988                displayList.setAlpha(alpha);
12989            }
12990        }
12991    }
12992
12993    /**
12994     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12995     * This draw() method is an implementation detail and is not intended to be overridden or
12996     * to be called from anywhere else other than ViewGroup.drawChild().
12997     */
12998    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12999        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13000        boolean more = false;
13001        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13002        final int flags = parent.mGroupFlags;
13003
13004        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13005            parent.mChildTransformation.clear();
13006            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13007        }
13008
13009        Transformation transformToApply = null;
13010        boolean concatMatrix = false;
13011
13012        boolean scalingRequired = false;
13013        boolean caching;
13014        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
13015
13016        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13017        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13018                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13019            caching = true;
13020            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13021            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13022        } else {
13023            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13024        }
13025
13026        final Animation a = getAnimation();
13027        if (a != null) {
13028            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13029            concatMatrix = a.willChangeTransformationMatrix();
13030            if (concatMatrix) {
13031                mPrivateFlags2 |= VIEW_IS_ANIMATING_TRANSFORM;
13032            }
13033            transformToApply = parent.mChildTransformation;
13034        } else {
13035            if ((mPrivateFlags2 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
13036                    mDisplayList != null) {
13037                // No longer animating: clear out old animation matrix
13038                mDisplayList.setAnimationMatrix(null);
13039                mPrivateFlags2 &= ~VIEW_IS_ANIMATING_TRANSFORM;
13040            }
13041            if (!useDisplayListProperties &&
13042                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13043                final boolean hasTransform =
13044                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13045                if (hasTransform) {
13046                    final int transformType = parent.mChildTransformation.getTransformationType();
13047                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13048                            parent.mChildTransformation : null;
13049                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13050                }
13051            }
13052        }
13053
13054        concatMatrix |= !childHasIdentityMatrix;
13055
13056        // Sets the flag as early as possible to allow draw() implementations
13057        // to call invalidate() successfully when doing animations
13058        mPrivateFlags |= DRAWN;
13059
13060        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13061                (mPrivateFlags & DRAW_ANIMATION) == 0) {
13062            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
13063            return more;
13064        }
13065        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
13066
13067        if (hardwareAccelerated) {
13068            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13069            // retain the flag's value temporarily in the mRecreateDisplayList flag
13070            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
13071            mPrivateFlags &= ~INVALIDATED;
13072        }
13073
13074        computeScroll();
13075
13076        final int sx = mScrollX;
13077        final int sy = mScrollY;
13078
13079        DisplayList displayList = null;
13080        Bitmap cache = null;
13081        boolean hasDisplayList = false;
13082        if (caching) {
13083            if (!hardwareAccelerated) {
13084                if (layerType != LAYER_TYPE_NONE) {
13085                    layerType = LAYER_TYPE_SOFTWARE;
13086                    buildDrawingCache(true);
13087                }
13088                cache = getDrawingCache(true);
13089            } else {
13090                switch (layerType) {
13091                    case LAYER_TYPE_SOFTWARE:
13092                        if (useDisplayListProperties) {
13093                            hasDisplayList = canHaveDisplayList();
13094                        } else {
13095                            buildDrawingCache(true);
13096                            cache = getDrawingCache(true);
13097                        }
13098                        break;
13099                    case LAYER_TYPE_HARDWARE:
13100                        if (useDisplayListProperties) {
13101                            hasDisplayList = canHaveDisplayList();
13102                        }
13103                        break;
13104                    case LAYER_TYPE_NONE:
13105                        // Delay getting the display list until animation-driven alpha values are
13106                        // set up and possibly passed on to the view
13107                        hasDisplayList = canHaveDisplayList();
13108                        break;
13109                }
13110            }
13111        }
13112        useDisplayListProperties &= hasDisplayList;
13113        if (useDisplayListProperties) {
13114            displayList = getDisplayList();
13115            if (!displayList.isValid()) {
13116                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13117                // to getDisplayList(), the display list will be marked invalid and we should not
13118                // try to use it again.
13119                displayList = null;
13120                hasDisplayList = false;
13121                useDisplayListProperties = false;
13122            }
13123        }
13124
13125        final boolean hasNoCache = cache == null || hasDisplayList;
13126        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13127                layerType != LAYER_TYPE_HARDWARE;
13128
13129        int restoreTo = -1;
13130        if (!useDisplayListProperties || transformToApply != null) {
13131            restoreTo = canvas.save();
13132        }
13133        if (offsetForScroll) {
13134            canvas.translate(mLeft - sx, mTop - sy);
13135        } else {
13136            if (!useDisplayListProperties) {
13137                canvas.translate(mLeft, mTop);
13138            }
13139            if (scalingRequired) {
13140                if (useDisplayListProperties) {
13141                    // TODO: Might not need this if we put everything inside the DL
13142                    restoreTo = canvas.save();
13143                }
13144                // mAttachInfo cannot be null, otherwise scalingRequired == false
13145                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13146                canvas.scale(scale, scale);
13147            }
13148        }
13149
13150        float alpha = useDisplayListProperties ? 1 : getAlpha();
13151        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
13152            if (transformToApply != null || !childHasIdentityMatrix) {
13153                int transX = 0;
13154                int transY = 0;
13155
13156                if (offsetForScroll) {
13157                    transX = -sx;
13158                    transY = -sy;
13159                }
13160
13161                if (transformToApply != null) {
13162                    if (concatMatrix) {
13163                        if (useDisplayListProperties) {
13164                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13165                        } else {
13166                            // Undo the scroll translation, apply the transformation matrix,
13167                            // then redo the scroll translate to get the correct result.
13168                            canvas.translate(-transX, -transY);
13169                            canvas.concat(transformToApply.getMatrix());
13170                            canvas.translate(transX, transY);
13171                        }
13172                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13173                    }
13174
13175                    float transformAlpha = transformToApply.getAlpha();
13176                    if (transformAlpha < 1) {
13177                        alpha *= transformToApply.getAlpha();
13178                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13179                    }
13180                }
13181
13182                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13183                    canvas.translate(-transX, -transY);
13184                    canvas.concat(getMatrix());
13185                    canvas.translate(transX, transY);
13186                }
13187            }
13188
13189            if (alpha < 1) {
13190                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13191                if (hasNoCache) {
13192                    final int multipliedAlpha = (int) (255 * alpha);
13193                    if (!onSetAlpha(multipliedAlpha)) {
13194                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13195                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13196                                layerType != LAYER_TYPE_NONE) {
13197                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13198                        }
13199                        if (useDisplayListProperties) {
13200                            displayList.setAlpha(alpha * getAlpha());
13201                        } else  if (layerType == LAYER_TYPE_NONE) {
13202                            final int scrollX = hasDisplayList ? 0 : sx;
13203                            final int scrollY = hasDisplayList ? 0 : sy;
13204                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13205                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13206                        }
13207                    } else {
13208                        // Alpha is handled by the child directly, clobber the layer's alpha
13209                        mPrivateFlags |= ALPHA_SET;
13210                    }
13211                }
13212            }
13213        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13214            onSetAlpha(255);
13215            mPrivateFlags &= ~ALPHA_SET;
13216        }
13217
13218        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13219                !useDisplayListProperties) {
13220            if (offsetForScroll) {
13221                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13222            } else {
13223                if (!scalingRequired || cache == null) {
13224                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13225                } else {
13226                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13227                }
13228            }
13229        }
13230
13231        if (!useDisplayListProperties && hasDisplayList) {
13232            displayList = getDisplayList();
13233            if (!displayList.isValid()) {
13234                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13235                // to getDisplayList(), the display list will be marked invalid and we should not
13236                // try to use it again.
13237                displayList = null;
13238                hasDisplayList = false;
13239            }
13240        }
13241
13242        if (hasNoCache) {
13243            boolean layerRendered = false;
13244            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13245                final HardwareLayer layer = getHardwareLayer();
13246                if (layer != null && layer.isValid()) {
13247                    mLayerPaint.setAlpha((int) (alpha * 255));
13248                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13249                    layerRendered = true;
13250                } else {
13251                    final int scrollX = hasDisplayList ? 0 : sx;
13252                    final int scrollY = hasDisplayList ? 0 : sy;
13253                    canvas.saveLayer(scrollX, scrollY,
13254                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13255                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13256                }
13257            }
13258
13259            if (!layerRendered) {
13260                if (!hasDisplayList) {
13261                    // Fast path for layouts with no backgrounds
13262                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13263                        mPrivateFlags &= ~DIRTY_MASK;
13264                        dispatchDraw(canvas);
13265                    } else {
13266                        draw(canvas);
13267                    }
13268                } else {
13269                    mPrivateFlags &= ~DIRTY_MASK;
13270                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13271                }
13272            }
13273        } else if (cache != null) {
13274            mPrivateFlags &= ~DIRTY_MASK;
13275            Paint cachePaint;
13276
13277            if (layerType == LAYER_TYPE_NONE) {
13278                cachePaint = parent.mCachePaint;
13279                if (cachePaint == null) {
13280                    cachePaint = new Paint();
13281                    cachePaint.setDither(false);
13282                    parent.mCachePaint = cachePaint;
13283                }
13284                if (alpha < 1) {
13285                    cachePaint.setAlpha((int) (alpha * 255));
13286                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13287                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13288                    cachePaint.setAlpha(255);
13289                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13290                }
13291            } else {
13292                cachePaint = mLayerPaint;
13293                cachePaint.setAlpha((int) (alpha * 255));
13294            }
13295            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13296        }
13297
13298        if (restoreTo >= 0) {
13299            canvas.restoreToCount(restoreTo);
13300        }
13301
13302        if (a != null && !more) {
13303            if (!hardwareAccelerated && !a.getFillAfter()) {
13304                onSetAlpha(255);
13305            }
13306            parent.finishAnimatingView(this, a);
13307        }
13308
13309        if (more && hardwareAccelerated) {
13310            // invalidation is the trigger to recreate display lists, so if we're using
13311            // display lists to render, force an invalidate to allow the animation to
13312            // continue drawing another frame
13313            parent.invalidate(true);
13314            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13315                // alpha animations should cause the child to recreate its display list
13316                invalidate(true);
13317            }
13318        }
13319
13320        mRecreateDisplayList = false;
13321
13322        return more;
13323    }
13324
13325    /**
13326     * Manually render this view (and all of its children) to the given Canvas.
13327     * The view must have already done a full layout before this function is
13328     * called.  When implementing a view, implement
13329     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13330     * If you do need to override this method, call the superclass version.
13331     *
13332     * @param canvas The Canvas to which the View is rendered.
13333     */
13334    public void draw(Canvas canvas) {
13335        final int privateFlags = mPrivateFlags;
13336        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13337                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13338        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13339
13340        /*
13341         * Draw traversal performs several drawing steps which must be executed
13342         * in the appropriate order:
13343         *
13344         *      1. Draw the background
13345         *      2. If necessary, save the canvas' layers to prepare for fading
13346         *      3. Draw view's content
13347         *      4. Draw children
13348         *      5. If necessary, draw the fading edges and restore layers
13349         *      6. Draw decorations (scrollbars for instance)
13350         */
13351
13352        // Step 1, draw the background, if needed
13353        int saveCount;
13354
13355        if (!dirtyOpaque) {
13356            final Drawable background = mBackground;
13357            if (background != null) {
13358                final int scrollX = mScrollX;
13359                final int scrollY = mScrollY;
13360
13361                if (mBackgroundSizeChanged) {
13362                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13363                    mBackgroundSizeChanged = false;
13364                }
13365
13366                if ((scrollX | scrollY) == 0) {
13367                    background.draw(canvas);
13368                } else {
13369                    canvas.translate(scrollX, scrollY);
13370                    background.draw(canvas);
13371                    canvas.translate(-scrollX, -scrollY);
13372                }
13373            }
13374        }
13375
13376        // skip step 2 & 5 if possible (common case)
13377        final int viewFlags = mViewFlags;
13378        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13379        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13380        if (!verticalEdges && !horizontalEdges) {
13381            // Step 3, draw the content
13382            if (!dirtyOpaque) onDraw(canvas);
13383
13384            // Step 4, draw the children
13385            dispatchDraw(canvas);
13386
13387            // Step 6, draw decorations (scrollbars)
13388            onDrawScrollBars(canvas);
13389
13390            // we're done...
13391            return;
13392        }
13393
13394        /*
13395         * Here we do the full fledged routine...
13396         * (this is an uncommon case where speed matters less,
13397         * this is why we repeat some of the tests that have been
13398         * done above)
13399         */
13400
13401        boolean drawTop = false;
13402        boolean drawBottom = false;
13403        boolean drawLeft = false;
13404        boolean drawRight = false;
13405
13406        float topFadeStrength = 0.0f;
13407        float bottomFadeStrength = 0.0f;
13408        float leftFadeStrength = 0.0f;
13409        float rightFadeStrength = 0.0f;
13410
13411        // Step 2, save the canvas' layers
13412        int paddingLeft = mPaddingLeft;
13413
13414        final boolean offsetRequired = isPaddingOffsetRequired();
13415        if (offsetRequired) {
13416            paddingLeft += getLeftPaddingOffset();
13417        }
13418
13419        int left = mScrollX + paddingLeft;
13420        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13421        int top = mScrollY + getFadeTop(offsetRequired);
13422        int bottom = top + getFadeHeight(offsetRequired);
13423
13424        if (offsetRequired) {
13425            right += getRightPaddingOffset();
13426            bottom += getBottomPaddingOffset();
13427        }
13428
13429        final ScrollabilityCache scrollabilityCache = mScrollCache;
13430        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13431        int length = (int) fadeHeight;
13432
13433        // clip the fade length if top and bottom fades overlap
13434        // overlapping fades produce odd-looking artifacts
13435        if (verticalEdges && (top + length > bottom - length)) {
13436            length = (bottom - top) / 2;
13437        }
13438
13439        // also clip horizontal fades if necessary
13440        if (horizontalEdges && (left + length > right - length)) {
13441            length = (right - left) / 2;
13442        }
13443
13444        if (verticalEdges) {
13445            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13446            drawTop = topFadeStrength * fadeHeight > 1.0f;
13447            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13448            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13449        }
13450
13451        if (horizontalEdges) {
13452            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13453            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13454            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13455            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13456        }
13457
13458        saveCount = canvas.getSaveCount();
13459
13460        int solidColor = getSolidColor();
13461        if (solidColor == 0) {
13462            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13463
13464            if (drawTop) {
13465                canvas.saveLayer(left, top, right, top + length, null, flags);
13466            }
13467
13468            if (drawBottom) {
13469                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13470            }
13471
13472            if (drawLeft) {
13473                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13474            }
13475
13476            if (drawRight) {
13477                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13478            }
13479        } else {
13480            scrollabilityCache.setFadeColor(solidColor);
13481        }
13482
13483        // Step 3, draw the content
13484        if (!dirtyOpaque) onDraw(canvas);
13485
13486        // Step 4, draw the children
13487        dispatchDraw(canvas);
13488
13489        // Step 5, draw the fade effect and restore layers
13490        final Paint p = scrollabilityCache.paint;
13491        final Matrix matrix = scrollabilityCache.matrix;
13492        final Shader fade = scrollabilityCache.shader;
13493
13494        if (drawTop) {
13495            matrix.setScale(1, fadeHeight * topFadeStrength);
13496            matrix.postTranslate(left, top);
13497            fade.setLocalMatrix(matrix);
13498            canvas.drawRect(left, top, right, top + length, p);
13499        }
13500
13501        if (drawBottom) {
13502            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13503            matrix.postRotate(180);
13504            matrix.postTranslate(left, bottom);
13505            fade.setLocalMatrix(matrix);
13506            canvas.drawRect(left, bottom - length, right, bottom, p);
13507        }
13508
13509        if (drawLeft) {
13510            matrix.setScale(1, fadeHeight * leftFadeStrength);
13511            matrix.postRotate(-90);
13512            matrix.postTranslate(left, top);
13513            fade.setLocalMatrix(matrix);
13514            canvas.drawRect(left, top, left + length, bottom, p);
13515        }
13516
13517        if (drawRight) {
13518            matrix.setScale(1, fadeHeight * rightFadeStrength);
13519            matrix.postRotate(90);
13520            matrix.postTranslate(right, top);
13521            fade.setLocalMatrix(matrix);
13522            canvas.drawRect(right - length, top, right, bottom, p);
13523        }
13524
13525        canvas.restoreToCount(saveCount);
13526
13527        // Step 6, draw decorations (scrollbars)
13528        onDrawScrollBars(canvas);
13529    }
13530
13531    /**
13532     * Override this if your view is known to always be drawn on top of a solid color background,
13533     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13534     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13535     * should be set to 0xFF.
13536     *
13537     * @see #setVerticalFadingEdgeEnabled(boolean)
13538     * @see #setHorizontalFadingEdgeEnabled(boolean)
13539     *
13540     * @return The known solid color background for this view, or 0 if the color may vary
13541     */
13542    @ViewDebug.ExportedProperty(category = "drawing")
13543    public int getSolidColor() {
13544        return 0;
13545    }
13546
13547    /**
13548     * Build a human readable string representation of the specified view flags.
13549     *
13550     * @param flags the view flags to convert to a string
13551     * @return a String representing the supplied flags
13552     */
13553    private static String printFlags(int flags) {
13554        String output = "";
13555        int numFlags = 0;
13556        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13557            output += "TAKES_FOCUS";
13558            numFlags++;
13559        }
13560
13561        switch (flags & VISIBILITY_MASK) {
13562        case INVISIBLE:
13563            if (numFlags > 0) {
13564                output += " ";
13565            }
13566            output += "INVISIBLE";
13567            // USELESS HERE numFlags++;
13568            break;
13569        case GONE:
13570            if (numFlags > 0) {
13571                output += " ";
13572            }
13573            output += "GONE";
13574            // USELESS HERE numFlags++;
13575            break;
13576        default:
13577            break;
13578        }
13579        return output;
13580    }
13581
13582    /**
13583     * Build a human readable string representation of the specified private
13584     * view flags.
13585     *
13586     * @param privateFlags the private view flags to convert to a string
13587     * @return a String representing the supplied flags
13588     */
13589    private static String printPrivateFlags(int privateFlags) {
13590        String output = "";
13591        int numFlags = 0;
13592
13593        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13594            output += "WANTS_FOCUS";
13595            numFlags++;
13596        }
13597
13598        if ((privateFlags & FOCUSED) == FOCUSED) {
13599            if (numFlags > 0) {
13600                output += " ";
13601            }
13602            output += "FOCUSED";
13603            numFlags++;
13604        }
13605
13606        if ((privateFlags & SELECTED) == SELECTED) {
13607            if (numFlags > 0) {
13608                output += " ";
13609            }
13610            output += "SELECTED";
13611            numFlags++;
13612        }
13613
13614        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13615            if (numFlags > 0) {
13616                output += " ";
13617            }
13618            output += "IS_ROOT_NAMESPACE";
13619            numFlags++;
13620        }
13621
13622        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13623            if (numFlags > 0) {
13624                output += " ";
13625            }
13626            output += "HAS_BOUNDS";
13627            numFlags++;
13628        }
13629
13630        if ((privateFlags & DRAWN) == DRAWN) {
13631            if (numFlags > 0) {
13632                output += " ";
13633            }
13634            output += "DRAWN";
13635            // USELESS HERE numFlags++;
13636        }
13637        return output;
13638    }
13639
13640    /**
13641     * <p>Indicates whether or not this view's layout will be requested during
13642     * the next hierarchy layout pass.</p>
13643     *
13644     * @return true if the layout will be forced during next layout pass
13645     */
13646    public boolean isLayoutRequested() {
13647        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13648    }
13649
13650    /**
13651     * Assign a size and position to a view and all of its
13652     * descendants
13653     *
13654     * <p>This is the second phase of the layout mechanism.
13655     * (The first is measuring). In this phase, each parent calls
13656     * layout on all of its children to position them.
13657     * This is typically done using the child measurements
13658     * that were stored in the measure pass().</p>
13659     *
13660     * <p>Derived classes should not override this method.
13661     * Derived classes with children should override
13662     * onLayout. In that method, they should
13663     * call layout on each of their children.</p>
13664     *
13665     * @param l Left position, relative to parent
13666     * @param t Top position, relative to parent
13667     * @param r Right position, relative to parent
13668     * @param b Bottom position, relative to parent
13669     */
13670    @SuppressWarnings({"unchecked"})
13671    public void layout(int l, int t, int r, int b) {
13672        int oldL = mLeft;
13673        int oldT = mTop;
13674        int oldB = mBottom;
13675        int oldR = mRight;
13676        boolean changed = setFrame(l, t, r, b);
13677        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13678            onLayout(changed, l, t, r, b);
13679            mPrivateFlags &= ~LAYOUT_REQUIRED;
13680
13681            ListenerInfo li = mListenerInfo;
13682            if (li != null && li.mOnLayoutChangeListeners != null) {
13683                ArrayList<OnLayoutChangeListener> listenersCopy =
13684                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13685                int numListeners = listenersCopy.size();
13686                for (int i = 0; i < numListeners; ++i) {
13687                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13688                }
13689            }
13690        }
13691        mPrivateFlags &= ~FORCE_LAYOUT;
13692    }
13693
13694    /**
13695     * Called from layout when this view should
13696     * assign a size and position to each of its children.
13697     *
13698     * Derived classes with children should override
13699     * this method and call layout on each of
13700     * their children.
13701     * @param changed This is a new size or position for this view
13702     * @param left Left position, relative to parent
13703     * @param top Top position, relative to parent
13704     * @param right Right position, relative to parent
13705     * @param bottom Bottom position, relative to parent
13706     */
13707    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13708    }
13709
13710    /**
13711     * Assign a size and position to this view.
13712     *
13713     * This is called from layout.
13714     *
13715     * @param left Left position, relative to parent
13716     * @param top Top position, relative to parent
13717     * @param right Right position, relative to parent
13718     * @param bottom Bottom position, relative to parent
13719     * @return true if the new size and position are different than the
13720     *         previous ones
13721     * {@hide}
13722     */
13723    protected boolean setFrame(int left, int top, int right, int bottom) {
13724        boolean changed = false;
13725
13726        if (DBG) {
13727            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13728                    + right + "," + bottom + ")");
13729        }
13730
13731        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13732            changed = true;
13733
13734            // Remember our drawn bit
13735            int drawn = mPrivateFlags & DRAWN;
13736
13737            int oldWidth = mRight - mLeft;
13738            int oldHeight = mBottom - mTop;
13739            int newWidth = right - left;
13740            int newHeight = bottom - top;
13741            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13742
13743            // Invalidate our old position
13744            invalidate(sizeChanged);
13745
13746            mLeft = left;
13747            mTop = top;
13748            mRight = right;
13749            mBottom = bottom;
13750            if (mDisplayList != null) {
13751                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13752            }
13753
13754            mPrivateFlags |= HAS_BOUNDS;
13755
13756
13757            if (sizeChanged) {
13758                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13759                    // A change in dimension means an auto-centered pivot point changes, too
13760                    if (mTransformationInfo != null) {
13761                        mTransformationInfo.mMatrixDirty = true;
13762                    }
13763                }
13764                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13765            }
13766
13767            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13768                // If we are visible, force the DRAWN bit to on so that
13769                // this invalidate will go through (at least to our parent).
13770                // This is because someone may have invalidated this view
13771                // before this call to setFrame came in, thereby clearing
13772                // the DRAWN bit.
13773                mPrivateFlags |= DRAWN;
13774                invalidate(sizeChanged);
13775                // parent display list may need to be recreated based on a change in the bounds
13776                // of any child
13777                invalidateParentCaches();
13778            }
13779
13780            // Reset drawn bit to original value (invalidate turns it off)
13781            mPrivateFlags |= drawn;
13782
13783            mBackgroundSizeChanged = true;
13784        }
13785        return changed;
13786    }
13787
13788    /**
13789     * Finalize inflating a view from XML.  This is called as the last phase
13790     * of inflation, after all child views have been added.
13791     *
13792     * <p>Even if the subclass overrides onFinishInflate, they should always be
13793     * sure to call the super method, so that we get called.
13794     */
13795    protected void onFinishInflate() {
13796    }
13797
13798    /**
13799     * Returns the resources associated with this view.
13800     *
13801     * @return Resources object.
13802     */
13803    public Resources getResources() {
13804        return mResources;
13805    }
13806
13807    /**
13808     * Invalidates the specified Drawable.
13809     *
13810     * @param drawable the drawable to invalidate
13811     */
13812    public void invalidateDrawable(Drawable drawable) {
13813        if (verifyDrawable(drawable)) {
13814            final Rect dirty = drawable.getBounds();
13815            final int scrollX = mScrollX;
13816            final int scrollY = mScrollY;
13817
13818            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13819                    dirty.right + scrollX, dirty.bottom + scrollY);
13820        }
13821    }
13822
13823    /**
13824     * Schedules an action on a drawable to occur at a specified time.
13825     *
13826     * @param who the recipient of the action
13827     * @param what the action to run on the drawable
13828     * @param when the time at which the action must occur. Uses the
13829     *        {@link SystemClock#uptimeMillis} timebase.
13830     */
13831    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13832        if (verifyDrawable(who) && what != null) {
13833            final long delay = when - SystemClock.uptimeMillis();
13834            if (mAttachInfo != null) {
13835                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13836                        Choreographer.CALLBACK_ANIMATION, what, who,
13837                        Choreographer.subtractFrameDelay(delay));
13838            } else {
13839                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13840            }
13841        }
13842    }
13843
13844    /**
13845     * Cancels a scheduled action on a drawable.
13846     *
13847     * @param who the recipient of the action
13848     * @param what the action to cancel
13849     */
13850    public void unscheduleDrawable(Drawable who, Runnable what) {
13851        if (verifyDrawable(who) && what != null) {
13852            if (mAttachInfo != null) {
13853                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13854                        Choreographer.CALLBACK_ANIMATION, what, who);
13855            } else {
13856                ViewRootImpl.getRunQueue().removeCallbacks(what);
13857            }
13858        }
13859    }
13860
13861    /**
13862     * Unschedule any events associated with the given Drawable.  This can be
13863     * used when selecting a new Drawable into a view, so that the previous
13864     * one is completely unscheduled.
13865     *
13866     * @param who The Drawable to unschedule.
13867     *
13868     * @see #drawableStateChanged
13869     */
13870    public void unscheduleDrawable(Drawable who) {
13871        if (mAttachInfo != null && who != null) {
13872            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13873                    Choreographer.CALLBACK_ANIMATION, null, who);
13874        }
13875    }
13876
13877    /**
13878     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
13879     * that the View directionality can and will be resolved before its Drawables.
13880     *
13881     * Will call {@link View#onResolveDrawables} when resolution is done.
13882     */
13883    public void resolveDrawables() {
13884        if (mBackground != null) {
13885            mBackground.setLayoutDirection(getResolvedLayoutDirection());
13886        }
13887        onResolveDrawables(getResolvedLayoutDirection());
13888    }
13889
13890    /**
13891     * Called when layout direction has been resolved.
13892     *
13893     * The default implementation does nothing.
13894     *
13895     * @param layoutDirection The resolved layout direction.
13896     *
13897     * @see {@link #LAYOUT_DIRECTION_LTR}
13898     * @see {@link #LAYOUT_DIRECTION_RTL}
13899     */
13900    public void onResolveDrawables(int layoutDirection) {
13901    }
13902
13903    /**
13904     * If your view subclass is displaying its own Drawable objects, it should
13905     * override this function and return true for any Drawable it is
13906     * displaying.  This allows animations for those drawables to be
13907     * scheduled.
13908     *
13909     * <p>Be sure to call through to the super class when overriding this
13910     * function.
13911     *
13912     * @param who The Drawable to verify.  Return true if it is one you are
13913     *            displaying, else return the result of calling through to the
13914     *            super class.
13915     *
13916     * @return boolean If true than the Drawable is being displayed in the
13917     *         view; else false and it is not allowed to animate.
13918     *
13919     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13920     * @see #drawableStateChanged()
13921     */
13922    protected boolean verifyDrawable(Drawable who) {
13923        return who == mBackground;
13924    }
13925
13926    /**
13927     * This function is called whenever the state of the view changes in such
13928     * a way that it impacts the state of drawables being shown.
13929     *
13930     * <p>Be sure to call through to the superclass when overriding this
13931     * function.
13932     *
13933     * @see Drawable#setState(int[])
13934     */
13935    protected void drawableStateChanged() {
13936        Drawable d = mBackground;
13937        if (d != null && d.isStateful()) {
13938            d.setState(getDrawableState());
13939        }
13940    }
13941
13942    /**
13943     * Call this to force a view to update its drawable state. This will cause
13944     * drawableStateChanged to be called on this view. Views that are interested
13945     * in the new state should call getDrawableState.
13946     *
13947     * @see #drawableStateChanged
13948     * @see #getDrawableState
13949     */
13950    public void refreshDrawableState() {
13951        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13952        drawableStateChanged();
13953
13954        ViewParent parent = mParent;
13955        if (parent != null) {
13956            parent.childDrawableStateChanged(this);
13957        }
13958    }
13959
13960    /**
13961     * Return an array of resource IDs of the drawable states representing the
13962     * current state of the view.
13963     *
13964     * @return The current drawable state
13965     *
13966     * @see Drawable#setState(int[])
13967     * @see #drawableStateChanged()
13968     * @see #onCreateDrawableState(int)
13969     */
13970    public final int[] getDrawableState() {
13971        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13972            return mDrawableState;
13973        } else {
13974            mDrawableState = onCreateDrawableState(0);
13975            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13976            return mDrawableState;
13977        }
13978    }
13979
13980    /**
13981     * Generate the new {@link android.graphics.drawable.Drawable} state for
13982     * this view. This is called by the view
13983     * system when the cached Drawable state is determined to be invalid.  To
13984     * retrieve the current state, you should use {@link #getDrawableState}.
13985     *
13986     * @param extraSpace if non-zero, this is the number of extra entries you
13987     * would like in the returned array in which you can place your own
13988     * states.
13989     *
13990     * @return Returns an array holding the current {@link Drawable} state of
13991     * the view.
13992     *
13993     * @see #mergeDrawableStates(int[], int[])
13994     */
13995    protected int[] onCreateDrawableState(int extraSpace) {
13996        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13997                mParent instanceof View) {
13998            return ((View) mParent).onCreateDrawableState(extraSpace);
13999        }
14000
14001        int[] drawableState;
14002
14003        int privateFlags = mPrivateFlags;
14004
14005        int viewStateIndex = 0;
14006        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14007        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14008        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14009        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14010        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14011        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14012        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14013                HardwareRenderer.isAvailable()) {
14014            // This is set if HW acceleration is requested, even if the current
14015            // process doesn't allow it.  This is just to allow app preview
14016            // windows to better match their app.
14017            viewStateIndex |= VIEW_STATE_ACCELERATED;
14018        }
14019        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14020
14021        final int privateFlags2 = mPrivateFlags2;
14022        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14023        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14024
14025        drawableState = VIEW_STATE_SETS[viewStateIndex];
14026
14027        //noinspection ConstantIfStatement
14028        if (false) {
14029            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14030            Log.i("View", toString()
14031                    + " pressed=" + ((privateFlags & PRESSED) != 0)
14032                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14033                    + " fo=" + hasFocus()
14034                    + " sl=" + ((privateFlags & SELECTED) != 0)
14035                    + " wf=" + hasWindowFocus()
14036                    + ": " + Arrays.toString(drawableState));
14037        }
14038
14039        if (extraSpace == 0) {
14040            return drawableState;
14041        }
14042
14043        final int[] fullState;
14044        if (drawableState != null) {
14045            fullState = new int[drawableState.length + extraSpace];
14046            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14047        } else {
14048            fullState = new int[extraSpace];
14049        }
14050
14051        return fullState;
14052    }
14053
14054    /**
14055     * Merge your own state values in <var>additionalState</var> into the base
14056     * state values <var>baseState</var> that were returned by
14057     * {@link #onCreateDrawableState(int)}.
14058     *
14059     * @param baseState The base state values returned by
14060     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14061     * own additional state values.
14062     *
14063     * @param additionalState The additional state values you would like
14064     * added to <var>baseState</var>; this array is not modified.
14065     *
14066     * @return As a convenience, the <var>baseState</var> array you originally
14067     * passed into the function is returned.
14068     *
14069     * @see #onCreateDrawableState(int)
14070     */
14071    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14072        final int N = baseState.length;
14073        int i = N - 1;
14074        while (i >= 0 && baseState[i] == 0) {
14075            i--;
14076        }
14077        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14078        return baseState;
14079    }
14080
14081    /**
14082     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14083     * on all Drawable objects associated with this view.
14084     */
14085    public void jumpDrawablesToCurrentState() {
14086        if (mBackground != null) {
14087            mBackground.jumpToCurrentState();
14088        }
14089    }
14090
14091    /**
14092     * Sets the background color for this view.
14093     * @param color the color of the background
14094     */
14095    @RemotableViewMethod
14096    public void setBackgroundColor(int color) {
14097        if (mBackground instanceof ColorDrawable) {
14098            ((ColorDrawable) mBackground).setColor(color);
14099        } else {
14100            setBackground(new ColorDrawable(color));
14101        }
14102    }
14103
14104    /**
14105     * Set the background to a given resource. The resource should refer to
14106     * a Drawable object or 0 to remove the background.
14107     * @param resid The identifier of the resource.
14108     *
14109     * @attr ref android.R.styleable#View_background
14110     */
14111    @RemotableViewMethod
14112    public void setBackgroundResource(int resid) {
14113        if (resid != 0 && resid == mBackgroundResource) {
14114            return;
14115        }
14116
14117        Drawable d= null;
14118        if (resid != 0) {
14119            d = mResources.getDrawable(resid);
14120        }
14121        setBackground(d);
14122
14123        mBackgroundResource = resid;
14124    }
14125
14126    /**
14127     * Set the background to a given Drawable, or remove the background. If the
14128     * background has padding, this View's padding is set to the background's
14129     * padding. However, when a background is removed, this View's padding isn't
14130     * touched. If setting the padding is desired, please use
14131     * {@link #setPadding(int, int, int, int)}.
14132     *
14133     * @param background The Drawable to use as the background, or null to remove the
14134     *        background
14135     */
14136    public void setBackground(Drawable background) {
14137        //noinspection deprecation
14138        setBackgroundDrawable(background);
14139    }
14140
14141    /**
14142     * @deprecated use {@link #setBackground(Drawable)} instead
14143     */
14144    @Deprecated
14145    public void setBackgroundDrawable(Drawable background) {
14146        if (background == mBackground) {
14147            return;
14148        }
14149
14150        boolean requestLayout = false;
14151
14152        mBackgroundResource = 0;
14153
14154        /*
14155         * Regardless of whether we're setting a new background or not, we want
14156         * to clear the previous drawable.
14157         */
14158        if (mBackground != null) {
14159            mBackground.setCallback(null);
14160            unscheduleDrawable(mBackground);
14161        }
14162
14163        if (background != null) {
14164            Rect padding = sThreadLocal.get();
14165            if (padding == null) {
14166                padding = new Rect();
14167                sThreadLocal.set(padding);
14168            }
14169            background.setLayoutDirection(getResolvedLayoutDirection());
14170            if (background.getPadding(padding)) {
14171                switch (background.getLayoutDirection()) {
14172                    case LAYOUT_DIRECTION_RTL:
14173                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
14174                        break;
14175                    case LAYOUT_DIRECTION_LTR:
14176                    default:
14177                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14178                }
14179            }
14180
14181            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14182            // if it has a different minimum size, we should layout again
14183            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14184                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14185                requestLayout = true;
14186            }
14187
14188            background.setCallback(this);
14189            if (background.isStateful()) {
14190                background.setState(getDrawableState());
14191            }
14192            background.setVisible(getVisibility() == VISIBLE, false);
14193            mBackground = background;
14194
14195            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14196                mPrivateFlags &= ~SKIP_DRAW;
14197                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14198                requestLayout = true;
14199            }
14200        } else {
14201            /* Remove the background */
14202            mBackground = null;
14203
14204            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14205                /*
14206                 * This view ONLY drew the background before and we're removing
14207                 * the background, so now it won't draw anything
14208                 * (hence we SKIP_DRAW)
14209                 */
14210                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14211                mPrivateFlags |= SKIP_DRAW;
14212            }
14213
14214            /*
14215             * When the background is set, we try to apply its padding to this
14216             * View. When the background is removed, we don't touch this View's
14217             * padding. This is noted in the Javadocs. Hence, we don't need to
14218             * requestLayout(), the invalidate() below is sufficient.
14219             */
14220
14221            // The old background's minimum size could have affected this
14222            // View's layout, so let's requestLayout
14223            requestLayout = true;
14224        }
14225
14226        computeOpaqueFlags();
14227
14228        if (requestLayout) {
14229            requestLayout();
14230        }
14231
14232        mBackgroundSizeChanged = true;
14233        invalidate(true);
14234    }
14235
14236    /**
14237     * Gets the background drawable
14238     *
14239     * @return The drawable used as the background for this view, if any.
14240     *
14241     * @see #setBackground(Drawable)
14242     *
14243     * @attr ref android.R.styleable#View_background
14244     */
14245    public Drawable getBackground() {
14246        return mBackground;
14247    }
14248
14249    /**
14250     * Sets the padding. The view may add on the space required to display
14251     * the scrollbars, depending on the style and visibility of the scrollbars.
14252     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14253     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14254     * from the values set in this call.
14255     *
14256     * @attr ref android.R.styleable#View_padding
14257     * @attr ref android.R.styleable#View_paddingBottom
14258     * @attr ref android.R.styleable#View_paddingLeft
14259     * @attr ref android.R.styleable#View_paddingRight
14260     * @attr ref android.R.styleable#View_paddingTop
14261     * @param left the left padding in pixels
14262     * @param top the top padding in pixels
14263     * @param right the right padding in pixels
14264     * @param bottom the bottom padding in pixels
14265     */
14266    public void setPadding(int left, int top, int right, int bottom) {
14267        mUserPaddingStart = -1;
14268        mUserPaddingEnd = -1;
14269        mUserPaddingRelative = false;
14270
14271        internalSetPadding(left, top, right, bottom);
14272    }
14273
14274    private void internalSetPadding(int left, int top, int right, int bottom) {
14275        mUserPaddingLeft = left;
14276        mUserPaddingRight = right;
14277        mUserPaddingBottom = bottom;
14278
14279        final int viewFlags = mViewFlags;
14280        boolean changed = false;
14281
14282        // Common case is there are no scroll bars.
14283        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14284            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14285                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14286                        ? 0 : getVerticalScrollbarWidth();
14287                switch (mVerticalScrollbarPosition) {
14288                    case SCROLLBAR_POSITION_DEFAULT:
14289                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14290                            left += offset;
14291                        } else {
14292                            right += offset;
14293                        }
14294                        break;
14295                    case SCROLLBAR_POSITION_RIGHT:
14296                        right += offset;
14297                        break;
14298                    case SCROLLBAR_POSITION_LEFT:
14299                        left += offset;
14300                        break;
14301                }
14302            }
14303            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14304                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14305                        ? 0 : getHorizontalScrollbarHeight();
14306            }
14307        }
14308
14309        if (mPaddingLeft != left) {
14310            changed = true;
14311            mPaddingLeft = left;
14312        }
14313        if (mPaddingTop != top) {
14314            changed = true;
14315            mPaddingTop = top;
14316        }
14317        if (mPaddingRight != right) {
14318            changed = true;
14319            mPaddingRight = right;
14320        }
14321        if (mPaddingBottom != bottom) {
14322            changed = true;
14323            mPaddingBottom = bottom;
14324        }
14325
14326        if (changed) {
14327            requestLayout();
14328        }
14329    }
14330
14331    /**
14332     * Sets the relative padding. The view may add on the space required to display
14333     * the scrollbars, depending on the style and visibility of the scrollbars.
14334     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14335     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14336     * from the values set in this call.
14337     *
14338     * @attr ref android.R.styleable#View_padding
14339     * @attr ref android.R.styleable#View_paddingBottom
14340     * @attr ref android.R.styleable#View_paddingStart
14341     * @attr ref android.R.styleable#View_paddingEnd
14342     * @attr ref android.R.styleable#View_paddingTop
14343     * @param start the start padding in pixels
14344     * @param top the top padding in pixels
14345     * @param end the end padding in pixels
14346     * @param bottom the bottom padding in pixels
14347     */
14348    public void setPaddingRelative(int start, int top, int end, int bottom) {
14349        mUserPaddingStart = start;
14350        mUserPaddingEnd = end;
14351        mUserPaddingRelative = true;
14352
14353        switch(getResolvedLayoutDirection()) {
14354            case LAYOUT_DIRECTION_RTL:
14355                internalSetPadding(end, top, start, bottom);
14356                break;
14357            case LAYOUT_DIRECTION_LTR:
14358            default:
14359                internalSetPadding(start, top, end, bottom);
14360        }
14361    }
14362
14363    /**
14364     * Returns the top padding of this view.
14365     *
14366     * @return the top padding in pixels
14367     */
14368    public int getPaddingTop() {
14369        return mPaddingTop;
14370    }
14371
14372    /**
14373     * Returns the bottom padding of this view. If there are inset and enabled
14374     * scrollbars, this value may include the space required to display the
14375     * scrollbars as well.
14376     *
14377     * @return the bottom padding in pixels
14378     */
14379    public int getPaddingBottom() {
14380        return mPaddingBottom;
14381    }
14382
14383    /**
14384     * Returns the left padding of this view. If there are inset and enabled
14385     * scrollbars, this value may include the space required to display the
14386     * scrollbars as well.
14387     *
14388     * @return the left padding in pixels
14389     */
14390    public int getPaddingLeft() {
14391        return mPaddingLeft;
14392    }
14393
14394    /**
14395     * Returns the start padding of this view depending on its resolved layout direction.
14396     * If there are inset and enabled scrollbars, this value may include the space
14397     * required to display the scrollbars as well.
14398     *
14399     * @return the start padding in pixels
14400     */
14401    public int getPaddingStart() {
14402        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14403                mPaddingRight : mPaddingLeft;
14404    }
14405
14406    /**
14407     * Returns the right padding of this view. If there are inset and enabled
14408     * scrollbars, this value may include the space required to display the
14409     * scrollbars as well.
14410     *
14411     * @return the right padding in pixels
14412     */
14413    public int getPaddingRight() {
14414        return mPaddingRight;
14415    }
14416
14417    /**
14418     * Returns the end padding of this view depending on its resolved layout direction.
14419     * If there are inset and enabled scrollbars, this value may include the space
14420     * required to display the scrollbars as well.
14421     *
14422     * @return the end padding in pixels
14423     */
14424    public int getPaddingEnd() {
14425        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14426                mPaddingLeft : mPaddingRight;
14427    }
14428
14429    /**
14430     * Return if the padding as been set thru relative values
14431     * {@link #setPaddingRelative(int, int, int, int)} or thru
14432     * @attr ref android.R.styleable#View_paddingStart or
14433     * @attr ref android.R.styleable#View_paddingEnd
14434     *
14435     * @return true if the padding is relative or false if it is not.
14436     */
14437    public boolean isPaddingRelative() {
14438        return mUserPaddingRelative;
14439    }
14440
14441    /**
14442     * @hide
14443     */
14444    public Insets getOpticalInsets() {
14445        if (mLayoutInsets == null) {
14446            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14447        }
14448        return mLayoutInsets;
14449    }
14450
14451    /**
14452     * @hide
14453     */
14454    public void setLayoutInsets(Insets layoutInsets) {
14455        mLayoutInsets = layoutInsets;
14456    }
14457
14458    /**
14459     * Changes the selection state of this view. A view can be selected or not.
14460     * Note that selection is not the same as focus. Views are typically
14461     * selected in the context of an AdapterView like ListView or GridView;
14462     * the selected view is the view that is highlighted.
14463     *
14464     * @param selected true if the view must be selected, false otherwise
14465     */
14466    public void setSelected(boolean selected) {
14467        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14468            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14469            if (!selected) resetPressedState();
14470            invalidate(true);
14471            refreshDrawableState();
14472            dispatchSetSelected(selected);
14473            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14474                notifyAccessibilityStateChanged();
14475            }
14476        }
14477    }
14478
14479    /**
14480     * Dispatch setSelected to all of this View's children.
14481     *
14482     * @see #setSelected(boolean)
14483     *
14484     * @param selected The new selected state
14485     */
14486    protected void dispatchSetSelected(boolean selected) {
14487    }
14488
14489    /**
14490     * Indicates the selection state of this view.
14491     *
14492     * @return true if the view is selected, false otherwise
14493     */
14494    @ViewDebug.ExportedProperty
14495    public boolean isSelected() {
14496        return (mPrivateFlags & SELECTED) != 0;
14497    }
14498
14499    /**
14500     * Changes the activated state of this view. A view can be activated or not.
14501     * Note that activation is not the same as selection.  Selection is
14502     * a transient property, representing the view (hierarchy) the user is
14503     * currently interacting with.  Activation is a longer-term state that the
14504     * user can move views in and out of.  For example, in a list view with
14505     * single or multiple selection enabled, the views in the current selection
14506     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14507     * here.)  The activated state is propagated down to children of the view it
14508     * is set on.
14509     *
14510     * @param activated true if the view must be activated, false otherwise
14511     */
14512    public void setActivated(boolean activated) {
14513        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14514            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14515            invalidate(true);
14516            refreshDrawableState();
14517            dispatchSetActivated(activated);
14518        }
14519    }
14520
14521    /**
14522     * Dispatch setActivated to all of this View's children.
14523     *
14524     * @see #setActivated(boolean)
14525     *
14526     * @param activated The new activated state
14527     */
14528    protected void dispatchSetActivated(boolean activated) {
14529    }
14530
14531    /**
14532     * Indicates the activation state of this view.
14533     *
14534     * @return true if the view is activated, false otherwise
14535     */
14536    @ViewDebug.ExportedProperty
14537    public boolean isActivated() {
14538        return (mPrivateFlags & ACTIVATED) != 0;
14539    }
14540
14541    /**
14542     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14543     * observer can be used to get notifications when global events, like
14544     * layout, happen.
14545     *
14546     * The returned ViewTreeObserver observer is not guaranteed to remain
14547     * valid for the lifetime of this View. If the caller of this method keeps
14548     * a long-lived reference to ViewTreeObserver, it should always check for
14549     * the return value of {@link ViewTreeObserver#isAlive()}.
14550     *
14551     * @return The ViewTreeObserver for this view's hierarchy.
14552     */
14553    public ViewTreeObserver getViewTreeObserver() {
14554        if (mAttachInfo != null) {
14555            return mAttachInfo.mTreeObserver;
14556        }
14557        if (mFloatingTreeObserver == null) {
14558            mFloatingTreeObserver = new ViewTreeObserver();
14559        }
14560        return mFloatingTreeObserver;
14561    }
14562
14563    /**
14564     * <p>Finds the topmost view in the current view hierarchy.</p>
14565     *
14566     * @return the topmost view containing this view
14567     */
14568    public View getRootView() {
14569        if (mAttachInfo != null) {
14570            final View v = mAttachInfo.mRootView;
14571            if (v != null) {
14572                return v;
14573            }
14574        }
14575
14576        View parent = this;
14577
14578        while (parent.mParent != null && parent.mParent instanceof View) {
14579            parent = (View) parent.mParent;
14580        }
14581
14582        return parent;
14583    }
14584
14585    /**
14586     * <p>Computes the coordinates of this view on the screen. The argument
14587     * must be an array of two integers. After the method returns, the array
14588     * contains the x and y location in that order.</p>
14589     *
14590     * @param location an array of two integers in which to hold the coordinates
14591     */
14592    public void getLocationOnScreen(int[] location) {
14593        getLocationInWindow(location);
14594
14595        final AttachInfo info = mAttachInfo;
14596        if (info != null) {
14597            location[0] += info.mWindowLeft;
14598            location[1] += info.mWindowTop;
14599        }
14600    }
14601
14602    /**
14603     * <p>Computes the coordinates of this view in its window. The argument
14604     * must be an array of two integers. After the method returns, the array
14605     * contains the x and y location in that order.</p>
14606     *
14607     * @param location an array of two integers in which to hold the coordinates
14608     */
14609    public void getLocationInWindow(int[] location) {
14610        if (location == null || location.length < 2) {
14611            throw new IllegalArgumentException("location must be an array of two integers");
14612        }
14613
14614        if (mAttachInfo == null) {
14615            // When the view is not attached to a window, this method does not make sense
14616            location[0] = location[1] = 0;
14617            return;
14618        }
14619
14620        float[] position = mAttachInfo.mTmpTransformLocation;
14621        position[0] = position[1] = 0.0f;
14622
14623        if (!hasIdentityMatrix()) {
14624            getMatrix().mapPoints(position);
14625        }
14626
14627        position[0] += mLeft;
14628        position[1] += mTop;
14629
14630        ViewParent viewParent = mParent;
14631        while (viewParent instanceof View) {
14632            final View view = (View) viewParent;
14633
14634            position[0] -= view.mScrollX;
14635            position[1] -= view.mScrollY;
14636
14637            if (!view.hasIdentityMatrix()) {
14638                view.getMatrix().mapPoints(position);
14639            }
14640
14641            position[0] += view.mLeft;
14642            position[1] += view.mTop;
14643
14644            viewParent = view.mParent;
14645         }
14646
14647        if (viewParent instanceof ViewRootImpl) {
14648            // *cough*
14649            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14650            position[1] -= vr.mCurScrollY;
14651        }
14652
14653        location[0] = (int) (position[0] + 0.5f);
14654        location[1] = (int) (position[1] + 0.5f);
14655    }
14656
14657    /**
14658     * {@hide}
14659     * @param id the id of the view to be found
14660     * @return the view of the specified id, null if cannot be found
14661     */
14662    protected View findViewTraversal(int id) {
14663        if (id == mID) {
14664            return this;
14665        }
14666        return null;
14667    }
14668
14669    /**
14670     * {@hide}
14671     * @param tag the tag of the view to be found
14672     * @return the view of specified tag, null if cannot be found
14673     */
14674    protected View findViewWithTagTraversal(Object tag) {
14675        if (tag != null && tag.equals(mTag)) {
14676            return this;
14677        }
14678        return null;
14679    }
14680
14681    /**
14682     * {@hide}
14683     * @param predicate The predicate to evaluate.
14684     * @param childToSkip If not null, ignores this child during the recursive traversal.
14685     * @return The first view that matches the predicate or null.
14686     */
14687    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14688        if (predicate.apply(this)) {
14689            return this;
14690        }
14691        return null;
14692    }
14693
14694    /**
14695     * Look for a child view with the given id.  If this view has the given
14696     * id, return this view.
14697     *
14698     * @param id The id to search for.
14699     * @return The view that has the given id in the hierarchy or null
14700     */
14701    public final View findViewById(int id) {
14702        if (id < 0) {
14703            return null;
14704        }
14705        return findViewTraversal(id);
14706    }
14707
14708    /**
14709     * Finds a view by its unuque and stable accessibility id.
14710     *
14711     * @param accessibilityId The searched accessibility id.
14712     * @return The found view.
14713     */
14714    final View findViewByAccessibilityId(int accessibilityId) {
14715        if (accessibilityId < 0) {
14716            return null;
14717        }
14718        return findViewByAccessibilityIdTraversal(accessibilityId);
14719    }
14720
14721    /**
14722     * Performs the traversal to find a view by its unuque and stable accessibility id.
14723     *
14724     * <strong>Note:</strong>This method does not stop at the root namespace
14725     * boundary since the user can touch the screen at an arbitrary location
14726     * potentially crossing the root namespace bounday which will send an
14727     * accessibility event to accessibility services and they should be able
14728     * to obtain the event source. Also accessibility ids are guaranteed to be
14729     * unique in the window.
14730     *
14731     * @param accessibilityId The accessibility id.
14732     * @return The found view.
14733     */
14734    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14735        if (getAccessibilityViewId() == accessibilityId) {
14736            return this;
14737        }
14738        return null;
14739    }
14740
14741    /**
14742     * Look for a child view with the given tag.  If this view has the given
14743     * tag, return this view.
14744     *
14745     * @param tag The tag to search for, using "tag.equals(getTag())".
14746     * @return The View that has the given tag in the hierarchy or null
14747     */
14748    public final View findViewWithTag(Object tag) {
14749        if (tag == null) {
14750            return null;
14751        }
14752        return findViewWithTagTraversal(tag);
14753    }
14754
14755    /**
14756     * {@hide}
14757     * Look for a child view that matches the specified predicate.
14758     * If this view matches the predicate, return this view.
14759     *
14760     * @param predicate The predicate to evaluate.
14761     * @return The first view that matches the predicate or null.
14762     */
14763    public final View findViewByPredicate(Predicate<View> predicate) {
14764        return findViewByPredicateTraversal(predicate, null);
14765    }
14766
14767    /**
14768     * {@hide}
14769     * Look for a child view that matches the specified predicate,
14770     * starting with the specified view and its descendents and then
14771     * recusively searching the ancestors and siblings of that view
14772     * until this view is reached.
14773     *
14774     * This method is useful in cases where the predicate does not match
14775     * a single unique view (perhaps multiple views use the same id)
14776     * and we are trying to find the view that is "closest" in scope to the
14777     * starting view.
14778     *
14779     * @param start The view to start from.
14780     * @param predicate The predicate to evaluate.
14781     * @return The first view that matches the predicate or null.
14782     */
14783    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14784        View childToSkip = null;
14785        for (;;) {
14786            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14787            if (view != null || start == this) {
14788                return view;
14789            }
14790
14791            ViewParent parent = start.getParent();
14792            if (parent == null || !(parent instanceof View)) {
14793                return null;
14794            }
14795
14796            childToSkip = start;
14797            start = (View) parent;
14798        }
14799    }
14800
14801    /**
14802     * Sets the identifier for this view. The identifier does not have to be
14803     * unique in this view's hierarchy. The identifier should be a positive
14804     * number.
14805     *
14806     * @see #NO_ID
14807     * @see #getId()
14808     * @see #findViewById(int)
14809     *
14810     * @param id a number used to identify the view
14811     *
14812     * @attr ref android.R.styleable#View_id
14813     */
14814    public void setId(int id) {
14815        mID = id;
14816    }
14817
14818    /**
14819     * {@hide}
14820     *
14821     * @param isRoot true if the view belongs to the root namespace, false
14822     *        otherwise
14823     */
14824    public void setIsRootNamespace(boolean isRoot) {
14825        if (isRoot) {
14826            mPrivateFlags |= IS_ROOT_NAMESPACE;
14827        } else {
14828            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14829        }
14830    }
14831
14832    /**
14833     * {@hide}
14834     *
14835     * @return true if the view belongs to the root namespace, false otherwise
14836     */
14837    public boolean isRootNamespace() {
14838        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14839    }
14840
14841    /**
14842     * Returns this view's identifier.
14843     *
14844     * @return a positive integer used to identify the view or {@link #NO_ID}
14845     *         if the view has no ID
14846     *
14847     * @see #setId(int)
14848     * @see #findViewById(int)
14849     * @attr ref android.R.styleable#View_id
14850     */
14851    @ViewDebug.CapturedViewProperty
14852    public int getId() {
14853        return mID;
14854    }
14855
14856    /**
14857     * Returns this view's tag.
14858     *
14859     * @return the Object stored in this view as a tag
14860     *
14861     * @see #setTag(Object)
14862     * @see #getTag(int)
14863     */
14864    @ViewDebug.ExportedProperty
14865    public Object getTag() {
14866        return mTag;
14867    }
14868
14869    /**
14870     * Sets the tag associated with this view. A tag can be used to mark
14871     * a view in its hierarchy and does not have to be unique within the
14872     * hierarchy. Tags can also be used to store data within a view without
14873     * resorting to another data structure.
14874     *
14875     * @param tag an Object to tag the view with
14876     *
14877     * @see #getTag()
14878     * @see #setTag(int, Object)
14879     */
14880    public void setTag(final Object tag) {
14881        mTag = tag;
14882    }
14883
14884    /**
14885     * Returns the tag associated with this view and the specified key.
14886     *
14887     * @param key The key identifying the tag
14888     *
14889     * @return the Object stored in this view as a tag
14890     *
14891     * @see #setTag(int, Object)
14892     * @see #getTag()
14893     */
14894    public Object getTag(int key) {
14895        if (mKeyedTags != null) return mKeyedTags.get(key);
14896        return null;
14897    }
14898
14899    /**
14900     * Sets a tag associated with this view and a key. A tag can be used
14901     * to mark a view in its hierarchy and does not have to be unique within
14902     * the hierarchy. Tags can also be used to store data within a view
14903     * without resorting to another data structure.
14904     *
14905     * The specified key should be an id declared in the resources of the
14906     * application to ensure it is unique (see the <a
14907     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14908     * Keys identified as belonging to
14909     * the Android framework or not associated with any package will cause
14910     * an {@link IllegalArgumentException} to be thrown.
14911     *
14912     * @param key The key identifying the tag
14913     * @param tag An Object to tag the view with
14914     *
14915     * @throws IllegalArgumentException If they specified key is not valid
14916     *
14917     * @see #setTag(Object)
14918     * @see #getTag(int)
14919     */
14920    public void setTag(int key, final Object tag) {
14921        // If the package id is 0x00 or 0x01, it's either an undefined package
14922        // or a framework id
14923        if ((key >>> 24) < 2) {
14924            throw new IllegalArgumentException("The key must be an application-specific "
14925                    + "resource id.");
14926        }
14927
14928        setKeyedTag(key, tag);
14929    }
14930
14931    /**
14932     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14933     * framework id.
14934     *
14935     * @hide
14936     */
14937    public void setTagInternal(int key, Object tag) {
14938        if ((key >>> 24) != 0x1) {
14939            throw new IllegalArgumentException("The key must be a framework-specific "
14940                    + "resource id.");
14941        }
14942
14943        setKeyedTag(key, tag);
14944    }
14945
14946    private void setKeyedTag(int key, Object tag) {
14947        if (mKeyedTags == null) {
14948            mKeyedTags = new SparseArray<Object>();
14949        }
14950
14951        mKeyedTags.put(key, tag);
14952    }
14953
14954    /**
14955     * Prints information about this view in the log output, with the tag
14956     * {@link #VIEW_LOG_TAG}.
14957     *
14958     * @hide
14959     */
14960    public void debug() {
14961        debug(0);
14962    }
14963
14964    /**
14965     * Prints information about this view in the log output, with the tag
14966     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14967     * indentation defined by the <code>depth</code>.
14968     *
14969     * @param depth the indentation level
14970     *
14971     * @hide
14972     */
14973    protected void debug(int depth) {
14974        String output = debugIndent(depth - 1);
14975
14976        output += "+ " + this;
14977        int id = getId();
14978        if (id != -1) {
14979            output += " (id=" + id + ")";
14980        }
14981        Object tag = getTag();
14982        if (tag != null) {
14983            output += " (tag=" + tag + ")";
14984        }
14985        Log.d(VIEW_LOG_TAG, output);
14986
14987        if ((mPrivateFlags & FOCUSED) != 0) {
14988            output = debugIndent(depth) + " FOCUSED";
14989            Log.d(VIEW_LOG_TAG, output);
14990        }
14991
14992        output = debugIndent(depth);
14993        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14994                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14995                + "} ";
14996        Log.d(VIEW_LOG_TAG, output);
14997
14998        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14999                || mPaddingBottom != 0) {
15000            output = debugIndent(depth);
15001            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15002                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15003            Log.d(VIEW_LOG_TAG, output);
15004        }
15005
15006        output = debugIndent(depth);
15007        output += "mMeasureWidth=" + mMeasuredWidth +
15008                " mMeasureHeight=" + mMeasuredHeight;
15009        Log.d(VIEW_LOG_TAG, output);
15010
15011        output = debugIndent(depth);
15012        if (mLayoutParams == null) {
15013            output += "BAD! no layout params";
15014        } else {
15015            output = mLayoutParams.debug(output);
15016        }
15017        Log.d(VIEW_LOG_TAG, output);
15018
15019        output = debugIndent(depth);
15020        output += "flags={";
15021        output += View.printFlags(mViewFlags);
15022        output += "}";
15023        Log.d(VIEW_LOG_TAG, output);
15024
15025        output = debugIndent(depth);
15026        output += "privateFlags={";
15027        output += View.printPrivateFlags(mPrivateFlags);
15028        output += "}";
15029        Log.d(VIEW_LOG_TAG, output);
15030    }
15031
15032    /**
15033     * Creates a string of whitespaces used for indentation.
15034     *
15035     * @param depth the indentation level
15036     * @return a String containing (depth * 2 + 3) * 2 white spaces
15037     *
15038     * @hide
15039     */
15040    protected static String debugIndent(int depth) {
15041        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15042        for (int i = 0; i < (depth * 2) + 3; i++) {
15043            spaces.append(' ').append(' ');
15044        }
15045        return spaces.toString();
15046    }
15047
15048    /**
15049     * <p>Return the offset of the widget's text baseline from the widget's top
15050     * boundary. If this widget does not support baseline alignment, this
15051     * method returns -1. </p>
15052     *
15053     * @return the offset of the baseline within the widget's bounds or -1
15054     *         if baseline alignment is not supported
15055     */
15056    @ViewDebug.ExportedProperty(category = "layout")
15057    public int getBaseline() {
15058        return -1;
15059    }
15060
15061    /**
15062     * Call this when something has changed which has invalidated the
15063     * layout of this view. This will schedule a layout pass of the view
15064     * tree.
15065     */
15066    public void requestLayout() {
15067        mPrivateFlags |= FORCE_LAYOUT;
15068        mPrivateFlags |= INVALIDATED;
15069
15070        if (mLayoutParams != null) {
15071            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
15072        }
15073
15074        if (mParent != null && !mParent.isLayoutRequested()) {
15075            mParent.requestLayout();
15076        }
15077    }
15078
15079    /**
15080     * Forces this view to be laid out during the next layout pass.
15081     * This method does not call requestLayout() or forceLayout()
15082     * on the parent.
15083     */
15084    public void forceLayout() {
15085        mPrivateFlags |= FORCE_LAYOUT;
15086        mPrivateFlags |= INVALIDATED;
15087    }
15088
15089    /**
15090     * <p>
15091     * This is called to find out how big a view should be. The parent
15092     * supplies constraint information in the width and height parameters.
15093     * </p>
15094     *
15095     * <p>
15096     * The actual measurement work of a view is performed in
15097     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15098     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15099     * </p>
15100     *
15101     *
15102     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15103     *        parent
15104     * @param heightMeasureSpec Vertical space requirements as imposed by the
15105     *        parent
15106     *
15107     * @see #onMeasure(int, int)
15108     */
15109    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15110        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
15111                widthMeasureSpec != mOldWidthMeasureSpec ||
15112                heightMeasureSpec != mOldHeightMeasureSpec) {
15113
15114            // first clears the measured dimension flag
15115            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
15116
15117            // measure ourselves, this should set the measured dimension flag back
15118            onMeasure(widthMeasureSpec, heightMeasureSpec);
15119
15120            // flag not set, setMeasuredDimension() was not invoked, we raise
15121            // an exception to warn the developer
15122            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
15123                throw new IllegalStateException("onMeasure() did not set the"
15124                        + " measured dimension by calling"
15125                        + " setMeasuredDimension()");
15126            }
15127
15128            mPrivateFlags |= LAYOUT_REQUIRED;
15129        }
15130
15131        mOldWidthMeasureSpec = widthMeasureSpec;
15132        mOldHeightMeasureSpec = heightMeasureSpec;
15133    }
15134
15135    /**
15136     * <p>
15137     * Measure the view and its content to determine the measured width and the
15138     * measured height. This method is invoked by {@link #measure(int, int)} and
15139     * should be overriden by subclasses to provide accurate and efficient
15140     * measurement of their contents.
15141     * </p>
15142     *
15143     * <p>
15144     * <strong>CONTRACT:</strong> When overriding this method, you
15145     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15146     * measured width and height of this view. Failure to do so will trigger an
15147     * <code>IllegalStateException</code>, thrown by
15148     * {@link #measure(int, int)}. Calling the superclass'
15149     * {@link #onMeasure(int, int)} is a valid use.
15150     * </p>
15151     *
15152     * <p>
15153     * The base class implementation of measure defaults to the background size,
15154     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15155     * override {@link #onMeasure(int, int)} to provide better measurements of
15156     * their content.
15157     * </p>
15158     *
15159     * <p>
15160     * If this method is overridden, it is the subclass's responsibility to make
15161     * sure the measured height and width are at least the view's minimum height
15162     * and width ({@link #getSuggestedMinimumHeight()} and
15163     * {@link #getSuggestedMinimumWidth()}).
15164     * </p>
15165     *
15166     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15167     *                         The requirements are encoded with
15168     *                         {@link android.view.View.MeasureSpec}.
15169     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15170     *                         The requirements are encoded with
15171     *                         {@link android.view.View.MeasureSpec}.
15172     *
15173     * @see #getMeasuredWidth()
15174     * @see #getMeasuredHeight()
15175     * @see #setMeasuredDimension(int, int)
15176     * @see #getSuggestedMinimumHeight()
15177     * @see #getSuggestedMinimumWidth()
15178     * @see android.view.View.MeasureSpec#getMode(int)
15179     * @see android.view.View.MeasureSpec#getSize(int)
15180     */
15181    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15182        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15183                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15184    }
15185
15186    /**
15187     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15188     * measured width and measured height. Failing to do so will trigger an
15189     * exception at measurement time.</p>
15190     *
15191     * @param measuredWidth The measured width of this view.  May be a complex
15192     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15193     * {@link #MEASURED_STATE_TOO_SMALL}.
15194     * @param measuredHeight The measured height of this view.  May be a complex
15195     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15196     * {@link #MEASURED_STATE_TOO_SMALL}.
15197     */
15198    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15199        mMeasuredWidth = measuredWidth;
15200        mMeasuredHeight = measuredHeight;
15201
15202        mPrivateFlags |= MEASURED_DIMENSION_SET;
15203    }
15204
15205    /**
15206     * Merge two states as returned by {@link #getMeasuredState()}.
15207     * @param curState The current state as returned from a view or the result
15208     * of combining multiple views.
15209     * @param newState The new view state to combine.
15210     * @return Returns a new integer reflecting the combination of the two
15211     * states.
15212     */
15213    public static int combineMeasuredStates(int curState, int newState) {
15214        return curState | newState;
15215    }
15216
15217    /**
15218     * Version of {@link #resolveSizeAndState(int, int, int)}
15219     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15220     */
15221    public static int resolveSize(int size, int measureSpec) {
15222        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15223    }
15224
15225    /**
15226     * Utility to reconcile a desired size and state, with constraints imposed
15227     * by a MeasureSpec.  Will take the desired size, unless a different size
15228     * is imposed by the constraints.  The returned value is a compound integer,
15229     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15230     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15231     * size is smaller than the size the view wants to be.
15232     *
15233     * @param size How big the view wants to be
15234     * @param measureSpec Constraints imposed by the parent
15235     * @return Size information bit mask as defined by
15236     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15237     */
15238    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15239        int result = size;
15240        int specMode = MeasureSpec.getMode(measureSpec);
15241        int specSize =  MeasureSpec.getSize(measureSpec);
15242        switch (specMode) {
15243        case MeasureSpec.UNSPECIFIED:
15244            result = size;
15245            break;
15246        case MeasureSpec.AT_MOST:
15247            if (specSize < size) {
15248                result = specSize | MEASURED_STATE_TOO_SMALL;
15249            } else {
15250                result = size;
15251            }
15252            break;
15253        case MeasureSpec.EXACTLY:
15254            result = specSize;
15255            break;
15256        }
15257        return result | (childMeasuredState&MEASURED_STATE_MASK);
15258    }
15259
15260    /**
15261     * Utility to return a default size. Uses the supplied size if the
15262     * MeasureSpec imposed no constraints. Will get larger if allowed
15263     * by the MeasureSpec.
15264     *
15265     * @param size Default size for this view
15266     * @param measureSpec Constraints imposed by the parent
15267     * @return The size this view should be.
15268     */
15269    public static int getDefaultSize(int size, int measureSpec) {
15270        int result = size;
15271        int specMode = MeasureSpec.getMode(measureSpec);
15272        int specSize = MeasureSpec.getSize(measureSpec);
15273
15274        switch (specMode) {
15275        case MeasureSpec.UNSPECIFIED:
15276            result = size;
15277            break;
15278        case MeasureSpec.AT_MOST:
15279        case MeasureSpec.EXACTLY:
15280            result = specSize;
15281            break;
15282        }
15283        return result;
15284    }
15285
15286    /**
15287     * Returns the suggested minimum height that the view should use. This
15288     * returns the maximum of the view's minimum height
15289     * and the background's minimum height
15290     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15291     * <p>
15292     * When being used in {@link #onMeasure(int, int)}, the caller should still
15293     * ensure the returned height is within the requirements of the parent.
15294     *
15295     * @return The suggested minimum height of the view.
15296     */
15297    protected int getSuggestedMinimumHeight() {
15298        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15299
15300    }
15301
15302    /**
15303     * Returns the suggested minimum width that the view should use. This
15304     * returns the maximum of the view's minimum width)
15305     * and the background's minimum width
15306     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15307     * <p>
15308     * When being used in {@link #onMeasure(int, int)}, the caller should still
15309     * ensure the returned width is within the requirements of the parent.
15310     *
15311     * @return The suggested minimum width of the view.
15312     */
15313    protected int getSuggestedMinimumWidth() {
15314        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15315    }
15316
15317    /**
15318     * Returns the minimum height of the view.
15319     *
15320     * @return the minimum height the view will try to be.
15321     *
15322     * @see #setMinimumHeight(int)
15323     *
15324     * @attr ref android.R.styleable#View_minHeight
15325     */
15326    public int getMinimumHeight() {
15327        return mMinHeight;
15328    }
15329
15330    /**
15331     * Sets the minimum height of the view. It is not guaranteed the view will
15332     * be able to achieve this minimum height (for example, if its parent layout
15333     * constrains it with less available height).
15334     *
15335     * @param minHeight The minimum height the view will try to be.
15336     *
15337     * @see #getMinimumHeight()
15338     *
15339     * @attr ref android.R.styleable#View_minHeight
15340     */
15341    public void setMinimumHeight(int minHeight) {
15342        mMinHeight = minHeight;
15343        requestLayout();
15344    }
15345
15346    /**
15347     * Returns the minimum width of the view.
15348     *
15349     * @return the minimum width the view will try to be.
15350     *
15351     * @see #setMinimumWidth(int)
15352     *
15353     * @attr ref android.R.styleable#View_minWidth
15354     */
15355    public int getMinimumWidth() {
15356        return mMinWidth;
15357    }
15358
15359    /**
15360     * Sets the minimum width of the view. It is not guaranteed the view will
15361     * be able to achieve this minimum width (for example, if its parent layout
15362     * constrains it with less available width).
15363     *
15364     * @param minWidth The minimum width the view will try to be.
15365     *
15366     * @see #getMinimumWidth()
15367     *
15368     * @attr ref android.R.styleable#View_minWidth
15369     */
15370    public void setMinimumWidth(int minWidth) {
15371        mMinWidth = minWidth;
15372        requestLayout();
15373
15374    }
15375
15376    /**
15377     * Get the animation currently associated with this view.
15378     *
15379     * @return The animation that is currently playing or
15380     *         scheduled to play for this view.
15381     */
15382    public Animation getAnimation() {
15383        return mCurrentAnimation;
15384    }
15385
15386    /**
15387     * Start the specified animation now.
15388     *
15389     * @param animation the animation to start now
15390     */
15391    public void startAnimation(Animation animation) {
15392        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15393        setAnimation(animation);
15394        invalidateParentCaches();
15395        invalidate(true);
15396    }
15397
15398    /**
15399     * Cancels any animations for this view.
15400     */
15401    public void clearAnimation() {
15402        if (mCurrentAnimation != null) {
15403            mCurrentAnimation.detach();
15404        }
15405        mCurrentAnimation = null;
15406        invalidateParentIfNeeded();
15407    }
15408
15409    /**
15410     * Sets the next animation to play for this view.
15411     * If you want the animation to play immediately, use
15412     * {@link #startAnimation(android.view.animation.Animation)} instead.
15413     * This method provides allows fine-grained
15414     * control over the start time and invalidation, but you
15415     * must make sure that 1) the animation has a start time set, and
15416     * 2) the view's parent (which controls animations on its children)
15417     * will be invalidated when the animation is supposed to
15418     * start.
15419     *
15420     * @param animation The next animation, or null.
15421     */
15422    public void setAnimation(Animation animation) {
15423        mCurrentAnimation = animation;
15424
15425        if (animation != null) {
15426            // If the screen is off assume the animation start time is now instead of
15427            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15428            // would cause the animation to start when the screen turns back on
15429            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15430                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15431                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15432            }
15433            animation.reset();
15434        }
15435    }
15436
15437    /**
15438     * Invoked by a parent ViewGroup to notify the start of the animation
15439     * currently associated with this view. If you override this method,
15440     * always call super.onAnimationStart();
15441     *
15442     * @see #setAnimation(android.view.animation.Animation)
15443     * @see #getAnimation()
15444     */
15445    protected void onAnimationStart() {
15446        mPrivateFlags |= ANIMATION_STARTED;
15447    }
15448
15449    /**
15450     * Invoked by a parent ViewGroup to notify the end of the animation
15451     * currently associated with this view. If you override this method,
15452     * always call super.onAnimationEnd();
15453     *
15454     * @see #setAnimation(android.view.animation.Animation)
15455     * @see #getAnimation()
15456     */
15457    protected void onAnimationEnd() {
15458        mPrivateFlags &= ~ANIMATION_STARTED;
15459    }
15460
15461    /**
15462     * Invoked if there is a Transform that involves alpha. Subclass that can
15463     * draw themselves with the specified alpha should return true, and then
15464     * respect that alpha when their onDraw() is called. If this returns false
15465     * then the view may be redirected to draw into an offscreen buffer to
15466     * fulfill the request, which will look fine, but may be slower than if the
15467     * subclass handles it internally. The default implementation returns false.
15468     *
15469     * @param alpha The alpha (0..255) to apply to the view's drawing
15470     * @return true if the view can draw with the specified alpha.
15471     */
15472    protected boolean onSetAlpha(int alpha) {
15473        return false;
15474    }
15475
15476    /**
15477     * This is used by the RootView to perform an optimization when
15478     * the view hierarchy contains one or several SurfaceView.
15479     * SurfaceView is always considered transparent, but its children are not,
15480     * therefore all View objects remove themselves from the global transparent
15481     * region (passed as a parameter to this function).
15482     *
15483     * @param region The transparent region for this ViewAncestor (window).
15484     *
15485     * @return Returns true if the effective visibility of the view at this
15486     * point is opaque, regardless of the transparent region; returns false
15487     * if it is possible for underlying windows to be seen behind the view.
15488     *
15489     * {@hide}
15490     */
15491    public boolean gatherTransparentRegion(Region region) {
15492        final AttachInfo attachInfo = mAttachInfo;
15493        if (region != null && attachInfo != null) {
15494            final int pflags = mPrivateFlags;
15495            if ((pflags & SKIP_DRAW) == 0) {
15496                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15497                // remove it from the transparent region.
15498                final int[] location = attachInfo.mTransparentLocation;
15499                getLocationInWindow(location);
15500                region.op(location[0], location[1], location[0] + mRight - mLeft,
15501                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15502            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15503                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15504                // exists, so we remove the background drawable's non-transparent
15505                // parts from this transparent region.
15506                applyDrawableToTransparentRegion(mBackground, region);
15507            }
15508        }
15509        return true;
15510    }
15511
15512    /**
15513     * Play a sound effect for this view.
15514     *
15515     * <p>The framework will play sound effects for some built in actions, such as
15516     * clicking, but you may wish to play these effects in your widget,
15517     * for instance, for internal navigation.
15518     *
15519     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15520     * {@link #isSoundEffectsEnabled()} is true.
15521     *
15522     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15523     */
15524    public void playSoundEffect(int soundConstant) {
15525        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15526            return;
15527        }
15528        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15529    }
15530
15531    /**
15532     * BZZZTT!!1!
15533     *
15534     * <p>Provide haptic feedback to the user for this view.
15535     *
15536     * <p>The framework will provide haptic feedback for some built in actions,
15537     * such as long presses, but you may wish to provide feedback for your
15538     * own widget.
15539     *
15540     * <p>The feedback will only be performed if
15541     * {@link #isHapticFeedbackEnabled()} is true.
15542     *
15543     * @param feedbackConstant One of the constants defined in
15544     * {@link HapticFeedbackConstants}
15545     */
15546    public boolean performHapticFeedback(int feedbackConstant) {
15547        return performHapticFeedback(feedbackConstant, 0);
15548    }
15549
15550    /**
15551     * BZZZTT!!1!
15552     *
15553     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15554     *
15555     * @param feedbackConstant One of the constants defined in
15556     * {@link HapticFeedbackConstants}
15557     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15558     */
15559    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15560        if (mAttachInfo == null) {
15561            return false;
15562        }
15563        //noinspection SimplifiableIfStatement
15564        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15565                && !isHapticFeedbackEnabled()) {
15566            return false;
15567        }
15568        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15569                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15570    }
15571
15572    /**
15573     * Request that the visibility of the status bar or other screen/window
15574     * decorations be changed.
15575     *
15576     * <p>This method is used to put the over device UI into temporary modes
15577     * where the user's attention is focused more on the application content,
15578     * by dimming or hiding surrounding system affordances.  This is typically
15579     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15580     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15581     * to be placed behind the action bar (and with these flags other system
15582     * affordances) so that smooth transitions between hiding and showing them
15583     * can be done.
15584     *
15585     * <p>Two representative examples of the use of system UI visibility is
15586     * implementing a content browsing application (like a magazine reader)
15587     * and a video playing application.
15588     *
15589     * <p>The first code shows a typical implementation of a View in a content
15590     * browsing application.  In this implementation, the application goes
15591     * into a content-oriented mode by hiding the status bar and action bar,
15592     * and putting the navigation elements into lights out mode.  The user can
15593     * then interact with content while in this mode.  Such an application should
15594     * provide an easy way for the user to toggle out of the mode (such as to
15595     * check information in the status bar or access notifications).  In the
15596     * implementation here, this is done simply by tapping on the content.
15597     *
15598     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15599     *      content}
15600     *
15601     * <p>This second code sample shows a typical implementation of a View
15602     * in a video playing application.  In this situation, while the video is
15603     * playing the application would like to go into a complete full-screen mode,
15604     * to use as much of the display as possible for the video.  When in this state
15605     * the user can not interact with the application; the system intercepts
15606     * touching on the screen to pop the UI out of full screen mode.  See
15607     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15608     *
15609     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15610     *      content}
15611     *
15612     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15613     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15614     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15615     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15616     */
15617    public void setSystemUiVisibility(int visibility) {
15618        if (visibility != mSystemUiVisibility) {
15619            mSystemUiVisibility = visibility;
15620            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15621                mParent.recomputeViewAttributes(this);
15622            }
15623        }
15624    }
15625
15626    /**
15627     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15628     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15629     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15630     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15631     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15632     */
15633    public int getSystemUiVisibility() {
15634        return mSystemUiVisibility;
15635    }
15636
15637    /**
15638     * Returns the current system UI visibility that is currently set for
15639     * the entire window.  This is the combination of the
15640     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15641     * views in the window.
15642     */
15643    public int getWindowSystemUiVisibility() {
15644        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15645    }
15646
15647    /**
15648     * Override to find out when the window's requested system UI visibility
15649     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15650     * This is different from the callbacks recieved through
15651     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15652     * in that this is only telling you about the local request of the window,
15653     * not the actual values applied by the system.
15654     */
15655    public void onWindowSystemUiVisibilityChanged(int visible) {
15656    }
15657
15658    /**
15659     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15660     * the view hierarchy.
15661     */
15662    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15663        onWindowSystemUiVisibilityChanged(visible);
15664    }
15665
15666    /**
15667     * Set a listener to receive callbacks when the visibility of the system bar changes.
15668     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15669     */
15670    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15671        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15672        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15673            mParent.recomputeViewAttributes(this);
15674        }
15675    }
15676
15677    /**
15678     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15679     * the view hierarchy.
15680     */
15681    public void dispatchSystemUiVisibilityChanged(int visibility) {
15682        ListenerInfo li = mListenerInfo;
15683        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15684            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15685                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15686        }
15687    }
15688
15689    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15690        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15691        if (val != mSystemUiVisibility) {
15692            setSystemUiVisibility(val);
15693            return true;
15694        }
15695        return false;
15696    }
15697
15698    /** @hide */
15699    public void setDisabledSystemUiVisibility(int flags) {
15700        if (mAttachInfo != null) {
15701            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15702                mAttachInfo.mDisabledSystemUiVisibility = flags;
15703                if (mParent != null) {
15704                    mParent.recomputeViewAttributes(this);
15705                }
15706            }
15707        }
15708    }
15709
15710    /**
15711     * Creates an image that the system displays during the drag and drop
15712     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15713     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15714     * appearance as the given View. The default also positions the center of the drag shadow
15715     * directly under the touch point. If no View is provided (the constructor with no parameters
15716     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15717     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15718     * default is an invisible drag shadow.
15719     * <p>
15720     * You are not required to use the View you provide to the constructor as the basis of the
15721     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15722     * anything you want as the drag shadow.
15723     * </p>
15724     * <p>
15725     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15726     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15727     *  size and position of the drag shadow. It uses this data to construct a
15728     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15729     *  so that your application can draw the shadow image in the Canvas.
15730     * </p>
15731     *
15732     * <div class="special reference">
15733     * <h3>Developer Guides</h3>
15734     * <p>For a guide to implementing drag and drop features, read the
15735     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15736     * </div>
15737     */
15738    public static class DragShadowBuilder {
15739        private final WeakReference<View> mView;
15740
15741        /**
15742         * Constructs a shadow image builder based on a View. By default, the resulting drag
15743         * shadow will have the same appearance and dimensions as the View, with the touch point
15744         * over the center of the View.
15745         * @param view A View. Any View in scope can be used.
15746         */
15747        public DragShadowBuilder(View view) {
15748            mView = new WeakReference<View>(view);
15749        }
15750
15751        /**
15752         * Construct a shadow builder object with no associated View.  This
15753         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15754         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15755         * to supply the drag shadow's dimensions and appearance without
15756         * reference to any View object. If they are not overridden, then the result is an
15757         * invisible drag shadow.
15758         */
15759        public DragShadowBuilder() {
15760            mView = new WeakReference<View>(null);
15761        }
15762
15763        /**
15764         * Returns the View object that had been passed to the
15765         * {@link #View.DragShadowBuilder(View)}
15766         * constructor.  If that View parameter was {@code null} or if the
15767         * {@link #View.DragShadowBuilder()}
15768         * constructor was used to instantiate the builder object, this method will return
15769         * null.
15770         *
15771         * @return The View object associate with this builder object.
15772         */
15773        @SuppressWarnings({"JavadocReference"})
15774        final public View getView() {
15775            return mView.get();
15776        }
15777
15778        /**
15779         * Provides the metrics for the shadow image. These include the dimensions of
15780         * the shadow image, and the point within that shadow that should
15781         * be centered under the touch location while dragging.
15782         * <p>
15783         * The default implementation sets the dimensions of the shadow to be the
15784         * same as the dimensions of the View itself and centers the shadow under
15785         * the touch point.
15786         * </p>
15787         *
15788         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15789         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15790         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15791         * image.
15792         *
15793         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15794         * shadow image that should be underneath the touch point during the drag and drop
15795         * operation. Your application must set {@link android.graphics.Point#x} to the
15796         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15797         */
15798        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15799            final View view = mView.get();
15800            if (view != null) {
15801                shadowSize.set(view.getWidth(), view.getHeight());
15802                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15803            } else {
15804                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15805            }
15806        }
15807
15808        /**
15809         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15810         * based on the dimensions it received from the
15811         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15812         *
15813         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15814         */
15815        public void onDrawShadow(Canvas canvas) {
15816            final View view = mView.get();
15817            if (view != null) {
15818                view.draw(canvas);
15819            } else {
15820                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15821            }
15822        }
15823    }
15824
15825    /**
15826     * Starts a drag and drop operation. When your application calls this method, it passes a
15827     * {@link android.view.View.DragShadowBuilder} object to the system. The
15828     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15829     * to get metrics for the drag shadow, and then calls the object's
15830     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15831     * <p>
15832     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15833     *  drag events to all the View objects in your application that are currently visible. It does
15834     *  this either by calling the View object's drag listener (an implementation of
15835     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15836     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15837     *  Both are passed a {@link android.view.DragEvent} object that has a
15838     *  {@link android.view.DragEvent#getAction()} value of
15839     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15840     * </p>
15841     * <p>
15842     * Your application can invoke startDrag() on any attached View object. The View object does not
15843     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15844     * be related to the View the user selected for dragging.
15845     * </p>
15846     * @param data A {@link android.content.ClipData} object pointing to the data to be
15847     * transferred by the drag and drop operation.
15848     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15849     * drag shadow.
15850     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15851     * drop operation. This Object is put into every DragEvent object sent by the system during the
15852     * current drag.
15853     * <p>
15854     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15855     * to the target Views. For example, it can contain flags that differentiate between a
15856     * a copy operation and a move operation.
15857     * </p>
15858     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15859     * so the parameter should be set to 0.
15860     * @return {@code true} if the method completes successfully, or
15861     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15862     * do a drag, and so no drag operation is in progress.
15863     */
15864    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15865            Object myLocalState, int flags) {
15866        if (ViewDebug.DEBUG_DRAG) {
15867            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15868        }
15869        boolean okay = false;
15870
15871        Point shadowSize = new Point();
15872        Point shadowTouchPoint = new Point();
15873        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15874
15875        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15876                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15877            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15878        }
15879
15880        if (ViewDebug.DEBUG_DRAG) {
15881            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15882                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15883        }
15884        Surface surface = new Surface();
15885        try {
15886            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15887                    flags, shadowSize.x, shadowSize.y, surface);
15888            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15889                    + " surface=" + surface);
15890            if (token != null) {
15891                Canvas canvas = surface.lockCanvas(null);
15892                try {
15893                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15894                    shadowBuilder.onDrawShadow(canvas);
15895                } finally {
15896                    surface.unlockCanvasAndPost(canvas);
15897                }
15898
15899                final ViewRootImpl root = getViewRootImpl();
15900
15901                // Cache the local state object for delivery with DragEvents
15902                root.setLocalDragState(myLocalState);
15903
15904                // repurpose 'shadowSize' for the last touch point
15905                root.getLastTouchPoint(shadowSize);
15906
15907                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15908                        shadowSize.x, shadowSize.y,
15909                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15910                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15911
15912                // Off and running!  Release our local surface instance; the drag
15913                // shadow surface is now managed by the system process.
15914                surface.release();
15915            }
15916        } catch (Exception e) {
15917            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15918            surface.destroy();
15919        }
15920
15921        return okay;
15922    }
15923
15924    /**
15925     * Handles drag events sent by the system following a call to
15926     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15927     *<p>
15928     * When the system calls this method, it passes a
15929     * {@link android.view.DragEvent} object. A call to
15930     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15931     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15932     * operation.
15933     * @param event The {@link android.view.DragEvent} sent by the system.
15934     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15935     * in DragEvent, indicating the type of drag event represented by this object.
15936     * @return {@code true} if the method was successful, otherwise {@code false}.
15937     * <p>
15938     *  The method should return {@code true} in response to an action type of
15939     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15940     *  operation.
15941     * </p>
15942     * <p>
15943     *  The method should also return {@code true} in response to an action type of
15944     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15945     *  {@code false} if it didn't.
15946     * </p>
15947     */
15948    public boolean onDragEvent(DragEvent event) {
15949        return false;
15950    }
15951
15952    /**
15953     * Detects if this View is enabled and has a drag event listener.
15954     * If both are true, then it calls the drag event listener with the
15955     * {@link android.view.DragEvent} it received. If the drag event listener returns
15956     * {@code true}, then dispatchDragEvent() returns {@code true}.
15957     * <p>
15958     * For all other cases, the method calls the
15959     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15960     * method and returns its result.
15961     * </p>
15962     * <p>
15963     * This ensures that a drag event is always consumed, even if the View does not have a drag
15964     * event listener. However, if the View has a listener and the listener returns true, then
15965     * onDragEvent() is not called.
15966     * </p>
15967     */
15968    public boolean dispatchDragEvent(DragEvent event) {
15969        //noinspection SimplifiableIfStatement
15970        ListenerInfo li = mListenerInfo;
15971        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15972                && li.mOnDragListener.onDrag(this, event)) {
15973            return true;
15974        }
15975        return onDragEvent(event);
15976    }
15977
15978    boolean canAcceptDrag() {
15979        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15980    }
15981
15982    /**
15983     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15984     * it is ever exposed at all.
15985     * @hide
15986     */
15987    public void onCloseSystemDialogs(String reason) {
15988    }
15989
15990    /**
15991     * Given a Drawable whose bounds have been set to draw into this view,
15992     * update a Region being computed for
15993     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15994     * that any non-transparent parts of the Drawable are removed from the
15995     * given transparent region.
15996     *
15997     * @param dr The Drawable whose transparency is to be applied to the region.
15998     * @param region A Region holding the current transparency information,
15999     * where any parts of the region that are set are considered to be
16000     * transparent.  On return, this region will be modified to have the
16001     * transparency information reduced by the corresponding parts of the
16002     * Drawable that are not transparent.
16003     * {@hide}
16004     */
16005    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16006        if (DBG) {
16007            Log.i("View", "Getting transparent region for: " + this);
16008        }
16009        final Region r = dr.getTransparentRegion();
16010        final Rect db = dr.getBounds();
16011        final AttachInfo attachInfo = mAttachInfo;
16012        if (r != null && attachInfo != null) {
16013            final int w = getRight()-getLeft();
16014            final int h = getBottom()-getTop();
16015            if (db.left > 0) {
16016                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16017                r.op(0, 0, db.left, h, Region.Op.UNION);
16018            }
16019            if (db.right < w) {
16020                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16021                r.op(db.right, 0, w, h, Region.Op.UNION);
16022            }
16023            if (db.top > 0) {
16024                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16025                r.op(0, 0, w, db.top, Region.Op.UNION);
16026            }
16027            if (db.bottom < h) {
16028                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16029                r.op(0, db.bottom, w, h, Region.Op.UNION);
16030            }
16031            final int[] location = attachInfo.mTransparentLocation;
16032            getLocationInWindow(location);
16033            r.translate(location[0], location[1]);
16034            region.op(r, Region.Op.INTERSECT);
16035        } else {
16036            region.op(db, Region.Op.DIFFERENCE);
16037        }
16038    }
16039
16040    private void checkForLongClick(int delayOffset) {
16041        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16042            mHasPerformedLongPress = false;
16043
16044            if (mPendingCheckForLongPress == null) {
16045                mPendingCheckForLongPress = new CheckForLongPress();
16046            }
16047            mPendingCheckForLongPress.rememberWindowAttachCount();
16048            postDelayed(mPendingCheckForLongPress,
16049                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16050        }
16051    }
16052
16053    /**
16054     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16055     * LayoutInflater} class, which provides a full range of options for view inflation.
16056     *
16057     * @param context The Context object for your activity or application.
16058     * @param resource The resource ID to inflate
16059     * @param root A view group that will be the parent.  Used to properly inflate the
16060     * layout_* parameters.
16061     * @see LayoutInflater
16062     */
16063    public static View inflate(Context context, int resource, ViewGroup root) {
16064        LayoutInflater factory = LayoutInflater.from(context);
16065        return factory.inflate(resource, root);
16066    }
16067
16068    /**
16069     * Scroll the view with standard behavior for scrolling beyond the normal
16070     * content boundaries. Views that call this method should override
16071     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16072     * results of an over-scroll operation.
16073     *
16074     * Views can use this method to handle any touch or fling-based scrolling.
16075     *
16076     * @param deltaX Change in X in pixels
16077     * @param deltaY Change in Y in pixels
16078     * @param scrollX Current X scroll value in pixels before applying deltaX
16079     * @param scrollY Current Y scroll value in pixels before applying deltaY
16080     * @param scrollRangeX Maximum content scroll range along the X axis
16081     * @param scrollRangeY Maximum content scroll range along the Y axis
16082     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16083     *          along the X axis.
16084     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16085     *          along the Y axis.
16086     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16087     * @return true if scrolling was clamped to an over-scroll boundary along either
16088     *          axis, false otherwise.
16089     */
16090    @SuppressWarnings({"UnusedParameters"})
16091    protected boolean overScrollBy(int deltaX, int deltaY,
16092            int scrollX, int scrollY,
16093            int scrollRangeX, int scrollRangeY,
16094            int maxOverScrollX, int maxOverScrollY,
16095            boolean isTouchEvent) {
16096        final int overScrollMode = mOverScrollMode;
16097        final boolean canScrollHorizontal =
16098                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16099        final boolean canScrollVertical =
16100                computeVerticalScrollRange() > computeVerticalScrollExtent();
16101        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16102                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16103        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16104                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16105
16106        int newScrollX = scrollX + deltaX;
16107        if (!overScrollHorizontal) {
16108            maxOverScrollX = 0;
16109        }
16110
16111        int newScrollY = scrollY + deltaY;
16112        if (!overScrollVertical) {
16113            maxOverScrollY = 0;
16114        }
16115
16116        // Clamp values if at the limits and record
16117        final int left = -maxOverScrollX;
16118        final int right = maxOverScrollX + scrollRangeX;
16119        final int top = -maxOverScrollY;
16120        final int bottom = maxOverScrollY + scrollRangeY;
16121
16122        boolean clampedX = false;
16123        if (newScrollX > right) {
16124            newScrollX = right;
16125            clampedX = true;
16126        } else if (newScrollX < left) {
16127            newScrollX = left;
16128            clampedX = true;
16129        }
16130
16131        boolean clampedY = false;
16132        if (newScrollY > bottom) {
16133            newScrollY = bottom;
16134            clampedY = true;
16135        } else if (newScrollY < top) {
16136            newScrollY = top;
16137            clampedY = true;
16138        }
16139
16140        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16141
16142        return clampedX || clampedY;
16143    }
16144
16145    /**
16146     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16147     * respond to the results of an over-scroll operation.
16148     *
16149     * @param scrollX New X scroll value in pixels
16150     * @param scrollY New Y scroll value in pixels
16151     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16152     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16153     */
16154    protected void onOverScrolled(int scrollX, int scrollY,
16155            boolean clampedX, boolean clampedY) {
16156        // Intentionally empty.
16157    }
16158
16159    /**
16160     * Returns the over-scroll mode for this view. The result will be
16161     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16162     * (allow over-scrolling only if the view content is larger than the container),
16163     * or {@link #OVER_SCROLL_NEVER}.
16164     *
16165     * @return This view's over-scroll mode.
16166     */
16167    public int getOverScrollMode() {
16168        return mOverScrollMode;
16169    }
16170
16171    /**
16172     * Set the over-scroll mode for this view. Valid over-scroll modes are
16173     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16174     * (allow over-scrolling only if the view content is larger than the container),
16175     * or {@link #OVER_SCROLL_NEVER}.
16176     *
16177     * Setting the over-scroll mode of a view will have an effect only if the
16178     * view is capable of scrolling.
16179     *
16180     * @param overScrollMode The new over-scroll mode for this view.
16181     */
16182    public void setOverScrollMode(int overScrollMode) {
16183        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16184                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16185                overScrollMode != OVER_SCROLL_NEVER) {
16186            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16187        }
16188        mOverScrollMode = overScrollMode;
16189    }
16190
16191    /**
16192     * Gets a scale factor that determines the distance the view should scroll
16193     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16194     * @return The vertical scroll scale factor.
16195     * @hide
16196     */
16197    protected float getVerticalScrollFactor() {
16198        if (mVerticalScrollFactor == 0) {
16199            TypedValue outValue = new TypedValue();
16200            if (!mContext.getTheme().resolveAttribute(
16201                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16202                throw new IllegalStateException(
16203                        "Expected theme to define listPreferredItemHeight.");
16204            }
16205            mVerticalScrollFactor = outValue.getDimension(
16206                    mContext.getResources().getDisplayMetrics());
16207        }
16208        return mVerticalScrollFactor;
16209    }
16210
16211    /**
16212     * Gets a scale factor that determines the distance the view should scroll
16213     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16214     * @return The horizontal scroll scale factor.
16215     * @hide
16216     */
16217    protected float getHorizontalScrollFactor() {
16218        // TODO: Should use something else.
16219        return getVerticalScrollFactor();
16220    }
16221
16222    /**
16223     * Return the value specifying the text direction or policy that was set with
16224     * {@link #setTextDirection(int)}.
16225     *
16226     * @return the defined text direction. It can be one of:
16227     *
16228     * {@link #TEXT_DIRECTION_INHERIT},
16229     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16230     * {@link #TEXT_DIRECTION_ANY_RTL},
16231     * {@link #TEXT_DIRECTION_LTR},
16232     * {@link #TEXT_DIRECTION_RTL},
16233     * {@link #TEXT_DIRECTION_LOCALE}
16234     */
16235    @ViewDebug.ExportedProperty(category = "text", mapping = {
16236            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16237            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16238            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16239            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16240            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16241            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16242    })
16243    public int getTextDirection() {
16244        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16245    }
16246
16247    /**
16248     * Set the text direction.
16249     *
16250     * @param textDirection the direction to set. Should be one of:
16251     *
16252     * {@link #TEXT_DIRECTION_INHERIT},
16253     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16254     * {@link #TEXT_DIRECTION_ANY_RTL},
16255     * {@link #TEXT_DIRECTION_LTR},
16256     * {@link #TEXT_DIRECTION_RTL},
16257     * {@link #TEXT_DIRECTION_LOCALE}
16258     */
16259    public void setTextDirection(int textDirection) {
16260        if (getTextDirection() != textDirection) {
16261            // Reset the current text direction and the resolved one
16262            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16263            resetResolvedTextDirection();
16264            // Set the new text direction
16265            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16266            // Refresh
16267            requestLayout();
16268            invalidate(true);
16269        }
16270    }
16271
16272    /**
16273     * Return the resolved text direction.
16274     *
16275     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16276     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16277     * up the parent chain of the view. if there is no parent, then it will return the default
16278     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16279     *
16280     * @return the resolved text direction. Returns one of:
16281     *
16282     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16283     * {@link #TEXT_DIRECTION_ANY_RTL},
16284     * {@link #TEXT_DIRECTION_LTR},
16285     * {@link #TEXT_DIRECTION_RTL},
16286     * {@link #TEXT_DIRECTION_LOCALE}
16287     */
16288    public int getResolvedTextDirection() {
16289        // The text direction will be resolved only if needed
16290        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16291            resolveTextDirection();
16292        }
16293        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16294    }
16295
16296    /**
16297     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16298     * resolution is done.
16299     */
16300    public void resolveTextDirection() {
16301        // Reset any previous text direction resolution
16302        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16303
16304        if (hasRtlSupport()) {
16305            // Set resolved text direction flag depending on text direction flag
16306            final int textDirection = getTextDirection();
16307            switch(textDirection) {
16308                case TEXT_DIRECTION_INHERIT:
16309                    if (canResolveTextDirection()) {
16310                        ViewGroup viewGroup = ((ViewGroup) mParent);
16311
16312                        // Set current resolved direction to the same value as the parent's one
16313                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16314                        switch (parentResolvedDirection) {
16315                            case TEXT_DIRECTION_FIRST_STRONG:
16316                            case TEXT_DIRECTION_ANY_RTL:
16317                            case TEXT_DIRECTION_LTR:
16318                            case TEXT_DIRECTION_RTL:
16319                            case TEXT_DIRECTION_LOCALE:
16320                                mPrivateFlags2 |=
16321                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16322                                break;
16323                            default:
16324                                // Default resolved direction is "first strong" heuristic
16325                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16326                        }
16327                    } else {
16328                        // We cannot do the resolution if there is no parent, so use the default one
16329                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16330                    }
16331                    break;
16332                case TEXT_DIRECTION_FIRST_STRONG:
16333                case TEXT_DIRECTION_ANY_RTL:
16334                case TEXT_DIRECTION_LTR:
16335                case TEXT_DIRECTION_RTL:
16336                case TEXT_DIRECTION_LOCALE:
16337                    // Resolved direction is the same as text direction
16338                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16339                    break;
16340                default:
16341                    // Default resolved direction is "first strong" heuristic
16342                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16343            }
16344        } else {
16345            // Default resolved direction is "first strong" heuristic
16346            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16347        }
16348
16349        // Set to resolved
16350        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16351        onResolvedTextDirectionChanged();
16352    }
16353
16354    /**
16355     * Called when text direction has been resolved. Subclasses that care about text direction
16356     * resolution should override this method.
16357     *
16358     * The default implementation does nothing.
16359     */
16360    public void onResolvedTextDirectionChanged() {
16361    }
16362
16363    /**
16364     * Check if text direction resolution can be done.
16365     *
16366     * @return true if text direction resolution can be done otherwise return false.
16367     */
16368    public boolean canResolveTextDirection() {
16369        switch (getTextDirection()) {
16370            case TEXT_DIRECTION_INHERIT:
16371                return (mParent != null) && (mParent instanceof ViewGroup);
16372            default:
16373                return true;
16374        }
16375    }
16376
16377    /**
16378     * Reset resolved text direction. Text direction can be resolved with a call to
16379     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16380     * reset is done.
16381     */
16382    public void resetResolvedTextDirection() {
16383        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16384        onResolvedTextDirectionReset();
16385    }
16386
16387    /**
16388     * Called when text direction is reset. Subclasses that care about text direction reset should
16389     * override this method and do a reset of the text direction of their children. The default
16390     * implementation does nothing.
16391     */
16392    public void onResolvedTextDirectionReset() {
16393    }
16394
16395    /**
16396     * Return the value specifying the text alignment or policy that was set with
16397     * {@link #setTextAlignment(int)}.
16398     *
16399     * @return the defined text alignment. It can be one of:
16400     *
16401     * {@link #TEXT_ALIGNMENT_INHERIT},
16402     * {@link #TEXT_ALIGNMENT_GRAVITY},
16403     * {@link #TEXT_ALIGNMENT_CENTER},
16404     * {@link #TEXT_ALIGNMENT_TEXT_START},
16405     * {@link #TEXT_ALIGNMENT_TEXT_END},
16406     * {@link #TEXT_ALIGNMENT_VIEW_START},
16407     * {@link #TEXT_ALIGNMENT_VIEW_END}
16408     */
16409    @ViewDebug.ExportedProperty(category = "text", mapping = {
16410            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16411            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16412            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16413            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16414            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16415            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16416            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16417    })
16418    public int getTextAlignment() {
16419        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16420    }
16421
16422    /**
16423     * Set the text alignment.
16424     *
16425     * @param textAlignment The text alignment to set. Should be one of
16426     *
16427     * {@link #TEXT_ALIGNMENT_INHERIT},
16428     * {@link #TEXT_ALIGNMENT_GRAVITY},
16429     * {@link #TEXT_ALIGNMENT_CENTER},
16430     * {@link #TEXT_ALIGNMENT_TEXT_START},
16431     * {@link #TEXT_ALIGNMENT_TEXT_END},
16432     * {@link #TEXT_ALIGNMENT_VIEW_START},
16433     * {@link #TEXT_ALIGNMENT_VIEW_END}
16434     *
16435     * @attr ref android.R.styleable#View_textAlignment
16436     */
16437    public void setTextAlignment(int textAlignment) {
16438        if (textAlignment != getTextAlignment()) {
16439            // Reset the current and resolved text alignment
16440            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16441            resetResolvedTextAlignment();
16442            // Set the new text alignment
16443            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16444            // Refresh
16445            requestLayout();
16446            invalidate(true);
16447        }
16448    }
16449
16450    /**
16451     * Return the resolved text alignment.
16452     *
16453     * The resolved text alignment. This needs resolution if the value is
16454     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16455     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16456     *
16457     * @return the resolved text alignment. Returns one of:
16458     *
16459     * {@link #TEXT_ALIGNMENT_GRAVITY},
16460     * {@link #TEXT_ALIGNMENT_CENTER},
16461     * {@link #TEXT_ALIGNMENT_TEXT_START},
16462     * {@link #TEXT_ALIGNMENT_TEXT_END},
16463     * {@link #TEXT_ALIGNMENT_VIEW_START},
16464     * {@link #TEXT_ALIGNMENT_VIEW_END}
16465     */
16466    @ViewDebug.ExportedProperty(category = "text", mapping = {
16467            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16468            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16469            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16470            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16471            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16472            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16473            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16474    })
16475    public int getResolvedTextAlignment() {
16476        // If text alignment is not resolved, then resolve it
16477        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16478            resolveTextAlignment();
16479        }
16480        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16481    }
16482
16483    /**
16484     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16485     * resolution is done.
16486     */
16487    public void resolveTextAlignment() {
16488        // Reset any previous text alignment resolution
16489        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16490
16491        if (hasRtlSupport()) {
16492            // Set resolved text alignment flag depending on text alignment flag
16493            final int textAlignment = getTextAlignment();
16494            switch (textAlignment) {
16495                case TEXT_ALIGNMENT_INHERIT:
16496                    // Check if we can resolve the text alignment
16497                    if (canResolveLayoutDirection() && mParent instanceof View) {
16498                        View view = (View) mParent;
16499
16500                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16501                        switch (parentResolvedTextAlignment) {
16502                            case TEXT_ALIGNMENT_GRAVITY:
16503                            case TEXT_ALIGNMENT_TEXT_START:
16504                            case TEXT_ALIGNMENT_TEXT_END:
16505                            case TEXT_ALIGNMENT_CENTER:
16506                            case TEXT_ALIGNMENT_VIEW_START:
16507                            case TEXT_ALIGNMENT_VIEW_END:
16508                                // Resolved text alignment is the same as the parent resolved
16509                                // text alignment
16510                                mPrivateFlags2 |=
16511                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16512                                break;
16513                            default:
16514                                // Use default resolved text alignment
16515                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16516                        }
16517                    }
16518                    else {
16519                        // We cannot do the resolution if there is no parent so use the default
16520                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16521                    }
16522                    break;
16523                case TEXT_ALIGNMENT_GRAVITY:
16524                case TEXT_ALIGNMENT_TEXT_START:
16525                case TEXT_ALIGNMENT_TEXT_END:
16526                case TEXT_ALIGNMENT_CENTER:
16527                case TEXT_ALIGNMENT_VIEW_START:
16528                case TEXT_ALIGNMENT_VIEW_END:
16529                    // Resolved text alignment is the same as text alignment
16530                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16531                    break;
16532                default:
16533                    // Use default resolved text alignment
16534                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16535            }
16536        } else {
16537            // Use default resolved text alignment
16538            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16539        }
16540
16541        // Set the resolved
16542        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16543        onResolvedTextAlignmentChanged();
16544    }
16545
16546    /**
16547     * Check if text alignment resolution can be done.
16548     *
16549     * @return true if text alignment resolution can be done otherwise return false.
16550     */
16551    public boolean canResolveTextAlignment() {
16552        switch (getTextAlignment()) {
16553            case TEXT_DIRECTION_INHERIT:
16554                return (mParent != null);
16555            default:
16556                return true;
16557        }
16558    }
16559
16560    /**
16561     * Called when text alignment has been resolved. Subclasses that care about text alignment
16562     * resolution should override this method.
16563     *
16564     * The default implementation does nothing.
16565     */
16566    public void onResolvedTextAlignmentChanged() {
16567    }
16568
16569    /**
16570     * Reset resolved text alignment. Text alignment can be resolved with a call to
16571     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16572     * reset is done.
16573     */
16574    public void resetResolvedTextAlignment() {
16575        // Reset any previous text alignment resolution
16576        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16577        onResolvedTextAlignmentReset();
16578    }
16579
16580    /**
16581     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16582     * override this method and do a reset of the text alignment of their children. The default
16583     * implementation does nothing.
16584     */
16585    public void onResolvedTextAlignmentReset() {
16586    }
16587
16588    //
16589    // Properties
16590    //
16591    /**
16592     * A Property wrapper around the <code>alpha</code> functionality handled by the
16593     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16594     */
16595    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16596        @Override
16597        public void setValue(View object, float value) {
16598            object.setAlpha(value);
16599        }
16600
16601        @Override
16602        public Float get(View object) {
16603            return object.getAlpha();
16604        }
16605    };
16606
16607    /**
16608     * A Property wrapper around the <code>translationX</code> functionality handled by the
16609     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16610     */
16611    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16612        @Override
16613        public void setValue(View object, float value) {
16614            object.setTranslationX(value);
16615        }
16616
16617                @Override
16618        public Float get(View object) {
16619            return object.getTranslationX();
16620        }
16621    };
16622
16623    /**
16624     * A Property wrapper around the <code>translationY</code> functionality handled by the
16625     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16626     */
16627    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16628        @Override
16629        public void setValue(View object, float value) {
16630            object.setTranslationY(value);
16631        }
16632
16633        @Override
16634        public Float get(View object) {
16635            return object.getTranslationY();
16636        }
16637    };
16638
16639    /**
16640     * A Property wrapper around the <code>x</code> functionality handled by the
16641     * {@link View#setX(float)} and {@link View#getX()} methods.
16642     */
16643    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16644        @Override
16645        public void setValue(View object, float value) {
16646            object.setX(value);
16647        }
16648
16649        @Override
16650        public Float get(View object) {
16651            return object.getX();
16652        }
16653    };
16654
16655    /**
16656     * A Property wrapper around the <code>y</code> functionality handled by the
16657     * {@link View#setY(float)} and {@link View#getY()} methods.
16658     */
16659    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16660        @Override
16661        public void setValue(View object, float value) {
16662            object.setY(value);
16663        }
16664
16665        @Override
16666        public Float get(View object) {
16667            return object.getY();
16668        }
16669    };
16670
16671    /**
16672     * A Property wrapper around the <code>rotation</code> functionality handled by the
16673     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16674     */
16675    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16676        @Override
16677        public void setValue(View object, float value) {
16678            object.setRotation(value);
16679        }
16680
16681        @Override
16682        public Float get(View object) {
16683            return object.getRotation();
16684        }
16685    };
16686
16687    /**
16688     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16689     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16690     */
16691    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16692        @Override
16693        public void setValue(View object, float value) {
16694            object.setRotationX(value);
16695        }
16696
16697        @Override
16698        public Float get(View object) {
16699            return object.getRotationX();
16700        }
16701    };
16702
16703    /**
16704     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16705     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16706     */
16707    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16708        @Override
16709        public void setValue(View object, float value) {
16710            object.setRotationY(value);
16711        }
16712
16713        @Override
16714        public Float get(View object) {
16715            return object.getRotationY();
16716        }
16717    };
16718
16719    /**
16720     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16721     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16722     */
16723    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16724        @Override
16725        public void setValue(View object, float value) {
16726            object.setScaleX(value);
16727        }
16728
16729        @Override
16730        public Float get(View object) {
16731            return object.getScaleX();
16732        }
16733    };
16734
16735    /**
16736     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16737     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16738     */
16739    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16740        @Override
16741        public void setValue(View object, float value) {
16742            object.setScaleY(value);
16743        }
16744
16745        @Override
16746        public Float get(View object) {
16747            return object.getScaleY();
16748        }
16749    };
16750
16751    /**
16752     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16753     * Each MeasureSpec represents a requirement for either the width or the height.
16754     * A MeasureSpec is comprised of a size and a mode. There are three possible
16755     * modes:
16756     * <dl>
16757     * <dt>UNSPECIFIED</dt>
16758     * <dd>
16759     * The parent has not imposed any constraint on the child. It can be whatever size
16760     * it wants.
16761     * </dd>
16762     *
16763     * <dt>EXACTLY</dt>
16764     * <dd>
16765     * The parent has determined an exact size for the child. The child is going to be
16766     * given those bounds regardless of how big it wants to be.
16767     * </dd>
16768     *
16769     * <dt>AT_MOST</dt>
16770     * <dd>
16771     * The child can be as large as it wants up to the specified size.
16772     * </dd>
16773     * </dl>
16774     *
16775     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16776     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16777     */
16778    public static class MeasureSpec {
16779        private static final int MODE_SHIFT = 30;
16780        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16781
16782        /**
16783         * Measure specification mode: The parent has not imposed any constraint
16784         * on the child. It can be whatever size it wants.
16785         */
16786        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16787
16788        /**
16789         * Measure specification mode: The parent has determined an exact size
16790         * for the child. The child is going to be given those bounds regardless
16791         * of how big it wants to be.
16792         */
16793        public static final int EXACTLY     = 1 << MODE_SHIFT;
16794
16795        /**
16796         * Measure specification mode: The child can be as large as it wants up
16797         * to the specified size.
16798         */
16799        public static final int AT_MOST     = 2 << MODE_SHIFT;
16800
16801        /**
16802         * Creates a measure specification based on the supplied size and mode.
16803         *
16804         * The mode must always be one of the following:
16805         * <ul>
16806         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16807         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16808         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16809         * </ul>
16810         *
16811         * @param size the size of the measure specification
16812         * @param mode the mode of the measure specification
16813         * @return the measure specification based on size and mode
16814         */
16815        public static int makeMeasureSpec(int size, int mode) {
16816            return size + mode;
16817        }
16818
16819        /**
16820         * Extracts the mode from the supplied measure specification.
16821         *
16822         * @param measureSpec the measure specification to extract the mode from
16823         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16824         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16825         *         {@link android.view.View.MeasureSpec#EXACTLY}
16826         */
16827        public static int getMode(int measureSpec) {
16828            return (measureSpec & MODE_MASK);
16829        }
16830
16831        /**
16832         * Extracts the size from the supplied measure specification.
16833         *
16834         * @param measureSpec the measure specification to extract the size from
16835         * @return the size in pixels defined in the supplied measure specification
16836         */
16837        public static int getSize(int measureSpec) {
16838            return (measureSpec & ~MODE_MASK);
16839        }
16840
16841        /**
16842         * Returns a String representation of the specified measure
16843         * specification.
16844         *
16845         * @param measureSpec the measure specification to convert to a String
16846         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16847         */
16848        public static String toString(int measureSpec) {
16849            int mode = getMode(measureSpec);
16850            int size = getSize(measureSpec);
16851
16852            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16853
16854            if (mode == UNSPECIFIED)
16855                sb.append("UNSPECIFIED ");
16856            else if (mode == EXACTLY)
16857                sb.append("EXACTLY ");
16858            else if (mode == AT_MOST)
16859                sb.append("AT_MOST ");
16860            else
16861                sb.append(mode).append(" ");
16862
16863            sb.append(size);
16864            return sb.toString();
16865        }
16866    }
16867
16868    class CheckForLongPress implements Runnable {
16869
16870        private int mOriginalWindowAttachCount;
16871
16872        public void run() {
16873            if (isPressed() && (mParent != null)
16874                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16875                if (performLongClick()) {
16876                    mHasPerformedLongPress = true;
16877                }
16878            }
16879        }
16880
16881        public void rememberWindowAttachCount() {
16882            mOriginalWindowAttachCount = mWindowAttachCount;
16883        }
16884    }
16885
16886    private final class CheckForTap implements Runnable {
16887        public void run() {
16888            mPrivateFlags &= ~PREPRESSED;
16889            setPressed(true);
16890            checkForLongClick(ViewConfiguration.getTapTimeout());
16891        }
16892    }
16893
16894    private final class PerformClick implements Runnable {
16895        public void run() {
16896            performClick();
16897        }
16898    }
16899
16900    /** @hide */
16901    public void hackTurnOffWindowResizeAnim(boolean off) {
16902        mAttachInfo.mTurnOffWindowResizeAnim = off;
16903    }
16904
16905    /**
16906     * This method returns a ViewPropertyAnimator object, which can be used to animate
16907     * specific properties on this View.
16908     *
16909     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16910     */
16911    public ViewPropertyAnimator animate() {
16912        if (mAnimator == null) {
16913            mAnimator = new ViewPropertyAnimator(this);
16914        }
16915        return mAnimator;
16916    }
16917
16918    /**
16919     * Interface definition for a callback to be invoked when a hardware key event is
16920     * dispatched to this view. The callback will be invoked before the key event is
16921     * given to the view. This is only useful for hardware keyboards; a software input
16922     * method has no obligation to trigger this listener.
16923     */
16924    public interface OnKeyListener {
16925        /**
16926         * Called when a hardware key is dispatched to a view. This allows listeners to
16927         * get a chance to respond before the target view.
16928         * <p>Key presses in software keyboards will generally NOT trigger this method,
16929         * although some may elect to do so in some situations. Do not assume a
16930         * software input method has to be key-based; even if it is, it may use key presses
16931         * in a different way than you expect, so there is no way to reliably catch soft
16932         * input key presses.
16933         *
16934         * @param v The view the key has been dispatched to.
16935         * @param keyCode The code for the physical key that was pressed
16936         * @param event The KeyEvent object containing full information about
16937         *        the event.
16938         * @return True if the listener has consumed the event, false otherwise.
16939         */
16940        boolean onKey(View v, int keyCode, KeyEvent event);
16941    }
16942
16943    /**
16944     * Interface definition for a callback to be invoked when a touch event is
16945     * dispatched to this view. The callback will be invoked before the touch
16946     * event is given to the view.
16947     */
16948    public interface OnTouchListener {
16949        /**
16950         * Called when a touch event is dispatched to a view. This allows listeners to
16951         * get a chance to respond before the target view.
16952         *
16953         * @param v The view the touch event has been dispatched to.
16954         * @param event The MotionEvent object containing full information about
16955         *        the event.
16956         * @return True if the listener has consumed the event, false otherwise.
16957         */
16958        boolean onTouch(View v, MotionEvent event);
16959    }
16960
16961    /**
16962     * Interface definition for a callback to be invoked when a hover event is
16963     * dispatched to this view. The callback will be invoked before the hover
16964     * event is given to the view.
16965     */
16966    public interface OnHoverListener {
16967        /**
16968         * Called when a hover event is dispatched to a view. This allows listeners to
16969         * get a chance to respond before the target view.
16970         *
16971         * @param v The view the hover event has been dispatched to.
16972         * @param event The MotionEvent object containing full information about
16973         *        the event.
16974         * @return True if the listener has consumed the event, false otherwise.
16975         */
16976        boolean onHover(View v, MotionEvent event);
16977    }
16978
16979    /**
16980     * Interface definition for a callback to be invoked when a generic motion event is
16981     * dispatched to this view. The callback will be invoked before the generic motion
16982     * event is given to the view.
16983     */
16984    public interface OnGenericMotionListener {
16985        /**
16986         * Called when a generic motion event is dispatched to a view. This allows listeners to
16987         * get a chance to respond before the target view.
16988         *
16989         * @param v The view the generic motion event has been dispatched to.
16990         * @param event The MotionEvent object containing full information about
16991         *        the event.
16992         * @return True if the listener has consumed the event, false otherwise.
16993         */
16994        boolean onGenericMotion(View v, MotionEvent event);
16995    }
16996
16997    /**
16998     * Interface definition for a callback to be invoked when a view has been clicked and held.
16999     */
17000    public interface OnLongClickListener {
17001        /**
17002         * Called when a view has been clicked and held.
17003         *
17004         * @param v The view that was clicked and held.
17005         *
17006         * @return true if the callback consumed the long click, false otherwise.
17007         */
17008        boolean onLongClick(View v);
17009    }
17010
17011    /**
17012     * Interface definition for a callback to be invoked when a drag is being dispatched
17013     * to this view.  The callback will be invoked before the hosting view's own
17014     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17015     * onDrag(event) behavior, it should return 'false' from this callback.
17016     *
17017     * <div class="special reference">
17018     * <h3>Developer Guides</h3>
17019     * <p>For a guide to implementing drag and drop features, read the
17020     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17021     * </div>
17022     */
17023    public interface OnDragListener {
17024        /**
17025         * Called when a drag event is dispatched to a view. This allows listeners
17026         * to get a chance to override base View behavior.
17027         *
17028         * @param v The View that received the drag event.
17029         * @param event The {@link android.view.DragEvent} object for the drag event.
17030         * @return {@code true} if the drag event was handled successfully, or {@code false}
17031         * if the drag event was not handled. Note that {@code false} will trigger the View
17032         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17033         */
17034        boolean onDrag(View v, DragEvent event);
17035    }
17036
17037    /**
17038     * Interface definition for a callback to be invoked when the focus state of
17039     * a view changed.
17040     */
17041    public interface OnFocusChangeListener {
17042        /**
17043         * Called when the focus state of a view has changed.
17044         *
17045         * @param v The view whose state has changed.
17046         * @param hasFocus The new focus state of v.
17047         */
17048        void onFocusChange(View v, boolean hasFocus);
17049    }
17050
17051    /**
17052     * Interface definition for a callback to be invoked when a view is clicked.
17053     */
17054    public interface OnClickListener {
17055        /**
17056         * Called when a view has been clicked.
17057         *
17058         * @param v The view that was clicked.
17059         */
17060        void onClick(View v);
17061    }
17062
17063    /**
17064     * Interface definition for a callback to be invoked when the context menu
17065     * for this view is being built.
17066     */
17067    public interface OnCreateContextMenuListener {
17068        /**
17069         * Called when the context menu for this view is being built. It is not
17070         * safe to hold onto the menu after this method returns.
17071         *
17072         * @param menu The context menu that is being built
17073         * @param v The view for which the context menu is being built
17074         * @param menuInfo Extra information about the item for which the
17075         *            context menu should be shown. This information will vary
17076         *            depending on the class of v.
17077         */
17078        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17079    }
17080
17081    /**
17082     * Interface definition for a callback to be invoked when the status bar changes
17083     * visibility.  This reports <strong>global</strong> changes to the system UI
17084     * state, not what the application is requesting.
17085     *
17086     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17087     */
17088    public interface OnSystemUiVisibilityChangeListener {
17089        /**
17090         * Called when the status bar changes visibility because of a call to
17091         * {@link View#setSystemUiVisibility(int)}.
17092         *
17093         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17094         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17095         * This tells you the <strong>global</strong> state of these UI visibility
17096         * flags, not what your app is currently applying.
17097         */
17098        public void onSystemUiVisibilityChange(int visibility);
17099    }
17100
17101    /**
17102     * Interface definition for a callback to be invoked when this view is attached
17103     * or detached from its window.
17104     */
17105    public interface OnAttachStateChangeListener {
17106        /**
17107         * Called when the view is attached to a window.
17108         * @param v The view that was attached
17109         */
17110        public void onViewAttachedToWindow(View v);
17111        /**
17112         * Called when the view is detached from a window.
17113         * @param v The view that was detached
17114         */
17115        public void onViewDetachedFromWindow(View v);
17116    }
17117
17118    private final class UnsetPressedState implements Runnable {
17119        public void run() {
17120            setPressed(false);
17121        }
17122    }
17123
17124    /**
17125     * Base class for derived classes that want to save and restore their own
17126     * state in {@link android.view.View#onSaveInstanceState()}.
17127     */
17128    public static class BaseSavedState extends AbsSavedState {
17129        /**
17130         * Constructor used when reading from a parcel. Reads the state of the superclass.
17131         *
17132         * @param source
17133         */
17134        public BaseSavedState(Parcel source) {
17135            super(source);
17136        }
17137
17138        /**
17139         * Constructor called by derived classes when creating their SavedState objects
17140         *
17141         * @param superState The state of the superclass of this view
17142         */
17143        public BaseSavedState(Parcelable superState) {
17144            super(superState);
17145        }
17146
17147        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17148                new Parcelable.Creator<BaseSavedState>() {
17149            public BaseSavedState createFromParcel(Parcel in) {
17150                return new BaseSavedState(in);
17151            }
17152
17153            public BaseSavedState[] newArray(int size) {
17154                return new BaseSavedState[size];
17155            }
17156        };
17157    }
17158
17159    /**
17160     * A set of information given to a view when it is attached to its parent
17161     * window.
17162     */
17163    static class AttachInfo {
17164        interface Callbacks {
17165            void playSoundEffect(int effectId);
17166            boolean performHapticFeedback(int effectId, boolean always);
17167        }
17168
17169        /**
17170         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17171         * to a Handler. This class contains the target (View) to invalidate and
17172         * the coordinates of the dirty rectangle.
17173         *
17174         * For performance purposes, this class also implements a pool of up to
17175         * POOL_LIMIT objects that get reused. This reduces memory allocations
17176         * whenever possible.
17177         */
17178        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17179            private static final int POOL_LIMIT = 10;
17180            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17181                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17182                        public InvalidateInfo newInstance() {
17183                            return new InvalidateInfo();
17184                        }
17185
17186                        public void onAcquired(InvalidateInfo element) {
17187                        }
17188
17189                        public void onReleased(InvalidateInfo element) {
17190                            element.target = null;
17191                        }
17192                    }, POOL_LIMIT)
17193            );
17194
17195            private InvalidateInfo mNext;
17196            private boolean mIsPooled;
17197
17198            View target;
17199
17200            int left;
17201            int top;
17202            int right;
17203            int bottom;
17204
17205            public void setNextPoolable(InvalidateInfo element) {
17206                mNext = element;
17207            }
17208
17209            public InvalidateInfo getNextPoolable() {
17210                return mNext;
17211            }
17212
17213            static InvalidateInfo acquire() {
17214                return sPool.acquire();
17215            }
17216
17217            void release() {
17218                sPool.release(this);
17219            }
17220
17221            public boolean isPooled() {
17222                return mIsPooled;
17223            }
17224
17225            public void setPooled(boolean isPooled) {
17226                mIsPooled = isPooled;
17227            }
17228        }
17229
17230        final IWindowSession mSession;
17231
17232        final IWindow mWindow;
17233
17234        final IBinder mWindowToken;
17235
17236        final Callbacks mRootCallbacks;
17237
17238        HardwareCanvas mHardwareCanvas;
17239
17240        /**
17241         * The top view of the hierarchy.
17242         */
17243        View mRootView;
17244
17245        IBinder mPanelParentWindowToken;
17246        Surface mSurface;
17247
17248        boolean mHardwareAccelerated;
17249        boolean mHardwareAccelerationRequested;
17250        HardwareRenderer mHardwareRenderer;
17251
17252        boolean mScreenOn;
17253
17254        /**
17255         * Scale factor used by the compatibility mode
17256         */
17257        float mApplicationScale;
17258
17259        /**
17260         * Indicates whether the application is in compatibility mode
17261         */
17262        boolean mScalingRequired;
17263
17264        /**
17265         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17266         */
17267        boolean mTurnOffWindowResizeAnim;
17268
17269        /**
17270         * Left position of this view's window
17271         */
17272        int mWindowLeft;
17273
17274        /**
17275         * Top position of this view's window
17276         */
17277        int mWindowTop;
17278
17279        /**
17280         * Indicates whether views need to use 32-bit drawing caches
17281         */
17282        boolean mUse32BitDrawingCache;
17283
17284        /**
17285         * For windows that are full-screen but using insets to layout inside
17286         * of the screen decorations, these are the current insets for the
17287         * content of the window.
17288         */
17289        final Rect mContentInsets = new Rect();
17290
17291        /**
17292         * For windows that are full-screen but using insets to layout inside
17293         * of the screen decorations, these are the current insets for the
17294         * actual visible parts of the window.
17295         */
17296        final Rect mVisibleInsets = new Rect();
17297
17298        /**
17299         * The internal insets given by this window.  This value is
17300         * supplied by the client (through
17301         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17302         * be given to the window manager when changed to be used in laying
17303         * out windows behind it.
17304         */
17305        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17306                = new ViewTreeObserver.InternalInsetsInfo();
17307
17308        /**
17309         * All views in the window's hierarchy that serve as scroll containers,
17310         * used to determine if the window can be resized or must be panned
17311         * to adjust for a soft input area.
17312         */
17313        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17314
17315        final KeyEvent.DispatcherState mKeyDispatchState
17316                = new KeyEvent.DispatcherState();
17317
17318        /**
17319         * Indicates whether the view's window currently has the focus.
17320         */
17321        boolean mHasWindowFocus;
17322
17323        /**
17324         * The current visibility of the window.
17325         */
17326        int mWindowVisibility;
17327
17328        /**
17329         * Indicates the time at which drawing started to occur.
17330         */
17331        long mDrawingTime;
17332
17333        /**
17334         * Indicates whether or not ignoring the DIRTY_MASK flags.
17335         */
17336        boolean mIgnoreDirtyState;
17337
17338        /**
17339         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17340         * to avoid clearing that flag prematurely.
17341         */
17342        boolean mSetIgnoreDirtyState = false;
17343
17344        /**
17345         * Indicates whether the view's window is currently in touch mode.
17346         */
17347        boolean mInTouchMode;
17348
17349        /**
17350         * Indicates that ViewAncestor should trigger a global layout change
17351         * the next time it performs a traversal
17352         */
17353        boolean mRecomputeGlobalAttributes;
17354
17355        /**
17356         * Always report new attributes at next traversal.
17357         */
17358        boolean mForceReportNewAttributes;
17359
17360        /**
17361         * Set during a traveral if any views want to keep the screen on.
17362         */
17363        boolean mKeepScreenOn;
17364
17365        /**
17366         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17367         */
17368        int mSystemUiVisibility;
17369
17370        /**
17371         * Hack to force certain system UI visibility flags to be cleared.
17372         */
17373        int mDisabledSystemUiVisibility;
17374
17375        /**
17376         * Last global system UI visibility reported by the window manager.
17377         */
17378        int mGlobalSystemUiVisibility;
17379
17380        /**
17381         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17382         * attached.
17383         */
17384        boolean mHasSystemUiListeners;
17385
17386        /**
17387         * Set if the visibility of any views has changed.
17388         */
17389        boolean mViewVisibilityChanged;
17390
17391        /**
17392         * Set to true if a view has been scrolled.
17393         */
17394        boolean mViewScrollChanged;
17395
17396        /**
17397         * Global to the view hierarchy used as a temporary for dealing with
17398         * x/y points in the transparent region computations.
17399         */
17400        final int[] mTransparentLocation = new int[2];
17401
17402        /**
17403         * Global to the view hierarchy used as a temporary for dealing with
17404         * x/y points in the ViewGroup.invalidateChild implementation.
17405         */
17406        final int[] mInvalidateChildLocation = new int[2];
17407
17408
17409        /**
17410         * Global to the view hierarchy used as a temporary for dealing with
17411         * x/y location when view is transformed.
17412         */
17413        final float[] mTmpTransformLocation = new float[2];
17414
17415        /**
17416         * The view tree observer used to dispatch global events like
17417         * layout, pre-draw, touch mode change, etc.
17418         */
17419        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17420
17421        /**
17422         * A Canvas used by the view hierarchy to perform bitmap caching.
17423         */
17424        Canvas mCanvas;
17425
17426        /**
17427         * The view root impl.
17428         */
17429        final ViewRootImpl mViewRootImpl;
17430
17431        /**
17432         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17433         * handler can be used to pump events in the UI events queue.
17434         */
17435        final Handler mHandler;
17436
17437        /**
17438         * Temporary for use in computing invalidate rectangles while
17439         * calling up the hierarchy.
17440         */
17441        final Rect mTmpInvalRect = new Rect();
17442
17443        /**
17444         * Temporary for use in computing hit areas with transformed views
17445         */
17446        final RectF mTmpTransformRect = new RectF();
17447
17448        /**
17449         * Temporary list for use in collecting focusable descendents of a view.
17450         */
17451        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17452
17453        /**
17454         * The id of the window for accessibility purposes.
17455         */
17456        int mAccessibilityWindowId = View.NO_ID;
17457
17458        /**
17459         * Whether to ingore not exposed for accessibility Views when
17460         * reporting the view tree to accessibility services.
17461         */
17462        boolean mIncludeNotImportantViews;
17463
17464        /**
17465         * The drawable for highlighting accessibility focus.
17466         */
17467        Drawable mAccessibilityFocusDrawable;
17468
17469        /**
17470         * Show where the margins, bounds and layout bounds are for each view.
17471         */
17472        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17473
17474        /**
17475         * Point used to compute visible regions.
17476         */
17477        final Point mPoint = new Point();
17478
17479        /**
17480         * Creates a new set of attachment information with the specified
17481         * events handler and thread.
17482         *
17483         * @param handler the events handler the view must use
17484         */
17485        AttachInfo(IWindowSession session, IWindow window,
17486                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17487            mSession = session;
17488            mWindow = window;
17489            mWindowToken = window.asBinder();
17490            mViewRootImpl = viewRootImpl;
17491            mHandler = handler;
17492            mRootCallbacks = effectPlayer;
17493        }
17494    }
17495
17496    /**
17497     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17498     * is supported. This avoids keeping too many unused fields in most
17499     * instances of View.</p>
17500     */
17501    private static class ScrollabilityCache implements Runnable {
17502
17503        /**
17504         * Scrollbars are not visible
17505         */
17506        public static final int OFF = 0;
17507
17508        /**
17509         * Scrollbars are visible
17510         */
17511        public static final int ON = 1;
17512
17513        /**
17514         * Scrollbars are fading away
17515         */
17516        public static final int FADING = 2;
17517
17518        public boolean fadeScrollBars;
17519
17520        public int fadingEdgeLength;
17521        public int scrollBarDefaultDelayBeforeFade;
17522        public int scrollBarFadeDuration;
17523
17524        public int scrollBarSize;
17525        public ScrollBarDrawable scrollBar;
17526        public float[] interpolatorValues;
17527        public View host;
17528
17529        public final Paint paint;
17530        public final Matrix matrix;
17531        public Shader shader;
17532
17533        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17534
17535        private static final float[] OPAQUE = { 255 };
17536        private static final float[] TRANSPARENT = { 0.0f };
17537
17538        /**
17539         * When fading should start. This time moves into the future every time
17540         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17541         */
17542        public long fadeStartTime;
17543
17544
17545        /**
17546         * The current state of the scrollbars: ON, OFF, or FADING
17547         */
17548        public int state = OFF;
17549
17550        private int mLastColor;
17551
17552        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17553            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17554            scrollBarSize = configuration.getScaledScrollBarSize();
17555            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17556            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17557
17558            paint = new Paint();
17559            matrix = new Matrix();
17560            // use use a height of 1, and then wack the matrix each time we
17561            // actually use it.
17562            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17563
17564            paint.setShader(shader);
17565            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17566            this.host = host;
17567        }
17568
17569        public void setFadeColor(int color) {
17570            if (color != 0 && color != mLastColor) {
17571                mLastColor = color;
17572                color |= 0xFF000000;
17573
17574                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17575                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17576
17577                paint.setShader(shader);
17578                // Restore the default transfer mode (src_over)
17579                paint.setXfermode(null);
17580            }
17581        }
17582
17583        public void run() {
17584            long now = AnimationUtils.currentAnimationTimeMillis();
17585            if (now >= fadeStartTime) {
17586
17587                // the animation fades the scrollbars out by changing
17588                // the opacity (alpha) from fully opaque to fully
17589                // transparent
17590                int nextFrame = (int) now;
17591                int framesCount = 0;
17592
17593                Interpolator interpolator = scrollBarInterpolator;
17594
17595                // Start opaque
17596                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17597
17598                // End transparent
17599                nextFrame += scrollBarFadeDuration;
17600                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17601
17602                state = FADING;
17603
17604                // Kick off the fade animation
17605                host.invalidate(true);
17606            }
17607        }
17608    }
17609
17610    /**
17611     * Resuable callback for sending
17612     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17613     */
17614    private class SendViewScrolledAccessibilityEvent implements Runnable {
17615        public volatile boolean mIsPending;
17616
17617        public void run() {
17618            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17619            mIsPending = false;
17620        }
17621    }
17622
17623    /**
17624     * <p>
17625     * This class represents a delegate that can be registered in a {@link View}
17626     * to enhance accessibility support via composition rather via inheritance.
17627     * It is specifically targeted to widget developers that extend basic View
17628     * classes i.e. classes in package android.view, that would like their
17629     * applications to be backwards compatible.
17630     * </p>
17631     * <div class="special reference">
17632     * <h3>Developer Guides</h3>
17633     * <p>For more information about making applications accessible, read the
17634     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17635     * developer guide.</p>
17636     * </div>
17637     * <p>
17638     * A scenario in which a developer would like to use an accessibility delegate
17639     * is overriding a method introduced in a later API version then the minimal API
17640     * version supported by the application. For example, the method
17641     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17642     * in API version 4 when the accessibility APIs were first introduced. If a
17643     * developer would like his application to run on API version 4 devices (assuming
17644     * all other APIs used by the application are version 4 or lower) and take advantage
17645     * of this method, instead of overriding the method which would break the application's
17646     * backwards compatibility, he can override the corresponding method in this
17647     * delegate and register the delegate in the target View if the API version of
17648     * the system is high enough i.e. the API version is same or higher to the API
17649     * version that introduced
17650     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17651     * </p>
17652     * <p>
17653     * Here is an example implementation:
17654     * </p>
17655     * <code><pre><p>
17656     * if (Build.VERSION.SDK_INT >= 14) {
17657     *     // If the API version is equal of higher than the version in
17658     *     // which onInitializeAccessibilityNodeInfo was introduced we
17659     *     // register a delegate with a customized implementation.
17660     *     View view = findViewById(R.id.view_id);
17661     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17662     *         public void onInitializeAccessibilityNodeInfo(View host,
17663     *                 AccessibilityNodeInfo info) {
17664     *             // Let the default implementation populate the info.
17665     *             super.onInitializeAccessibilityNodeInfo(host, info);
17666     *             // Set some other information.
17667     *             info.setEnabled(host.isEnabled());
17668     *         }
17669     *     });
17670     * }
17671     * </code></pre></p>
17672     * <p>
17673     * This delegate contains methods that correspond to the accessibility methods
17674     * in View. If a delegate has been specified the implementation in View hands
17675     * off handling to the corresponding method in this delegate. The default
17676     * implementation the delegate methods behaves exactly as the corresponding
17677     * method in View for the case of no accessibility delegate been set. Hence,
17678     * to customize the behavior of a View method, clients can override only the
17679     * corresponding delegate method without altering the behavior of the rest
17680     * accessibility related methods of the host view.
17681     * </p>
17682     */
17683    public static class AccessibilityDelegate {
17684
17685        /**
17686         * Sends an accessibility event of the given type. If accessibility is not
17687         * enabled this method has no effect.
17688         * <p>
17689         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17690         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17691         * been set.
17692         * </p>
17693         *
17694         * @param host The View hosting the delegate.
17695         * @param eventType The type of the event to send.
17696         *
17697         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17698         */
17699        public void sendAccessibilityEvent(View host, int eventType) {
17700            host.sendAccessibilityEventInternal(eventType);
17701        }
17702
17703        /**
17704         * Performs the specified accessibility action on the view. For
17705         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17706         * <p>
17707         * The default implementation behaves as
17708         * {@link View#performAccessibilityAction(int, Bundle)
17709         *  View#performAccessibilityAction(int, Bundle)} for the case of
17710         *  no accessibility delegate been set.
17711         * </p>
17712         *
17713         * @param action The action to perform.
17714         * @return Whether the action was performed.
17715         *
17716         * @see View#performAccessibilityAction(int, Bundle)
17717         *      View#performAccessibilityAction(int, Bundle)
17718         */
17719        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17720            return host.performAccessibilityActionInternal(action, args);
17721        }
17722
17723        /**
17724         * Sends an accessibility event. This method behaves exactly as
17725         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17726         * empty {@link AccessibilityEvent} and does not perform a check whether
17727         * accessibility is enabled.
17728         * <p>
17729         * The default implementation behaves as
17730         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17731         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17732         * the case of no accessibility delegate been set.
17733         * </p>
17734         *
17735         * @param host The View hosting the delegate.
17736         * @param event The event to send.
17737         *
17738         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17739         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17740         */
17741        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17742            host.sendAccessibilityEventUncheckedInternal(event);
17743        }
17744
17745        /**
17746         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17747         * to its children for adding their text content to the event.
17748         * <p>
17749         * The default implementation behaves as
17750         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17751         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17752         * the case of no accessibility delegate been set.
17753         * </p>
17754         *
17755         * @param host The View hosting the delegate.
17756         * @param event The event.
17757         * @return True if the event population was completed.
17758         *
17759         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17760         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17761         */
17762        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17763            return host.dispatchPopulateAccessibilityEventInternal(event);
17764        }
17765
17766        /**
17767         * Gives a chance to the host View to populate the accessibility event with its
17768         * text content.
17769         * <p>
17770         * The default implementation behaves as
17771         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17772         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17773         * the case of no accessibility delegate been set.
17774         * </p>
17775         *
17776         * @param host The View hosting the delegate.
17777         * @param event The accessibility event which to populate.
17778         *
17779         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17780         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17781         */
17782        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17783            host.onPopulateAccessibilityEventInternal(event);
17784        }
17785
17786        /**
17787         * Initializes an {@link AccessibilityEvent} with information about the
17788         * the host View which is the event source.
17789         * <p>
17790         * The default implementation behaves as
17791         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17792         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17793         * the case of no accessibility delegate been set.
17794         * </p>
17795         *
17796         * @param host The View hosting the delegate.
17797         * @param event The event to initialize.
17798         *
17799         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17800         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17801         */
17802        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17803            host.onInitializeAccessibilityEventInternal(event);
17804        }
17805
17806        /**
17807         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17808         * <p>
17809         * The default implementation behaves as
17810         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17811         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17812         * the case of no accessibility delegate been set.
17813         * </p>
17814         *
17815         * @param host The View hosting the delegate.
17816         * @param info The instance to initialize.
17817         *
17818         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17819         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17820         */
17821        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17822            host.onInitializeAccessibilityNodeInfoInternal(info);
17823        }
17824
17825        /**
17826         * Called when a child of the host View has requested sending an
17827         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17828         * to augment the event.
17829         * <p>
17830         * The default implementation behaves as
17831         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17832         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17833         * the case of no accessibility delegate been set.
17834         * </p>
17835         *
17836         * @param host The View hosting the delegate.
17837         * @param child The child which requests sending the event.
17838         * @param event The event to be sent.
17839         * @return True if the event should be sent
17840         *
17841         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17842         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17843         */
17844        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17845                AccessibilityEvent event) {
17846            return host.onRequestSendAccessibilityEventInternal(child, event);
17847        }
17848
17849        /**
17850         * Gets the provider for managing a virtual view hierarchy rooted at this View
17851         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17852         * that explore the window content.
17853         * <p>
17854         * The default implementation behaves as
17855         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17856         * the case of no accessibility delegate been set.
17857         * </p>
17858         *
17859         * @return The provider.
17860         *
17861         * @see AccessibilityNodeProvider
17862         */
17863        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17864            return null;
17865        }
17866    }
17867}
17868