View.java revision a53de0629f3b94472c0f160f5bbe1090b020feab
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.util.AttributeSet;
51import android.util.FloatProperty;
52import android.util.LocaleUtil;
53import android.util.Log;
54import android.util.Pool;
55import android.util.Poolable;
56import android.util.PoolableManager;
57import android.util.Pools;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.widget.ScrollBarDrawable;
78
79import static android.os.Build.VERSION_CODES.*;
80import static java.lang.Math.max;
81
82import com.android.internal.R;
83import com.android.internal.util.Predicate;
84import com.android.internal.view.menu.MenuBuilder;
85
86import java.lang.ref.WeakReference;
87import java.lang.reflect.InvocationTargetException;
88import java.lang.reflect.Method;
89import java.util.ArrayList;
90import java.util.Arrays;
91import java.util.Locale;
92import java.util.concurrent.CopyOnWriteArrayList;
93
94/**
95 * <p>
96 * This class represents the basic building block for user interface components. A View
97 * occupies a rectangular area on the screen and is responsible for drawing and
98 * event handling. View is the base class for <em>widgets</em>, which are
99 * used to create interactive UI components (buttons, text fields, etc.). The
100 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
101 * are invisible containers that hold other Views (or other ViewGroups) and define
102 * their layout properties.
103 * </p>
104 *
105 * <div class="special reference">
106 * <h3>Developer Guides</h3>
107 * <p>For information about using this class to develop your application's user interface,
108 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
109 * </div>
110 *
111 * <a name="Using"></a>
112 * <h3>Using Views</h3>
113 * <p>
114 * All of the views in a window are arranged in a single tree. You can add views
115 * either from code or by specifying a tree of views in one or more XML layout
116 * files. There are many specialized subclasses of views that act as controls or
117 * are capable of displaying text, images, or other content.
118 * </p>
119 * <p>
120 * Once you have created a tree of views, there are typically a few types of
121 * common operations you may wish to perform:
122 * <ul>
123 * <li><strong>Set properties:</strong> for example setting the text of a
124 * {@link android.widget.TextView}. The available properties and the methods
125 * that set them will vary among the different subclasses of views. Note that
126 * properties that are known at build time can be set in the XML layout
127 * files.</li>
128 * <li><strong>Set focus:</strong> The framework will handled moving focus in
129 * response to user input. To force focus to a specific view, call
130 * {@link #requestFocus}.</li>
131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
132 * that will be notified when something interesting happens to the view. For
133 * example, all views will let you set a listener to be notified when the view
134 * gains or loses focus. You can register such a listener using
135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
136 * Other view subclasses offer more specialized listeners. For example, a Button
137 * exposes a listener to notify clients when the button is clicked.</li>
138 * <li><strong>Set visibility:</strong> You can hide or show views using
139 * {@link #setVisibility(int)}.</li>
140 * </ul>
141 * </p>
142 * <p><em>
143 * Note: The Android framework is responsible for measuring, laying out and
144 * drawing views. You should not call methods that perform these actions on
145 * views yourself unless you are actually implementing a
146 * {@link android.view.ViewGroup}.
147 * </em></p>
148 *
149 * <a name="Lifecycle"></a>
150 * <h3>Implementing a Custom View</h3>
151 *
152 * <p>
153 * To implement a custom view, you will usually begin by providing overrides for
154 * some of the standard methods that the framework calls on all views. You do
155 * not need to override all of these methods. In fact, you can start by just
156 * overriding {@link #onDraw(android.graphics.Canvas)}.
157 * <table border="2" width="85%" align="center" cellpadding="5">
158 *     <thead>
159 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
160 *     </thead>
161 *
162 *     <tbody>
163 *     <tr>
164 *         <td rowspan="2">Creation</td>
165 *         <td>Constructors</td>
166 *         <td>There is a form of the constructor that are called when the view
167 *         is created from code and a form that is called when the view is
168 *         inflated from a layout file. The second form should parse and apply
169 *         any attributes defined in the layout file.
170 *         </td>
171 *     </tr>
172 *     <tr>
173 *         <td><code>{@link #onFinishInflate()}</code></td>
174 *         <td>Called after a view and all of its children has been inflated
175 *         from XML.</td>
176 *     </tr>
177 *
178 *     <tr>
179 *         <td rowspan="3">Layout</td>
180 *         <td><code>{@link #onMeasure(int, int)}</code></td>
181 *         <td>Called to determine the size requirements for this view and all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
187 *         <td>Called when this view should assign a size and position to all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
193 *         <td>Called when the size of this view has changed.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td>Drawing</td>
199 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
200 *         <td>Called when the view should render its content.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td rowspan="4">Event processing</td>
206 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
207 *         <td>Called when a new key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a key up event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
217 *         <td>Called when a trackball motion event occurs.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
222 *         <td>Called when a touch screen motion event occurs.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="2">Focus</td>
228 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
229 *         <td>Called when the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
235 *         <td>Called when the window containing the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="3">Attaching</td>
241 *         <td><code>{@link #onAttachedToWindow()}</code></td>
242 *         <td>Called when the view is attached to a window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onDetachedFromWindow}</code></td>
248 *         <td>Called when the view is detached from its window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
254 *         <td>Called when the visibility of the window containing the view
255 *         has changed.
256 *         </td>
257 *     </tr>
258 *     </tbody>
259 *
260 * </table>
261 * </p>
262 *
263 * <a name="IDs"></a>
264 * <h3>IDs</h3>
265 * Views may have an integer id associated with them. These ids are typically
266 * assigned in the layout XML files, and are used to find specific views within
267 * the view tree. A common pattern is to:
268 * <ul>
269 * <li>Define a Button in the layout file and assign it a unique ID.
270 * <pre>
271 * &lt;Button
272 *     android:id="@+id/my_button"
273 *     android:layout_width="wrap_content"
274 *     android:layout_height="wrap_content"
275 *     android:text="@string/my_button_text"/&gt;
276 * </pre></li>
277 * <li>From the onCreate method of an Activity, find the Button
278 * <pre class="prettyprint">
279 *      Button myButton = (Button) findViewById(R.id.my_button);
280 * </pre></li>
281 * </ul>
282 * <p>
283 * View IDs need not be unique throughout the tree, but it is good practice to
284 * ensure that they are at least unique within the part of the tree you are
285 * searching.
286 * </p>
287 *
288 * <a name="Position"></a>
289 * <h3>Position</h3>
290 * <p>
291 * The geometry of a view is that of a rectangle. A view has a location,
292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
293 * two dimensions, expressed as a width and a height. The unit for location
294 * and dimensions is the pixel.
295 * </p>
296 *
297 * <p>
298 * It is possible to retrieve the location of a view by invoking the methods
299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
300 * coordinate of the rectangle representing the view. The latter returns the
301 * top, or Y, coordinate of the rectangle representing the view. These methods
302 * both return the location of the view relative to its parent. For instance,
303 * when getLeft() returns 20, that means the view is located 20 pixels to the
304 * right of the left edge of its direct parent.
305 * </p>
306 *
307 * <p>
308 * In addition, several convenience methods are offered to avoid unnecessary
309 * computations, namely {@link #getRight()} and {@link #getBottom()}.
310 * These methods return the coordinates of the right and bottom edges of the
311 * rectangle representing the view. For instance, calling {@link #getRight()}
312 * is similar to the following computation: <code>getLeft() + getWidth()</code>
313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
314 * </p>
315 *
316 * <a name="SizePaddingMargins"></a>
317 * <h3>Size, padding and margins</h3>
318 * <p>
319 * The size of a view is expressed with a width and a height. A view actually
320 * possess two pairs of width and height values.
321 * </p>
322 *
323 * <p>
324 * The first pair is known as <em>measured width</em> and
325 * <em>measured height</em>. These dimensions define how big a view wants to be
326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
328 * and {@link #getMeasuredHeight()}.
329 * </p>
330 *
331 * <p>
332 * The second pair is simply known as <em>width</em> and <em>height</em>, or
333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
334 * dimensions define the actual size of the view on screen, at drawing time and
335 * after layout. These values may, but do not have to, be different from the
336 * measured width and height. The width and height can be obtained by calling
337 * {@link #getWidth()} and {@link #getHeight()}.
338 * </p>
339 *
340 * <p>
341 * To measure its dimensions, a view takes into account its padding. The padding
342 * is expressed in pixels for the left, top, right and bottom parts of the view.
343 * Padding can be used to offset the content of the view by a specific amount of
344 * pixels. For instance, a left padding of 2 will push the view's content by
345 * 2 pixels to the right of the left edge. Padding can be set using the
346 * {@link #setPadding(int, int, int, int)} method and queried by calling
347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, {@link #getPaddingRight()},
348 * {@link #getPaddingBottom()}.
349 * </p>
350 *
351 * <p>
352 * Even though a view can define a padding, it does not provide any support for
353 * margins. However, view groups provide such a support. Refer to
354 * {@link android.view.ViewGroup} and
355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
356 * </p>
357 *
358 * <a name="Layout"></a>
359 * <h3>Layout</h3>
360 * <p>
361 * Layout is a two pass process: a measure pass and a layout pass. The measuring
362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
363 * of the view tree. Each view pushes dimension specifications down the tree
364 * during the recursion. At the end of the measure pass, every view has stored
365 * its measurements. The second pass happens in
366 * {@link #layout(int,int,int,int)} and is also top-down. During
367 * this pass each parent is responsible for positioning all of its children
368 * using the sizes computed in the measure pass.
369 * </p>
370 *
371 * <p>
372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
373 * {@link #getMeasuredHeight()} values must be set, along with those for all of
374 * that view's descendants. A view's measured width and measured height values
375 * must respect the constraints imposed by the view's parents. This guarantees
376 * that at the end of the measure pass, all parents accept all of their
377 * children's measurements. A parent view may call measure() more than once on
378 * its children. For example, the parent may measure each child once with
379 * unspecified dimensions to find out how big they want to be, then call
380 * measure() on them again with actual numbers if the sum of all the children's
381 * unconstrained sizes is too big or too small.
382 * </p>
383 *
384 * <p>
385 * The measure pass uses two classes to communicate dimensions. The
386 * {@link MeasureSpec} class is used by views to tell their parents how they
387 * want to be measured and positioned. The base LayoutParams class just
388 * describes how big the view wants to be for both width and height. For each
389 * dimension, it can specify one of:
390 * <ul>
391 * <li> an exact number
392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
393 * (minus padding)
394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
395 * enclose its content (plus padding).
396 * </ul>
397 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
399 * an X and Y value.
400 * </p>
401 *
402 * <p>
403 * MeasureSpecs are used to push requirements down the tree from parent to
404 * child. A MeasureSpec can be in one of three modes:
405 * <ul>
406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
407 * of a child view. For example, a LinearLayout may call measure() on its child
408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
409 * tall the child view wants to be given a width of 240 pixels.
410 * <li>EXACTLY: This is used by the parent to impose an exact size on the
411 * child. The child must use this size, and guarantee that all of its
412 * descendants will fit within this size.
413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
414 * child. The child must gurantee that it and all of its descendants will fit
415 * within this size.
416 * </ul>
417 * </p>
418 *
419 * <p>
420 * To intiate a layout, call {@link #requestLayout}. This method is typically
421 * called by a view on itself when it believes that is can no longer fit within
422 * its current bounds.
423 * </p>
424 *
425 * <a name="Drawing"></a>
426 * <h3>Drawing</h3>
427 * <p>
428 * Drawing is handled by walking the tree and rendering each view that
429 * intersects the invalid region. Because the tree is traversed in-order,
430 * this means that parents will draw before (i.e., behind) their children, with
431 * siblings drawn in the order they appear in the tree.
432 * If you set a background drawable for a View, then the View will draw it for you
433 * before calling back to its <code>onDraw()</code> method.
434 * </p>
435 *
436 * <p>
437 * Note that the framework will not draw views that are not in the invalid region.
438 * </p>
439 *
440 * <p>
441 * To force a view to draw, call {@link #invalidate()}.
442 * </p>
443 *
444 * <a name="EventHandlingThreading"></a>
445 * <h3>Event Handling and Threading</h3>
446 * <p>
447 * The basic cycle of a view is as follows:
448 * <ol>
449 * <li>An event comes in and is dispatched to the appropriate view. The view
450 * handles the event and notifies any listeners.</li>
451 * <li>If in the course of processing the event, the view's bounds may need
452 * to be changed, the view will call {@link #requestLayout()}.</li>
453 * <li>Similarly, if in the course of processing the event the view's appearance
454 * may need to be changed, the view will call {@link #invalidate()}.</li>
455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
456 * the framework will take care of measuring, laying out, and drawing the tree
457 * as appropriate.</li>
458 * </ol>
459 * </p>
460 *
461 * <p><em>Note: The entire view tree is single threaded. You must always be on
462 * the UI thread when calling any method on any view.</em>
463 * If you are doing work on other threads and want to update the state of a view
464 * from that thread, you should use a {@link Handler}.
465 * </p>
466 *
467 * <a name="FocusHandling"></a>
468 * <h3>Focus Handling</h3>
469 * <p>
470 * The framework will handle routine focus movement in response to user input.
471 * This includes changing the focus as views are removed or hidden, or as new
472 * views become available. Views indicate their willingness to take focus
473 * through the {@link #isFocusable} method. To change whether a view can take
474 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
476 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
477 * </p>
478 * <p>
479 * Focus movement is based on an algorithm which finds the nearest neighbor in a
480 * given direction. In rare cases, the default algorithm may not match the
481 * intended behavior of the developer. In these situations, you can provide
482 * explicit overrides by using these XML attributes in the layout file:
483 * <pre>
484 * nextFocusDown
485 * nextFocusLeft
486 * nextFocusRight
487 * nextFocusUp
488 * </pre>
489 * </p>
490 *
491 *
492 * <p>
493 * To get a particular view to take focus, call {@link #requestFocus()}.
494 * </p>
495 *
496 * <a name="TouchMode"></a>
497 * <h3>Touch Mode</h3>
498 * <p>
499 * When a user is navigating a user interface via directional keys such as a D-pad, it is
500 * necessary to give focus to actionable items such as buttons so the user can see
501 * what will take input.  If the device has touch capabilities, however, and the user
502 * begins interacting with the interface by touching it, it is no longer necessary to
503 * always highlight, or give focus to, a particular view.  This motivates a mode
504 * for interaction named 'touch mode'.
505 * </p>
506 * <p>
507 * For a touch capable device, once the user touches the screen, the device
508 * will enter touch mode.  From this point onward, only views for which
509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
510 * Other views that are touchable, like buttons, will not take focus when touched; they will
511 * only fire the on click listeners.
512 * </p>
513 * <p>
514 * Any time a user hits a directional key, such as a D-pad direction, the view device will
515 * exit touch mode, and find a view to take focus, so that the user may resume interacting
516 * with the user interface without touching the screen again.
517 * </p>
518 * <p>
519 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
520 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
521 * </p>
522 *
523 * <a name="Scrolling"></a>
524 * <h3>Scrolling</h3>
525 * <p>
526 * The framework provides basic support for views that wish to internally
527 * scroll their content. This includes keeping track of the X and Y scroll
528 * offset as well as mechanisms for drawing scrollbars. See
529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
530 * {@link #awakenScrollBars()} for more details.
531 * </p>
532 *
533 * <a name="Tags"></a>
534 * <h3>Tags</h3>
535 * <p>
536 * Unlike IDs, tags are not used to identify views. Tags are essentially an
537 * extra piece of information that can be associated with a view. They are most
538 * often used as a convenience to store data related to views in the views
539 * themselves rather than by putting them in a separate structure.
540 * </p>
541 *
542 * <a name="Properties"></a>
543 * <h3>Properties</h3>
544 * <p>
545 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
546 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
547 * available both in the {@link Property} form as well as in similarly-named setter/getter
548 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
549 * be used to set persistent state associated with these rendering-related properties on the view.
550 * The properties and methods can also be used in conjunction with
551 * {@link android.animation.Animator Animator}-based animations, described more in the
552 * <a href="#Animation">Animation</a> section.
553 * </p>
554 *
555 * <a name="Animation"></a>
556 * <h3>Animation</h3>
557 * <p>
558 * Starting with Android 3.0, the preferred way of animating views is to use the
559 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
560 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
561 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
562 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
563 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
564 * makes animating these View properties particularly easy and efficient.
565 * </p>
566 * <p>
567 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
568 * You can attach an {@link Animation} object to a view using
569 * {@link #setAnimation(Animation)} or
570 * {@link #startAnimation(Animation)}. The animation can alter the scale,
571 * rotation, translation and alpha of a view over time. If the animation is
572 * attached to a view that has children, the animation will affect the entire
573 * subtree rooted by that node. When an animation is started, the framework will
574 * take care of redrawing the appropriate views until the animation completes.
575 * </p>
576 *
577 * <a name="Security"></a>
578 * <h3>Security</h3>
579 * <p>
580 * Sometimes it is essential that an application be able to verify that an action
581 * is being performed with the full knowledge and consent of the user, such as
582 * granting a permission request, making a purchase or clicking on an advertisement.
583 * Unfortunately, a malicious application could try to spoof the user into
584 * performing these actions, unaware, by concealing the intended purpose of the view.
585 * As a remedy, the framework offers a touch filtering mechanism that can be used to
586 * improve the security of views that provide access to sensitive functionality.
587 * </p><p>
588 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
589 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
590 * will discard touches that are received whenever the view's window is obscured by
591 * another visible window.  As a result, the view will not receive touches whenever a
592 * toast, dialog or other window appears above the view's window.
593 * </p><p>
594 * For more fine-grained control over security, consider overriding the
595 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
596 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
597 * </p>
598 *
599 * @attr ref android.R.styleable#View_alpha
600 * @attr ref android.R.styleable#View_background
601 * @attr ref android.R.styleable#View_clickable
602 * @attr ref android.R.styleable#View_contentDescription
603 * @attr ref android.R.styleable#View_drawingCacheQuality
604 * @attr ref android.R.styleable#View_duplicateParentState
605 * @attr ref android.R.styleable#View_id
606 * @attr ref android.R.styleable#View_requiresFadingEdge
607 * @attr ref android.R.styleable#View_fadeScrollbars
608 * @attr ref android.R.styleable#View_fadingEdgeLength
609 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
610 * @attr ref android.R.styleable#View_fitsSystemWindows
611 * @attr ref android.R.styleable#View_isScrollContainer
612 * @attr ref android.R.styleable#View_focusable
613 * @attr ref android.R.styleable#View_focusableInTouchMode
614 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
615 * @attr ref android.R.styleable#View_keepScreenOn
616 * @attr ref android.R.styleable#View_layerType
617 * @attr ref android.R.styleable#View_longClickable
618 * @attr ref android.R.styleable#View_minHeight
619 * @attr ref android.R.styleable#View_minWidth
620 * @attr ref android.R.styleable#View_nextFocusDown
621 * @attr ref android.R.styleable#View_nextFocusLeft
622 * @attr ref android.R.styleable#View_nextFocusRight
623 * @attr ref android.R.styleable#View_nextFocusUp
624 * @attr ref android.R.styleable#View_onClick
625 * @attr ref android.R.styleable#View_padding
626 * @attr ref android.R.styleable#View_paddingBottom
627 * @attr ref android.R.styleable#View_paddingLeft
628 * @attr ref android.R.styleable#View_paddingRight
629 * @attr ref android.R.styleable#View_paddingTop
630 * @attr ref android.R.styleable#View_saveEnabled
631 * @attr ref android.R.styleable#View_rotation
632 * @attr ref android.R.styleable#View_rotationX
633 * @attr ref android.R.styleable#View_rotationY
634 * @attr ref android.R.styleable#View_scaleX
635 * @attr ref android.R.styleable#View_scaleY
636 * @attr ref android.R.styleable#View_scrollX
637 * @attr ref android.R.styleable#View_scrollY
638 * @attr ref android.R.styleable#View_scrollbarSize
639 * @attr ref android.R.styleable#View_scrollbarStyle
640 * @attr ref android.R.styleable#View_scrollbars
641 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
642 * @attr ref android.R.styleable#View_scrollbarFadeDuration
643 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
644 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
645 * @attr ref android.R.styleable#View_scrollbarThumbVertical
646 * @attr ref android.R.styleable#View_scrollbarTrackVertical
647 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
648 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
649 * @attr ref android.R.styleable#View_soundEffectsEnabled
650 * @attr ref android.R.styleable#View_tag
651 * @attr ref android.R.styleable#View_transformPivotX
652 * @attr ref android.R.styleable#View_transformPivotY
653 * @attr ref android.R.styleable#View_translationX
654 * @attr ref android.R.styleable#View_translationY
655 * @attr ref android.R.styleable#View_visibility
656 *
657 * @see android.view.ViewGroup
658 */
659public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
660        AccessibilityEventSource {
661    private static final boolean DBG = false;
662
663    /**
664     * The logging tag used by this class with android.util.Log.
665     */
666    protected static final String VIEW_LOG_TAG = "View";
667
668    /**
669     * When set to true, apps will draw debugging information about their layouts.
670     *
671     * @hide
672     */
673    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
674
675    /**
676     * Used to mark a View that has no ID.
677     */
678    public static final int NO_ID = -1;
679
680    /**
681     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
682     * calling setFlags.
683     */
684    private static final int NOT_FOCUSABLE = 0x00000000;
685
686    /**
687     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
688     * setFlags.
689     */
690    private static final int FOCUSABLE = 0x00000001;
691
692    /**
693     * Mask for use with setFlags indicating bits used for focus.
694     */
695    private static final int FOCUSABLE_MASK = 0x00000001;
696
697    /**
698     * This view will adjust its padding to fit sytem windows (e.g. status bar)
699     */
700    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
701
702    /**
703     * This view is visible.
704     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
705     * android:visibility}.
706     */
707    public static final int VISIBLE = 0x00000000;
708
709    /**
710     * This view is invisible, but it still takes up space for layout purposes.
711     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
712     * android:visibility}.
713     */
714    public static final int INVISIBLE = 0x00000004;
715
716    /**
717     * This view is invisible, and it doesn't take any space for layout
718     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
719     * android:visibility}.
720     */
721    public static final int GONE = 0x00000008;
722
723    /**
724     * Mask for use with setFlags indicating bits used for visibility.
725     * {@hide}
726     */
727    static final int VISIBILITY_MASK = 0x0000000C;
728
729    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
730
731    /**
732     * This view is enabled. Interpretation varies by subclass.
733     * Use with ENABLED_MASK when calling setFlags.
734     * {@hide}
735     */
736    static final int ENABLED = 0x00000000;
737
738    /**
739     * This view is disabled. Interpretation varies by subclass.
740     * Use with ENABLED_MASK when calling setFlags.
741     * {@hide}
742     */
743    static final int DISABLED = 0x00000020;
744
745   /**
746    * Mask for use with setFlags indicating bits used for indicating whether
747    * this view is enabled
748    * {@hide}
749    */
750    static final int ENABLED_MASK = 0x00000020;
751
752    /**
753     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
754     * called and further optimizations will be performed. It is okay to have
755     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
756     * {@hide}
757     */
758    static final int WILL_NOT_DRAW = 0x00000080;
759
760    /**
761     * Mask for use with setFlags indicating bits used for indicating whether
762     * this view is will draw
763     * {@hide}
764     */
765    static final int DRAW_MASK = 0x00000080;
766
767    /**
768     * <p>This view doesn't show scrollbars.</p>
769     * {@hide}
770     */
771    static final int SCROLLBARS_NONE = 0x00000000;
772
773    /**
774     * <p>This view shows horizontal scrollbars.</p>
775     * {@hide}
776     */
777    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
778
779    /**
780     * <p>This view shows vertical scrollbars.</p>
781     * {@hide}
782     */
783    static final int SCROLLBARS_VERTICAL = 0x00000200;
784
785    /**
786     * <p>Mask for use with setFlags indicating bits used for indicating which
787     * scrollbars are enabled.</p>
788     * {@hide}
789     */
790    static final int SCROLLBARS_MASK = 0x00000300;
791
792    /**
793     * Indicates that the view should filter touches when its window is obscured.
794     * Refer to the class comments for more information about this security feature.
795     * {@hide}
796     */
797    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
798
799    /**
800     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
801     * that they are optional and should be skipped if the window has
802     * requested system UI flags that ignore those insets for layout.
803     */
804    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
805
806    /**
807     * <p>This view doesn't show fading edges.</p>
808     * {@hide}
809     */
810    static final int FADING_EDGE_NONE = 0x00000000;
811
812    /**
813     * <p>This view shows horizontal fading edges.</p>
814     * {@hide}
815     */
816    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
817
818    /**
819     * <p>This view shows vertical fading edges.</p>
820     * {@hide}
821     */
822    static final int FADING_EDGE_VERTICAL = 0x00002000;
823
824    /**
825     * <p>Mask for use with setFlags indicating bits used for indicating which
826     * fading edges are enabled.</p>
827     * {@hide}
828     */
829    static final int FADING_EDGE_MASK = 0x00003000;
830
831    /**
832     * <p>Indicates this view can be clicked. When clickable, a View reacts
833     * to clicks by notifying the OnClickListener.<p>
834     * {@hide}
835     */
836    static final int CLICKABLE = 0x00004000;
837
838    /**
839     * <p>Indicates this view is caching its drawing into a bitmap.</p>
840     * {@hide}
841     */
842    static final int DRAWING_CACHE_ENABLED = 0x00008000;
843
844    /**
845     * <p>Indicates that no icicle should be saved for this view.<p>
846     * {@hide}
847     */
848    static final int SAVE_DISABLED = 0x000010000;
849
850    /**
851     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
852     * property.</p>
853     * {@hide}
854     */
855    static final int SAVE_DISABLED_MASK = 0x000010000;
856
857    /**
858     * <p>Indicates that no drawing cache should ever be created for this view.<p>
859     * {@hide}
860     */
861    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
862
863    /**
864     * <p>Indicates this view can take / keep focus when int touch mode.</p>
865     * {@hide}
866     */
867    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
868
869    /**
870     * <p>Enables low quality mode for the drawing cache.</p>
871     */
872    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
873
874    /**
875     * <p>Enables high quality mode for the drawing cache.</p>
876     */
877    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
878
879    /**
880     * <p>Enables automatic quality mode for the drawing cache.</p>
881     */
882    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
883
884    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
885            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
886    };
887
888    /**
889     * <p>Mask for use with setFlags indicating bits used for the cache
890     * quality property.</p>
891     * {@hide}
892     */
893    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
894
895    /**
896     * <p>
897     * Indicates this view can be long clicked. When long clickable, a View
898     * reacts to long clicks by notifying the OnLongClickListener or showing a
899     * context menu.
900     * </p>
901     * {@hide}
902     */
903    static final int LONG_CLICKABLE = 0x00200000;
904
905    /**
906     * <p>Indicates that this view gets its drawable states from its direct parent
907     * and ignores its original internal states.</p>
908     *
909     * @hide
910     */
911    static final int DUPLICATE_PARENT_STATE = 0x00400000;
912
913    /**
914     * The scrollbar style to display the scrollbars inside the content area,
915     * without increasing the padding. The scrollbars will be overlaid with
916     * translucency on the view's content.
917     */
918    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
919
920    /**
921     * The scrollbar style to display the scrollbars inside the padded area,
922     * increasing the padding of the view. The scrollbars will not overlap the
923     * content area of the view.
924     */
925    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
926
927    /**
928     * The scrollbar style to display the scrollbars at the edge of the view,
929     * without increasing the padding. The scrollbars will be overlaid with
930     * translucency.
931     */
932    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
933
934    /**
935     * The scrollbar style to display the scrollbars at the edge of the view,
936     * increasing the padding of the view. The scrollbars will only overlap the
937     * background, if any.
938     */
939    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
940
941    /**
942     * Mask to check if the scrollbar style is overlay or inset.
943     * {@hide}
944     */
945    static final int SCROLLBARS_INSET_MASK = 0x01000000;
946
947    /**
948     * Mask to check if the scrollbar style is inside or outside.
949     * {@hide}
950     */
951    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
952
953    /**
954     * Mask for scrollbar style.
955     * {@hide}
956     */
957    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
958
959    /**
960     * View flag indicating that the screen should remain on while the
961     * window containing this view is visible to the user.  This effectively
962     * takes care of automatically setting the WindowManager's
963     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
964     */
965    public static final int KEEP_SCREEN_ON = 0x04000000;
966
967    /**
968     * View flag indicating whether this view should have sound effects enabled
969     * for events such as clicking and touching.
970     */
971    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
972
973    /**
974     * View flag indicating whether this view should have haptic feedback
975     * enabled for events such as long presses.
976     */
977    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
978
979    /**
980     * <p>Indicates that the view hierarchy should stop saving state when
981     * it reaches this view.  If state saving is initiated immediately at
982     * the view, it will be allowed.
983     * {@hide}
984     */
985    static final int PARENT_SAVE_DISABLED = 0x20000000;
986
987    /**
988     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
989     * {@hide}
990     */
991    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
992
993    /**
994     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
995     * should add all focusable Views regardless if they are focusable in touch mode.
996     */
997    public static final int FOCUSABLES_ALL = 0x00000000;
998
999    /**
1000     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1001     * should add only Views focusable in touch mode.
1002     */
1003    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1004
1005    /**
1006     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1007     * should add only accessibility focusable Views.
1008     *
1009     * @hide
1010     */
1011    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1012
1013    /**
1014     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1015     * item.
1016     */
1017    public static final int FOCUS_BACKWARD = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1021     * item.
1022     */
1023    public static final int FOCUS_FORWARD = 0x00000002;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the left.
1027     */
1028    public static final int FOCUS_LEFT = 0x00000011;
1029
1030    /**
1031     * Use with {@link #focusSearch(int)}. Move focus up.
1032     */
1033    public static final int FOCUS_UP = 0x00000021;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move focus to the right.
1037     */
1038    public static final int FOCUS_RIGHT = 0x00000042;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move focus down.
1042     */
1043    public static final int FOCUS_DOWN = 0x00000082;
1044
1045    // Accessibility focus directions.
1046
1047    /**
1048     * The accessibility focus which is the current user position when
1049     * interacting with the accessibility framework.
1050     */
1051    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1052
1053    /**
1054     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1055     */
1056    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1057
1058    /**
1059     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1060     */
1061    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1062
1063    /**
1064     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1065     */
1066    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1067
1068    /**
1069     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1070     */
1071    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1072
1073    /**
1074     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1075     */
1076    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1077
1078    /**
1079     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1080     */
1081    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1082
1083    /**
1084     * Bits of {@link #getMeasuredWidthAndState()} and
1085     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1086     */
1087    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1088
1089    /**
1090     * Bits of {@link #getMeasuredWidthAndState()} and
1091     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1092     */
1093    public static final int MEASURED_STATE_MASK = 0xff000000;
1094
1095    /**
1096     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1097     * for functions that combine both width and height into a single int,
1098     * such as {@link #getMeasuredState()} and the childState argument of
1099     * {@link #resolveSizeAndState(int, int, int)}.
1100     */
1101    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1102
1103    /**
1104     * Bit of {@link #getMeasuredWidthAndState()} and
1105     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1106     * is smaller that the space the view would like to have.
1107     */
1108    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1109
1110    /**
1111     * Base View state sets
1112     */
1113    // Singles
1114    /**
1115     * Indicates the view has no states set. States are used with
1116     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1117     * view depending on its state.
1118     *
1119     * @see android.graphics.drawable.Drawable
1120     * @see #getDrawableState()
1121     */
1122    protected static final int[] EMPTY_STATE_SET;
1123    /**
1124     * Indicates the view is enabled. States are used with
1125     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1126     * view depending on its state.
1127     *
1128     * @see android.graphics.drawable.Drawable
1129     * @see #getDrawableState()
1130     */
1131    protected static final int[] ENABLED_STATE_SET;
1132    /**
1133     * Indicates the view is focused. States are used with
1134     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1135     * view depending on its state.
1136     *
1137     * @see android.graphics.drawable.Drawable
1138     * @see #getDrawableState()
1139     */
1140    protected static final int[] FOCUSED_STATE_SET;
1141    /**
1142     * Indicates the view is selected. States are used with
1143     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1144     * view depending on its state.
1145     *
1146     * @see android.graphics.drawable.Drawable
1147     * @see #getDrawableState()
1148     */
1149    protected static final int[] SELECTED_STATE_SET;
1150    /**
1151     * Indicates the view is pressed. States are used with
1152     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1153     * view depending on its state.
1154     *
1155     * @see android.graphics.drawable.Drawable
1156     * @see #getDrawableState()
1157     * @hide
1158     */
1159    protected static final int[] PRESSED_STATE_SET;
1160    /**
1161     * Indicates the view's window has focus. States are used with
1162     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1163     * view depending on its state.
1164     *
1165     * @see android.graphics.drawable.Drawable
1166     * @see #getDrawableState()
1167     */
1168    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1169    // Doubles
1170    /**
1171     * Indicates the view is enabled and has the focus.
1172     *
1173     * @see #ENABLED_STATE_SET
1174     * @see #FOCUSED_STATE_SET
1175     */
1176    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1177    /**
1178     * Indicates the view is enabled and selected.
1179     *
1180     * @see #ENABLED_STATE_SET
1181     * @see #SELECTED_STATE_SET
1182     */
1183    protected static final int[] ENABLED_SELECTED_STATE_SET;
1184    /**
1185     * Indicates the view is enabled and that its window has focus.
1186     *
1187     * @see #ENABLED_STATE_SET
1188     * @see #WINDOW_FOCUSED_STATE_SET
1189     */
1190    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1191    /**
1192     * Indicates the view is focused and selected.
1193     *
1194     * @see #FOCUSED_STATE_SET
1195     * @see #SELECTED_STATE_SET
1196     */
1197    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1198    /**
1199     * Indicates the view has the focus and that its window has the focus.
1200     *
1201     * @see #FOCUSED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is selected and that its window has the focus.
1207     *
1208     * @see #SELECTED_STATE_SET
1209     * @see #WINDOW_FOCUSED_STATE_SET
1210     */
1211    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1212    // Triples
1213    /**
1214     * Indicates the view is enabled, focused and selected.
1215     *
1216     * @see #ENABLED_STATE_SET
1217     * @see #FOCUSED_STATE_SET
1218     * @see #SELECTED_STATE_SET
1219     */
1220    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1221    /**
1222     * Indicates the view is enabled, focused and its window has the focus.
1223     *
1224     * @see #ENABLED_STATE_SET
1225     * @see #FOCUSED_STATE_SET
1226     * @see #WINDOW_FOCUSED_STATE_SET
1227     */
1228    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1229    /**
1230     * Indicates the view is enabled, selected and its window has the focus.
1231     *
1232     * @see #ENABLED_STATE_SET
1233     * @see #SELECTED_STATE_SET
1234     * @see #WINDOW_FOCUSED_STATE_SET
1235     */
1236    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1237    /**
1238     * Indicates the view is focused, selected and its window has the focus.
1239     *
1240     * @see #FOCUSED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is enabled, focused, selected and its window
1247     * has the focus.
1248     *
1249     * @see #ENABLED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     * @see #SELECTED_STATE_SET
1252     * @see #WINDOW_FOCUSED_STATE_SET
1253     */
1254    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1255    /**
1256     * Indicates the view is pressed and its window has the focus.
1257     *
1258     * @see #PRESSED_STATE_SET
1259     * @see #WINDOW_FOCUSED_STATE_SET
1260     */
1261    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1262    /**
1263     * Indicates the view is pressed and selected.
1264     *
1265     * @see #PRESSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed and focused.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #FOCUSED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, focused and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #FOCUSED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, focused and selected.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #SELECTED_STATE_SET
1297     * @see #FOCUSED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, focused, selected and its window has the focus.
1302     *
1303     * @see #PRESSED_STATE_SET
1304     * @see #FOCUSED_STATE_SET
1305     * @see #SELECTED_STATE_SET
1306     * @see #WINDOW_FOCUSED_STATE_SET
1307     */
1308    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1309    /**
1310     * Indicates the view is pressed and enabled.
1311     *
1312     * @see #PRESSED_STATE_SET
1313     * @see #ENABLED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_ENABLED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed, enabled and its window has the focus.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #ENABLED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, enabled and selected.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #ENABLED_STATE_SET
1329     * @see #SELECTED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, enabled, selected and its window has the
1334     * focus.
1335     *
1336     * @see #PRESSED_STATE_SET
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     * @see #WINDOW_FOCUSED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1342    /**
1343     * Indicates the view is pressed, enabled and focused.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #ENABLED_STATE_SET
1347     * @see #FOCUSED_STATE_SET
1348     */
1349    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1350    /**
1351     * Indicates the view is pressed, enabled, focused and its window has the
1352     * focus.
1353     *
1354     * @see #PRESSED_STATE_SET
1355     * @see #ENABLED_STATE_SET
1356     * @see #FOCUSED_STATE_SET
1357     * @see #WINDOW_FOCUSED_STATE_SET
1358     */
1359    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1360    /**
1361     * Indicates the view is pressed, enabled, focused and selected.
1362     *
1363     * @see #PRESSED_STATE_SET
1364     * @see #ENABLED_STATE_SET
1365     * @see #SELECTED_STATE_SET
1366     * @see #FOCUSED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed, enabled, focused, selected and its window
1371     * has the focus.
1372     *
1373     * @see #PRESSED_STATE_SET
1374     * @see #ENABLED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     * @see #FOCUSED_STATE_SET
1377     * @see #WINDOW_FOCUSED_STATE_SET
1378     */
1379    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1380
1381    /**
1382     * The order here is very important to {@link #getDrawableState()}
1383     */
1384    private static final int[][] VIEW_STATE_SETS;
1385
1386    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1387    static final int VIEW_STATE_SELECTED = 1 << 1;
1388    static final int VIEW_STATE_FOCUSED = 1 << 2;
1389    static final int VIEW_STATE_ENABLED = 1 << 3;
1390    static final int VIEW_STATE_PRESSED = 1 << 4;
1391    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1392    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1393    static final int VIEW_STATE_HOVERED = 1 << 7;
1394    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1395    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1396
1397    static final int[] VIEW_STATE_IDS = new int[] {
1398        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1399        R.attr.state_selected,          VIEW_STATE_SELECTED,
1400        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1401        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1402        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1403        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1404        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1405        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1406        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1407        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1408    };
1409
1410    static {
1411        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1412            throw new IllegalStateException(
1413                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1414        }
1415        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1416        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1417            int viewState = R.styleable.ViewDrawableStates[i];
1418            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1419                if (VIEW_STATE_IDS[j] == viewState) {
1420                    orderedIds[i * 2] = viewState;
1421                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1422                }
1423            }
1424        }
1425        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1426        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1427        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1428            int numBits = Integer.bitCount(i);
1429            int[] set = new int[numBits];
1430            int pos = 0;
1431            for (int j = 0; j < orderedIds.length; j += 2) {
1432                if ((i & orderedIds[j+1]) != 0) {
1433                    set[pos++] = orderedIds[j];
1434                }
1435            }
1436            VIEW_STATE_SETS[i] = set;
1437        }
1438
1439        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1440        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1441        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1442        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1444        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1445        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1447        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1449        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1451                | VIEW_STATE_FOCUSED];
1452        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1453        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1455        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1457        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_ENABLED];
1460        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1462        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1464                | VIEW_STATE_ENABLED];
1465        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1467                | VIEW_STATE_ENABLED];
1468        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1471
1472        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1473        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1475        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1477        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1479                | VIEW_STATE_PRESSED];
1480        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1482        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1483                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1484                | VIEW_STATE_PRESSED];
1485        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1486                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1487                | VIEW_STATE_PRESSED];
1488        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1490                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1491        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1493        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1495                | VIEW_STATE_PRESSED];
1496        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1498                | VIEW_STATE_PRESSED];
1499        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1501                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1502        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1504                | VIEW_STATE_PRESSED];
1505        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1507                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1508        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1510                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1511        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1512                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1513                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1514                | VIEW_STATE_PRESSED];
1515    }
1516
1517    /**
1518     * Accessibility event types that are dispatched for text population.
1519     */
1520    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1521            AccessibilityEvent.TYPE_VIEW_CLICKED
1522            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1523            | AccessibilityEvent.TYPE_VIEW_SELECTED
1524            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1525            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1526            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1527            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1528            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1529            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1530            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1531            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1532
1533    /**
1534     * Temporary Rect currently for use in setBackground().  This will probably
1535     * be extended in the future to hold our own class with more than just
1536     * a Rect. :)
1537     */
1538    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1539
1540    /**
1541     * Map used to store views' tags.
1542     */
1543    private SparseArray<Object> mKeyedTags;
1544
1545    /**
1546     * The next available accessiiblity id.
1547     */
1548    private static int sNextAccessibilityViewId;
1549
1550    /**
1551     * The animation currently associated with this view.
1552     * @hide
1553     */
1554    protected Animation mCurrentAnimation = null;
1555
1556    /**
1557     * Width as measured during measure pass.
1558     * {@hide}
1559     */
1560    @ViewDebug.ExportedProperty(category = "measurement")
1561    int mMeasuredWidth;
1562
1563    /**
1564     * Height as measured during measure pass.
1565     * {@hide}
1566     */
1567    @ViewDebug.ExportedProperty(category = "measurement")
1568    int mMeasuredHeight;
1569
1570    /**
1571     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1572     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1573     * its display list. This flag, used only when hw accelerated, allows us to clear the
1574     * flag while retaining this information until it's needed (at getDisplayList() time and
1575     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1576     *
1577     * {@hide}
1578     */
1579    boolean mRecreateDisplayList = false;
1580
1581    /**
1582     * The view's identifier.
1583     * {@hide}
1584     *
1585     * @see #setId(int)
1586     * @see #getId()
1587     */
1588    @ViewDebug.ExportedProperty(resolveId = true)
1589    int mID = NO_ID;
1590
1591    /**
1592     * The stable ID of this view for accessibility purposes.
1593     */
1594    int mAccessibilityViewId = NO_ID;
1595
1596    /**
1597     * @hide
1598     */
1599    private int mAccessibilityCursorPosition = -1;
1600
1601    /**
1602     * The view's tag.
1603     * {@hide}
1604     *
1605     * @see #setTag(Object)
1606     * @see #getTag()
1607     */
1608    protected Object mTag;
1609
1610    // for mPrivateFlags:
1611    /** {@hide} */
1612    static final int WANTS_FOCUS                    = 0x00000001;
1613    /** {@hide} */
1614    static final int FOCUSED                        = 0x00000002;
1615    /** {@hide} */
1616    static final int SELECTED                       = 0x00000004;
1617    /** {@hide} */
1618    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1619    /** {@hide} */
1620    static final int HAS_BOUNDS                     = 0x00000010;
1621    /** {@hide} */
1622    static final int DRAWN                          = 0x00000020;
1623    /**
1624     * When this flag is set, this view is running an animation on behalf of its
1625     * children and should therefore not cancel invalidate requests, even if they
1626     * lie outside of this view's bounds.
1627     *
1628     * {@hide}
1629     */
1630    static final int DRAW_ANIMATION                 = 0x00000040;
1631    /** {@hide} */
1632    static final int SKIP_DRAW                      = 0x00000080;
1633    /** {@hide} */
1634    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1635    /** {@hide} */
1636    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1637    /** {@hide} */
1638    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1639    /** {@hide} */
1640    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1641    /** {@hide} */
1642    static final int FORCE_LAYOUT                   = 0x00001000;
1643    /** {@hide} */
1644    static final int LAYOUT_REQUIRED                = 0x00002000;
1645
1646    private static final int PRESSED                = 0x00004000;
1647
1648    /** {@hide} */
1649    static final int DRAWING_CACHE_VALID            = 0x00008000;
1650    /**
1651     * Flag used to indicate that this view should be drawn once more (and only once
1652     * more) after its animation has completed.
1653     * {@hide}
1654     */
1655    static final int ANIMATION_STARTED              = 0x00010000;
1656
1657    private static final int SAVE_STATE_CALLED      = 0x00020000;
1658
1659    /**
1660     * Indicates that the View returned true when onSetAlpha() was called and that
1661     * the alpha must be restored.
1662     * {@hide}
1663     */
1664    static final int ALPHA_SET                      = 0x00040000;
1665
1666    /**
1667     * Set by {@link #setScrollContainer(boolean)}.
1668     */
1669    static final int SCROLL_CONTAINER               = 0x00080000;
1670
1671    /**
1672     * Set by {@link #setScrollContainer(boolean)}.
1673     */
1674    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1675
1676    /**
1677     * View flag indicating whether this view was invalidated (fully or partially.)
1678     *
1679     * @hide
1680     */
1681    static final int DIRTY                          = 0x00200000;
1682
1683    /**
1684     * View flag indicating whether this view was invalidated by an opaque
1685     * invalidate request.
1686     *
1687     * @hide
1688     */
1689    static final int DIRTY_OPAQUE                   = 0x00400000;
1690
1691    /**
1692     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1693     *
1694     * @hide
1695     */
1696    static final int DIRTY_MASK                     = 0x00600000;
1697
1698    /**
1699     * Indicates whether the background is opaque.
1700     *
1701     * @hide
1702     */
1703    static final int OPAQUE_BACKGROUND              = 0x00800000;
1704
1705    /**
1706     * Indicates whether the scrollbars are opaque.
1707     *
1708     * @hide
1709     */
1710    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1711
1712    /**
1713     * Indicates whether the view is opaque.
1714     *
1715     * @hide
1716     */
1717    static final int OPAQUE_MASK                    = 0x01800000;
1718
1719    /**
1720     * Indicates a prepressed state;
1721     * the short time between ACTION_DOWN and recognizing
1722     * a 'real' press. Prepressed is used to recognize quick taps
1723     * even when they are shorter than ViewConfiguration.getTapTimeout().
1724     *
1725     * @hide
1726     */
1727    private static final int PREPRESSED             = 0x02000000;
1728
1729    /**
1730     * Indicates whether the view is temporarily detached.
1731     *
1732     * @hide
1733     */
1734    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1735
1736    /**
1737     * Indicates that we should awaken scroll bars once attached
1738     *
1739     * @hide
1740     */
1741    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1742
1743    /**
1744     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1745     * @hide
1746     */
1747    private static final int HOVERED              = 0x10000000;
1748
1749    /**
1750     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1751     * for transform operations
1752     *
1753     * @hide
1754     */
1755    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1756
1757    /** {@hide} */
1758    static final int ACTIVATED                    = 0x40000000;
1759
1760    /**
1761     * Indicates that this view was specifically invalidated, not just dirtied because some
1762     * child view was invalidated. The flag is used to determine when we need to recreate
1763     * a view's display list (as opposed to just returning a reference to its existing
1764     * display list).
1765     *
1766     * @hide
1767     */
1768    static final int INVALIDATED                  = 0x80000000;
1769
1770    /* Masks for mPrivateFlags2 */
1771
1772    /**
1773     * Indicates that this view has reported that it can accept the current drag's content.
1774     * Cleared when the drag operation concludes.
1775     * @hide
1776     */
1777    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1778
1779    /**
1780     * Indicates that this view is currently directly under the drag location in a
1781     * drag-and-drop operation involving content that it can accept.  Cleared when
1782     * the drag exits the view, or when the drag operation concludes.
1783     * @hide
1784     */
1785    static final int DRAG_HOVERED                 = 0x00000002;
1786
1787    /**
1788     * Horizontal layout direction of this view is from Left to Right.
1789     * Use with {@link #setLayoutDirection}.
1790     * @hide
1791     */
1792    public static final int LAYOUT_DIRECTION_LTR = 0;
1793
1794    /**
1795     * Horizontal layout direction of this view is from Right to Left.
1796     * Use with {@link #setLayoutDirection}.
1797     * @hide
1798     */
1799    public static final int LAYOUT_DIRECTION_RTL = 1;
1800
1801    /**
1802     * Horizontal layout direction of this view is inherited from its parent.
1803     * Use with {@link #setLayoutDirection}.
1804     * @hide
1805     */
1806    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1807
1808    /**
1809     * Horizontal layout direction of this view is from deduced from the default language
1810     * script for the locale. Use with {@link #setLayoutDirection}.
1811     * @hide
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     * @hide
1877     */
1878    public static final int TEXT_DIRECTION_INHERIT = 0;
1879
1880    /**
1881     * Text direction is using "first strong algorithm". The first strong directional character
1882     * determines the paragraph direction. If there is no strong directional character, the
1883     * paragraph direction is the view's resolved layout direction.
1884     * @hide
1885     */
1886    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1887
1888    /**
1889     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1890     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1891     * If there are neither, the paragraph direction is the view's resolved layout direction.
1892     * @hide
1893     */
1894    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1895
1896    /**
1897     * Text direction is forced to LTR.
1898     * @hide
1899     */
1900    public static final int TEXT_DIRECTION_LTR = 3;
1901
1902    /**
1903     * Text direction is forced to RTL.
1904     * @hide
1905     */
1906    public static final int TEXT_DIRECTION_RTL = 4;
1907
1908    /**
1909     * Text direction is coming from the system Locale.
1910     * @hide
1911     */
1912    public static final int TEXT_DIRECTION_LOCALE = 5;
1913
1914    /**
1915     * Default text direction is inherited
1916     * @hide
1917     */
1918    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1919
1920    /**
1921     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1922     * @hide
1923     */
1924    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1925
1926    /**
1927     * Mask for use with private flags indicating bits used for text direction.
1928     * @hide
1929     */
1930    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1931
1932    /**
1933     * Array of text direction flags for mapping attribute "textDirection" to correct
1934     * flag value.
1935     * @hide
1936     */
1937    private static final int[] TEXT_DIRECTION_FLAGS = {
1938            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1939            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1940            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1941            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1942            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1943            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1944    };
1945
1946    /**
1947     * Indicates whether the view text direction has been resolved.
1948     * @hide
1949     */
1950    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1951
1952    /**
1953     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1954     * @hide
1955     */
1956    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1957
1958    /**
1959     * Mask for use with private flags indicating bits used for resolved text direction.
1960     * @hide
1961     */
1962    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1963
1964    /**
1965     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1966     * @hide
1967     */
1968    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1969            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1970
1971    /*
1972     * Default text alignment. The text alignment of this View is inherited from its parent.
1973     * Use with {@link #setTextAlignment(int)}
1974     * @hide
1975     */
1976    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1977
1978    /**
1979     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1980     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1981     *
1982     * Use with {@link #setTextAlignment(int)}
1983     * @hide
1984     */
1985    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1986
1987    /**
1988     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1989     *
1990     * Use with {@link #setTextAlignment(int)}
1991     * @hide
1992     */
1993    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1994
1995    /**
1996     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1997     *
1998     * Use with {@link #setTextAlignment(int)}
1999     * @hide
2000     */
2001    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2002
2003    /**
2004     * Center the paragraph, e.g. ALIGN_CENTER.
2005     *
2006     * Use with {@link #setTextAlignment(int)}
2007     * @hide
2008     */
2009    public static final int TEXT_ALIGNMENT_CENTER = 4;
2010
2011    /**
2012     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2013     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2014     *
2015     * Use with {@link #setTextAlignment(int)}
2016     * @hide
2017     */
2018    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2019
2020    /**
2021     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2022     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2023     *
2024     * Use with {@link #setTextAlignment(int)}
2025     * @hide
2026     */
2027    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2028
2029    /**
2030     * Default text alignment is inherited
2031     * @hide
2032     */
2033    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2034
2035    /**
2036      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2037      * @hide
2038      */
2039    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2040
2041    /**
2042      * Mask for use with private flags indicating bits used for text alignment.
2043      * @hide
2044      */
2045    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2046
2047    /**
2048     * Array of text direction flags for mapping attribute "textAlignment" to correct
2049     * flag value.
2050     * @hide
2051     */
2052    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2053            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2054            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2055            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2056            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2057            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2058            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2059            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2060    };
2061
2062    /**
2063     * Indicates whether the view text alignment has been resolved.
2064     * @hide
2065     */
2066    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2067
2068    /**
2069     * Bit shift to get the resolved text alignment.
2070     * @hide
2071     */
2072    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2073
2074    /**
2075     * Mask for use with private flags indicating bits used for text alignment.
2076     * @hide
2077     */
2078    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2079
2080    /**
2081     * Indicates whether if the view text alignment has been resolved to gravity
2082     */
2083    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2084            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2085
2086    // Accessiblity constants for mPrivateFlags2
2087
2088    /**
2089     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2090     */
2091    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2092
2093    /**
2094     * Automatically determine whether a view is important for accessibility.
2095     */
2096    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2097
2098    /**
2099     * The view is important for accessibility.
2100     */
2101    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2102
2103    /**
2104     * The view is not important for accessibility.
2105     */
2106    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2107
2108    /**
2109     * The default whether the view is important for accessiblity.
2110     */
2111    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2112
2113    /**
2114     * Mask for obtainig the bits which specify how to determine
2115     * whether a view is important for accessibility.
2116     */
2117    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2118        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2119        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2120
2121    /**
2122     * Flag indicating whether a view has accessibility focus.
2123     */
2124    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2125
2126    /**
2127     * Flag indicating whether a view state for accessibility has changed.
2128     */
2129    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2130
2131    /* End of masks for mPrivateFlags2 */
2132
2133    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2134
2135    /**
2136     * Always allow a user to over-scroll this view, provided it is a
2137     * view that can scroll.
2138     *
2139     * @see #getOverScrollMode()
2140     * @see #setOverScrollMode(int)
2141     */
2142    public static final int OVER_SCROLL_ALWAYS = 0;
2143
2144    /**
2145     * Allow a user to over-scroll this view only if the content is large
2146     * enough to meaningfully scroll, provided it is a view that can scroll.
2147     *
2148     * @see #getOverScrollMode()
2149     * @see #setOverScrollMode(int)
2150     */
2151    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2152
2153    /**
2154     * Never allow a user to over-scroll this view.
2155     *
2156     * @see #getOverScrollMode()
2157     * @see #setOverScrollMode(int)
2158     */
2159    public static final int OVER_SCROLL_NEVER = 2;
2160
2161    /**
2162     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2163     * requested the system UI (status bar) to be visible (the default).
2164     *
2165     * @see #setSystemUiVisibility(int)
2166     */
2167    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2168
2169    /**
2170     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2171     * system UI to enter an unobtrusive "low profile" mode.
2172     *
2173     * <p>This is for use in games, book readers, video players, or any other
2174     * "immersive" application where the usual system chrome is deemed too distracting.
2175     *
2176     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2177     *
2178     * @see #setSystemUiVisibility(int)
2179     */
2180    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2181
2182    /**
2183     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2184     * system navigation be temporarily hidden.
2185     *
2186     * <p>This is an even less obtrusive state than that called for by
2187     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2188     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2189     * those to disappear. This is useful (in conjunction with the
2190     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2191     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2192     * window flags) for displaying content using every last pixel on the display.
2193     *
2194     * <p>There is a limitation: because navigation controls are so important, the least user
2195     * interaction will cause them to reappear immediately.  When this happens, both
2196     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2197     * so that both elements reappear at the same time.
2198     *
2199     * @see #setSystemUiVisibility(int)
2200     */
2201    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2202
2203    /**
2204     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2205     * into the normal fullscreen mode so that its content can take over the screen
2206     * while still allowing the user to interact with the application.
2207     *
2208     * <p>This has the same visual effect as
2209     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2210     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2211     * meaning that non-critical screen decorations (such as the status bar) will be
2212     * hidden while the user is in the View's window, focusing the experience on
2213     * that content.  Unlike the window flag, if you are using ActionBar in
2214     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2215     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2216     * hide the action bar.
2217     *
2218     * <p>This approach to going fullscreen is best used over the window flag when
2219     * it is a transient state -- that is, the application does this at certain
2220     * points in its user interaction where it wants to allow the user to focus
2221     * on content, but not as a continuous state.  For situations where the application
2222     * would like to simply stay full screen the entire time (such as a game that
2223     * wants to take over the screen), the
2224     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2225     * is usually a better approach.  The state set here will be removed by the system
2226     * in various situations (such as the user moving to another application) like
2227     * the other system UI states.
2228     *
2229     * <p>When using this flag, the application should provide some easy facility
2230     * for the user to go out of it.  A common example would be in an e-book
2231     * reader, where tapping on the screen brings back whatever screen and UI
2232     * decorations that had been hidden while the user was immersed in reading
2233     * the book.
2234     *
2235     * @see #setSystemUiVisibility(int)
2236     */
2237    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2238
2239    /**
2240     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2241     * flags, we would like a stable view of the content insets given to
2242     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2243     * will always represent the worst case that the application can expect
2244     * as a continue state.  In practice this means with any of system bar,
2245     * nav bar, and status bar shown, but not the space that would be needed
2246     * for an input method.
2247     *
2248     * <p>If you are using ActionBar in
2249     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2250     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2251     * insets it adds to those given to the application.
2252     */
2253    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2254
2255    /**
2256     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2257     * to be layed out as if it has requested
2258     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2259     * allows it to avoid artifacts when switching in and out of that mode, at
2260     * the expense that some of its user interface may be covered by screen
2261     * decorations when they are shown.  You can perform layout of your inner
2262     * UI elements to account for the navagation system UI through the
2263     * {@link #fitSystemWindows(Rect)} method.
2264     */
2265    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2266
2267    /**
2268     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2269     * to be layed out as if it has requested
2270     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2271     * allows it to avoid artifacts when switching in and out of that mode, at
2272     * the expense that some of its user interface may be covered by screen
2273     * decorations when they are shown.  You can perform layout of your inner
2274     * UI elements to account for non-fullscreen system UI through the
2275     * {@link #fitSystemWindows(Rect)} method.
2276     */
2277    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2278
2279    /**
2280     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2281     */
2282    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2283
2284    /**
2285     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2286     */
2287    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2288
2289    /**
2290     * @hide
2291     *
2292     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2293     * out of the public fields to keep the undefined bits out of the developer's way.
2294     *
2295     * Flag to make the status bar not expandable.  Unless you also
2296     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2297     */
2298    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2299
2300    /**
2301     * @hide
2302     *
2303     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2304     * out of the public fields to keep the undefined bits out of the developer's way.
2305     *
2306     * Flag to hide notification icons and scrolling ticker text.
2307     */
2308    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2309
2310    /**
2311     * @hide
2312     *
2313     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2314     * out of the public fields to keep the undefined bits out of the developer's way.
2315     *
2316     * Flag to disable incoming notification alerts.  This will not block
2317     * icons, but it will block sound, vibrating and other visual or aural notifications.
2318     */
2319    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2320
2321    /**
2322     * @hide
2323     *
2324     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2325     * out of the public fields to keep the undefined bits out of the developer's way.
2326     *
2327     * Flag to hide only the scrolling ticker.  Note that
2328     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2329     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2330     */
2331    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2332
2333    /**
2334     * @hide
2335     *
2336     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2337     * out of the public fields to keep the undefined bits out of the developer's way.
2338     *
2339     * Flag to hide the center system info area.
2340     */
2341    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2342
2343    /**
2344     * @hide
2345     *
2346     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2347     * out of the public fields to keep the undefined bits out of the developer's way.
2348     *
2349     * Flag to hide only the home button.  Don't use this
2350     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2351     */
2352    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2353
2354    /**
2355     * @hide
2356     *
2357     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2358     * out of the public fields to keep the undefined bits out of the developer's way.
2359     *
2360     * Flag to hide only the back button. Don't use this
2361     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2362     */
2363    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2364
2365    /**
2366     * @hide
2367     *
2368     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2369     * out of the public fields to keep the undefined bits out of the developer's way.
2370     *
2371     * Flag to hide only the clock.  You might use this if your activity has
2372     * its own clock making the status bar's clock redundant.
2373     */
2374    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2375
2376    /**
2377     * @hide
2378     *
2379     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2380     * out of the public fields to keep the undefined bits out of the developer's way.
2381     *
2382     * Flag to hide only the recent apps button. Don't use this
2383     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2384     */
2385    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2386
2387    /**
2388     * @hide
2389     */
2390    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2391
2392    /**
2393     * These are the system UI flags that can be cleared by events outside
2394     * of an application.  Currently this is just the ability to tap on the
2395     * screen while hiding the navigation bar to have it return.
2396     * @hide
2397     */
2398    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2399            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2400            | SYSTEM_UI_FLAG_FULLSCREEN;
2401
2402    /**
2403     * Flags that can impact the layout in relation to system UI.
2404     */
2405    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2406            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2407            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2408
2409    /**
2410     * Find views that render the specified text.
2411     *
2412     * @see #findViewsWithText(ArrayList, CharSequence, int)
2413     */
2414    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2415
2416    /**
2417     * Find find views that contain the specified content description.
2418     *
2419     * @see #findViewsWithText(ArrayList, CharSequence, int)
2420     */
2421    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2422
2423    /**
2424     * Find views that contain {@link AccessibilityNodeProvider}. Such
2425     * a View is a root of virtual view hierarchy and may contain the searched
2426     * text. If this flag is set Views with providers are automatically
2427     * added and it is a responsibility of the client to call the APIs of
2428     * the provider to determine whether the virtual tree rooted at this View
2429     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2430     * represeting the virtual views with this text.
2431     *
2432     * @see #findViewsWithText(ArrayList, CharSequence, int)
2433     *
2434     * @hide
2435     */
2436    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2437
2438    /**
2439     * Indicates that the screen has changed state and is now off.
2440     *
2441     * @see #onScreenStateChanged(int)
2442     */
2443    public static final int SCREEN_STATE_OFF = 0x0;
2444
2445    /**
2446     * Indicates that the screen has changed state and is now on.
2447     *
2448     * @see #onScreenStateChanged(int)
2449     */
2450    public static final int SCREEN_STATE_ON = 0x1;
2451
2452    /**
2453     * Controls the over-scroll mode for this view.
2454     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2455     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2456     * and {@link #OVER_SCROLL_NEVER}.
2457     */
2458    private int mOverScrollMode;
2459
2460    /**
2461     * The parent this view is attached to.
2462     * {@hide}
2463     *
2464     * @see #getParent()
2465     */
2466    protected ViewParent mParent;
2467
2468    /**
2469     * {@hide}
2470     */
2471    AttachInfo mAttachInfo;
2472
2473    /**
2474     * {@hide}
2475     */
2476    @ViewDebug.ExportedProperty(flagMapping = {
2477        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2478                name = "FORCE_LAYOUT"),
2479        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2480                name = "LAYOUT_REQUIRED"),
2481        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2482            name = "DRAWING_CACHE_INVALID", outputIf = false),
2483        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2484        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2485        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2486        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2487    })
2488    int mPrivateFlags;
2489    int mPrivateFlags2;
2490
2491    /**
2492     * This view's request for the visibility of the status bar.
2493     * @hide
2494     */
2495    @ViewDebug.ExportedProperty(flagMapping = {
2496        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2497                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2498                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2499        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2500                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2501                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2502        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2503                                equals = SYSTEM_UI_FLAG_VISIBLE,
2504                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2505    })
2506    int mSystemUiVisibility;
2507
2508    /**
2509     * Reference count for transient state.
2510     * @see #setHasTransientState(boolean)
2511     */
2512    int mTransientStateCount = 0;
2513
2514    /**
2515     * Count of how many windows this view has been attached to.
2516     */
2517    int mWindowAttachCount;
2518
2519    /**
2520     * The layout parameters associated with this view and used by the parent
2521     * {@link android.view.ViewGroup} to determine how this view should be
2522     * laid out.
2523     * {@hide}
2524     */
2525    protected ViewGroup.LayoutParams mLayoutParams;
2526
2527    /**
2528     * The view flags hold various views states.
2529     * {@hide}
2530     */
2531    @ViewDebug.ExportedProperty
2532    int mViewFlags;
2533
2534    static class TransformationInfo {
2535        /**
2536         * The transform matrix for the View. This transform is calculated internally
2537         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2538         * is used by default. Do *not* use this variable directly; instead call
2539         * getMatrix(), which will automatically recalculate the matrix if necessary
2540         * to get the correct matrix based on the latest rotation and scale properties.
2541         */
2542        private final Matrix mMatrix = new Matrix();
2543
2544        /**
2545         * The transform matrix for the View. This transform is calculated internally
2546         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2547         * is used by default. Do *not* use this variable directly; instead call
2548         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2549         * to get the correct matrix based on the latest rotation and scale properties.
2550         */
2551        private Matrix mInverseMatrix;
2552
2553        /**
2554         * An internal variable that tracks whether we need to recalculate the
2555         * transform matrix, based on whether the rotation or scaleX/Y properties
2556         * have changed since the matrix was last calculated.
2557         */
2558        boolean mMatrixDirty = false;
2559
2560        /**
2561         * An internal variable that tracks whether we need to recalculate the
2562         * transform matrix, based on whether the rotation or scaleX/Y properties
2563         * have changed since the matrix was last calculated.
2564         */
2565        private boolean mInverseMatrixDirty = true;
2566
2567        /**
2568         * A variable that tracks whether we need to recalculate the
2569         * transform matrix, based on whether the rotation or scaleX/Y properties
2570         * have changed since the matrix was last calculated. This variable
2571         * is only valid after a call to updateMatrix() or to a function that
2572         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2573         */
2574        private boolean mMatrixIsIdentity = true;
2575
2576        /**
2577         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2578         */
2579        private Camera mCamera = null;
2580
2581        /**
2582         * This matrix is used when computing the matrix for 3D rotations.
2583         */
2584        private Matrix matrix3D = null;
2585
2586        /**
2587         * These prev values are used to recalculate a centered pivot point when necessary. The
2588         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2589         * set), so thes values are only used then as well.
2590         */
2591        private int mPrevWidth = -1;
2592        private int mPrevHeight = -1;
2593
2594        /**
2595         * The degrees rotation around the vertical axis through the pivot point.
2596         */
2597        @ViewDebug.ExportedProperty
2598        float mRotationY = 0f;
2599
2600        /**
2601         * The degrees rotation around the horizontal axis through the pivot point.
2602         */
2603        @ViewDebug.ExportedProperty
2604        float mRotationX = 0f;
2605
2606        /**
2607         * The degrees rotation around the pivot point.
2608         */
2609        @ViewDebug.ExportedProperty
2610        float mRotation = 0f;
2611
2612        /**
2613         * The amount of translation of the object away from its left property (post-layout).
2614         */
2615        @ViewDebug.ExportedProperty
2616        float mTranslationX = 0f;
2617
2618        /**
2619         * The amount of translation of the object away from its top property (post-layout).
2620         */
2621        @ViewDebug.ExportedProperty
2622        float mTranslationY = 0f;
2623
2624        /**
2625         * The amount of scale in the x direction around the pivot point. A
2626         * value of 1 means no scaling is applied.
2627         */
2628        @ViewDebug.ExportedProperty
2629        float mScaleX = 1f;
2630
2631        /**
2632         * The amount of scale in the y direction around the pivot point. A
2633         * value of 1 means no scaling is applied.
2634         */
2635        @ViewDebug.ExportedProperty
2636        float mScaleY = 1f;
2637
2638        /**
2639         * The x location of the point around which the view is rotated and scaled.
2640         */
2641        @ViewDebug.ExportedProperty
2642        float mPivotX = 0f;
2643
2644        /**
2645         * The y location of the point around which the view is rotated and scaled.
2646         */
2647        @ViewDebug.ExportedProperty
2648        float mPivotY = 0f;
2649
2650        /**
2651         * The opacity of the View. This is a value from 0 to 1, where 0 means
2652         * completely transparent and 1 means completely opaque.
2653         */
2654        @ViewDebug.ExportedProperty
2655        float mAlpha = 1f;
2656    }
2657
2658    TransformationInfo mTransformationInfo;
2659
2660    private boolean mLastIsOpaque;
2661
2662    /**
2663     * Convenience value to check for float values that are close enough to zero to be considered
2664     * zero.
2665     */
2666    private static final float NONZERO_EPSILON = .001f;
2667
2668    /**
2669     * The distance in pixels from the left edge of this view's parent
2670     * to the left edge of this view.
2671     * {@hide}
2672     */
2673    @ViewDebug.ExportedProperty(category = "layout")
2674    protected int mLeft;
2675    /**
2676     * The distance in pixels from the left edge of this view's parent
2677     * to the right edge of this view.
2678     * {@hide}
2679     */
2680    @ViewDebug.ExportedProperty(category = "layout")
2681    protected int mRight;
2682    /**
2683     * The distance in pixels from the top edge of this view's parent
2684     * to the top edge of this view.
2685     * {@hide}
2686     */
2687    @ViewDebug.ExportedProperty(category = "layout")
2688    protected int mTop;
2689    /**
2690     * The distance in pixels from the top edge of this view's parent
2691     * to the bottom edge of this view.
2692     * {@hide}
2693     */
2694    @ViewDebug.ExportedProperty(category = "layout")
2695    protected int mBottom;
2696
2697    /**
2698     * The offset, in pixels, by which the content of this view is scrolled
2699     * horizontally.
2700     * {@hide}
2701     */
2702    @ViewDebug.ExportedProperty(category = "scrolling")
2703    protected int mScrollX;
2704    /**
2705     * The offset, in pixels, by which the content of this view is scrolled
2706     * vertically.
2707     * {@hide}
2708     */
2709    @ViewDebug.ExportedProperty(category = "scrolling")
2710    protected int mScrollY;
2711
2712    /**
2713     * The left padding in pixels, that is the distance in pixels between the
2714     * left edge of this view and the left edge of its content.
2715     * {@hide}
2716     */
2717    @ViewDebug.ExportedProperty(category = "padding")
2718    protected int mPaddingLeft;
2719    /**
2720     * The right padding in pixels, that is the distance in pixels between the
2721     * right edge of this view and the right edge of its content.
2722     * {@hide}
2723     */
2724    @ViewDebug.ExportedProperty(category = "padding")
2725    protected int mPaddingRight;
2726    /**
2727     * The top padding in pixels, that is the distance in pixels between the
2728     * top edge of this view and the top edge of its content.
2729     * {@hide}
2730     */
2731    @ViewDebug.ExportedProperty(category = "padding")
2732    protected int mPaddingTop;
2733    /**
2734     * The bottom padding in pixels, that is the distance in pixels between the
2735     * bottom edge of this view and the bottom edge of its content.
2736     * {@hide}
2737     */
2738    @ViewDebug.ExportedProperty(category = "padding")
2739    protected int mPaddingBottom;
2740
2741    /**
2742     * The layout insets in pixels, that is the distance in pixels between the
2743     * visible edges of this view its bounds.
2744     */
2745    private Insets mLayoutInsets;
2746
2747    /**
2748     * Briefly describes the view and is primarily used for accessibility support.
2749     */
2750    private CharSequence mContentDescription;
2751
2752    /**
2753     * Cache the paddingRight set by the user to append to the scrollbar's size.
2754     *
2755     * @hide
2756     */
2757    @ViewDebug.ExportedProperty(category = "padding")
2758    protected int mUserPaddingRight;
2759
2760    /**
2761     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2762     *
2763     * @hide
2764     */
2765    @ViewDebug.ExportedProperty(category = "padding")
2766    protected int mUserPaddingBottom;
2767
2768    /**
2769     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2770     *
2771     * @hide
2772     */
2773    @ViewDebug.ExportedProperty(category = "padding")
2774    protected int mUserPaddingLeft;
2775
2776    /**
2777     * Cache if the user padding is relative.
2778     *
2779     */
2780    @ViewDebug.ExportedProperty(category = "padding")
2781    boolean mUserPaddingRelative;
2782
2783    /**
2784     * Cache the paddingStart set by the user to append to the scrollbar's size.
2785     *
2786     */
2787    @ViewDebug.ExportedProperty(category = "padding")
2788    int mUserPaddingStart;
2789
2790    /**
2791     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2792     *
2793     */
2794    @ViewDebug.ExportedProperty(category = "padding")
2795    int mUserPaddingEnd;
2796
2797    /**
2798     * @hide
2799     */
2800    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2801    /**
2802     * @hide
2803     */
2804    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2805
2806    private Drawable mBackground;
2807
2808    private int mBackgroundResource;
2809    private boolean mBackgroundSizeChanged;
2810
2811    static class ListenerInfo {
2812        /**
2813         * Listener used to dispatch focus change events.
2814         * This field should be made private, so it is hidden from the SDK.
2815         * {@hide}
2816         */
2817        protected OnFocusChangeListener mOnFocusChangeListener;
2818
2819        /**
2820         * Listeners for layout change events.
2821         */
2822        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2823
2824        /**
2825         * Listeners for attach events.
2826         */
2827        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2828
2829        /**
2830         * Listener used to dispatch click events.
2831         * This field should be made private, so it is hidden from the SDK.
2832         * {@hide}
2833         */
2834        public OnClickListener mOnClickListener;
2835
2836        /**
2837         * Listener used to dispatch long click events.
2838         * This field should be made private, so it is hidden from the SDK.
2839         * {@hide}
2840         */
2841        protected OnLongClickListener mOnLongClickListener;
2842
2843        /**
2844         * Listener used to build the context menu.
2845         * This field should be made private, so it is hidden from the SDK.
2846         * {@hide}
2847         */
2848        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2849
2850        private OnKeyListener mOnKeyListener;
2851
2852        private OnTouchListener mOnTouchListener;
2853
2854        private OnHoverListener mOnHoverListener;
2855
2856        private OnGenericMotionListener mOnGenericMotionListener;
2857
2858        private OnDragListener mOnDragListener;
2859
2860        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2861    }
2862
2863    ListenerInfo mListenerInfo;
2864
2865    /**
2866     * The application environment this view lives in.
2867     * This field should be made private, so it is hidden from the SDK.
2868     * {@hide}
2869     */
2870    protected Context mContext;
2871
2872    private final Resources mResources;
2873
2874    private ScrollabilityCache mScrollCache;
2875
2876    private int[] mDrawableState = null;
2877
2878    /**
2879     * Set to true when drawing cache is enabled and cannot be created.
2880     *
2881     * @hide
2882     */
2883    public boolean mCachingFailed;
2884
2885    private Bitmap mDrawingCache;
2886    private Bitmap mUnscaledDrawingCache;
2887    private HardwareLayer mHardwareLayer;
2888    DisplayList mDisplayList;
2889
2890    /**
2891     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2892     * the user may specify which view to go to next.
2893     */
2894    private int mNextFocusLeftId = View.NO_ID;
2895
2896    /**
2897     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2898     * the user may specify which view to go to next.
2899     */
2900    private int mNextFocusRightId = View.NO_ID;
2901
2902    /**
2903     * When this view has focus and the next focus is {@link #FOCUS_UP},
2904     * the user may specify which view to go to next.
2905     */
2906    private int mNextFocusUpId = View.NO_ID;
2907
2908    /**
2909     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2910     * the user may specify which view to go to next.
2911     */
2912    private int mNextFocusDownId = View.NO_ID;
2913
2914    /**
2915     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2916     * the user may specify which view to go to next.
2917     */
2918    int mNextFocusForwardId = View.NO_ID;
2919
2920    private CheckForLongPress mPendingCheckForLongPress;
2921    private CheckForTap mPendingCheckForTap = null;
2922    private PerformClick mPerformClick;
2923    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2924
2925    private UnsetPressedState mUnsetPressedState;
2926
2927    /**
2928     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2929     * up event while a long press is invoked as soon as the long press duration is reached, so
2930     * a long press could be performed before the tap is checked, in which case the tap's action
2931     * should not be invoked.
2932     */
2933    private boolean mHasPerformedLongPress;
2934
2935    /**
2936     * The minimum height of the view. We'll try our best to have the height
2937     * of this view to at least this amount.
2938     */
2939    @ViewDebug.ExportedProperty(category = "measurement")
2940    private int mMinHeight;
2941
2942    /**
2943     * The minimum width of the view. We'll try our best to have the width
2944     * of this view to at least this amount.
2945     */
2946    @ViewDebug.ExportedProperty(category = "measurement")
2947    private int mMinWidth;
2948
2949    /**
2950     * The delegate to handle touch events that are physically in this view
2951     * but should be handled by another view.
2952     */
2953    private TouchDelegate mTouchDelegate = null;
2954
2955    /**
2956     * Solid color to use as a background when creating the drawing cache. Enables
2957     * the cache to use 16 bit bitmaps instead of 32 bit.
2958     */
2959    private int mDrawingCacheBackgroundColor = 0;
2960
2961    /**
2962     * Special tree observer used when mAttachInfo is null.
2963     */
2964    private ViewTreeObserver mFloatingTreeObserver;
2965
2966    /**
2967     * Cache the touch slop from the context that created the view.
2968     */
2969    private int mTouchSlop;
2970
2971    /**
2972     * Object that handles automatic animation of view properties.
2973     */
2974    private ViewPropertyAnimator mAnimator = null;
2975
2976    /**
2977     * Flag indicating that a drag can cross window boundaries.  When
2978     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2979     * with this flag set, all visible applications will be able to participate
2980     * in the drag operation and receive the dragged content.
2981     *
2982     * @hide
2983     */
2984    public static final int DRAG_FLAG_GLOBAL = 1;
2985
2986    /**
2987     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2988     */
2989    private float mVerticalScrollFactor;
2990
2991    /**
2992     * Position of the vertical scroll bar.
2993     */
2994    private int mVerticalScrollbarPosition;
2995
2996    /**
2997     * Position the scroll bar at the default position as determined by the system.
2998     */
2999    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3000
3001    /**
3002     * Position the scroll bar along the left edge.
3003     */
3004    public static final int SCROLLBAR_POSITION_LEFT = 1;
3005
3006    /**
3007     * Position the scroll bar along the right edge.
3008     */
3009    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3010
3011    /**
3012     * Indicates that the view does not have a layer.
3013     *
3014     * @see #getLayerType()
3015     * @see #setLayerType(int, android.graphics.Paint)
3016     * @see #LAYER_TYPE_SOFTWARE
3017     * @see #LAYER_TYPE_HARDWARE
3018     */
3019    public static final int LAYER_TYPE_NONE = 0;
3020
3021    /**
3022     * <p>Indicates that the view has a software layer. A software layer is backed
3023     * by a bitmap and causes the view to be rendered using Android's software
3024     * rendering pipeline, even if hardware acceleration is enabled.</p>
3025     *
3026     * <p>Software layers have various usages:</p>
3027     * <p>When the application is not using hardware acceleration, a software layer
3028     * is useful to apply a specific color filter and/or blending mode and/or
3029     * translucency to a view and all its children.</p>
3030     * <p>When the application is using hardware acceleration, a software layer
3031     * is useful to render drawing primitives not supported by the hardware
3032     * accelerated pipeline. It can also be used to cache a complex view tree
3033     * into a texture and reduce the complexity of drawing operations. For instance,
3034     * when animating a complex view tree with a translation, a software layer can
3035     * be used to render the view tree only once.</p>
3036     * <p>Software layers should be avoided when the affected view tree updates
3037     * often. Every update will require to re-render the software layer, which can
3038     * potentially be slow (particularly when hardware acceleration is turned on
3039     * since the layer will have to be uploaded into a hardware texture after every
3040     * update.)</p>
3041     *
3042     * @see #getLayerType()
3043     * @see #setLayerType(int, android.graphics.Paint)
3044     * @see #LAYER_TYPE_NONE
3045     * @see #LAYER_TYPE_HARDWARE
3046     */
3047    public static final int LAYER_TYPE_SOFTWARE = 1;
3048
3049    /**
3050     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3051     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3052     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3053     * rendering pipeline, but only if hardware acceleration is turned on for the
3054     * view hierarchy. When hardware acceleration is turned off, hardware layers
3055     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3056     *
3057     * <p>A hardware layer is useful to apply a specific color filter and/or
3058     * blending mode and/or translucency to a view and all its children.</p>
3059     * <p>A hardware layer can be used to cache a complex view tree into a
3060     * texture and reduce the complexity of drawing operations. For instance,
3061     * when animating a complex view tree with a translation, a hardware layer can
3062     * be used to render the view tree only once.</p>
3063     * <p>A hardware layer can also be used to increase the rendering quality when
3064     * rotation transformations are applied on a view. It can also be used to
3065     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3066     *
3067     * @see #getLayerType()
3068     * @see #setLayerType(int, android.graphics.Paint)
3069     * @see #LAYER_TYPE_NONE
3070     * @see #LAYER_TYPE_SOFTWARE
3071     */
3072    public static final int LAYER_TYPE_HARDWARE = 2;
3073
3074    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3075            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3076            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3077            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3078    })
3079    int mLayerType = LAYER_TYPE_NONE;
3080    Paint mLayerPaint;
3081    Rect mLocalDirtyRect;
3082
3083    /**
3084     * Set to true when the view is sending hover accessibility events because it
3085     * is the innermost hovered view.
3086     */
3087    private boolean mSendingHoverAccessibilityEvents;
3088
3089    /**
3090     * Simple constructor to use when creating a view from code.
3091     *
3092     * @param context The Context the view is running in, through which it can
3093     *        access the current theme, resources, etc.
3094     */
3095    public View(Context context) {
3096        mContext = context;
3097        mResources = context != null ? context.getResources() : null;
3098        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3099        // Set layout and text direction defaults
3100        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3101                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3102                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3103                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3104        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3105        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3106        mUserPaddingStart = -1;
3107        mUserPaddingEnd = -1;
3108        mUserPaddingRelative = false;
3109    }
3110
3111    /**
3112     * Delegate for injecting accessiblity functionality.
3113     */
3114    AccessibilityDelegate mAccessibilityDelegate;
3115
3116    /**
3117     * Consistency verifier for debugging purposes.
3118     * @hide
3119     */
3120    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3121            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3122                    new InputEventConsistencyVerifier(this, 0) : null;
3123
3124    /**
3125     * Constructor that is called when inflating a view from XML. This is called
3126     * when a view is being constructed from an XML file, supplying attributes
3127     * that were specified in the XML file. This version uses a default style of
3128     * 0, so the only attribute values applied are those in the Context's Theme
3129     * and the given AttributeSet.
3130     *
3131     * <p>
3132     * The method onFinishInflate() will be called after all children have been
3133     * added.
3134     *
3135     * @param context The Context the view is running in, through which it can
3136     *        access the current theme, resources, etc.
3137     * @param attrs The attributes of the XML tag that is inflating the view.
3138     * @see #View(Context, AttributeSet, int)
3139     */
3140    public View(Context context, AttributeSet attrs) {
3141        this(context, attrs, 0);
3142    }
3143
3144    /**
3145     * Perform inflation from XML and apply a class-specific base style. This
3146     * constructor of View allows subclasses to use their own base style when
3147     * they are inflating. For example, a Button class's constructor would call
3148     * this version of the super class constructor and supply
3149     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3150     * the theme's button style to modify all of the base view attributes (in
3151     * particular its background) as well as the Button class's attributes.
3152     *
3153     * @param context The Context the view is running in, through which it can
3154     *        access the current theme, resources, etc.
3155     * @param attrs The attributes of the XML tag that is inflating the view.
3156     * @param defStyle The default style to apply to this view. If 0, no style
3157     *        will be applied (beyond what is included in the theme). This may
3158     *        either be an attribute resource, whose value will be retrieved
3159     *        from the current theme, or an explicit style resource.
3160     * @see #View(Context, AttributeSet)
3161     */
3162    public View(Context context, AttributeSet attrs, int defStyle) {
3163        this(context);
3164
3165        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3166                defStyle, 0);
3167
3168        Drawable background = null;
3169
3170        int leftPadding = -1;
3171        int topPadding = -1;
3172        int rightPadding = -1;
3173        int bottomPadding = -1;
3174        int startPadding = -1;
3175        int endPadding = -1;
3176
3177        int padding = -1;
3178
3179        int viewFlagValues = 0;
3180        int viewFlagMasks = 0;
3181
3182        boolean setScrollContainer = false;
3183
3184        int x = 0;
3185        int y = 0;
3186
3187        float tx = 0;
3188        float ty = 0;
3189        float rotation = 0;
3190        float rotationX = 0;
3191        float rotationY = 0;
3192        float sx = 1f;
3193        float sy = 1f;
3194        boolean transformSet = false;
3195
3196        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3197
3198        int overScrollMode = mOverScrollMode;
3199        final int N = a.getIndexCount();
3200        for (int i = 0; i < N; i++) {
3201            int attr = a.getIndex(i);
3202            switch (attr) {
3203                case com.android.internal.R.styleable.View_background:
3204                    background = a.getDrawable(attr);
3205                    break;
3206                case com.android.internal.R.styleable.View_padding:
3207                    padding = a.getDimensionPixelSize(attr, -1);
3208                    break;
3209                 case com.android.internal.R.styleable.View_paddingLeft:
3210                    leftPadding = a.getDimensionPixelSize(attr, -1);
3211                    break;
3212                case com.android.internal.R.styleable.View_paddingTop:
3213                    topPadding = a.getDimensionPixelSize(attr, -1);
3214                    break;
3215                case com.android.internal.R.styleable.View_paddingRight:
3216                    rightPadding = a.getDimensionPixelSize(attr, -1);
3217                    break;
3218                case com.android.internal.R.styleable.View_paddingBottom:
3219                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3220                    break;
3221                case com.android.internal.R.styleable.View_paddingStart:
3222                    startPadding = a.getDimensionPixelSize(attr, -1);
3223                    break;
3224                case com.android.internal.R.styleable.View_paddingEnd:
3225                    endPadding = a.getDimensionPixelSize(attr, -1);
3226                    break;
3227                case com.android.internal.R.styleable.View_scrollX:
3228                    x = a.getDimensionPixelOffset(attr, 0);
3229                    break;
3230                case com.android.internal.R.styleable.View_scrollY:
3231                    y = a.getDimensionPixelOffset(attr, 0);
3232                    break;
3233                case com.android.internal.R.styleable.View_alpha:
3234                    setAlpha(a.getFloat(attr, 1f));
3235                    break;
3236                case com.android.internal.R.styleable.View_transformPivotX:
3237                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3238                    break;
3239                case com.android.internal.R.styleable.View_transformPivotY:
3240                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3241                    break;
3242                case com.android.internal.R.styleable.View_translationX:
3243                    tx = a.getDimensionPixelOffset(attr, 0);
3244                    transformSet = true;
3245                    break;
3246                case com.android.internal.R.styleable.View_translationY:
3247                    ty = a.getDimensionPixelOffset(attr, 0);
3248                    transformSet = true;
3249                    break;
3250                case com.android.internal.R.styleable.View_rotation:
3251                    rotation = a.getFloat(attr, 0);
3252                    transformSet = true;
3253                    break;
3254                case com.android.internal.R.styleable.View_rotationX:
3255                    rotationX = a.getFloat(attr, 0);
3256                    transformSet = true;
3257                    break;
3258                case com.android.internal.R.styleable.View_rotationY:
3259                    rotationY = a.getFloat(attr, 0);
3260                    transformSet = true;
3261                    break;
3262                case com.android.internal.R.styleable.View_scaleX:
3263                    sx = a.getFloat(attr, 1f);
3264                    transformSet = true;
3265                    break;
3266                case com.android.internal.R.styleable.View_scaleY:
3267                    sy = a.getFloat(attr, 1f);
3268                    transformSet = true;
3269                    break;
3270                case com.android.internal.R.styleable.View_id:
3271                    mID = a.getResourceId(attr, NO_ID);
3272                    break;
3273                case com.android.internal.R.styleable.View_tag:
3274                    mTag = a.getText(attr);
3275                    break;
3276                case com.android.internal.R.styleable.View_fitsSystemWindows:
3277                    if (a.getBoolean(attr, false)) {
3278                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3279                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3280                    }
3281                    break;
3282                case com.android.internal.R.styleable.View_focusable:
3283                    if (a.getBoolean(attr, false)) {
3284                        viewFlagValues |= FOCUSABLE;
3285                        viewFlagMasks |= FOCUSABLE_MASK;
3286                    }
3287                    break;
3288                case com.android.internal.R.styleable.View_focusableInTouchMode:
3289                    if (a.getBoolean(attr, false)) {
3290                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3291                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3292                    }
3293                    break;
3294                case com.android.internal.R.styleable.View_clickable:
3295                    if (a.getBoolean(attr, false)) {
3296                        viewFlagValues |= CLICKABLE;
3297                        viewFlagMasks |= CLICKABLE;
3298                    }
3299                    break;
3300                case com.android.internal.R.styleable.View_longClickable:
3301                    if (a.getBoolean(attr, false)) {
3302                        viewFlagValues |= LONG_CLICKABLE;
3303                        viewFlagMasks |= LONG_CLICKABLE;
3304                    }
3305                    break;
3306                case com.android.internal.R.styleable.View_saveEnabled:
3307                    if (!a.getBoolean(attr, true)) {
3308                        viewFlagValues |= SAVE_DISABLED;
3309                        viewFlagMasks |= SAVE_DISABLED_MASK;
3310                    }
3311                    break;
3312                case com.android.internal.R.styleable.View_duplicateParentState:
3313                    if (a.getBoolean(attr, false)) {
3314                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3315                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3316                    }
3317                    break;
3318                case com.android.internal.R.styleable.View_visibility:
3319                    final int visibility = a.getInt(attr, 0);
3320                    if (visibility != 0) {
3321                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3322                        viewFlagMasks |= VISIBILITY_MASK;
3323                    }
3324                    break;
3325                case com.android.internal.R.styleable.View_layoutDirection:
3326                    // Clear any layout direction flags (included resolved bits) already set
3327                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3328                    // Set the layout direction flags depending on the value of the attribute
3329                    final int layoutDirection = a.getInt(attr, -1);
3330                    final int value = (layoutDirection != -1) ?
3331                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3332                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3333                    break;
3334                case com.android.internal.R.styleable.View_drawingCacheQuality:
3335                    final int cacheQuality = a.getInt(attr, 0);
3336                    if (cacheQuality != 0) {
3337                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3338                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3339                    }
3340                    break;
3341                case com.android.internal.R.styleable.View_contentDescription:
3342                    mContentDescription = a.getString(attr);
3343                    break;
3344                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3345                    if (!a.getBoolean(attr, true)) {
3346                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3347                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3348                    }
3349                    break;
3350                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3351                    if (!a.getBoolean(attr, true)) {
3352                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3353                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3354                    }
3355                    break;
3356                case R.styleable.View_scrollbars:
3357                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3358                    if (scrollbars != SCROLLBARS_NONE) {
3359                        viewFlagValues |= scrollbars;
3360                        viewFlagMasks |= SCROLLBARS_MASK;
3361                        initializeScrollbars(a);
3362                    }
3363                    break;
3364                //noinspection deprecation
3365                case R.styleable.View_fadingEdge:
3366                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3367                        // Ignore the attribute starting with ICS
3368                        break;
3369                    }
3370                    // With builds < ICS, fall through and apply fading edges
3371                case R.styleable.View_requiresFadingEdge:
3372                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3373                    if (fadingEdge != FADING_EDGE_NONE) {
3374                        viewFlagValues |= fadingEdge;
3375                        viewFlagMasks |= FADING_EDGE_MASK;
3376                        initializeFadingEdge(a);
3377                    }
3378                    break;
3379                case R.styleable.View_scrollbarStyle:
3380                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3381                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3382                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3383                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3384                    }
3385                    break;
3386                case R.styleable.View_isScrollContainer:
3387                    setScrollContainer = true;
3388                    if (a.getBoolean(attr, false)) {
3389                        setScrollContainer(true);
3390                    }
3391                    break;
3392                case com.android.internal.R.styleable.View_keepScreenOn:
3393                    if (a.getBoolean(attr, false)) {
3394                        viewFlagValues |= KEEP_SCREEN_ON;
3395                        viewFlagMasks |= KEEP_SCREEN_ON;
3396                    }
3397                    break;
3398                case R.styleable.View_filterTouchesWhenObscured:
3399                    if (a.getBoolean(attr, false)) {
3400                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3401                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3402                    }
3403                    break;
3404                case R.styleable.View_nextFocusLeft:
3405                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3406                    break;
3407                case R.styleable.View_nextFocusRight:
3408                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3409                    break;
3410                case R.styleable.View_nextFocusUp:
3411                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3412                    break;
3413                case R.styleable.View_nextFocusDown:
3414                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3415                    break;
3416                case R.styleable.View_nextFocusForward:
3417                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3418                    break;
3419                case R.styleable.View_minWidth:
3420                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3421                    break;
3422                case R.styleable.View_minHeight:
3423                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3424                    break;
3425                case R.styleable.View_onClick:
3426                    if (context.isRestricted()) {
3427                        throw new IllegalStateException("The android:onClick attribute cannot "
3428                                + "be used within a restricted context");
3429                    }
3430
3431                    final String handlerName = a.getString(attr);
3432                    if (handlerName != null) {
3433                        setOnClickListener(new OnClickListener() {
3434                            private Method mHandler;
3435
3436                            public void onClick(View v) {
3437                                if (mHandler == null) {
3438                                    try {
3439                                        mHandler = getContext().getClass().getMethod(handlerName,
3440                                                View.class);
3441                                    } catch (NoSuchMethodException e) {
3442                                        int id = getId();
3443                                        String idText = id == NO_ID ? "" : " with id '"
3444                                                + getContext().getResources().getResourceEntryName(
3445                                                    id) + "'";
3446                                        throw new IllegalStateException("Could not find a method " +
3447                                                handlerName + "(View) in the activity "
3448                                                + getContext().getClass() + " for onClick handler"
3449                                                + " on view " + View.this.getClass() + idText, e);
3450                                    }
3451                                }
3452
3453                                try {
3454                                    mHandler.invoke(getContext(), View.this);
3455                                } catch (IllegalAccessException e) {
3456                                    throw new IllegalStateException("Could not execute non "
3457                                            + "public method of the activity", e);
3458                                } catch (InvocationTargetException e) {
3459                                    throw new IllegalStateException("Could not execute "
3460                                            + "method of the activity", e);
3461                                }
3462                            }
3463                        });
3464                    }
3465                    break;
3466                case R.styleable.View_overScrollMode:
3467                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3468                    break;
3469                case R.styleable.View_verticalScrollbarPosition:
3470                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3471                    break;
3472                case R.styleable.View_layerType:
3473                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3474                    break;
3475                case R.styleable.View_textDirection:
3476                    // Clear any text direction flag already set
3477                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3478                    // Set the text direction flags depending on the value of the attribute
3479                    final int textDirection = a.getInt(attr, -1);
3480                    if (textDirection != -1) {
3481                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3482                    }
3483                    break;
3484                case R.styleable.View_textAlignment:
3485                    // Clear any text alignment flag already set
3486                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3487                    // Set the text alignment flag depending on the value of the attribute
3488                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3489                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3490                    break;
3491                case R.styleable.View_importantForAccessibility:
3492                    setImportantForAccessibility(a.getInt(attr,
3493                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3494            }
3495        }
3496
3497        a.recycle();
3498
3499        setOverScrollMode(overScrollMode);
3500
3501        if (background != null) {
3502            setBackground(background);
3503        }
3504
3505        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3506        // layout direction). Those cached values will be used later during padding resolution.
3507        mUserPaddingStart = startPadding;
3508        mUserPaddingEnd = endPadding;
3509
3510        updateUserPaddingRelative();
3511
3512        if (padding >= 0) {
3513            leftPadding = padding;
3514            topPadding = padding;
3515            rightPadding = padding;
3516            bottomPadding = padding;
3517        }
3518
3519        // If the user specified the padding (either with android:padding or
3520        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3521        // use the default padding or the padding from the background drawable
3522        // (stored at this point in mPadding*)
3523        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3524                topPadding >= 0 ? topPadding : mPaddingTop,
3525                rightPadding >= 0 ? rightPadding : mPaddingRight,
3526                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3527
3528        if (viewFlagMasks != 0) {
3529            setFlags(viewFlagValues, viewFlagMasks);
3530        }
3531
3532        // Needs to be called after mViewFlags is set
3533        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3534            recomputePadding();
3535        }
3536
3537        if (x != 0 || y != 0) {
3538            scrollTo(x, y);
3539        }
3540
3541        if (transformSet) {
3542            setTranslationX(tx);
3543            setTranslationY(ty);
3544            setRotation(rotation);
3545            setRotationX(rotationX);
3546            setRotationY(rotationY);
3547            setScaleX(sx);
3548            setScaleY(sy);
3549        }
3550
3551        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3552            setScrollContainer(true);
3553        }
3554
3555        computeOpaqueFlags();
3556    }
3557
3558    private void updateUserPaddingRelative() {
3559        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3560    }
3561
3562    /**
3563     * Non-public constructor for use in testing
3564     */
3565    View() {
3566        mResources = null;
3567    }
3568
3569    /**
3570     * <p>
3571     * Initializes the fading edges from a given set of styled attributes. This
3572     * method should be called by subclasses that need fading edges and when an
3573     * instance of these subclasses is created programmatically rather than
3574     * being inflated from XML. This method is automatically called when the XML
3575     * is inflated.
3576     * </p>
3577     *
3578     * @param a the styled attributes set to initialize the fading edges from
3579     */
3580    protected void initializeFadingEdge(TypedArray a) {
3581        initScrollCache();
3582
3583        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3584                R.styleable.View_fadingEdgeLength,
3585                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3586    }
3587
3588    /**
3589     * Returns the size of the vertical faded edges used to indicate that more
3590     * content in this view is visible.
3591     *
3592     * @return The size in pixels of the vertical faded edge or 0 if vertical
3593     *         faded edges are not enabled for this view.
3594     * @attr ref android.R.styleable#View_fadingEdgeLength
3595     */
3596    public int getVerticalFadingEdgeLength() {
3597        if (isVerticalFadingEdgeEnabled()) {
3598            ScrollabilityCache cache = mScrollCache;
3599            if (cache != null) {
3600                return cache.fadingEdgeLength;
3601            }
3602        }
3603        return 0;
3604    }
3605
3606    /**
3607     * Set the size of the faded edge used to indicate that more content in this
3608     * view is available.  Will not change whether the fading edge is enabled; use
3609     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3610     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3611     * for the vertical or horizontal fading edges.
3612     *
3613     * @param length The size in pixels of the faded edge used to indicate that more
3614     *        content in this view is visible.
3615     */
3616    public void setFadingEdgeLength(int length) {
3617        initScrollCache();
3618        mScrollCache.fadingEdgeLength = length;
3619    }
3620
3621    /**
3622     * Returns the size of the horizontal faded edges used to indicate that more
3623     * content in this view is visible.
3624     *
3625     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3626     *         faded edges are not enabled for this view.
3627     * @attr ref android.R.styleable#View_fadingEdgeLength
3628     */
3629    public int getHorizontalFadingEdgeLength() {
3630        if (isHorizontalFadingEdgeEnabled()) {
3631            ScrollabilityCache cache = mScrollCache;
3632            if (cache != null) {
3633                return cache.fadingEdgeLength;
3634            }
3635        }
3636        return 0;
3637    }
3638
3639    /**
3640     * Returns the width of the vertical scrollbar.
3641     *
3642     * @return The width in pixels of the vertical scrollbar or 0 if there
3643     *         is no vertical scrollbar.
3644     */
3645    public int getVerticalScrollbarWidth() {
3646        ScrollabilityCache cache = mScrollCache;
3647        if (cache != null) {
3648            ScrollBarDrawable scrollBar = cache.scrollBar;
3649            if (scrollBar != null) {
3650                int size = scrollBar.getSize(true);
3651                if (size <= 0) {
3652                    size = cache.scrollBarSize;
3653                }
3654                return size;
3655            }
3656            return 0;
3657        }
3658        return 0;
3659    }
3660
3661    /**
3662     * Returns the height of the horizontal scrollbar.
3663     *
3664     * @return The height in pixels of the horizontal scrollbar or 0 if
3665     *         there is no horizontal scrollbar.
3666     */
3667    protected int getHorizontalScrollbarHeight() {
3668        ScrollabilityCache cache = mScrollCache;
3669        if (cache != null) {
3670            ScrollBarDrawable scrollBar = cache.scrollBar;
3671            if (scrollBar != null) {
3672                int size = scrollBar.getSize(false);
3673                if (size <= 0) {
3674                    size = cache.scrollBarSize;
3675                }
3676                return size;
3677            }
3678            return 0;
3679        }
3680        return 0;
3681    }
3682
3683    /**
3684     * <p>
3685     * Initializes the scrollbars from a given set of styled attributes. This
3686     * method should be called by subclasses that need scrollbars and when an
3687     * instance of these subclasses is created programmatically rather than
3688     * being inflated from XML. This method is automatically called when the XML
3689     * is inflated.
3690     * </p>
3691     *
3692     * @param a the styled attributes set to initialize the scrollbars from
3693     */
3694    protected void initializeScrollbars(TypedArray a) {
3695        initScrollCache();
3696
3697        final ScrollabilityCache scrollabilityCache = mScrollCache;
3698
3699        if (scrollabilityCache.scrollBar == null) {
3700            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3701        }
3702
3703        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3704
3705        if (!fadeScrollbars) {
3706            scrollabilityCache.state = ScrollabilityCache.ON;
3707        }
3708        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3709
3710
3711        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3712                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3713                        .getScrollBarFadeDuration());
3714        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3715                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3716                ViewConfiguration.getScrollDefaultDelay());
3717
3718
3719        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3720                com.android.internal.R.styleable.View_scrollbarSize,
3721                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3722
3723        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3724        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3725
3726        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3727        if (thumb != null) {
3728            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3729        }
3730
3731        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3732                false);
3733        if (alwaysDraw) {
3734            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3735        }
3736
3737        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3738        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3739
3740        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3741        if (thumb != null) {
3742            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3743        }
3744
3745        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3746                false);
3747        if (alwaysDraw) {
3748            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3749        }
3750
3751        // Re-apply user/background padding so that scrollbar(s) get added
3752        resolvePadding();
3753    }
3754
3755    /**
3756     * <p>
3757     * Initalizes the scrollability cache if necessary.
3758     * </p>
3759     */
3760    private void initScrollCache() {
3761        if (mScrollCache == null) {
3762            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3763        }
3764    }
3765
3766    private ScrollabilityCache getScrollCache() {
3767        initScrollCache();
3768        return mScrollCache;
3769    }
3770
3771    /**
3772     * Set the position of the vertical scroll bar. Should be one of
3773     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3774     * {@link #SCROLLBAR_POSITION_RIGHT}.
3775     *
3776     * @param position Where the vertical scroll bar should be positioned.
3777     */
3778    public void setVerticalScrollbarPosition(int position) {
3779        if (mVerticalScrollbarPosition != position) {
3780            mVerticalScrollbarPosition = position;
3781            computeOpaqueFlags();
3782            resolvePadding();
3783        }
3784    }
3785
3786    /**
3787     * @return The position where the vertical scroll bar will show, if applicable.
3788     * @see #setVerticalScrollbarPosition(int)
3789     */
3790    public int getVerticalScrollbarPosition() {
3791        return mVerticalScrollbarPosition;
3792    }
3793
3794    ListenerInfo getListenerInfo() {
3795        if (mListenerInfo != null) {
3796            return mListenerInfo;
3797        }
3798        mListenerInfo = new ListenerInfo();
3799        return mListenerInfo;
3800    }
3801
3802    /**
3803     * Register a callback to be invoked when focus of this view changed.
3804     *
3805     * @param l The callback that will run.
3806     */
3807    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3808        getListenerInfo().mOnFocusChangeListener = l;
3809    }
3810
3811    /**
3812     * Add a listener that will be called when the bounds of the view change due to
3813     * layout processing.
3814     *
3815     * @param listener The listener that will be called when layout bounds change.
3816     */
3817    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3818        ListenerInfo li = getListenerInfo();
3819        if (li.mOnLayoutChangeListeners == null) {
3820            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3821        }
3822        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3823            li.mOnLayoutChangeListeners.add(listener);
3824        }
3825    }
3826
3827    /**
3828     * Remove a listener for layout changes.
3829     *
3830     * @param listener The listener for layout bounds change.
3831     */
3832    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3833        ListenerInfo li = mListenerInfo;
3834        if (li == null || li.mOnLayoutChangeListeners == null) {
3835            return;
3836        }
3837        li.mOnLayoutChangeListeners.remove(listener);
3838    }
3839
3840    /**
3841     * Add a listener for attach state changes.
3842     *
3843     * This listener will be called whenever this view is attached or detached
3844     * from a window. Remove the listener using
3845     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3846     *
3847     * @param listener Listener to attach
3848     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3849     */
3850    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3851        ListenerInfo li = getListenerInfo();
3852        if (li.mOnAttachStateChangeListeners == null) {
3853            li.mOnAttachStateChangeListeners
3854                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3855        }
3856        li.mOnAttachStateChangeListeners.add(listener);
3857    }
3858
3859    /**
3860     * Remove a listener for attach state changes. The listener will receive no further
3861     * notification of window attach/detach events.
3862     *
3863     * @param listener Listener to remove
3864     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3865     */
3866    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3867        ListenerInfo li = mListenerInfo;
3868        if (li == null || li.mOnAttachStateChangeListeners == null) {
3869            return;
3870        }
3871        li.mOnAttachStateChangeListeners.remove(listener);
3872    }
3873
3874    /**
3875     * Returns the focus-change callback registered for this view.
3876     *
3877     * @return The callback, or null if one is not registered.
3878     */
3879    public OnFocusChangeListener getOnFocusChangeListener() {
3880        ListenerInfo li = mListenerInfo;
3881        return li != null ? li.mOnFocusChangeListener : null;
3882    }
3883
3884    /**
3885     * Register a callback to be invoked when this view is clicked. If this view is not
3886     * clickable, it becomes clickable.
3887     *
3888     * @param l The callback that will run
3889     *
3890     * @see #setClickable(boolean)
3891     */
3892    public void setOnClickListener(OnClickListener l) {
3893        if (!isClickable()) {
3894            setClickable(true);
3895        }
3896        getListenerInfo().mOnClickListener = l;
3897    }
3898
3899    /**
3900     * Return whether this view has an attached OnClickListener.  Returns
3901     * true if there is a listener, false if there is none.
3902     */
3903    public boolean hasOnClickListeners() {
3904        ListenerInfo li = mListenerInfo;
3905        return (li != null && li.mOnClickListener != null);
3906    }
3907
3908    /**
3909     * Register a callback to be invoked when this view is clicked and held. If this view is not
3910     * long clickable, it becomes long clickable.
3911     *
3912     * @param l The callback that will run
3913     *
3914     * @see #setLongClickable(boolean)
3915     */
3916    public void setOnLongClickListener(OnLongClickListener l) {
3917        if (!isLongClickable()) {
3918            setLongClickable(true);
3919        }
3920        getListenerInfo().mOnLongClickListener = l;
3921    }
3922
3923    /**
3924     * Register a callback to be invoked when the context menu for this view is
3925     * being built. If this view is not long clickable, it becomes long clickable.
3926     *
3927     * @param l The callback that will run
3928     *
3929     */
3930    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3931        if (!isLongClickable()) {
3932            setLongClickable(true);
3933        }
3934        getListenerInfo().mOnCreateContextMenuListener = l;
3935    }
3936
3937    /**
3938     * Call this view's OnClickListener, if it is defined.  Performs all normal
3939     * actions associated with clicking: reporting accessibility event, playing
3940     * a sound, etc.
3941     *
3942     * @return True there was an assigned OnClickListener that was called, false
3943     *         otherwise is returned.
3944     */
3945    public boolean performClick() {
3946        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3947
3948        ListenerInfo li = mListenerInfo;
3949        if (li != null && li.mOnClickListener != null) {
3950            playSoundEffect(SoundEffectConstants.CLICK);
3951            li.mOnClickListener.onClick(this);
3952            return true;
3953        }
3954
3955        return false;
3956    }
3957
3958    /**
3959     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3960     * this only calls the listener, and does not do any associated clicking
3961     * actions like reporting an accessibility event.
3962     *
3963     * @return True there was an assigned OnClickListener that was called, false
3964     *         otherwise is returned.
3965     */
3966    public boolean callOnClick() {
3967        ListenerInfo li = mListenerInfo;
3968        if (li != null && li.mOnClickListener != null) {
3969            li.mOnClickListener.onClick(this);
3970            return true;
3971        }
3972        return false;
3973    }
3974
3975    /**
3976     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3977     * OnLongClickListener did not consume the event.
3978     *
3979     * @return True if one of the above receivers consumed the event, false otherwise.
3980     */
3981    public boolean performLongClick() {
3982        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3983
3984        boolean handled = false;
3985        ListenerInfo li = mListenerInfo;
3986        if (li != null && li.mOnLongClickListener != null) {
3987            handled = li.mOnLongClickListener.onLongClick(View.this);
3988        }
3989        if (!handled) {
3990            handled = showContextMenu();
3991        }
3992        if (handled) {
3993            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3994        }
3995        return handled;
3996    }
3997
3998    /**
3999     * Performs button-related actions during a touch down event.
4000     *
4001     * @param event The event.
4002     * @return True if the down was consumed.
4003     *
4004     * @hide
4005     */
4006    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4007        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4008            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4009                return true;
4010            }
4011        }
4012        return false;
4013    }
4014
4015    /**
4016     * Bring up the context menu for this view.
4017     *
4018     * @return Whether a context menu was displayed.
4019     */
4020    public boolean showContextMenu() {
4021        return getParent().showContextMenuForChild(this);
4022    }
4023
4024    /**
4025     * Bring up the context menu for this view, referring to the item under the specified point.
4026     *
4027     * @param x The referenced x coordinate.
4028     * @param y The referenced y coordinate.
4029     * @param metaState The keyboard modifiers that were pressed.
4030     * @return Whether a context menu was displayed.
4031     *
4032     * @hide
4033     */
4034    public boolean showContextMenu(float x, float y, int metaState) {
4035        return showContextMenu();
4036    }
4037
4038    /**
4039     * Start an action mode.
4040     *
4041     * @param callback Callback that will control the lifecycle of the action mode
4042     * @return The new action mode if it is started, null otherwise
4043     *
4044     * @see ActionMode
4045     */
4046    public ActionMode startActionMode(ActionMode.Callback callback) {
4047        ViewParent parent = getParent();
4048        if (parent == null) return null;
4049        return parent.startActionModeForChild(this, callback);
4050    }
4051
4052    /**
4053     * Register a callback to be invoked when a key is pressed in this view.
4054     * @param l the key listener to attach to this view
4055     */
4056    public void setOnKeyListener(OnKeyListener l) {
4057        getListenerInfo().mOnKeyListener = l;
4058    }
4059
4060    /**
4061     * Register a callback to be invoked when a touch event is sent to this view.
4062     * @param l the touch listener to attach to this view
4063     */
4064    public void setOnTouchListener(OnTouchListener l) {
4065        getListenerInfo().mOnTouchListener = l;
4066    }
4067
4068    /**
4069     * Register a callback to be invoked when a generic motion event is sent to this view.
4070     * @param l the generic motion listener to attach to this view
4071     */
4072    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4073        getListenerInfo().mOnGenericMotionListener = l;
4074    }
4075
4076    /**
4077     * Register a callback to be invoked when a hover event is sent to this view.
4078     * @param l the hover listener to attach to this view
4079     */
4080    public void setOnHoverListener(OnHoverListener l) {
4081        getListenerInfo().mOnHoverListener = l;
4082    }
4083
4084    /**
4085     * Register a drag event listener callback object for this View. The parameter is
4086     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4087     * View, the system calls the
4088     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4089     * @param l An implementation of {@link android.view.View.OnDragListener}.
4090     */
4091    public void setOnDragListener(OnDragListener l) {
4092        getListenerInfo().mOnDragListener = l;
4093    }
4094
4095    /**
4096     * Give this view focus. This will cause
4097     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4098     *
4099     * Note: this does not check whether this {@link View} should get focus, it just
4100     * gives it focus no matter what.  It should only be called internally by framework
4101     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4102     *
4103     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4104     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4105     *        focus moved when requestFocus() is called. It may not always
4106     *        apply, in which case use the default View.FOCUS_DOWN.
4107     * @param previouslyFocusedRect The rectangle of the view that had focus
4108     *        prior in this View's coordinate system.
4109     */
4110    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4111        if (DBG) {
4112            System.out.println(this + " requestFocus()");
4113        }
4114
4115        if ((mPrivateFlags & FOCUSED) == 0) {
4116            mPrivateFlags |= FOCUSED;
4117
4118            if (mParent != null) {
4119                mParent.requestChildFocus(this, this);
4120            }
4121
4122            onFocusChanged(true, direction, previouslyFocusedRect);
4123            refreshDrawableState();
4124
4125            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4126                notifyAccessibilityStateChanged();
4127            }
4128        }
4129    }
4130
4131    /**
4132     * Request that a rectangle of this view be visible on the screen,
4133     * scrolling if necessary just enough.
4134     *
4135     * <p>A View should call this if it maintains some notion of which part
4136     * of its content is interesting.  For example, a text editing view
4137     * should call this when its cursor moves.
4138     *
4139     * @param rectangle The rectangle.
4140     * @return Whether any parent scrolled.
4141     */
4142    public boolean requestRectangleOnScreen(Rect rectangle) {
4143        return requestRectangleOnScreen(rectangle, false);
4144    }
4145
4146    /**
4147     * Request that a rectangle of this view be visible on the screen,
4148     * scrolling if necessary just enough.
4149     *
4150     * <p>A View should call this if it maintains some notion of which part
4151     * of its content is interesting.  For example, a text editing view
4152     * should call this when its cursor moves.
4153     *
4154     * <p>When <code>immediate</code> is set to true, scrolling will not be
4155     * animated.
4156     *
4157     * @param rectangle The rectangle.
4158     * @param immediate True to forbid animated scrolling, false otherwise
4159     * @return Whether any parent scrolled.
4160     */
4161    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4162        View child = this;
4163        ViewParent parent = mParent;
4164        boolean scrolled = false;
4165        while (parent != null) {
4166            scrolled |= parent.requestChildRectangleOnScreen(child,
4167                    rectangle, immediate);
4168
4169            // offset rect so next call has the rectangle in the
4170            // coordinate system of its direct child.
4171            rectangle.offset(child.getLeft(), child.getTop());
4172            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4173
4174            if (!(parent instanceof View)) {
4175                break;
4176            }
4177
4178            child = (View) parent;
4179            parent = child.getParent();
4180        }
4181        return scrolled;
4182    }
4183
4184    /**
4185     * Called when this view wants to give up focus. If focus is cleared
4186     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4187     * <p>
4188     * <strong>Note:</strong> When a View clears focus the framework is trying
4189     * to give focus to the first focusable View from the top. Hence, if this
4190     * View is the first from the top that can take focus, then all callbacks
4191     * related to clearing focus will be invoked after wich the framework will
4192     * give focus to this view.
4193     * </p>
4194     */
4195    public void clearFocus() {
4196        if (DBG) {
4197            System.out.println(this + " clearFocus()");
4198        }
4199
4200        if ((mPrivateFlags & FOCUSED) != 0) {
4201            mPrivateFlags &= ~FOCUSED;
4202
4203            if (mParent != null) {
4204                mParent.clearChildFocus(this);
4205            }
4206
4207            onFocusChanged(false, 0, null);
4208
4209            refreshDrawableState();
4210
4211            ensureInputFocusOnFirstFocusable();
4212
4213            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4214                notifyAccessibilityStateChanged();
4215            }
4216        }
4217    }
4218
4219    void ensureInputFocusOnFirstFocusable() {
4220        View root = getRootView();
4221        if (root != null) {
4222            root.requestFocus();
4223        }
4224    }
4225
4226    /**
4227     * Called internally by the view system when a new view is getting focus.
4228     * This is what clears the old focus.
4229     */
4230    void unFocus() {
4231        if (DBG) {
4232            System.out.println(this + " unFocus()");
4233        }
4234
4235        if ((mPrivateFlags & FOCUSED) != 0) {
4236            mPrivateFlags &= ~FOCUSED;
4237
4238            onFocusChanged(false, 0, null);
4239            refreshDrawableState();
4240
4241            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4242                notifyAccessibilityStateChanged();
4243            }
4244        }
4245    }
4246
4247    /**
4248     * Returns true if this view has focus iteself, or is the ancestor of the
4249     * view that has focus.
4250     *
4251     * @return True if this view has or contains focus, false otherwise.
4252     */
4253    @ViewDebug.ExportedProperty(category = "focus")
4254    public boolean hasFocus() {
4255        return (mPrivateFlags & FOCUSED) != 0;
4256    }
4257
4258    /**
4259     * Returns true if this view is focusable or if it contains a reachable View
4260     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4261     * is a View whose parents do not block descendants focus.
4262     *
4263     * Only {@link #VISIBLE} views are considered focusable.
4264     *
4265     * @return True if the view is focusable or if the view contains a focusable
4266     *         View, false otherwise.
4267     *
4268     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4269     */
4270    public boolean hasFocusable() {
4271        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4272    }
4273
4274    /**
4275     * Called by the view system when the focus state of this view changes.
4276     * When the focus change event is caused by directional navigation, direction
4277     * and previouslyFocusedRect provide insight into where the focus is coming from.
4278     * When overriding, be sure to call up through to the super class so that
4279     * the standard focus handling will occur.
4280     *
4281     * @param gainFocus True if the View has focus; false otherwise.
4282     * @param direction The direction focus has moved when requestFocus()
4283     *                  is called to give this view focus. Values are
4284     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4285     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4286     *                  It may not always apply, in which case use the default.
4287     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4288     *        system, of the previously focused view.  If applicable, this will be
4289     *        passed in as finer grained information about where the focus is coming
4290     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4291     */
4292    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4293        if (gainFocus) {
4294            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4295                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4296                requestAccessibilityFocus();
4297            }
4298        }
4299
4300        InputMethodManager imm = InputMethodManager.peekInstance();
4301        if (!gainFocus) {
4302            if (isPressed()) {
4303                setPressed(false);
4304            }
4305            if (imm != null && mAttachInfo != null
4306                    && mAttachInfo.mHasWindowFocus) {
4307                imm.focusOut(this);
4308            }
4309            onFocusLost();
4310        } else if (imm != null && mAttachInfo != null
4311                && mAttachInfo.mHasWindowFocus) {
4312            imm.focusIn(this);
4313        }
4314
4315        invalidate(true);
4316        ListenerInfo li = mListenerInfo;
4317        if (li != null && li.mOnFocusChangeListener != null) {
4318            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4319        }
4320
4321        if (mAttachInfo != null) {
4322            mAttachInfo.mKeyDispatchState.reset(this);
4323        }
4324    }
4325
4326    /**
4327     * Sends an accessibility event of the given type. If accessiiblity is
4328     * not enabled this method has no effect. The default implementation calls
4329     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4330     * to populate information about the event source (this View), then calls
4331     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4332     * populate the text content of the event source including its descendants,
4333     * and last calls
4334     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4335     * on its parent to resuest sending of the event to interested parties.
4336     * <p>
4337     * If an {@link AccessibilityDelegate} has been specified via calling
4338     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4339     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4340     * responsible for handling this call.
4341     * </p>
4342     *
4343     * @param eventType The type of the event to send, as defined by several types from
4344     * {@link android.view.accessibility.AccessibilityEvent}, such as
4345     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4346     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4347     *
4348     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4349     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4350     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4351     * @see AccessibilityDelegate
4352     */
4353    public void sendAccessibilityEvent(int eventType) {
4354        if (mAccessibilityDelegate != null) {
4355            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4356        } else {
4357            sendAccessibilityEventInternal(eventType);
4358        }
4359    }
4360
4361    /**
4362     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4363     * {@link AccessibilityEvent} to make an announcement which is related to some
4364     * sort of a context change for which none of the events representing UI transitions
4365     * is a good fit. For example, announcing a new page in a book. If accessibility
4366     * is not enabled this method does nothing.
4367     *
4368     * @param text The announcement text.
4369     */
4370    public void announceForAccessibility(CharSequence text) {
4371        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4372            AccessibilityEvent event = AccessibilityEvent.obtain(
4373                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4374            event.getText().add(text);
4375            sendAccessibilityEventUnchecked(event);
4376        }
4377    }
4378
4379    /**
4380     * @see #sendAccessibilityEvent(int)
4381     *
4382     * Note: Called from the default {@link AccessibilityDelegate}.
4383     */
4384    void sendAccessibilityEventInternal(int eventType) {
4385        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4386            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4387        }
4388    }
4389
4390    /**
4391     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4392     * takes as an argument an empty {@link AccessibilityEvent} and does not
4393     * perform a check whether accessibility is enabled.
4394     * <p>
4395     * If an {@link AccessibilityDelegate} has been specified via calling
4396     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4397     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4398     * is responsible for handling this call.
4399     * </p>
4400     *
4401     * @param event The event to send.
4402     *
4403     * @see #sendAccessibilityEvent(int)
4404     */
4405    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4406        if (mAccessibilityDelegate != null) {
4407            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4408        } else {
4409            sendAccessibilityEventUncheckedInternal(event);
4410        }
4411    }
4412
4413    /**
4414     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4415     *
4416     * Note: Called from the default {@link AccessibilityDelegate}.
4417     */
4418    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4419        if (!isShown()) {
4420            return;
4421        }
4422        onInitializeAccessibilityEvent(event);
4423        // Only a subset of accessibility events populates text content.
4424        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4425            dispatchPopulateAccessibilityEvent(event);
4426        }
4427        // Intercept accessibility focus events fired by virtual nodes to keep
4428        // track of accessibility focus position in such nodes.
4429        final int eventType = event.getEventType();
4430        switch (eventType) {
4431            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4432                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4433                        event.getSourceNodeId());
4434                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4435                    ViewRootImpl viewRootImpl = getViewRootImpl();
4436                    if (viewRootImpl != null) {
4437                        viewRootImpl.setAccessibilityFocusedHost(this);
4438                    }
4439                }
4440            } break;
4441            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4442                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4443                        event.getSourceNodeId());
4444                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4445                    ViewRootImpl viewRootImpl = getViewRootImpl();
4446                    if (viewRootImpl != null) {
4447                        viewRootImpl.setAccessibilityFocusedHost(null);
4448                    }
4449                }
4450            } break;
4451        }
4452        // In the beginning we called #isShown(), so we know that getParent() is not null.
4453        getParent().requestSendAccessibilityEvent(this, event);
4454    }
4455
4456    /**
4457     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4458     * to its children for adding their text content to the event. Note that the
4459     * event text is populated in a separate dispatch path since we add to the
4460     * event not only the text of the source but also the text of all its descendants.
4461     * A typical implementation will call
4462     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4463     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4464     * on each child. Override this method if custom population of the event text
4465     * content is required.
4466     * <p>
4467     * If an {@link AccessibilityDelegate} has been specified via calling
4468     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4469     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4470     * is responsible for handling this call.
4471     * </p>
4472     * <p>
4473     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4474     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4475     * </p>
4476     *
4477     * @param event The event.
4478     *
4479     * @return True if the event population was completed.
4480     */
4481    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4482        if (mAccessibilityDelegate != null) {
4483            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4484        } else {
4485            return dispatchPopulateAccessibilityEventInternal(event);
4486        }
4487    }
4488
4489    /**
4490     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4491     *
4492     * Note: Called from the default {@link AccessibilityDelegate}.
4493     */
4494    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4495        onPopulateAccessibilityEvent(event);
4496        return false;
4497    }
4498
4499    /**
4500     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4501     * giving a chance to this View to populate the accessibility event with its
4502     * text content. While this method is free to modify event
4503     * attributes other than text content, doing so should normally be performed in
4504     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4505     * <p>
4506     * Example: Adding formatted date string to an accessibility event in addition
4507     *          to the text added by the super implementation:
4508     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4509     *     super.onPopulateAccessibilityEvent(event);
4510     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4511     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4512     *         mCurrentDate.getTimeInMillis(), flags);
4513     *     event.getText().add(selectedDateUtterance);
4514     * }</pre>
4515     * <p>
4516     * If an {@link AccessibilityDelegate} has been specified via calling
4517     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4518     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4519     * is responsible for handling this call.
4520     * </p>
4521     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4522     * information to the event, in case the default implementation has basic information to add.
4523     * </p>
4524     *
4525     * @param event The accessibility event which to populate.
4526     *
4527     * @see #sendAccessibilityEvent(int)
4528     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4529     */
4530    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4531        if (mAccessibilityDelegate != null) {
4532            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4533        } else {
4534            onPopulateAccessibilityEventInternal(event);
4535        }
4536    }
4537
4538    /**
4539     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4540     *
4541     * Note: Called from the default {@link AccessibilityDelegate}.
4542     */
4543    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4544
4545    }
4546
4547    /**
4548     * Initializes an {@link AccessibilityEvent} with information about
4549     * this View which is the event source. In other words, the source of
4550     * an accessibility event is the view whose state change triggered firing
4551     * the event.
4552     * <p>
4553     * Example: Setting the password property of an event in addition
4554     *          to properties set by the super implementation:
4555     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4556     *     super.onInitializeAccessibilityEvent(event);
4557     *     event.setPassword(true);
4558     * }</pre>
4559     * <p>
4560     * If an {@link AccessibilityDelegate} has been specified via calling
4561     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4562     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4563     * is responsible for handling this call.
4564     * </p>
4565     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4566     * information to the event, in case the default implementation has basic information to add.
4567     * </p>
4568     * @param event The event to initialize.
4569     *
4570     * @see #sendAccessibilityEvent(int)
4571     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4572     */
4573    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4574        if (mAccessibilityDelegate != null) {
4575            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4576        } else {
4577            onInitializeAccessibilityEventInternal(event);
4578        }
4579    }
4580
4581    /**
4582     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4583     *
4584     * Note: Called from the default {@link AccessibilityDelegate}.
4585     */
4586    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4587        event.setSource(this);
4588        event.setClassName(View.class.getName());
4589        event.setPackageName(getContext().getPackageName());
4590        event.setEnabled(isEnabled());
4591        event.setContentDescription(mContentDescription);
4592
4593        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4594            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4595            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4596                    FOCUSABLES_ALL);
4597            event.setItemCount(focusablesTempList.size());
4598            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4599            focusablesTempList.clear();
4600        }
4601    }
4602
4603    /**
4604     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4605     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4606     * This method is responsible for obtaining an accessibility node info from a
4607     * pool of reusable instances and calling
4608     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4609     * initialize the former.
4610     * <p>
4611     * Note: The client is responsible for recycling the obtained instance by calling
4612     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4613     * </p>
4614     *
4615     * @return A populated {@link AccessibilityNodeInfo}.
4616     *
4617     * @see AccessibilityNodeInfo
4618     */
4619    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4620        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4621        if (provider != null) {
4622            return provider.createAccessibilityNodeInfo(View.NO_ID);
4623        } else {
4624            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4625            onInitializeAccessibilityNodeInfo(info);
4626            return info;
4627        }
4628    }
4629
4630    /**
4631     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4632     * The base implementation sets:
4633     * <ul>
4634     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4635     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4636     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4637     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4638     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4639     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4640     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4641     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4642     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4643     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4644     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4645     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4646     * </ul>
4647     * <p>
4648     * Subclasses should override this method, call the super implementation,
4649     * and set additional attributes.
4650     * </p>
4651     * <p>
4652     * If an {@link AccessibilityDelegate} has been specified via calling
4653     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4654     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4655     * is responsible for handling this call.
4656     * </p>
4657     *
4658     * @param info The instance to initialize.
4659     */
4660    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4661        if (mAccessibilityDelegate != null) {
4662            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4663        } else {
4664            onInitializeAccessibilityNodeInfoInternal(info);
4665        }
4666    }
4667
4668    /**
4669     * Gets the location of this view in screen coordintates.
4670     *
4671     * @param outRect The output location
4672     */
4673    private void getBoundsOnScreen(Rect outRect) {
4674        if (mAttachInfo == null) {
4675            return;
4676        }
4677
4678        RectF position = mAttachInfo.mTmpTransformRect;
4679        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4680
4681        if (!hasIdentityMatrix()) {
4682            getMatrix().mapRect(position);
4683        }
4684
4685        position.offset(mLeft, mTop);
4686
4687        ViewParent parent = mParent;
4688        while (parent instanceof View) {
4689            View parentView = (View) parent;
4690
4691            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4692
4693            if (!parentView.hasIdentityMatrix()) {
4694                parentView.getMatrix().mapRect(position);
4695            }
4696
4697            position.offset(parentView.mLeft, parentView.mTop);
4698
4699            parent = parentView.mParent;
4700        }
4701
4702        if (parent instanceof ViewRootImpl) {
4703            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4704            position.offset(0, -viewRootImpl.mCurScrollY);
4705        }
4706
4707        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4708
4709        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4710                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4711    }
4712
4713    /**
4714     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4715     *
4716     * Note: Called from the default {@link AccessibilityDelegate}.
4717     */
4718    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4719        Rect bounds = mAttachInfo.mTmpInvalRect;
4720        getDrawingRect(bounds);
4721        info.setBoundsInParent(bounds);
4722
4723        getBoundsOnScreen(bounds);
4724        info.setBoundsInScreen(bounds);
4725
4726        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4727            ViewParent parent = getParentForAccessibility();
4728            if (parent instanceof View) {
4729                info.setParent((View) parent);
4730            }
4731        }
4732
4733        info.setVisibleToUser(isVisibleToUser());
4734
4735        info.setPackageName(mContext.getPackageName());
4736        info.setClassName(View.class.getName());
4737        info.setContentDescription(getContentDescription());
4738
4739        info.setEnabled(isEnabled());
4740        info.setClickable(isClickable());
4741        info.setFocusable(isFocusable());
4742        info.setFocused(isFocused());
4743        info.setAccessibilityFocused(isAccessibilityFocused());
4744        info.setSelected(isSelected());
4745        info.setLongClickable(isLongClickable());
4746
4747        // TODO: These make sense only if we are in an AdapterView but all
4748        // views can be selected. Maybe from accessiiblity perspective
4749        // we should report as selectable view in an AdapterView.
4750        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4751        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4752
4753        if (isFocusable()) {
4754            if (isFocused()) {
4755                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4756            } else {
4757                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4758            }
4759        }
4760
4761        if (!isAccessibilityFocused()) {
4762            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4763        } else {
4764            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4765        }
4766
4767        if (isClickable()) {
4768            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4769        }
4770
4771        if (isLongClickable()) {
4772            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4773        }
4774
4775        if (mContentDescription != null && mContentDescription.length() > 0) {
4776            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4777            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4778            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4779                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4780                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4781        }
4782    }
4783
4784    /**
4785     * Computes whether this view is visible to the user. Such a view is
4786     * attached, visible, all its predecessors are visible, it is not clipped
4787     * entirely by its predecessors, and has an alpha greater than zero.
4788     *
4789     * @return Whether the view is visible on the screen.
4790     */
4791    private boolean isVisibleToUser() {
4792        // The first two checks are made also made by isShown() which
4793        // however traverses the tree up to the parent to catch that.
4794        // Therefore, we do some fail fast check to minimize the up
4795        // tree traversal.
4796        return (mAttachInfo != null
4797                && mAttachInfo.mWindowVisibility == View.VISIBLE
4798                && getAlpha() > 0
4799                && isShown()
4800                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
4801    }
4802
4803    /**
4804     * Sets a delegate for implementing accessibility support via compositon as
4805     * opposed to inheritance. The delegate's primary use is for implementing
4806     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4807     *
4808     * @param delegate The delegate instance.
4809     *
4810     * @see AccessibilityDelegate
4811     */
4812    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4813        mAccessibilityDelegate = delegate;
4814    }
4815
4816    /**
4817     * Gets the provider for managing a virtual view hierarchy rooted at this View
4818     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4819     * that explore the window content.
4820     * <p>
4821     * If this method returns an instance, this instance is responsible for managing
4822     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4823     * View including the one representing the View itself. Similarly the returned
4824     * instance is responsible for performing accessibility actions on any virtual
4825     * view or the root view itself.
4826     * </p>
4827     * <p>
4828     * If an {@link AccessibilityDelegate} has been specified via calling
4829     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4830     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4831     * is responsible for handling this call.
4832     * </p>
4833     *
4834     * @return The provider.
4835     *
4836     * @see AccessibilityNodeProvider
4837     */
4838    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4839        if (mAccessibilityDelegate != null) {
4840            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4841        } else {
4842            return null;
4843        }
4844    }
4845
4846    /**
4847     * Gets the unique identifier of this view on the screen for accessibility purposes.
4848     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4849     *
4850     * @return The view accessibility id.
4851     *
4852     * @hide
4853     */
4854    public int getAccessibilityViewId() {
4855        if (mAccessibilityViewId == NO_ID) {
4856            mAccessibilityViewId = sNextAccessibilityViewId++;
4857        }
4858        return mAccessibilityViewId;
4859    }
4860
4861    /**
4862     * Gets the unique identifier of the window in which this View reseides.
4863     *
4864     * @return The window accessibility id.
4865     *
4866     * @hide
4867     */
4868    public int getAccessibilityWindowId() {
4869        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4870    }
4871
4872    /**
4873     * Gets the {@link View} description. It briefly describes the view and is
4874     * primarily used for accessibility support. Set this property to enable
4875     * better accessibility support for your application. This is especially
4876     * true for views that do not have textual representation (For example,
4877     * ImageButton).
4878     *
4879     * @return The content description.
4880     *
4881     * @attr ref android.R.styleable#View_contentDescription
4882     */
4883    @ViewDebug.ExportedProperty(category = "accessibility")
4884    public CharSequence getContentDescription() {
4885        return mContentDescription;
4886    }
4887
4888    /**
4889     * Sets the {@link View} description. It briefly describes the view and is
4890     * primarily used for accessibility support. Set this property to enable
4891     * better accessibility support for your application. This is especially
4892     * true for views that do not have textual representation (For example,
4893     * ImageButton).
4894     *
4895     * @param contentDescription The content description.
4896     *
4897     * @attr ref android.R.styleable#View_contentDescription
4898     */
4899    @RemotableViewMethod
4900    public void setContentDescription(CharSequence contentDescription) {
4901        mContentDescription = contentDescription;
4902    }
4903
4904    /**
4905     * Invoked whenever this view loses focus, either by losing window focus or by losing
4906     * focus within its window. This method can be used to clear any state tied to the
4907     * focus. For instance, if a button is held pressed with the trackball and the window
4908     * loses focus, this method can be used to cancel the press.
4909     *
4910     * Subclasses of View overriding this method should always call super.onFocusLost().
4911     *
4912     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4913     * @see #onWindowFocusChanged(boolean)
4914     *
4915     * @hide pending API council approval
4916     */
4917    protected void onFocusLost() {
4918        resetPressedState();
4919    }
4920
4921    private void resetPressedState() {
4922        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4923            return;
4924        }
4925
4926        if (isPressed()) {
4927            setPressed(false);
4928
4929            if (!mHasPerformedLongPress) {
4930                removeLongPressCallback();
4931            }
4932        }
4933    }
4934
4935    /**
4936     * Returns true if this view has focus
4937     *
4938     * @return True if this view has focus, false otherwise.
4939     */
4940    @ViewDebug.ExportedProperty(category = "focus")
4941    public boolean isFocused() {
4942        return (mPrivateFlags & FOCUSED) != 0;
4943    }
4944
4945    /**
4946     * Find the view in the hierarchy rooted at this view that currently has
4947     * focus.
4948     *
4949     * @return The view that currently has focus, or null if no focused view can
4950     *         be found.
4951     */
4952    public View findFocus() {
4953        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4954    }
4955
4956    /**
4957     * Indicates whether this view is one of the set of scrollable containers in
4958     * its window.
4959     *
4960     * @return whether this view is one of the set of scrollable containers in
4961     * its window
4962     *
4963     * @attr ref android.R.styleable#View_isScrollContainer
4964     */
4965    public boolean isScrollContainer() {
4966        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4967    }
4968
4969    /**
4970     * Change whether this view is one of the set of scrollable containers in
4971     * its window.  This will be used to determine whether the window can
4972     * resize or must pan when a soft input area is open -- scrollable
4973     * containers allow the window to use resize mode since the container
4974     * will appropriately shrink.
4975     *
4976     * @attr ref android.R.styleable#View_isScrollContainer
4977     */
4978    public void setScrollContainer(boolean isScrollContainer) {
4979        if (isScrollContainer) {
4980            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4981                mAttachInfo.mScrollContainers.add(this);
4982                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4983            }
4984            mPrivateFlags |= SCROLL_CONTAINER;
4985        } else {
4986            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4987                mAttachInfo.mScrollContainers.remove(this);
4988            }
4989            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4990        }
4991    }
4992
4993    /**
4994     * Returns the quality of the drawing cache.
4995     *
4996     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4997     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4998     *
4999     * @see #setDrawingCacheQuality(int)
5000     * @see #setDrawingCacheEnabled(boolean)
5001     * @see #isDrawingCacheEnabled()
5002     *
5003     * @attr ref android.R.styleable#View_drawingCacheQuality
5004     */
5005    public int getDrawingCacheQuality() {
5006        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5007    }
5008
5009    /**
5010     * Set the drawing cache quality of this view. This value is used only when the
5011     * drawing cache is enabled
5012     *
5013     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5014     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5015     *
5016     * @see #getDrawingCacheQuality()
5017     * @see #setDrawingCacheEnabled(boolean)
5018     * @see #isDrawingCacheEnabled()
5019     *
5020     * @attr ref android.R.styleable#View_drawingCacheQuality
5021     */
5022    public void setDrawingCacheQuality(int quality) {
5023        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5024    }
5025
5026    /**
5027     * Returns whether the screen should remain on, corresponding to the current
5028     * value of {@link #KEEP_SCREEN_ON}.
5029     *
5030     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5031     *
5032     * @see #setKeepScreenOn(boolean)
5033     *
5034     * @attr ref android.R.styleable#View_keepScreenOn
5035     */
5036    public boolean getKeepScreenOn() {
5037        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5038    }
5039
5040    /**
5041     * Controls whether the screen should remain on, modifying the
5042     * value of {@link #KEEP_SCREEN_ON}.
5043     *
5044     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5045     *
5046     * @see #getKeepScreenOn()
5047     *
5048     * @attr ref android.R.styleable#View_keepScreenOn
5049     */
5050    public void setKeepScreenOn(boolean keepScreenOn) {
5051        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5052    }
5053
5054    /**
5055     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5056     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5057     *
5058     * @attr ref android.R.styleable#View_nextFocusLeft
5059     */
5060    public int getNextFocusLeftId() {
5061        return mNextFocusLeftId;
5062    }
5063
5064    /**
5065     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5066     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5067     * decide automatically.
5068     *
5069     * @attr ref android.R.styleable#View_nextFocusLeft
5070     */
5071    public void setNextFocusLeftId(int nextFocusLeftId) {
5072        mNextFocusLeftId = nextFocusLeftId;
5073    }
5074
5075    /**
5076     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5077     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5078     *
5079     * @attr ref android.R.styleable#View_nextFocusRight
5080     */
5081    public int getNextFocusRightId() {
5082        return mNextFocusRightId;
5083    }
5084
5085    /**
5086     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5087     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5088     * decide automatically.
5089     *
5090     * @attr ref android.R.styleable#View_nextFocusRight
5091     */
5092    public void setNextFocusRightId(int nextFocusRightId) {
5093        mNextFocusRightId = nextFocusRightId;
5094    }
5095
5096    /**
5097     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5098     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5099     *
5100     * @attr ref android.R.styleable#View_nextFocusUp
5101     */
5102    public int getNextFocusUpId() {
5103        return mNextFocusUpId;
5104    }
5105
5106    /**
5107     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5108     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5109     * decide automatically.
5110     *
5111     * @attr ref android.R.styleable#View_nextFocusUp
5112     */
5113    public void setNextFocusUpId(int nextFocusUpId) {
5114        mNextFocusUpId = nextFocusUpId;
5115    }
5116
5117    /**
5118     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5119     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5120     *
5121     * @attr ref android.R.styleable#View_nextFocusDown
5122     */
5123    public int getNextFocusDownId() {
5124        return mNextFocusDownId;
5125    }
5126
5127    /**
5128     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5129     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5130     * decide automatically.
5131     *
5132     * @attr ref android.R.styleable#View_nextFocusDown
5133     */
5134    public void setNextFocusDownId(int nextFocusDownId) {
5135        mNextFocusDownId = nextFocusDownId;
5136    }
5137
5138    /**
5139     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5140     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5141     *
5142     * @attr ref android.R.styleable#View_nextFocusForward
5143     */
5144    public int getNextFocusForwardId() {
5145        return mNextFocusForwardId;
5146    }
5147
5148    /**
5149     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5150     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5151     * decide automatically.
5152     *
5153     * @attr ref android.R.styleable#View_nextFocusForward
5154     */
5155    public void setNextFocusForwardId(int nextFocusForwardId) {
5156        mNextFocusForwardId = nextFocusForwardId;
5157    }
5158
5159    /**
5160     * Returns the visibility of this view and all of its ancestors
5161     *
5162     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5163     */
5164    public boolean isShown() {
5165        View current = this;
5166        //noinspection ConstantConditions
5167        do {
5168            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5169                return false;
5170            }
5171            ViewParent parent = current.mParent;
5172            if (parent == null) {
5173                return false; // We are not attached to the view root
5174            }
5175            if (!(parent instanceof View)) {
5176                return true;
5177            }
5178            current = (View) parent;
5179        } while (current != null);
5180
5181        return false;
5182    }
5183
5184    /**
5185     * Called by the view hierarchy when the content insets for a window have
5186     * changed, to allow it to adjust its content to fit within those windows.
5187     * The content insets tell you the space that the status bar, input method,
5188     * and other system windows infringe on the application's window.
5189     *
5190     * <p>You do not normally need to deal with this function, since the default
5191     * window decoration given to applications takes care of applying it to the
5192     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5193     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5194     * and your content can be placed under those system elements.  You can then
5195     * use this method within your view hierarchy if you have parts of your UI
5196     * which you would like to ensure are not being covered.
5197     *
5198     * <p>The default implementation of this method simply applies the content
5199     * inset's to the view's padding.  This can be enabled through
5200     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5201     * the method and handle the insets however you would like.  Note that the
5202     * insets provided by the framework are always relative to the far edges
5203     * of the window, not accounting for the location of the called view within
5204     * that window.  (In fact when this method is called you do not yet know
5205     * where the layout will place the view, as it is done before layout happens.)
5206     *
5207     * <p>Note: unlike many View methods, there is no dispatch phase to this
5208     * call.  If you are overriding it in a ViewGroup and want to allow the
5209     * call to continue to your children, you must be sure to call the super
5210     * implementation.
5211     *
5212     * @param insets Current content insets of the window.  Prior to
5213     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5214     * the insets or else you and Android will be unhappy.
5215     *
5216     * @return Return true if this view applied the insets and it should not
5217     * continue propagating further down the hierarchy, false otherwise.
5218     */
5219    protected boolean fitSystemWindows(Rect insets) {
5220        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5221            mUserPaddingStart = -1;
5222            mUserPaddingEnd = -1;
5223            mUserPaddingRelative = false;
5224            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5225                    || mAttachInfo == null
5226                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5227                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5228                return true;
5229            } else {
5230                internalSetPadding(0, 0, 0, 0);
5231                return false;
5232            }
5233        }
5234        return false;
5235    }
5236
5237    /**
5238     * Set whether or not this view should account for system screen decorations
5239     * such as the status bar and inset its content. This allows this view to be
5240     * positioned in absolute screen coordinates and remain visible to the user.
5241     *
5242     * <p>This should only be used by top-level window decor views.
5243     *
5244     * @param fitSystemWindows true to inset content for system screen decorations, false for
5245     *                         default behavior.
5246     *
5247     * @attr ref android.R.styleable#View_fitsSystemWindows
5248     */
5249    public void setFitsSystemWindows(boolean fitSystemWindows) {
5250        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5251    }
5252
5253    /**
5254     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5255     * will account for system screen decorations such as the status bar and inset its
5256     * content. This allows the view to be positioned in absolute screen coordinates
5257     * and remain visible to the user.
5258     *
5259     * @return true if this view will adjust its content bounds for system screen decorations.
5260     *
5261     * @attr ref android.R.styleable#View_fitsSystemWindows
5262     */
5263    public boolean fitsSystemWindows() {
5264        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5265    }
5266
5267    /**
5268     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5269     */
5270    public void requestFitSystemWindows() {
5271        if (mParent != null) {
5272            mParent.requestFitSystemWindows();
5273        }
5274    }
5275
5276    /**
5277     * For use by PhoneWindow to make its own system window fitting optional.
5278     * @hide
5279     */
5280    public void makeOptionalFitsSystemWindows() {
5281        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5282    }
5283
5284    /**
5285     * Returns the visibility status for this view.
5286     *
5287     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5288     * @attr ref android.R.styleable#View_visibility
5289     */
5290    @ViewDebug.ExportedProperty(mapping = {
5291        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5292        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5293        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5294    })
5295    public int getVisibility() {
5296        return mViewFlags & VISIBILITY_MASK;
5297    }
5298
5299    /**
5300     * Set the enabled state of this view.
5301     *
5302     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5303     * @attr ref android.R.styleable#View_visibility
5304     */
5305    @RemotableViewMethod
5306    public void setVisibility(int visibility) {
5307        setFlags(visibility, VISIBILITY_MASK);
5308        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5309    }
5310
5311    /**
5312     * Returns the enabled status for this view. The interpretation of the
5313     * enabled state varies by subclass.
5314     *
5315     * @return True if this view is enabled, false otherwise.
5316     */
5317    @ViewDebug.ExportedProperty
5318    public boolean isEnabled() {
5319        return (mViewFlags & ENABLED_MASK) == ENABLED;
5320    }
5321
5322    /**
5323     * Set the enabled state of this view. The interpretation of the enabled
5324     * state varies by subclass.
5325     *
5326     * @param enabled True if this view is enabled, false otherwise.
5327     */
5328    @RemotableViewMethod
5329    public void setEnabled(boolean enabled) {
5330        if (enabled == isEnabled()) return;
5331
5332        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5333
5334        /*
5335         * The View most likely has to change its appearance, so refresh
5336         * the drawable state.
5337         */
5338        refreshDrawableState();
5339
5340        // Invalidate too, since the default behavior for views is to be
5341        // be drawn at 50% alpha rather than to change the drawable.
5342        invalidate(true);
5343    }
5344
5345    /**
5346     * Set whether this view can receive the focus.
5347     *
5348     * Setting this to false will also ensure that this view is not focusable
5349     * in touch mode.
5350     *
5351     * @param focusable If true, this view can receive the focus.
5352     *
5353     * @see #setFocusableInTouchMode(boolean)
5354     * @attr ref android.R.styleable#View_focusable
5355     */
5356    public void setFocusable(boolean focusable) {
5357        if (!focusable) {
5358            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5359        }
5360        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5361    }
5362
5363    /**
5364     * Set whether this view can receive focus while in touch mode.
5365     *
5366     * Setting this to true will also ensure that this view is focusable.
5367     *
5368     * @param focusableInTouchMode If true, this view can receive the focus while
5369     *   in touch mode.
5370     *
5371     * @see #setFocusable(boolean)
5372     * @attr ref android.R.styleable#View_focusableInTouchMode
5373     */
5374    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5375        // Focusable in touch mode should always be set before the focusable flag
5376        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5377        // which, in touch mode, will not successfully request focus on this view
5378        // because the focusable in touch mode flag is not set
5379        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5380        if (focusableInTouchMode) {
5381            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5382        }
5383    }
5384
5385    /**
5386     * Set whether this view should have sound effects enabled for events such as
5387     * clicking and touching.
5388     *
5389     * <p>You may wish to disable sound effects for a view if you already play sounds,
5390     * for instance, a dial key that plays dtmf tones.
5391     *
5392     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5393     * @see #isSoundEffectsEnabled()
5394     * @see #playSoundEffect(int)
5395     * @attr ref android.R.styleable#View_soundEffectsEnabled
5396     */
5397    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5398        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5399    }
5400
5401    /**
5402     * @return whether this view should have sound effects enabled for events such as
5403     *     clicking and touching.
5404     *
5405     * @see #setSoundEffectsEnabled(boolean)
5406     * @see #playSoundEffect(int)
5407     * @attr ref android.R.styleable#View_soundEffectsEnabled
5408     */
5409    @ViewDebug.ExportedProperty
5410    public boolean isSoundEffectsEnabled() {
5411        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5412    }
5413
5414    /**
5415     * Set whether this view should have haptic feedback for events such as
5416     * long presses.
5417     *
5418     * <p>You may wish to disable haptic feedback if your view already controls
5419     * its own haptic feedback.
5420     *
5421     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5422     * @see #isHapticFeedbackEnabled()
5423     * @see #performHapticFeedback(int)
5424     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5425     */
5426    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5427        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5428    }
5429
5430    /**
5431     * @return whether this view should have haptic feedback enabled for events
5432     * long presses.
5433     *
5434     * @see #setHapticFeedbackEnabled(boolean)
5435     * @see #performHapticFeedback(int)
5436     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5437     */
5438    @ViewDebug.ExportedProperty
5439    public boolean isHapticFeedbackEnabled() {
5440        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5441    }
5442
5443    /**
5444     * Returns the layout direction for this view.
5445     *
5446     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5447     *   {@link #LAYOUT_DIRECTION_RTL},
5448     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5449     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5450     *
5451     * @attr ref android.R.styleable#View_layoutDirection
5452     * @hide
5453     */
5454    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5455        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5456        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5457        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5458        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5459    })
5460    public int getLayoutDirection() {
5461        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5462    }
5463
5464    /**
5465     * Set the layout direction for this view. This will propagate a reset of layout direction
5466     * resolution to the view's children and resolve layout direction for this view.
5467     *
5468     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5469     *   {@link #LAYOUT_DIRECTION_RTL},
5470     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5471     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5472     *
5473     * @attr ref android.R.styleable#View_layoutDirection
5474     * @hide
5475     */
5476    @RemotableViewMethod
5477    public void setLayoutDirection(int layoutDirection) {
5478        if (getLayoutDirection() != layoutDirection) {
5479            // Reset the current layout direction and the resolved one
5480            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5481            resetResolvedLayoutDirection();
5482            // Set the new layout direction (filtered) and ask for a layout pass
5483            mPrivateFlags2 |=
5484                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5485            requestLayout();
5486        }
5487    }
5488
5489    /**
5490     * Returns the resolved layout direction for this view.
5491     *
5492     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5493     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5494     * @hide
5495     */
5496    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5497        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5498        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5499    })
5500    public int getResolvedLayoutDirection() {
5501        // The layout diretion will be resolved only if needed
5502        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5503            resolveLayoutDirection();
5504        }
5505        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5506                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5507    }
5508
5509    /**
5510     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5511     * layout attribute and/or the inherited value from the parent
5512     *
5513     * @return true if the layout is right-to-left.
5514     * @hide
5515     */
5516    @ViewDebug.ExportedProperty(category = "layout")
5517    public boolean isLayoutRtl() {
5518        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5519    }
5520
5521    /**
5522     * Indicates whether the view is currently tracking transient state that the
5523     * app should not need to concern itself with saving and restoring, but that
5524     * the framework should take special note to preserve when possible.
5525     *
5526     * <p>A view with transient state cannot be trivially rebound from an external
5527     * data source, such as an adapter binding item views in a list. This may be
5528     * because the view is performing an animation, tracking user selection
5529     * of content, or similar.</p>
5530     *
5531     * @return true if the view has transient state
5532     */
5533    @ViewDebug.ExportedProperty(category = "layout")
5534    public boolean hasTransientState() {
5535        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5536    }
5537
5538    /**
5539     * Set whether this view is currently tracking transient state that the
5540     * framework should attempt to preserve when possible. This flag is reference counted,
5541     * so every call to setHasTransientState(true) should be paired with a later call
5542     * to setHasTransientState(false).
5543     *
5544     * <p>A view with transient state cannot be trivially rebound from an external
5545     * data source, such as an adapter binding item views in a list. This may be
5546     * because the view is performing an animation, tracking user selection
5547     * of content, or similar.</p>
5548     *
5549     * @param hasTransientState true if this view has transient state
5550     */
5551    public void setHasTransientState(boolean hasTransientState) {
5552        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5553                mTransientStateCount - 1;
5554        if (mTransientStateCount < 0) {
5555            mTransientStateCount = 0;
5556            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5557                    "unmatched pair of setHasTransientState calls");
5558        }
5559        if ((hasTransientState && mTransientStateCount == 1) ||
5560                (hasTransientState && mTransientStateCount == 0)) {
5561            // update flag if we've just incremented up from 0 or decremented down to 0
5562            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5563                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5564            if (mParent != null) {
5565                try {
5566                    mParent.childHasTransientStateChanged(this, hasTransientState);
5567                } catch (AbstractMethodError e) {
5568                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5569                            " does not fully implement ViewParent", e);
5570                }
5571            }
5572        }
5573    }
5574
5575    /**
5576     * If this view doesn't do any drawing on its own, set this flag to
5577     * allow further optimizations. By default, this flag is not set on
5578     * View, but could be set on some View subclasses such as ViewGroup.
5579     *
5580     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5581     * you should clear this flag.
5582     *
5583     * @param willNotDraw whether or not this View draw on its own
5584     */
5585    public void setWillNotDraw(boolean willNotDraw) {
5586        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5587    }
5588
5589    /**
5590     * Returns whether or not this View draws on its own.
5591     *
5592     * @return true if this view has nothing to draw, false otherwise
5593     */
5594    @ViewDebug.ExportedProperty(category = "drawing")
5595    public boolean willNotDraw() {
5596        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5597    }
5598
5599    /**
5600     * When a View's drawing cache is enabled, drawing is redirected to an
5601     * offscreen bitmap. Some views, like an ImageView, must be able to
5602     * bypass this mechanism if they already draw a single bitmap, to avoid
5603     * unnecessary usage of the memory.
5604     *
5605     * @param willNotCacheDrawing true if this view does not cache its
5606     *        drawing, false otherwise
5607     */
5608    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5609        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5610    }
5611
5612    /**
5613     * Returns whether or not this View can cache its drawing or not.
5614     *
5615     * @return true if this view does not cache its drawing, false otherwise
5616     */
5617    @ViewDebug.ExportedProperty(category = "drawing")
5618    public boolean willNotCacheDrawing() {
5619        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5620    }
5621
5622    /**
5623     * Indicates whether this view reacts to click events or not.
5624     *
5625     * @return true if the view is clickable, false otherwise
5626     *
5627     * @see #setClickable(boolean)
5628     * @attr ref android.R.styleable#View_clickable
5629     */
5630    @ViewDebug.ExportedProperty
5631    public boolean isClickable() {
5632        return (mViewFlags & CLICKABLE) == CLICKABLE;
5633    }
5634
5635    /**
5636     * Enables or disables click events for this view. When a view
5637     * is clickable it will change its state to "pressed" on every click.
5638     * Subclasses should set the view clickable to visually react to
5639     * user's clicks.
5640     *
5641     * @param clickable true to make the view clickable, false otherwise
5642     *
5643     * @see #isClickable()
5644     * @attr ref android.R.styleable#View_clickable
5645     */
5646    public void setClickable(boolean clickable) {
5647        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5648    }
5649
5650    /**
5651     * Indicates whether this view reacts to long click events or not.
5652     *
5653     * @return true if the view is long clickable, false otherwise
5654     *
5655     * @see #setLongClickable(boolean)
5656     * @attr ref android.R.styleable#View_longClickable
5657     */
5658    public boolean isLongClickable() {
5659        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5660    }
5661
5662    /**
5663     * Enables or disables long click events for this view. When a view is long
5664     * clickable it reacts to the user holding down the button for a longer
5665     * duration than a tap. This event can either launch the listener or a
5666     * context menu.
5667     *
5668     * @param longClickable true to make the view long clickable, false otherwise
5669     * @see #isLongClickable()
5670     * @attr ref android.R.styleable#View_longClickable
5671     */
5672    public void setLongClickable(boolean longClickable) {
5673        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5674    }
5675
5676    /**
5677     * Sets the pressed state for this view.
5678     *
5679     * @see #isClickable()
5680     * @see #setClickable(boolean)
5681     *
5682     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5683     *        the View's internal state from a previously set "pressed" state.
5684     */
5685    public void setPressed(boolean pressed) {
5686        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5687
5688        if (pressed) {
5689            mPrivateFlags |= PRESSED;
5690        } else {
5691            mPrivateFlags &= ~PRESSED;
5692        }
5693
5694        if (needsRefresh) {
5695            refreshDrawableState();
5696        }
5697        dispatchSetPressed(pressed);
5698    }
5699
5700    /**
5701     * Dispatch setPressed to all of this View's children.
5702     *
5703     * @see #setPressed(boolean)
5704     *
5705     * @param pressed The new pressed state
5706     */
5707    protected void dispatchSetPressed(boolean pressed) {
5708    }
5709
5710    /**
5711     * Indicates whether the view is currently in pressed state. Unless
5712     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5713     * the pressed state.
5714     *
5715     * @see #setPressed(boolean)
5716     * @see #isClickable()
5717     * @see #setClickable(boolean)
5718     *
5719     * @return true if the view is currently pressed, false otherwise
5720     */
5721    public boolean isPressed() {
5722        return (mPrivateFlags & PRESSED) == PRESSED;
5723    }
5724
5725    /**
5726     * Indicates whether this view will save its state (that is,
5727     * whether its {@link #onSaveInstanceState} method will be called).
5728     *
5729     * @return Returns true if the view state saving is enabled, else false.
5730     *
5731     * @see #setSaveEnabled(boolean)
5732     * @attr ref android.R.styleable#View_saveEnabled
5733     */
5734    public boolean isSaveEnabled() {
5735        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5736    }
5737
5738    /**
5739     * Controls whether the saving of this view's state is
5740     * enabled (that is, whether its {@link #onSaveInstanceState} method
5741     * will be called).  Note that even if freezing is enabled, the
5742     * view still must have an id assigned to it (via {@link #setId(int)})
5743     * for its state to be saved.  This flag can only disable the
5744     * saving of this view; any child views may still have their state saved.
5745     *
5746     * @param enabled Set to false to <em>disable</em> state saving, or true
5747     * (the default) to allow it.
5748     *
5749     * @see #isSaveEnabled()
5750     * @see #setId(int)
5751     * @see #onSaveInstanceState()
5752     * @attr ref android.R.styleable#View_saveEnabled
5753     */
5754    public void setSaveEnabled(boolean enabled) {
5755        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5756    }
5757
5758    /**
5759     * Gets whether the framework should discard touches when the view's
5760     * window is obscured by another visible window.
5761     * Refer to the {@link View} security documentation for more details.
5762     *
5763     * @return True if touch filtering is enabled.
5764     *
5765     * @see #setFilterTouchesWhenObscured(boolean)
5766     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5767     */
5768    @ViewDebug.ExportedProperty
5769    public boolean getFilterTouchesWhenObscured() {
5770        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5771    }
5772
5773    /**
5774     * Sets whether the framework should discard touches when the view's
5775     * window is obscured by another visible window.
5776     * Refer to the {@link View} security documentation for more details.
5777     *
5778     * @param enabled True if touch filtering should be enabled.
5779     *
5780     * @see #getFilterTouchesWhenObscured
5781     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5782     */
5783    public void setFilterTouchesWhenObscured(boolean enabled) {
5784        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5785                FILTER_TOUCHES_WHEN_OBSCURED);
5786    }
5787
5788    /**
5789     * Indicates whether the entire hierarchy under this view will save its
5790     * state when a state saving traversal occurs from its parent.  The default
5791     * is true; if false, these views will not be saved unless
5792     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5793     *
5794     * @return Returns true if the view state saving from parent is enabled, else false.
5795     *
5796     * @see #setSaveFromParentEnabled(boolean)
5797     */
5798    public boolean isSaveFromParentEnabled() {
5799        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5800    }
5801
5802    /**
5803     * Controls whether the entire hierarchy under this view will save its
5804     * state when a state saving traversal occurs from its parent.  The default
5805     * is true; if false, these views will not be saved unless
5806     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5807     *
5808     * @param enabled Set to false to <em>disable</em> state saving, or true
5809     * (the default) to allow it.
5810     *
5811     * @see #isSaveFromParentEnabled()
5812     * @see #setId(int)
5813     * @see #onSaveInstanceState()
5814     */
5815    public void setSaveFromParentEnabled(boolean enabled) {
5816        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5817    }
5818
5819
5820    /**
5821     * Returns whether this View is able to take focus.
5822     *
5823     * @return True if this view can take focus, or false otherwise.
5824     * @attr ref android.R.styleable#View_focusable
5825     */
5826    @ViewDebug.ExportedProperty(category = "focus")
5827    public final boolean isFocusable() {
5828        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5829    }
5830
5831    /**
5832     * When a view is focusable, it may not want to take focus when in touch mode.
5833     * For example, a button would like focus when the user is navigating via a D-pad
5834     * so that the user can click on it, but once the user starts touching the screen,
5835     * the button shouldn't take focus
5836     * @return Whether the view is focusable in touch mode.
5837     * @attr ref android.R.styleable#View_focusableInTouchMode
5838     */
5839    @ViewDebug.ExportedProperty
5840    public final boolean isFocusableInTouchMode() {
5841        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5842    }
5843
5844    /**
5845     * Find the nearest view in the specified direction that can take focus.
5846     * This does not actually give focus to that view.
5847     *
5848     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5849     *
5850     * @return The nearest focusable in the specified direction, or null if none
5851     *         can be found.
5852     */
5853    public View focusSearch(int direction) {
5854        if (mParent != null) {
5855            return mParent.focusSearch(this, direction);
5856        } else {
5857            return null;
5858        }
5859    }
5860
5861    /**
5862     * This method is the last chance for the focused view and its ancestors to
5863     * respond to an arrow key. This is called when the focused view did not
5864     * consume the key internally, nor could the view system find a new view in
5865     * the requested direction to give focus to.
5866     *
5867     * @param focused The currently focused view.
5868     * @param direction The direction focus wants to move. One of FOCUS_UP,
5869     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5870     * @return True if the this view consumed this unhandled move.
5871     */
5872    public boolean dispatchUnhandledMove(View focused, int direction) {
5873        return false;
5874    }
5875
5876    /**
5877     * If a user manually specified the next view id for a particular direction,
5878     * use the root to look up the view.
5879     * @param root The root view of the hierarchy containing this view.
5880     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5881     * or FOCUS_BACKWARD.
5882     * @return The user specified next view, or null if there is none.
5883     */
5884    View findUserSetNextFocus(View root, int direction) {
5885        switch (direction) {
5886            case FOCUS_LEFT:
5887                if (mNextFocusLeftId == View.NO_ID) return null;
5888                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5889            case FOCUS_RIGHT:
5890                if (mNextFocusRightId == View.NO_ID) return null;
5891                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5892            case FOCUS_UP:
5893                if (mNextFocusUpId == View.NO_ID) return null;
5894                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5895            case FOCUS_DOWN:
5896                if (mNextFocusDownId == View.NO_ID) return null;
5897                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5898            case FOCUS_FORWARD:
5899                if (mNextFocusForwardId == View.NO_ID) return null;
5900                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5901            case FOCUS_BACKWARD: {
5902                if (mID == View.NO_ID) return null;
5903                final int id = mID;
5904                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5905                    @Override
5906                    public boolean apply(View t) {
5907                        return t.mNextFocusForwardId == id;
5908                    }
5909                });
5910            }
5911        }
5912        return null;
5913    }
5914
5915    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5916        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5917            @Override
5918            public boolean apply(View t) {
5919                return t.mID == childViewId;
5920            }
5921        });
5922
5923        if (result == null) {
5924            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5925                    + "by user for id " + childViewId);
5926        }
5927        return result;
5928    }
5929
5930    /**
5931     * Find and return all focusable views that are descendants of this view,
5932     * possibly including this view if it is focusable itself.
5933     *
5934     * @param direction The direction of the focus
5935     * @return A list of focusable views
5936     */
5937    public ArrayList<View> getFocusables(int direction) {
5938        ArrayList<View> result = new ArrayList<View>(24);
5939        addFocusables(result, direction);
5940        return result;
5941    }
5942
5943    /**
5944     * Add any focusable views that are descendants of this view (possibly
5945     * including this view if it is focusable itself) to views.  If we are in touch mode,
5946     * only add views that are also focusable in touch mode.
5947     *
5948     * @param views Focusable views found so far
5949     * @param direction The direction of the focus
5950     */
5951    public void addFocusables(ArrayList<View> views, int direction) {
5952        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5953    }
5954
5955    /**
5956     * Adds any focusable views that are descendants of this view (possibly
5957     * including this view if it is focusable itself) to views. This method
5958     * adds all focusable views regardless if we are in touch mode or
5959     * only views focusable in touch mode if we are in touch mode or
5960     * only views that can take accessibility focus if accessibility is enabeld
5961     * depending on the focusable mode paramater.
5962     *
5963     * @param views Focusable views found so far or null if all we are interested is
5964     *        the number of focusables.
5965     * @param direction The direction of the focus.
5966     * @param focusableMode The type of focusables to be added.
5967     *
5968     * @see #FOCUSABLES_ALL
5969     * @see #FOCUSABLES_TOUCH_MODE
5970     */
5971    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5972        if (views == null) {
5973            return;
5974        }
5975        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5976            if (AccessibilityManager.getInstance(mContext).isEnabled()
5977                    && includeForAccessibility()) {
5978                views.add(this);
5979                return;
5980            }
5981        }
5982        if (!isFocusable()) {
5983            return;
5984        }
5985        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5986                && isInTouchMode() && !isFocusableInTouchMode()) {
5987            return;
5988        }
5989        views.add(this);
5990    }
5991
5992    /**
5993     * Finds the Views that contain given text. The containment is case insensitive.
5994     * The search is performed by either the text that the View renders or the content
5995     * description that describes the view for accessibility purposes and the view does
5996     * not render or both. Clients can specify how the search is to be performed via
5997     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5998     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5999     *
6000     * @param outViews The output list of matching Views.
6001     * @param searched The text to match against.
6002     *
6003     * @see #FIND_VIEWS_WITH_TEXT
6004     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6005     * @see #setContentDescription(CharSequence)
6006     */
6007    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6008        if (getAccessibilityNodeProvider() != null) {
6009            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6010                outViews.add(this);
6011            }
6012        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6013                && (searched != null && searched.length() > 0)
6014                && (mContentDescription != null && mContentDescription.length() > 0)) {
6015            String searchedLowerCase = searched.toString().toLowerCase();
6016            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6017            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6018                outViews.add(this);
6019            }
6020        }
6021    }
6022
6023    /**
6024     * Find and return all touchable views that are descendants of this view,
6025     * possibly including this view if it is touchable itself.
6026     *
6027     * @return A list of touchable views
6028     */
6029    public ArrayList<View> getTouchables() {
6030        ArrayList<View> result = new ArrayList<View>();
6031        addTouchables(result);
6032        return result;
6033    }
6034
6035    /**
6036     * Add any touchable views that are descendants of this view (possibly
6037     * including this view if it is touchable itself) to views.
6038     *
6039     * @param views Touchable views found so far
6040     */
6041    public void addTouchables(ArrayList<View> views) {
6042        final int viewFlags = mViewFlags;
6043
6044        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6045                && (viewFlags & ENABLED_MASK) == ENABLED) {
6046            views.add(this);
6047        }
6048    }
6049
6050    /**
6051     * Returns whether this View is accessibility focused.
6052     *
6053     * @return True if this View is accessibility focused.
6054     */
6055    boolean isAccessibilityFocused() {
6056        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6057    }
6058
6059    /**
6060     * Call this to try to give accessibility focus to this view.
6061     *
6062     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6063     * returns false or the view is no visible or the view already has accessibility
6064     * focus.
6065     *
6066     * See also {@link #focusSearch(int)}, which is what you call to say that you
6067     * have focus, and you want your parent to look for the next one.
6068     *
6069     * @return Whether this view actually took accessibility focus.
6070     *
6071     * @hide
6072     */
6073    public boolean requestAccessibilityFocus() {
6074        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6075        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6076            return false;
6077        }
6078        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6079            return false;
6080        }
6081        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6082            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6083            ViewRootImpl viewRootImpl = getViewRootImpl();
6084            if (viewRootImpl != null) {
6085                viewRootImpl.setAccessibilityFocusedHost(this);
6086            }
6087            invalidate();
6088            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6089            notifyAccessibilityStateChanged();
6090            // Try to give input focus to this view - not a descendant.
6091            requestFocusNoSearch(View.FOCUS_DOWN, null);
6092            return true;
6093        }
6094        return false;
6095    }
6096
6097    /**
6098     * Call this to try to clear accessibility focus of this view.
6099     *
6100     * See also {@link #focusSearch(int)}, which is what you call to say that you
6101     * have focus, and you want your parent to look for the next one.
6102     *
6103     * @hide
6104     */
6105    public void clearAccessibilityFocus() {
6106        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6107            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6108            ViewRootImpl viewRootImpl = getViewRootImpl();
6109            if (viewRootImpl != null) {
6110                viewRootImpl.setAccessibilityFocusedHost(null);
6111            }
6112            invalidate();
6113            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6114            notifyAccessibilityStateChanged();
6115
6116            // Clear the text navigation state.
6117            setAccessibilityCursorPosition(-1);
6118
6119            // Try to move accessibility focus to the input focus.
6120            View rootView = getRootView();
6121            if (rootView != null) {
6122                View inputFocus = rootView.findFocus();
6123                if (inputFocus != null) {
6124                    inputFocus.requestAccessibilityFocus();
6125                }
6126            }
6127        }
6128    }
6129
6130    /**
6131     * Find the best view to take accessibility focus from a hover.
6132     * This function finds the deepest actionable view and if that
6133     * fails ask the parent to take accessibility focus from hover.
6134     *
6135     * @param x The X hovered location in this view coorditantes.
6136     * @param y The Y hovered location in this view coorditantes.
6137     * @return Whether the request was handled.
6138     *
6139     * @hide
6140     */
6141    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6142        if (onRequestAccessibilityFocusFromHover(x, y)) {
6143            return true;
6144        }
6145        ViewParent parent = mParent;
6146        if (parent instanceof View) {
6147            View parentView = (View) parent;
6148
6149            float[] position = mAttachInfo.mTmpTransformLocation;
6150            position[0] = x;
6151            position[1] = y;
6152
6153            // Compensate for the transformation of the current matrix.
6154            if (!hasIdentityMatrix()) {
6155                getMatrix().mapPoints(position);
6156            }
6157
6158            // Compensate for the parent scroll and the offset
6159            // of this view stop from the parent top.
6160            position[0] += mLeft - parentView.mScrollX;
6161            position[1] += mTop - parentView.mScrollY;
6162
6163            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6164        }
6165        return false;
6166    }
6167
6168    /**
6169     * Requests to give this View focus from hover.
6170     *
6171     * @param x The X hovered location in this view coorditantes.
6172     * @param y The Y hovered location in this view coorditantes.
6173     * @return Whether the request was handled.
6174     *
6175     * @hide
6176     */
6177    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6178        if (includeForAccessibility()
6179                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6180            return requestAccessibilityFocus();
6181        }
6182        return false;
6183    }
6184
6185    /**
6186     * Clears accessibility focus without calling any callback methods
6187     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6188     * is used for clearing accessibility focus when giving this focus to
6189     * another view.
6190     */
6191    void clearAccessibilityFocusNoCallbacks() {
6192        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6193            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6194            invalidate();
6195        }
6196    }
6197
6198    /**
6199     * Call this to try to give focus to a specific view or to one of its
6200     * descendants.
6201     *
6202     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6203     * false), or if it is focusable and it is not focusable in touch mode
6204     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6205     *
6206     * See also {@link #focusSearch(int)}, which is what you call to say that you
6207     * have focus, and you want your parent to look for the next one.
6208     *
6209     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6210     * {@link #FOCUS_DOWN} and <code>null</code>.
6211     *
6212     * @return Whether this view or one of its descendants actually took focus.
6213     */
6214    public final boolean requestFocus() {
6215        return requestFocus(View.FOCUS_DOWN);
6216    }
6217
6218    /**
6219     * Call this to try to give focus to a specific view or to one of its
6220     * descendants and give it a hint about what direction focus is heading.
6221     *
6222     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6223     * false), or if it is focusable and it is not focusable in touch mode
6224     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6225     *
6226     * See also {@link #focusSearch(int)}, which is what you call to say that you
6227     * have focus, and you want your parent to look for the next one.
6228     *
6229     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6230     * <code>null</code> set for the previously focused rectangle.
6231     *
6232     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6233     * @return Whether this view or one of its descendants actually took focus.
6234     */
6235    public final boolean requestFocus(int direction) {
6236        return requestFocus(direction, null);
6237    }
6238
6239    /**
6240     * Call this to try to give focus to a specific view or to one of its descendants
6241     * and give it hints about the direction and a specific rectangle that the focus
6242     * is coming from.  The rectangle can help give larger views a finer grained hint
6243     * about where focus is coming from, and therefore, where to show selection, or
6244     * forward focus change internally.
6245     *
6246     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6247     * false), or if it is focusable and it is not focusable in touch mode
6248     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6249     *
6250     * A View will not take focus if it is not visible.
6251     *
6252     * A View will not take focus if one of its parents has
6253     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6254     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6255     *
6256     * See also {@link #focusSearch(int)}, which is what you call to say that you
6257     * have focus, and you want your parent to look for the next one.
6258     *
6259     * You may wish to override this method if your custom {@link View} has an internal
6260     * {@link View} that it wishes to forward the request to.
6261     *
6262     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6263     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6264     *        to give a finer grained hint about where focus is coming from.  May be null
6265     *        if there is no hint.
6266     * @return Whether this view or one of its descendants actually took focus.
6267     */
6268    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6269        return requestFocusNoSearch(direction, previouslyFocusedRect);
6270    }
6271
6272    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6273        // need to be focusable
6274        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6275                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6276            return false;
6277        }
6278
6279        // need to be focusable in touch mode if in touch mode
6280        if (isInTouchMode() &&
6281            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6282               return false;
6283        }
6284
6285        // need to not have any parents blocking us
6286        if (hasAncestorThatBlocksDescendantFocus()) {
6287            return false;
6288        }
6289
6290        handleFocusGainInternal(direction, previouslyFocusedRect);
6291        return true;
6292    }
6293
6294    /**
6295     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6296     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6297     * touch mode to request focus when they are touched.
6298     *
6299     * @return Whether this view or one of its descendants actually took focus.
6300     *
6301     * @see #isInTouchMode()
6302     *
6303     */
6304    public final boolean requestFocusFromTouch() {
6305        // Leave touch mode if we need to
6306        if (isInTouchMode()) {
6307            ViewRootImpl viewRoot = getViewRootImpl();
6308            if (viewRoot != null) {
6309                viewRoot.ensureTouchMode(false);
6310            }
6311        }
6312        return requestFocus(View.FOCUS_DOWN);
6313    }
6314
6315    /**
6316     * @return Whether any ancestor of this view blocks descendant focus.
6317     */
6318    private boolean hasAncestorThatBlocksDescendantFocus() {
6319        ViewParent ancestor = mParent;
6320        while (ancestor instanceof ViewGroup) {
6321            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6322            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6323                return true;
6324            } else {
6325                ancestor = vgAncestor.getParent();
6326            }
6327        }
6328        return false;
6329    }
6330
6331    /**
6332     * Gets the mode for determining whether this View is important for accessibility
6333     * which is if it fires accessibility events and if it is reported to
6334     * accessibility services that query the screen.
6335     *
6336     * @return The mode for determining whether a View is important for accessibility.
6337     *
6338     * @attr ref android.R.styleable#View_importantForAccessibility
6339     *
6340     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6341     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6342     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6343     */
6344    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6345            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6346                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6347            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6348                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6349            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6350                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6351        })
6352    public int getImportantForAccessibility() {
6353        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6354                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6355    }
6356
6357    /**
6358     * Sets how to determine whether this view is important for accessibility
6359     * which is if it fires accessibility events and if it is reported to
6360     * accessibility services that query the screen.
6361     *
6362     * @param mode How to determine whether this view is important for accessibility.
6363     *
6364     * @attr ref android.R.styleable#View_importantForAccessibility
6365     *
6366     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6367     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6368     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6369     */
6370    public void setImportantForAccessibility(int mode) {
6371        if (mode != getImportantForAccessibility()) {
6372            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6373            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6374                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6375            notifyAccessibilityStateChanged();
6376        }
6377    }
6378
6379    /**
6380     * Gets whether this view should be exposed for accessibility.
6381     *
6382     * @return Whether the view is exposed for accessibility.
6383     *
6384     * @hide
6385     */
6386    public boolean isImportantForAccessibility() {
6387        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6388                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6389        switch (mode) {
6390            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6391                return true;
6392            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6393                return false;
6394            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6395                return isActionableForAccessibility() || hasListenersForAccessibility();
6396            default:
6397                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6398                        + mode);
6399        }
6400    }
6401
6402    /**
6403     * Gets the parent for accessibility purposes. Note that the parent for
6404     * accessibility is not necessary the immediate parent. It is the first
6405     * predecessor that is important for accessibility.
6406     *
6407     * @return The parent for accessibility purposes.
6408     */
6409    public ViewParent getParentForAccessibility() {
6410        if (mParent instanceof View) {
6411            View parentView = (View) mParent;
6412            if (parentView.includeForAccessibility()) {
6413                return mParent;
6414            } else {
6415                return mParent.getParentForAccessibility();
6416            }
6417        }
6418        return null;
6419    }
6420
6421    /**
6422     * Adds the children of a given View for accessibility. Since some Views are
6423     * not important for accessibility the children for accessibility are not
6424     * necessarily direct children of the riew, rather they are the first level of
6425     * descendants important for accessibility.
6426     *
6427     * @param children The list of children for accessibility.
6428     */
6429    public void addChildrenForAccessibility(ArrayList<View> children) {
6430        if (includeForAccessibility()) {
6431            children.add(this);
6432        }
6433    }
6434
6435    /**
6436     * Whether to regard this view for accessibility. A view is regarded for
6437     * accessibility if it is important for accessibility or the querying
6438     * accessibility service has explicitly requested that view not
6439     * important for accessibility are regarded.
6440     *
6441     * @return Whether to regard the view for accessibility.
6442     */
6443    boolean includeForAccessibility() {
6444        if (mAttachInfo != null) {
6445            if (!mAttachInfo.mIncludeNotImportantViews) {
6446                return isImportantForAccessibility();
6447            } else {
6448                return true;
6449            }
6450        }
6451        return false;
6452    }
6453
6454    /**
6455     * Returns whether the View is considered actionable from
6456     * accessibility perspective. Such view are important for
6457     * accessiiblity.
6458     *
6459     * @return True if the view is actionable for accessibility.
6460     */
6461    private boolean isActionableForAccessibility() {
6462        return (isClickable() || isLongClickable() || isFocusable());
6463    }
6464
6465    /**
6466     * Returns whether the View has registered callbacks wich makes it
6467     * important for accessiiblity.
6468     *
6469     * @return True if the view is actionable for accessibility.
6470     */
6471    private boolean hasListenersForAccessibility() {
6472        ListenerInfo info = getListenerInfo();
6473        return mTouchDelegate != null || info.mOnKeyListener != null
6474                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6475                || info.mOnHoverListener != null || info.mOnDragListener != null;
6476    }
6477
6478    /**
6479     * Notifies accessibility services that some view's important for
6480     * accessibility state has changed. Note that such notifications
6481     * are made at most once every
6482     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6483     * to avoid unnecessary load to the system. Also once a view has
6484     * made a notifucation this method is a NOP until the notification has
6485     * been sent to clients.
6486     *
6487     * @hide
6488     *
6489     * TODO: Makse sure this method is called for any view state change
6490     *       that is interesting for accessilility purposes.
6491     */
6492    public void notifyAccessibilityStateChanged() {
6493        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6494            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6495            if (mParent != null) {
6496                mParent.childAccessibilityStateChanged(this);
6497            }
6498        }
6499    }
6500
6501    /**
6502     * Reset the state indicating the this view has requested clients
6503     * interested in its accessiblity state to be notified.
6504     *
6505     * @hide
6506     */
6507    public void resetAccessibilityStateChanged() {
6508        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6509    }
6510
6511    /**
6512     * Performs the specified accessibility action on the view. For
6513     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6514    * <p>
6515    * If an {@link AccessibilityDelegate} has been specified via calling
6516    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6517    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6518    * is responsible for handling this call.
6519    * </p>
6520     *
6521     * @param action The action to perform.
6522     * @param arguments Optional action arguments.
6523     * @return Whether the action was performed.
6524     */
6525    public boolean performAccessibilityAction(int action, Bundle arguments) {
6526      if (mAccessibilityDelegate != null) {
6527          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6528      } else {
6529          return performAccessibilityActionInternal(action, arguments);
6530      }
6531    }
6532
6533   /**
6534    * @see #performAccessibilityAction(int, Bundle)
6535    *
6536    * Note: Called from the default {@link AccessibilityDelegate}.
6537    */
6538    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6539        switch (action) {
6540            case AccessibilityNodeInfo.ACTION_CLICK: {
6541                if (isClickable()) {
6542                    return performClick();
6543                }
6544            } break;
6545            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6546                if (isLongClickable()) {
6547                    return performLongClick();
6548                }
6549            } break;
6550            case AccessibilityNodeInfo.ACTION_FOCUS: {
6551                if (!hasFocus()) {
6552                    // Get out of touch mode since accessibility
6553                    // wants to move focus around.
6554                    getViewRootImpl().ensureTouchMode(false);
6555                    return requestFocus();
6556                }
6557            } break;
6558            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6559                if (hasFocus()) {
6560                    clearFocus();
6561                    return !isFocused();
6562                }
6563            } break;
6564            case AccessibilityNodeInfo.ACTION_SELECT: {
6565                if (!isSelected()) {
6566                    setSelected(true);
6567                    return isSelected();
6568                }
6569            } break;
6570            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6571                if (isSelected()) {
6572                    setSelected(false);
6573                    return !isSelected();
6574                }
6575            } break;
6576            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6577                if (!isAccessibilityFocused()) {
6578                    return requestAccessibilityFocus();
6579                }
6580            } break;
6581            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6582                if (isAccessibilityFocused()) {
6583                    clearAccessibilityFocus();
6584                    return true;
6585                }
6586            } break;
6587            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6588                if (arguments != null) {
6589                    final int granularity = arguments.getInt(
6590                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6591                    return nextAtGranularity(granularity);
6592                }
6593            } break;
6594            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6595                if (arguments != null) {
6596                    final int granularity = arguments.getInt(
6597                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6598                    return previousAtGranularity(granularity);
6599                }
6600            } break;
6601        }
6602        return false;
6603    }
6604
6605    private boolean nextAtGranularity(int granularity) {
6606        CharSequence text = getIterableTextForAccessibility();
6607        if (text != null && text.length() > 0) {
6608            return false;
6609        }
6610        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6611        if (iterator == null) {
6612            return false;
6613        }
6614        final int current = getAccessibilityCursorPosition();
6615        final int[] range = iterator.following(current);
6616        if (range == null) {
6617            setAccessibilityCursorPosition(-1);
6618            return false;
6619        }
6620        final int start = range[0];
6621        final int end = range[1];
6622        setAccessibilityCursorPosition(start);
6623        sendViewTextTraversedAtGranularityEvent(
6624                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6625                granularity, start, end);
6626        return true;
6627    }
6628
6629    private boolean previousAtGranularity(int granularity) {
6630        CharSequence text = getIterableTextForAccessibility();
6631        if (text != null && text.length() > 0) {
6632            return false;
6633        }
6634        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6635        if (iterator == null) {
6636            return false;
6637        }
6638        final int selectionStart = getAccessibilityCursorPosition();
6639        final int current = selectionStart >= 0 ? selectionStart : text.length() + 1;
6640        final int[] range = iterator.preceding(current);
6641        if (range == null) {
6642            setAccessibilityCursorPosition(-1);
6643            return false;
6644        }
6645        final int start = range[0];
6646        final int end = range[1];
6647        setAccessibilityCursorPosition(end);
6648        sendViewTextTraversedAtGranularityEvent(
6649                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6650                granularity, start, end);
6651        return true;
6652    }
6653
6654    /**
6655     * Gets the text reported for accessibility purposes.
6656     *
6657     * @return The accessibility text.
6658     *
6659     * @hide
6660     */
6661    public CharSequence getIterableTextForAccessibility() {
6662        return mContentDescription;
6663    }
6664
6665    /**
6666     * @hide
6667     */
6668    public int getAccessibilityCursorPosition() {
6669        return mAccessibilityCursorPosition;
6670    }
6671
6672    /**
6673     * @hide
6674     */
6675    public void setAccessibilityCursorPosition(int position) {
6676        mAccessibilityCursorPosition = position;
6677    }
6678
6679    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6680            int fromIndex, int toIndex) {
6681        if (mParent == null) {
6682            return;
6683        }
6684        AccessibilityEvent event = AccessibilityEvent.obtain(
6685                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6686        onInitializeAccessibilityEvent(event);
6687        onPopulateAccessibilityEvent(event);
6688        event.setFromIndex(fromIndex);
6689        event.setToIndex(toIndex);
6690        event.setAction(action);
6691        event.setMovementGranularity(granularity);
6692        mParent.requestSendAccessibilityEvent(this, event);
6693    }
6694
6695    /**
6696     * @hide
6697     */
6698    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6699        switch (granularity) {
6700            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6701                CharSequence text = getIterableTextForAccessibility();
6702                if (text != null && text.length() > 0) {
6703                    CharacterTextSegmentIterator iterator =
6704                        CharacterTextSegmentIterator.getInstance(mContext);
6705                    iterator.initialize(text.toString());
6706                    return iterator;
6707                }
6708            } break;
6709            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6710                CharSequence text = getIterableTextForAccessibility();
6711                if (text != null && text.length() > 0) {
6712                    WordTextSegmentIterator iterator =
6713                        WordTextSegmentIterator.getInstance(mContext);
6714                    iterator.initialize(text.toString());
6715                    return iterator;
6716                }
6717            } break;
6718            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6719                CharSequence text = getIterableTextForAccessibility();
6720                if (text != null && text.length() > 0) {
6721                    ParagraphTextSegmentIterator iterator =
6722                        ParagraphTextSegmentIterator.getInstance();
6723                    iterator.initialize(text.toString());
6724                    return iterator;
6725                }
6726            } break;
6727        }
6728        return null;
6729    }
6730
6731    /**
6732     * @hide
6733     */
6734    public void dispatchStartTemporaryDetach() {
6735        clearAccessibilityFocus();
6736        onStartTemporaryDetach();
6737    }
6738
6739    /**
6740     * This is called when a container is going to temporarily detach a child, with
6741     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6742     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6743     * {@link #onDetachedFromWindow()} when the container is done.
6744     */
6745    public void onStartTemporaryDetach() {
6746        removeUnsetPressCallback();
6747        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6748    }
6749
6750    /**
6751     * @hide
6752     */
6753    public void dispatchFinishTemporaryDetach() {
6754        onFinishTemporaryDetach();
6755    }
6756
6757    /**
6758     * Called after {@link #onStartTemporaryDetach} when the container is done
6759     * changing the view.
6760     */
6761    public void onFinishTemporaryDetach() {
6762    }
6763
6764    /**
6765     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6766     * for this view's window.  Returns null if the view is not currently attached
6767     * to the window.  Normally you will not need to use this directly, but
6768     * just use the standard high-level event callbacks like
6769     * {@link #onKeyDown(int, KeyEvent)}.
6770     */
6771    public KeyEvent.DispatcherState getKeyDispatcherState() {
6772        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6773    }
6774
6775    /**
6776     * Dispatch a key event before it is processed by any input method
6777     * associated with the view hierarchy.  This can be used to intercept
6778     * key events in special situations before the IME consumes them; a
6779     * typical example would be handling the BACK key to update the application's
6780     * UI instead of allowing the IME to see it and close itself.
6781     *
6782     * @param event The key event to be dispatched.
6783     * @return True if the event was handled, false otherwise.
6784     */
6785    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6786        return onKeyPreIme(event.getKeyCode(), event);
6787    }
6788
6789    /**
6790     * Dispatch a key event to the next view on the focus path. This path runs
6791     * from the top of the view tree down to the currently focused view. If this
6792     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6793     * the next node down the focus path. This method also fires any key
6794     * listeners.
6795     *
6796     * @param event The key event to be dispatched.
6797     * @return True if the event was handled, false otherwise.
6798     */
6799    public boolean dispatchKeyEvent(KeyEvent event) {
6800        if (mInputEventConsistencyVerifier != null) {
6801            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6802        }
6803
6804        // Give any attached key listener a first crack at the event.
6805        //noinspection SimplifiableIfStatement
6806        ListenerInfo li = mListenerInfo;
6807        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6808                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6809            return true;
6810        }
6811
6812        if (event.dispatch(this, mAttachInfo != null
6813                ? mAttachInfo.mKeyDispatchState : null, this)) {
6814            return true;
6815        }
6816
6817        if (mInputEventConsistencyVerifier != null) {
6818            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6819        }
6820        return false;
6821    }
6822
6823    /**
6824     * Dispatches a key shortcut event.
6825     *
6826     * @param event The key event to be dispatched.
6827     * @return True if the event was handled by the view, false otherwise.
6828     */
6829    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6830        return onKeyShortcut(event.getKeyCode(), event);
6831    }
6832
6833    /**
6834     * Pass the touch screen motion event down to the target view, or this
6835     * view if it is the target.
6836     *
6837     * @param event The motion event to be dispatched.
6838     * @return True if the event was handled by the view, false otherwise.
6839     */
6840    public boolean dispatchTouchEvent(MotionEvent event) {
6841        if (mInputEventConsistencyVerifier != null) {
6842            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6843        }
6844
6845        if (onFilterTouchEventForSecurity(event)) {
6846            //noinspection SimplifiableIfStatement
6847            ListenerInfo li = mListenerInfo;
6848            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6849                    && li.mOnTouchListener.onTouch(this, event)) {
6850                return true;
6851            }
6852
6853            if (onTouchEvent(event)) {
6854                return true;
6855            }
6856        }
6857
6858        if (mInputEventConsistencyVerifier != null) {
6859            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6860        }
6861        return false;
6862    }
6863
6864    /**
6865     * Filter the touch event to apply security policies.
6866     *
6867     * @param event The motion event to be filtered.
6868     * @return True if the event should be dispatched, false if the event should be dropped.
6869     *
6870     * @see #getFilterTouchesWhenObscured
6871     */
6872    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6873        //noinspection RedundantIfStatement
6874        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6875                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6876            // Window is obscured, drop this touch.
6877            return false;
6878        }
6879        return true;
6880    }
6881
6882    /**
6883     * Pass a trackball motion event down to the focused view.
6884     *
6885     * @param event The motion event to be dispatched.
6886     * @return True if the event was handled by the view, false otherwise.
6887     */
6888    public boolean dispatchTrackballEvent(MotionEvent event) {
6889        if (mInputEventConsistencyVerifier != null) {
6890            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6891        }
6892
6893        return onTrackballEvent(event);
6894    }
6895
6896    /**
6897     * Dispatch a generic motion event.
6898     * <p>
6899     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6900     * are delivered to the view under the pointer.  All other generic motion events are
6901     * delivered to the focused view.  Hover events are handled specially and are delivered
6902     * to {@link #onHoverEvent(MotionEvent)}.
6903     * </p>
6904     *
6905     * @param event The motion event to be dispatched.
6906     * @return True if the event was handled by the view, false otherwise.
6907     */
6908    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6909        if (mInputEventConsistencyVerifier != null) {
6910            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6911        }
6912
6913        final int source = event.getSource();
6914        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6915            final int action = event.getAction();
6916            if (action == MotionEvent.ACTION_HOVER_ENTER
6917                    || action == MotionEvent.ACTION_HOVER_MOVE
6918                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6919                if (dispatchHoverEvent(event)) {
6920                    return true;
6921                }
6922            } else if (dispatchGenericPointerEvent(event)) {
6923                return true;
6924            }
6925        } else if (dispatchGenericFocusedEvent(event)) {
6926            return true;
6927        }
6928
6929        if (dispatchGenericMotionEventInternal(event)) {
6930            return true;
6931        }
6932
6933        if (mInputEventConsistencyVerifier != null) {
6934            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6935        }
6936        return false;
6937    }
6938
6939    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6940        //noinspection SimplifiableIfStatement
6941        ListenerInfo li = mListenerInfo;
6942        if (li != null && li.mOnGenericMotionListener != null
6943                && (mViewFlags & ENABLED_MASK) == ENABLED
6944                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6945            return true;
6946        }
6947
6948        if (onGenericMotionEvent(event)) {
6949            return true;
6950        }
6951
6952        if (mInputEventConsistencyVerifier != null) {
6953            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6954        }
6955        return false;
6956    }
6957
6958    /**
6959     * Dispatch a hover event.
6960     * <p>
6961     * Do not call this method directly.
6962     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6963     * </p>
6964     *
6965     * @param event The motion event to be dispatched.
6966     * @return True if the event was handled by the view, false otherwise.
6967     */
6968    protected boolean dispatchHoverEvent(MotionEvent event) {
6969        //noinspection SimplifiableIfStatement
6970        ListenerInfo li = mListenerInfo;
6971        if (li != null && li.mOnHoverListener != null
6972                && (mViewFlags & ENABLED_MASK) == ENABLED
6973                && li.mOnHoverListener.onHover(this, event)) {
6974            return true;
6975        }
6976
6977        return onHoverEvent(event);
6978    }
6979
6980    /**
6981     * Returns true if the view has a child to which it has recently sent
6982     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6983     * it does not have a hovered child, then it must be the innermost hovered view.
6984     * @hide
6985     */
6986    protected boolean hasHoveredChild() {
6987        return false;
6988    }
6989
6990    /**
6991     * Dispatch a generic motion event to the view under the first pointer.
6992     * <p>
6993     * Do not call this method directly.
6994     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6995     * </p>
6996     *
6997     * @param event The motion event to be dispatched.
6998     * @return True if the event was handled by the view, false otherwise.
6999     */
7000    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7001        return false;
7002    }
7003
7004    /**
7005     * Dispatch a generic motion event to the currently focused view.
7006     * <p>
7007     * Do not call this method directly.
7008     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7009     * </p>
7010     *
7011     * @param event The motion event to be dispatched.
7012     * @return True if the event was handled by the view, false otherwise.
7013     */
7014    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7015        return false;
7016    }
7017
7018    /**
7019     * Dispatch a pointer event.
7020     * <p>
7021     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7022     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7023     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7024     * and should not be expected to handle other pointing device features.
7025     * </p>
7026     *
7027     * @param event The motion event to be dispatched.
7028     * @return True if the event was handled by the view, false otherwise.
7029     * @hide
7030     */
7031    public final boolean dispatchPointerEvent(MotionEvent event) {
7032        if (event.isTouchEvent()) {
7033            return dispatchTouchEvent(event);
7034        } else {
7035            return dispatchGenericMotionEvent(event);
7036        }
7037    }
7038
7039    /**
7040     * Called when the window containing this view gains or loses window focus.
7041     * ViewGroups should override to route to their children.
7042     *
7043     * @param hasFocus True if the window containing this view now has focus,
7044     *        false otherwise.
7045     */
7046    public void dispatchWindowFocusChanged(boolean hasFocus) {
7047        onWindowFocusChanged(hasFocus);
7048    }
7049
7050    /**
7051     * Called when the window containing this view gains or loses focus.  Note
7052     * that this is separate from view focus: to receive key events, both
7053     * your view and its window must have focus.  If a window is displayed
7054     * on top of yours that takes input focus, then your own window will lose
7055     * focus but the view focus will remain unchanged.
7056     *
7057     * @param hasWindowFocus True if the window containing this view now has
7058     *        focus, false otherwise.
7059     */
7060    public void onWindowFocusChanged(boolean hasWindowFocus) {
7061        InputMethodManager imm = InputMethodManager.peekInstance();
7062        if (!hasWindowFocus) {
7063            if (isPressed()) {
7064                setPressed(false);
7065            }
7066            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7067                imm.focusOut(this);
7068            }
7069            removeLongPressCallback();
7070            removeTapCallback();
7071            onFocusLost();
7072        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7073            imm.focusIn(this);
7074        }
7075        refreshDrawableState();
7076    }
7077
7078    /**
7079     * Returns true if this view is in a window that currently has window focus.
7080     * Note that this is not the same as the view itself having focus.
7081     *
7082     * @return True if this view is in a window that currently has window focus.
7083     */
7084    public boolean hasWindowFocus() {
7085        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7086    }
7087
7088    /**
7089     * Dispatch a view visibility change down the view hierarchy.
7090     * ViewGroups should override to route to their children.
7091     * @param changedView The view whose visibility changed. Could be 'this' or
7092     * an ancestor view.
7093     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7094     * {@link #INVISIBLE} or {@link #GONE}.
7095     */
7096    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7097        onVisibilityChanged(changedView, visibility);
7098    }
7099
7100    /**
7101     * Called when the visibility of the view or an ancestor of the view is changed.
7102     * @param changedView The view whose visibility changed. Could be 'this' or
7103     * an ancestor view.
7104     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7105     * {@link #INVISIBLE} or {@link #GONE}.
7106     */
7107    protected void onVisibilityChanged(View changedView, int visibility) {
7108        if (visibility == VISIBLE) {
7109            if (mAttachInfo != null) {
7110                initialAwakenScrollBars();
7111            } else {
7112                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7113            }
7114        }
7115    }
7116
7117    /**
7118     * Dispatch a hint about whether this view is displayed. For instance, when
7119     * a View moves out of the screen, it might receives a display hint indicating
7120     * the view is not displayed. Applications should not <em>rely</em> on this hint
7121     * as there is no guarantee that they will receive one.
7122     *
7123     * @param hint A hint about whether or not this view is displayed:
7124     * {@link #VISIBLE} or {@link #INVISIBLE}.
7125     */
7126    public void dispatchDisplayHint(int hint) {
7127        onDisplayHint(hint);
7128    }
7129
7130    /**
7131     * Gives this view a hint about whether is displayed or not. For instance, when
7132     * a View moves out of the screen, it might receives a display hint indicating
7133     * the view is not displayed. Applications should not <em>rely</em> on this hint
7134     * as there is no guarantee that they will receive one.
7135     *
7136     * @param hint A hint about whether or not this view is displayed:
7137     * {@link #VISIBLE} or {@link #INVISIBLE}.
7138     */
7139    protected void onDisplayHint(int hint) {
7140    }
7141
7142    /**
7143     * Dispatch a window visibility change down the view hierarchy.
7144     * ViewGroups should override to route to their children.
7145     *
7146     * @param visibility The new visibility of the window.
7147     *
7148     * @see #onWindowVisibilityChanged(int)
7149     */
7150    public void dispatchWindowVisibilityChanged(int visibility) {
7151        onWindowVisibilityChanged(visibility);
7152    }
7153
7154    /**
7155     * Called when the window containing has change its visibility
7156     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7157     * that this tells you whether or not your window is being made visible
7158     * to the window manager; this does <em>not</em> tell you whether or not
7159     * your window is obscured by other windows on the screen, even if it
7160     * is itself visible.
7161     *
7162     * @param visibility The new visibility of the window.
7163     */
7164    protected void onWindowVisibilityChanged(int visibility) {
7165        if (visibility == VISIBLE) {
7166            initialAwakenScrollBars();
7167        }
7168    }
7169
7170    /**
7171     * Returns the current visibility of the window this view is attached to
7172     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7173     *
7174     * @return Returns the current visibility of the view's window.
7175     */
7176    public int getWindowVisibility() {
7177        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7178    }
7179
7180    /**
7181     * Retrieve the overall visible display size in which the window this view is
7182     * attached to has been positioned in.  This takes into account screen
7183     * decorations above the window, for both cases where the window itself
7184     * is being position inside of them or the window is being placed under
7185     * then and covered insets are used for the window to position its content
7186     * inside.  In effect, this tells you the available area where content can
7187     * be placed and remain visible to users.
7188     *
7189     * <p>This function requires an IPC back to the window manager to retrieve
7190     * the requested information, so should not be used in performance critical
7191     * code like drawing.
7192     *
7193     * @param outRect Filled in with the visible display frame.  If the view
7194     * is not attached to a window, this is simply the raw display size.
7195     */
7196    public void getWindowVisibleDisplayFrame(Rect outRect) {
7197        if (mAttachInfo != null) {
7198            try {
7199                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7200            } catch (RemoteException e) {
7201                return;
7202            }
7203            // XXX This is really broken, and probably all needs to be done
7204            // in the window manager, and we need to know more about whether
7205            // we want the area behind or in front of the IME.
7206            final Rect insets = mAttachInfo.mVisibleInsets;
7207            outRect.left += insets.left;
7208            outRect.top += insets.top;
7209            outRect.right -= insets.right;
7210            outRect.bottom -= insets.bottom;
7211            return;
7212        }
7213        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7214        d.getRectSize(outRect);
7215    }
7216
7217    /**
7218     * Dispatch a notification about a resource configuration change down
7219     * the view hierarchy.
7220     * ViewGroups should override to route to their children.
7221     *
7222     * @param newConfig The new resource configuration.
7223     *
7224     * @see #onConfigurationChanged(android.content.res.Configuration)
7225     */
7226    public void dispatchConfigurationChanged(Configuration newConfig) {
7227        onConfigurationChanged(newConfig);
7228    }
7229
7230    /**
7231     * Called when the current configuration of the resources being used
7232     * by the application have changed.  You can use this to decide when
7233     * to reload resources that can changed based on orientation and other
7234     * configuration characterstics.  You only need to use this if you are
7235     * not relying on the normal {@link android.app.Activity} mechanism of
7236     * recreating the activity instance upon a configuration change.
7237     *
7238     * @param newConfig The new resource configuration.
7239     */
7240    protected void onConfigurationChanged(Configuration newConfig) {
7241    }
7242
7243    /**
7244     * Private function to aggregate all per-view attributes in to the view
7245     * root.
7246     */
7247    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7248        performCollectViewAttributes(attachInfo, visibility);
7249    }
7250
7251    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7252        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7253            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7254                attachInfo.mKeepScreenOn = true;
7255            }
7256            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7257            ListenerInfo li = mListenerInfo;
7258            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7259                attachInfo.mHasSystemUiListeners = true;
7260            }
7261        }
7262    }
7263
7264    void needGlobalAttributesUpdate(boolean force) {
7265        final AttachInfo ai = mAttachInfo;
7266        if (ai != null) {
7267            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7268                    || ai.mHasSystemUiListeners) {
7269                ai.mRecomputeGlobalAttributes = true;
7270            }
7271        }
7272    }
7273
7274    /**
7275     * Returns whether the device is currently in touch mode.  Touch mode is entered
7276     * once the user begins interacting with the device by touch, and affects various
7277     * things like whether focus is always visible to the user.
7278     *
7279     * @return Whether the device is in touch mode.
7280     */
7281    @ViewDebug.ExportedProperty
7282    public boolean isInTouchMode() {
7283        if (mAttachInfo != null) {
7284            return mAttachInfo.mInTouchMode;
7285        } else {
7286            return ViewRootImpl.isInTouchMode();
7287        }
7288    }
7289
7290    /**
7291     * Returns the context the view is running in, through which it can
7292     * access the current theme, resources, etc.
7293     *
7294     * @return The view's Context.
7295     */
7296    @ViewDebug.CapturedViewProperty
7297    public final Context getContext() {
7298        return mContext;
7299    }
7300
7301    /**
7302     * Handle a key event before it is processed by any input method
7303     * associated with the view hierarchy.  This can be used to intercept
7304     * key events in special situations before the IME consumes them; a
7305     * typical example would be handling the BACK key to update the application's
7306     * UI instead of allowing the IME to see it and close itself.
7307     *
7308     * @param keyCode The value in event.getKeyCode().
7309     * @param event Description of the key event.
7310     * @return If you handled the event, return true. If you want to allow the
7311     *         event to be handled by the next receiver, return false.
7312     */
7313    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7314        return false;
7315    }
7316
7317    /**
7318     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7319     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7320     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7321     * is released, if the view is enabled and clickable.
7322     *
7323     * @param keyCode A key code that represents the button pressed, from
7324     *                {@link android.view.KeyEvent}.
7325     * @param event   The KeyEvent object that defines the button action.
7326     */
7327    public boolean onKeyDown(int keyCode, KeyEvent event) {
7328        boolean result = false;
7329
7330        switch (keyCode) {
7331            case KeyEvent.KEYCODE_DPAD_CENTER:
7332            case KeyEvent.KEYCODE_ENTER: {
7333                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7334                    return true;
7335                }
7336                // Long clickable items don't necessarily have to be clickable
7337                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7338                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7339                        (event.getRepeatCount() == 0)) {
7340                    setPressed(true);
7341                    checkForLongClick(0);
7342                    return true;
7343                }
7344                break;
7345            }
7346        }
7347        return result;
7348    }
7349
7350    /**
7351     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7352     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7353     * the event).
7354     */
7355    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7356        return false;
7357    }
7358
7359    /**
7360     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7361     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7362     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7363     * {@link KeyEvent#KEYCODE_ENTER} is released.
7364     *
7365     * @param keyCode A key code that represents the button pressed, from
7366     *                {@link android.view.KeyEvent}.
7367     * @param event   The KeyEvent object that defines the button action.
7368     */
7369    public boolean onKeyUp(int keyCode, KeyEvent event) {
7370        boolean result = false;
7371
7372        switch (keyCode) {
7373            case KeyEvent.KEYCODE_DPAD_CENTER:
7374            case KeyEvent.KEYCODE_ENTER: {
7375                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7376                    return true;
7377                }
7378                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7379                    setPressed(false);
7380
7381                    if (!mHasPerformedLongPress) {
7382                        // This is a tap, so remove the longpress check
7383                        removeLongPressCallback();
7384
7385                        result = performClick();
7386                    }
7387                }
7388                break;
7389            }
7390        }
7391        return result;
7392    }
7393
7394    /**
7395     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7396     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7397     * the event).
7398     *
7399     * @param keyCode     A key code that represents the button pressed, from
7400     *                    {@link android.view.KeyEvent}.
7401     * @param repeatCount The number of times the action was made.
7402     * @param event       The KeyEvent object that defines the button action.
7403     */
7404    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7405        return false;
7406    }
7407
7408    /**
7409     * Called on the focused view when a key shortcut event is not handled.
7410     * Override this method to implement local key shortcuts for the View.
7411     * Key shortcuts can also be implemented by setting the
7412     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7413     *
7414     * @param keyCode The value in event.getKeyCode().
7415     * @param event Description of the key event.
7416     * @return If you handled the event, return true. If you want to allow the
7417     *         event to be handled by the next receiver, return false.
7418     */
7419    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7420        return false;
7421    }
7422
7423    /**
7424     * Check whether the called view is a text editor, in which case it
7425     * would make sense to automatically display a soft input window for
7426     * it.  Subclasses should override this if they implement
7427     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7428     * a call on that method would return a non-null InputConnection, and
7429     * they are really a first-class editor that the user would normally
7430     * start typing on when the go into a window containing your view.
7431     *
7432     * <p>The default implementation always returns false.  This does
7433     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7434     * will not be called or the user can not otherwise perform edits on your
7435     * view; it is just a hint to the system that this is not the primary
7436     * purpose of this view.
7437     *
7438     * @return Returns true if this view is a text editor, else false.
7439     */
7440    public boolean onCheckIsTextEditor() {
7441        return false;
7442    }
7443
7444    /**
7445     * Create a new InputConnection for an InputMethod to interact
7446     * with the view.  The default implementation returns null, since it doesn't
7447     * support input methods.  You can override this to implement such support.
7448     * This is only needed for views that take focus and text input.
7449     *
7450     * <p>When implementing this, you probably also want to implement
7451     * {@link #onCheckIsTextEditor()} to indicate you will return a
7452     * non-null InputConnection.
7453     *
7454     * @param outAttrs Fill in with attribute information about the connection.
7455     */
7456    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7457        return null;
7458    }
7459
7460    /**
7461     * Called by the {@link android.view.inputmethod.InputMethodManager}
7462     * when a view who is not the current
7463     * input connection target is trying to make a call on the manager.  The
7464     * default implementation returns false; you can override this to return
7465     * true for certain views if you are performing InputConnection proxying
7466     * to them.
7467     * @param view The View that is making the InputMethodManager call.
7468     * @return Return true to allow the call, false to reject.
7469     */
7470    public boolean checkInputConnectionProxy(View view) {
7471        return false;
7472    }
7473
7474    /**
7475     * Show the context menu for this view. It is not safe to hold on to the
7476     * menu after returning from this method.
7477     *
7478     * You should normally not overload this method. Overload
7479     * {@link #onCreateContextMenu(ContextMenu)} or define an
7480     * {@link OnCreateContextMenuListener} to add items to the context menu.
7481     *
7482     * @param menu The context menu to populate
7483     */
7484    public void createContextMenu(ContextMenu menu) {
7485        ContextMenuInfo menuInfo = getContextMenuInfo();
7486
7487        // Sets the current menu info so all items added to menu will have
7488        // my extra info set.
7489        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7490
7491        onCreateContextMenu(menu);
7492        ListenerInfo li = mListenerInfo;
7493        if (li != null && li.mOnCreateContextMenuListener != null) {
7494            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7495        }
7496
7497        // Clear the extra information so subsequent items that aren't mine don't
7498        // have my extra info.
7499        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7500
7501        if (mParent != null) {
7502            mParent.createContextMenu(menu);
7503        }
7504    }
7505
7506    /**
7507     * Views should implement this if they have extra information to associate
7508     * with the context menu. The return result is supplied as a parameter to
7509     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7510     * callback.
7511     *
7512     * @return Extra information about the item for which the context menu
7513     *         should be shown. This information will vary across different
7514     *         subclasses of View.
7515     */
7516    protected ContextMenuInfo getContextMenuInfo() {
7517        return null;
7518    }
7519
7520    /**
7521     * Views should implement this if the view itself is going to add items to
7522     * the context menu.
7523     *
7524     * @param menu the context menu to populate
7525     */
7526    protected void onCreateContextMenu(ContextMenu menu) {
7527    }
7528
7529    /**
7530     * Implement this method to handle trackball motion events.  The
7531     * <em>relative</em> movement of the trackball since the last event
7532     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7533     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7534     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7535     * they will often be fractional values, representing the more fine-grained
7536     * movement information available from a trackball).
7537     *
7538     * @param event The motion event.
7539     * @return True if the event was handled, false otherwise.
7540     */
7541    public boolean onTrackballEvent(MotionEvent event) {
7542        return false;
7543    }
7544
7545    /**
7546     * Implement this method to handle generic motion events.
7547     * <p>
7548     * Generic motion events describe joystick movements, mouse hovers, track pad
7549     * touches, scroll wheel movements and other input events.  The
7550     * {@link MotionEvent#getSource() source} of the motion event specifies
7551     * the class of input that was received.  Implementations of this method
7552     * must examine the bits in the source before processing the event.
7553     * The following code example shows how this is done.
7554     * </p><p>
7555     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7556     * are delivered to the view under the pointer.  All other generic motion events are
7557     * delivered to the focused view.
7558     * </p>
7559     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7560     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7561     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7562     *             // process the joystick movement...
7563     *             return true;
7564     *         }
7565     *     }
7566     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7567     *         switch (event.getAction()) {
7568     *             case MotionEvent.ACTION_HOVER_MOVE:
7569     *                 // process the mouse hover movement...
7570     *                 return true;
7571     *             case MotionEvent.ACTION_SCROLL:
7572     *                 // process the scroll wheel movement...
7573     *                 return true;
7574     *         }
7575     *     }
7576     *     return super.onGenericMotionEvent(event);
7577     * }</pre>
7578     *
7579     * @param event The generic motion event being processed.
7580     * @return True if the event was handled, false otherwise.
7581     */
7582    public boolean onGenericMotionEvent(MotionEvent event) {
7583        return false;
7584    }
7585
7586    /**
7587     * Implement this method to handle hover events.
7588     * <p>
7589     * This method is called whenever a pointer is hovering into, over, or out of the
7590     * bounds of a view and the view is not currently being touched.
7591     * Hover events are represented as pointer events with action
7592     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7593     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7594     * </p>
7595     * <ul>
7596     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7597     * when the pointer enters the bounds of the view.</li>
7598     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7599     * when the pointer has already entered the bounds of the view and has moved.</li>
7600     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7601     * when the pointer has exited the bounds of the view or when the pointer is
7602     * about to go down due to a button click, tap, or similar user action that
7603     * causes the view to be touched.</li>
7604     * </ul>
7605     * <p>
7606     * The view should implement this method to return true to indicate that it is
7607     * handling the hover event, such as by changing its drawable state.
7608     * </p><p>
7609     * The default implementation calls {@link #setHovered} to update the hovered state
7610     * of the view when a hover enter or hover exit event is received, if the view
7611     * is enabled and is clickable.  The default implementation also sends hover
7612     * accessibility events.
7613     * </p>
7614     *
7615     * @param event The motion event that describes the hover.
7616     * @return True if the view handled the hover event.
7617     *
7618     * @see #isHovered
7619     * @see #setHovered
7620     * @see #onHoverChanged
7621     */
7622    public boolean onHoverEvent(MotionEvent event) {
7623        // The root view may receive hover (or touch) events that are outside the bounds of
7624        // the window.  This code ensures that we only send accessibility events for
7625        // hovers that are actually within the bounds of the root view.
7626        final int action = event.getActionMasked();
7627        if (!mSendingHoverAccessibilityEvents) {
7628            if ((action == MotionEvent.ACTION_HOVER_ENTER
7629                    || action == MotionEvent.ACTION_HOVER_MOVE)
7630                    && !hasHoveredChild()
7631                    && pointInView(event.getX(), event.getY())) {
7632                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7633                mSendingHoverAccessibilityEvents = true;
7634                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7635            }
7636        } else {
7637            if (action == MotionEvent.ACTION_HOVER_EXIT
7638                    || (action == MotionEvent.ACTION_MOVE
7639                            && !pointInView(event.getX(), event.getY()))) {
7640                mSendingHoverAccessibilityEvents = false;
7641                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7642                // If the window does not have input focus we take away accessibility
7643                // focus as soon as the user stop hovering over the view.
7644                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7645                    getViewRootImpl().setAccessibilityFocusedHost(null);
7646                }
7647            }
7648        }
7649
7650        if (isHoverable()) {
7651            switch (action) {
7652                case MotionEvent.ACTION_HOVER_ENTER:
7653                    setHovered(true);
7654                    break;
7655                case MotionEvent.ACTION_HOVER_EXIT:
7656                    setHovered(false);
7657                    break;
7658            }
7659
7660            // Dispatch the event to onGenericMotionEvent before returning true.
7661            // This is to provide compatibility with existing applications that
7662            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7663            // break because of the new default handling for hoverable views
7664            // in onHoverEvent.
7665            // Note that onGenericMotionEvent will be called by default when
7666            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7667            dispatchGenericMotionEventInternal(event);
7668            return true;
7669        }
7670
7671        return false;
7672    }
7673
7674    /**
7675     * Returns true if the view should handle {@link #onHoverEvent}
7676     * by calling {@link #setHovered} to change its hovered state.
7677     *
7678     * @return True if the view is hoverable.
7679     */
7680    private boolean isHoverable() {
7681        final int viewFlags = mViewFlags;
7682        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7683            return false;
7684        }
7685
7686        return (viewFlags & CLICKABLE) == CLICKABLE
7687                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7688    }
7689
7690    /**
7691     * Returns true if the view is currently hovered.
7692     *
7693     * @return True if the view is currently hovered.
7694     *
7695     * @see #setHovered
7696     * @see #onHoverChanged
7697     */
7698    @ViewDebug.ExportedProperty
7699    public boolean isHovered() {
7700        return (mPrivateFlags & HOVERED) != 0;
7701    }
7702
7703    /**
7704     * Sets whether the view is currently hovered.
7705     * <p>
7706     * Calling this method also changes the drawable state of the view.  This
7707     * enables the view to react to hover by using different drawable resources
7708     * to change its appearance.
7709     * </p><p>
7710     * The {@link #onHoverChanged} method is called when the hovered state changes.
7711     * </p>
7712     *
7713     * @param hovered True if the view is hovered.
7714     *
7715     * @see #isHovered
7716     * @see #onHoverChanged
7717     */
7718    public void setHovered(boolean hovered) {
7719        if (hovered) {
7720            if ((mPrivateFlags & HOVERED) == 0) {
7721                mPrivateFlags |= HOVERED;
7722                refreshDrawableState();
7723                onHoverChanged(true);
7724            }
7725        } else {
7726            if ((mPrivateFlags & HOVERED) != 0) {
7727                mPrivateFlags &= ~HOVERED;
7728                refreshDrawableState();
7729                onHoverChanged(false);
7730            }
7731        }
7732    }
7733
7734    /**
7735     * Implement this method to handle hover state changes.
7736     * <p>
7737     * This method is called whenever the hover state changes as a result of a
7738     * call to {@link #setHovered}.
7739     * </p>
7740     *
7741     * @param hovered The current hover state, as returned by {@link #isHovered}.
7742     *
7743     * @see #isHovered
7744     * @see #setHovered
7745     */
7746    public void onHoverChanged(boolean hovered) {
7747    }
7748
7749    /**
7750     * Implement this method to handle touch screen motion events.
7751     *
7752     * @param event The motion event.
7753     * @return True if the event was handled, false otherwise.
7754     */
7755    public boolean onTouchEvent(MotionEvent event) {
7756        final int viewFlags = mViewFlags;
7757
7758        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7759            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7760                setPressed(false);
7761            }
7762            // A disabled view that is clickable still consumes the touch
7763            // events, it just doesn't respond to them.
7764            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7765                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7766        }
7767
7768        if (mTouchDelegate != null) {
7769            if (mTouchDelegate.onTouchEvent(event)) {
7770                return true;
7771            }
7772        }
7773
7774        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7775                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7776            switch (event.getAction()) {
7777                case MotionEvent.ACTION_UP:
7778                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7779                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7780                        // take focus if we don't have it already and we should in
7781                        // touch mode.
7782                        boolean focusTaken = false;
7783                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7784                            focusTaken = requestFocus();
7785                        }
7786
7787                        if (prepressed) {
7788                            // The button is being released before we actually
7789                            // showed it as pressed.  Make it show the pressed
7790                            // state now (before scheduling the click) to ensure
7791                            // the user sees it.
7792                            setPressed(true);
7793                       }
7794
7795                        if (!mHasPerformedLongPress) {
7796                            // This is a tap, so remove the longpress check
7797                            removeLongPressCallback();
7798
7799                            // Only perform take click actions if we were in the pressed state
7800                            if (!focusTaken) {
7801                                // Use a Runnable and post this rather than calling
7802                                // performClick directly. This lets other visual state
7803                                // of the view update before click actions start.
7804                                if (mPerformClick == null) {
7805                                    mPerformClick = new PerformClick();
7806                                }
7807                                if (!post(mPerformClick)) {
7808                                    performClick();
7809                                }
7810                            }
7811                        }
7812
7813                        if (mUnsetPressedState == null) {
7814                            mUnsetPressedState = new UnsetPressedState();
7815                        }
7816
7817                        if (prepressed) {
7818                            postDelayed(mUnsetPressedState,
7819                                    ViewConfiguration.getPressedStateDuration());
7820                        } else if (!post(mUnsetPressedState)) {
7821                            // If the post failed, unpress right now
7822                            mUnsetPressedState.run();
7823                        }
7824                        removeTapCallback();
7825                    }
7826                    break;
7827
7828                case MotionEvent.ACTION_DOWN:
7829                    mHasPerformedLongPress = false;
7830
7831                    if (performButtonActionOnTouchDown(event)) {
7832                        break;
7833                    }
7834
7835                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7836                    boolean isInScrollingContainer = isInScrollingContainer();
7837
7838                    // For views inside a scrolling container, delay the pressed feedback for
7839                    // a short period in case this is a scroll.
7840                    if (isInScrollingContainer) {
7841                        mPrivateFlags |= PREPRESSED;
7842                        if (mPendingCheckForTap == null) {
7843                            mPendingCheckForTap = new CheckForTap();
7844                        }
7845                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7846                    } else {
7847                        // Not inside a scrolling container, so show the feedback right away
7848                        setPressed(true);
7849                        checkForLongClick(0);
7850                    }
7851                    break;
7852
7853                case MotionEvent.ACTION_CANCEL:
7854                    setPressed(false);
7855                    removeTapCallback();
7856                    break;
7857
7858                case MotionEvent.ACTION_MOVE:
7859                    final int x = (int) event.getX();
7860                    final int y = (int) event.getY();
7861
7862                    // Be lenient about moving outside of buttons
7863                    if (!pointInView(x, y, mTouchSlop)) {
7864                        // Outside button
7865                        removeTapCallback();
7866                        if ((mPrivateFlags & PRESSED) != 0) {
7867                            // Remove any future long press/tap checks
7868                            removeLongPressCallback();
7869
7870                            setPressed(false);
7871                        }
7872                    }
7873                    break;
7874            }
7875            return true;
7876        }
7877
7878        return false;
7879    }
7880
7881    /**
7882     * @hide
7883     */
7884    public boolean isInScrollingContainer() {
7885        ViewParent p = getParent();
7886        while (p != null && p instanceof ViewGroup) {
7887            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7888                return true;
7889            }
7890            p = p.getParent();
7891        }
7892        return false;
7893    }
7894
7895    /**
7896     * Remove the longpress detection timer.
7897     */
7898    private void removeLongPressCallback() {
7899        if (mPendingCheckForLongPress != null) {
7900          removeCallbacks(mPendingCheckForLongPress);
7901        }
7902    }
7903
7904    /**
7905     * Remove the pending click action
7906     */
7907    private void removePerformClickCallback() {
7908        if (mPerformClick != null) {
7909            removeCallbacks(mPerformClick);
7910        }
7911    }
7912
7913    /**
7914     * Remove the prepress detection timer.
7915     */
7916    private void removeUnsetPressCallback() {
7917        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7918            setPressed(false);
7919            removeCallbacks(mUnsetPressedState);
7920        }
7921    }
7922
7923    /**
7924     * Remove the tap detection timer.
7925     */
7926    private void removeTapCallback() {
7927        if (mPendingCheckForTap != null) {
7928            mPrivateFlags &= ~PREPRESSED;
7929            removeCallbacks(mPendingCheckForTap);
7930        }
7931    }
7932
7933    /**
7934     * Cancels a pending long press.  Your subclass can use this if you
7935     * want the context menu to come up if the user presses and holds
7936     * at the same place, but you don't want it to come up if they press
7937     * and then move around enough to cause scrolling.
7938     */
7939    public void cancelLongPress() {
7940        removeLongPressCallback();
7941
7942        /*
7943         * The prepressed state handled by the tap callback is a display
7944         * construct, but the tap callback will post a long press callback
7945         * less its own timeout. Remove it here.
7946         */
7947        removeTapCallback();
7948    }
7949
7950    /**
7951     * Remove the pending callback for sending a
7952     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7953     */
7954    private void removeSendViewScrolledAccessibilityEventCallback() {
7955        if (mSendViewScrolledAccessibilityEvent != null) {
7956            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7957        }
7958    }
7959
7960    /**
7961     * Sets the TouchDelegate for this View.
7962     */
7963    public void setTouchDelegate(TouchDelegate delegate) {
7964        mTouchDelegate = delegate;
7965    }
7966
7967    /**
7968     * Gets the TouchDelegate for this View.
7969     */
7970    public TouchDelegate getTouchDelegate() {
7971        return mTouchDelegate;
7972    }
7973
7974    /**
7975     * Set flags controlling behavior of this view.
7976     *
7977     * @param flags Constant indicating the value which should be set
7978     * @param mask Constant indicating the bit range that should be changed
7979     */
7980    void setFlags(int flags, int mask) {
7981        int old = mViewFlags;
7982        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7983
7984        int changed = mViewFlags ^ old;
7985        if (changed == 0) {
7986            return;
7987        }
7988        int privateFlags = mPrivateFlags;
7989
7990        /* Check if the FOCUSABLE bit has changed */
7991        if (((changed & FOCUSABLE_MASK) != 0) &&
7992                ((privateFlags & HAS_BOUNDS) !=0)) {
7993            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7994                    && ((privateFlags & FOCUSED) != 0)) {
7995                /* Give up focus if we are no longer focusable */
7996                clearFocus();
7997            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7998                    && ((privateFlags & FOCUSED) == 0)) {
7999                /*
8000                 * Tell the view system that we are now available to take focus
8001                 * if no one else already has it.
8002                 */
8003                if (mParent != null) mParent.focusableViewAvailable(this);
8004            }
8005            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8006                notifyAccessibilityStateChanged();
8007            }
8008        }
8009
8010        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8011            if ((changed & VISIBILITY_MASK) != 0) {
8012                /*
8013                 * If this view is becoming visible, invalidate it in case it changed while
8014                 * it was not visible. Marking it drawn ensures that the invalidation will
8015                 * go through.
8016                 */
8017                mPrivateFlags |= DRAWN;
8018                invalidate(true);
8019
8020                needGlobalAttributesUpdate(true);
8021
8022                // a view becoming visible is worth notifying the parent
8023                // about in case nothing has focus.  even if this specific view
8024                // isn't focusable, it may contain something that is, so let
8025                // the root view try to give this focus if nothing else does.
8026                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8027                    mParent.focusableViewAvailable(this);
8028                }
8029            }
8030        }
8031
8032        /* Check if the GONE bit has changed */
8033        if ((changed & GONE) != 0) {
8034            needGlobalAttributesUpdate(false);
8035            requestLayout();
8036
8037            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8038                if (hasFocus()) clearFocus();
8039                clearAccessibilityFocus();
8040                destroyDrawingCache();
8041                if (mParent instanceof View) {
8042                    // GONE views noop invalidation, so invalidate the parent
8043                    ((View) mParent).invalidate(true);
8044                }
8045                // Mark the view drawn to ensure that it gets invalidated properly the next
8046                // time it is visible and gets invalidated
8047                mPrivateFlags |= DRAWN;
8048            }
8049            if (mAttachInfo != null) {
8050                mAttachInfo.mViewVisibilityChanged = true;
8051            }
8052        }
8053
8054        /* Check if the VISIBLE bit has changed */
8055        if ((changed & INVISIBLE) != 0) {
8056            needGlobalAttributesUpdate(false);
8057            /*
8058             * If this view is becoming invisible, set the DRAWN flag so that
8059             * the next invalidate() will not be skipped.
8060             */
8061            mPrivateFlags |= DRAWN;
8062
8063            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8064                // root view becoming invisible shouldn't clear focus and accessibility focus
8065                if (getRootView() != this) {
8066                    clearFocus();
8067                    clearAccessibilityFocus();
8068                }
8069            }
8070            if (mAttachInfo != null) {
8071                mAttachInfo.mViewVisibilityChanged = true;
8072            }
8073        }
8074
8075        if ((changed & VISIBILITY_MASK) != 0) {
8076            if (mParent instanceof ViewGroup) {
8077                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8078                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8079                ((View) mParent).invalidate(true);
8080            } else if (mParent != null) {
8081                mParent.invalidateChild(this, null);
8082            }
8083            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8084        }
8085
8086        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8087            destroyDrawingCache();
8088        }
8089
8090        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8091            destroyDrawingCache();
8092            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8093            invalidateParentCaches();
8094        }
8095
8096        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8097            destroyDrawingCache();
8098            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8099        }
8100
8101        if ((changed & DRAW_MASK) != 0) {
8102            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8103                if (mBackground != null) {
8104                    mPrivateFlags &= ~SKIP_DRAW;
8105                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8106                } else {
8107                    mPrivateFlags |= SKIP_DRAW;
8108                }
8109            } else {
8110                mPrivateFlags &= ~SKIP_DRAW;
8111            }
8112            requestLayout();
8113            invalidate(true);
8114        }
8115
8116        if ((changed & KEEP_SCREEN_ON) != 0) {
8117            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8118                mParent.recomputeViewAttributes(this);
8119            }
8120        }
8121
8122        if (AccessibilityManager.getInstance(mContext).isEnabled()
8123                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8124                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8125            notifyAccessibilityStateChanged();
8126        }
8127    }
8128
8129    /**
8130     * Change the view's z order in the tree, so it's on top of other sibling
8131     * views
8132     */
8133    public void bringToFront() {
8134        if (mParent != null) {
8135            mParent.bringChildToFront(this);
8136        }
8137    }
8138
8139    /**
8140     * This is called in response to an internal scroll in this view (i.e., the
8141     * view scrolled its own contents). This is typically as a result of
8142     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8143     * called.
8144     *
8145     * @param l Current horizontal scroll origin.
8146     * @param t Current vertical scroll origin.
8147     * @param oldl Previous horizontal scroll origin.
8148     * @param oldt Previous vertical scroll origin.
8149     */
8150    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8151        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8152            postSendViewScrolledAccessibilityEventCallback();
8153        }
8154
8155        mBackgroundSizeChanged = true;
8156
8157        final AttachInfo ai = mAttachInfo;
8158        if (ai != null) {
8159            ai.mViewScrollChanged = true;
8160        }
8161    }
8162
8163    /**
8164     * Interface definition for a callback to be invoked when the layout bounds of a view
8165     * changes due to layout processing.
8166     */
8167    public interface OnLayoutChangeListener {
8168        /**
8169         * Called when the focus state of a view has changed.
8170         *
8171         * @param v The view whose state has changed.
8172         * @param left The new value of the view's left property.
8173         * @param top The new value of the view's top property.
8174         * @param right The new value of the view's right property.
8175         * @param bottom The new value of the view's bottom property.
8176         * @param oldLeft The previous value of the view's left property.
8177         * @param oldTop The previous value of the view's top property.
8178         * @param oldRight The previous value of the view's right property.
8179         * @param oldBottom The previous value of the view's bottom property.
8180         */
8181        void onLayoutChange(View v, int left, int top, int right, int bottom,
8182            int oldLeft, int oldTop, int oldRight, int oldBottom);
8183    }
8184
8185    /**
8186     * This is called during layout when the size of this view has changed. If
8187     * you were just added to the view hierarchy, you're called with the old
8188     * values of 0.
8189     *
8190     * @param w Current width of this view.
8191     * @param h Current height of this view.
8192     * @param oldw Old width of this view.
8193     * @param oldh Old height of this view.
8194     */
8195    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8196    }
8197
8198    /**
8199     * Called by draw to draw the child views. This may be overridden
8200     * by derived classes to gain control just before its children are drawn
8201     * (but after its own view has been drawn).
8202     * @param canvas the canvas on which to draw the view
8203     */
8204    protected void dispatchDraw(Canvas canvas) {
8205
8206    }
8207
8208    /**
8209     * Gets the parent of this view. Note that the parent is a
8210     * ViewParent and not necessarily a View.
8211     *
8212     * @return Parent of this view.
8213     */
8214    public final ViewParent getParent() {
8215        return mParent;
8216    }
8217
8218    /**
8219     * Set the horizontal scrolled position of your view. This will cause a call to
8220     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8221     * invalidated.
8222     * @param value the x position to scroll to
8223     */
8224    public void setScrollX(int value) {
8225        scrollTo(value, mScrollY);
8226    }
8227
8228    /**
8229     * Set the vertical scrolled position of your view. This will cause a call to
8230     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8231     * invalidated.
8232     * @param value the y position to scroll to
8233     */
8234    public void setScrollY(int value) {
8235        scrollTo(mScrollX, value);
8236    }
8237
8238    /**
8239     * Return the scrolled left position of this view. This is the left edge of
8240     * the displayed part of your view. You do not need to draw any pixels
8241     * farther left, since those are outside of the frame of your view on
8242     * screen.
8243     *
8244     * @return The left edge of the displayed part of your view, in pixels.
8245     */
8246    public final int getScrollX() {
8247        return mScrollX;
8248    }
8249
8250    /**
8251     * Return the scrolled top position of this view. This is the top edge of
8252     * the displayed part of your view. You do not need to draw any pixels above
8253     * it, since those are outside of the frame of your view on screen.
8254     *
8255     * @return The top edge of the displayed part of your view, in pixels.
8256     */
8257    public final int getScrollY() {
8258        return mScrollY;
8259    }
8260
8261    /**
8262     * Return the width of the your view.
8263     *
8264     * @return The width of your view, in pixels.
8265     */
8266    @ViewDebug.ExportedProperty(category = "layout")
8267    public final int getWidth() {
8268        return mRight - mLeft;
8269    }
8270
8271    /**
8272     * Return the height of your view.
8273     *
8274     * @return The height of your view, in pixels.
8275     */
8276    @ViewDebug.ExportedProperty(category = "layout")
8277    public final int getHeight() {
8278        return mBottom - mTop;
8279    }
8280
8281    /**
8282     * Return the visible drawing bounds of your view. Fills in the output
8283     * rectangle with the values from getScrollX(), getScrollY(),
8284     * getWidth(), and getHeight().
8285     *
8286     * @param outRect The (scrolled) drawing bounds of the view.
8287     */
8288    public void getDrawingRect(Rect outRect) {
8289        outRect.left = mScrollX;
8290        outRect.top = mScrollY;
8291        outRect.right = mScrollX + (mRight - mLeft);
8292        outRect.bottom = mScrollY + (mBottom - mTop);
8293    }
8294
8295    /**
8296     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8297     * raw width component (that is the result is masked by
8298     * {@link #MEASURED_SIZE_MASK}).
8299     *
8300     * @return The raw measured width of this view.
8301     */
8302    public final int getMeasuredWidth() {
8303        return mMeasuredWidth & MEASURED_SIZE_MASK;
8304    }
8305
8306    /**
8307     * Return the full width measurement information for this view as computed
8308     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8309     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8310     * This should be used during measurement and layout calculations only. Use
8311     * {@link #getWidth()} to see how wide a view is after layout.
8312     *
8313     * @return The measured width of this view as a bit mask.
8314     */
8315    public final int getMeasuredWidthAndState() {
8316        return mMeasuredWidth;
8317    }
8318
8319    /**
8320     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8321     * raw width component (that is the result is masked by
8322     * {@link #MEASURED_SIZE_MASK}).
8323     *
8324     * @return The raw measured height of this view.
8325     */
8326    public final int getMeasuredHeight() {
8327        return mMeasuredHeight & MEASURED_SIZE_MASK;
8328    }
8329
8330    /**
8331     * Return the full height measurement information for this view as computed
8332     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8333     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8334     * This should be used during measurement and layout calculations only. Use
8335     * {@link #getHeight()} to see how wide a view is after layout.
8336     *
8337     * @return The measured width of this view as a bit mask.
8338     */
8339    public final int getMeasuredHeightAndState() {
8340        return mMeasuredHeight;
8341    }
8342
8343    /**
8344     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8345     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8346     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8347     * and the height component is at the shifted bits
8348     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8349     */
8350    public final int getMeasuredState() {
8351        return (mMeasuredWidth&MEASURED_STATE_MASK)
8352                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8353                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8354    }
8355
8356    /**
8357     * The transform matrix of this view, which is calculated based on the current
8358     * roation, scale, and pivot properties.
8359     *
8360     * @see #getRotation()
8361     * @see #getScaleX()
8362     * @see #getScaleY()
8363     * @see #getPivotX()
8364     * @see #getPivotY()
8365     * @return The current transform matrix for the view
8366     */
8367    public Matrix getMatrix() {
8368        if (mTransformationInfo != null) {
8369            updateMatrix();
8370            return mTransformationInfo.mMatrix;
8371        }
8372        return Matrix.IDENTITY_MATRIX;
8373    }
8374
8375    /**
8376     * Utility function to determine if the value is far enough away from zero to be
8377     * considered non-zero.
8378     * @param value A floating point value to check for zero-ness
8379     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8380     */
8381    private static boolean nonzero(float value) {
8382        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8383    }
8384
8385    /**
8386     * Returns true if the transform matrix is the identity matrix.
8387     * Recomputes the matrix if necessary.
8388     *
8389     * @return True if the transform matrix is the identity matrix, false otherwise.
8390     */
8391    final boolean hasIdentityMatrix() {
8392        if (mTransformationInfo != null) {
8393            updateMatrix();
8394            return mTransformationInfo.mMatrixIsIdentity;
8395        }
8396        return true;
8397    }
8398
8399    void ensureTransformationInfo() {
8400        if (mTransformationInfo == null) {
8401            mTransformationInfo = new TransformationInfo();
8402        }
8403    }
8404
8405    /**
8406     * Recomputes the transform matrix if necessary.
8407     */
8408    private void updateMatrix() {
8409        final TransformationInfo info = mTransformationInfo;
8410        if (info == null) {
8411            return;
8412        }
8413        if (info.mMatrixDirty) {
8414            // transform-related properties have changed since the last time someone
8415            // asked for the matrix; recalculate it with the current values
8416
8417            // Figure out if we need to update the pivot point
8418            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8419                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8420                    info.mPrevWidth = mRight - mLeft;
8421                    info.mPrevHeight = mBottom - mTop;
8422                    info.mPivotX = info.mPrevWidth / 2f;
8423                    info.mPivotY = info.mPrevHeight / 2f;
8424                }
8425            }
8426            info.mMatrix.reset();
8427            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8428                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8429                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8430                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8431            } else {
8432                if (info.mCamera == null) {
8433                    info.mCamera = new Camera();
8434                    info.matrix3D = new Matrix();
8435                }
8436                info.mCamera.save();
8437                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8438                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8439                info.mCamera.getMatrix(info.matrix3D);
8440                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8441                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8442                        info.mPivotY + info.mTranslationY);
8443                info.mMatrix.postConcat(info.matrix3D);
8444                info.mCamera.restore();
8445            }
8446            info.mMatrixDirty = false;
8447            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8448            info.mInverseMatrixDirty = true;
8449        }
8450    }
8451
8452    /**
8453     * Utility method to retrieve the inverse of the current mMatrix property.
8454     * We cache the matrix to avoid recalculating it when transform properties
8455     * have not changed.
8456     *
8457     * @return The inverse of the current matrix of this view.
8458     */
8459    final Matrix getInverseMatrix() {
8460        final TransformationInfo info = mTransformationInfo;
8461        if (info != null) {
8462            updateMatrix();
8463            if (info.mInverseMatrixDirty) {
8464                if (info.mInverseMatrix == null) {
8465                    info.mInverseMatrix = new Matrix();
8466                }
8467                info.mMatrix.invert(info.mInverseMatrix);
8468                info.mInverseMatrixDirty = false;
8469            }
8470            return info.mInverseMatrix;
8471        }
8472        return Matrix.IDENTITY_MATRIX;
8473    }
8474
8475    /**
8476     * Gets the distance along the Z axis from the camera to this view.
8477     *
8478     * @see #setCameraDistance(float)
8479     *
8480     * @return The distance along the Z axis.
8481     */
8482    public float getCameraDistance() {
8483        ensureTransformationInfo();
8484        final float dpi = mResources.getDisplayMetrics().densityDpi;
8485        final TransformationInfo info = mTransformationInfo;
8486        if (info.mCamera == null) {
8487            info.mCamera = new Camera();
8488            info.matrix3D = new Matrix();
8489        }
8490        return -(info.mCamera.getLocationZ() * dpi);
8491    }
8492
8493    /**
8494     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8495     * views are drawn) from the camera to this view. The camera's distance
8496     * affects 3D transformations, for instance rotations around the X and Y
8497     * axis. If the rotationX or rotationY properties are changed and this view is
8498     * large (more than half the size of the screen), it is recommended to always
8499     * use a camera distance that's greater than the height (X axis rotation) or
8500     * the width (Y axis rotation) of this view.</p>
8501     *
8502     * <p>The distance of the camera from the view plane can have an affect on the
8503     * perspective distortion of the view when it is rotated around the x or y axis.
8504     * For example, a large distance will result in a large viewing angle, and there
8505     * will not be much perspective distortion of the view as it rotates. A short
8506     * distance may cause much more perspective distortion upon rotation, and can
8507     * also result in some drawing artifacts if the rotated view ends up partially
8508     * behind the camera (which is why the recommendation is to use a distance at
8509     * least as far as the size of the view, if the view is to be rotated.)</p>
8510     *
8511     * <p>The distance is expressed in "depth pixels." The default distance depends
8512     * on the screen density. For instance, on a medium density display, the
8513     * default distance is 1280. On a high density display, the default distance
8514     * is 1920.</p>
8515     *
8516     * <p>If you want to specify a distance that leads to visually consistent
8517     * results across various densities, use the following formula:</p>
8518     * <pre>
8519     * float scale = context.getResources().getDisplayMetrics().density;
8520     * view.setCameraDistance(distance * scale);
8521     * </pre>
8522     *
8523     * <p>The density scale factor of a high density display is 1.5,
8524     * and 1920 = 1280 * 1.5.</p>
8525     *
8526     * @param distance The distance in "depth pixels", if negative the opposite
8527     *        value is used
8528     *
8529     * @see #setRotationX(float)
8530     * @see #setRotationY(float)
8531     */
8532    public void setCameraDistance(float distance) {
8533        invalidateViewProperty(true, false);
8534
8535        ensureTransformationInfo();
8536        final float dpi = mResources.getDisplayMetrics().densityDpi;
8537        final TransformationInfo info = mTransformationInfo;
8538        if (info.mCamera == null) {
8539            info.mCamera = new Camera();
8540            info.matrix3D = new Matrix();
8541        }
8542
8543        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8544        info.mMatrixDirty = true;
8545
8546        invalidateViewProperty(false, false);
8547        if (mDisplayList != null) {
8548            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8549        }
8550    }
8551
8552    /**
8553     * The degrees that the view is rotated around the pivot point.
8554     *
8555     * @see #setRotation(float)
8556     * @see #getPivotX()
8557     * @see #getPivotY()
8558     *
8559     * @return The degrees of rotation.
8560     */
8561    @ViewDebug.ExportedProperty(category = "drawing")
8562    public float getRotation() {
8563        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8564    }
8565
8566    /**
8567     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8568     * result in clockwise rotation.
8569     *
8570     * @param rotation The degrees of rotation.
8571     *
8572     * @see #getRotation()
8573     * @see #getPivotX()
8574     * @see #getPivotY()
8575     * @see #setRotationX(float)
8576     * @see #setRotationY(float)
8577     *
8578     * @attr ref android.R.styleable#View_rotation
8579     */
8580    public void setRotation(float rotation) {
8581        ensureTransformationInfo();
8582        final TransformationInfo info = mTransformationInfo;
8583        if (info.mRotation != rotation) {
8584            // Double-invalidation is necessary to capture view's old and new areas
8585            invalidateViewProperty(true, false);
8586            info.mRotation = rotation;
8587            info.mMatrixDirty = true;
8588            invalidateViewProperty(false, true);
8589            if (mDisplayList != null) {
8590                mDisplayList.setRotation(rotation);
8591            }
8592        }
8593    }
8594
8595    /**
8596     * The degrees that the view is rotated around the vertical axis through the pivot point.
8597     *
8598     * @see #getPivotX()
8599     * @see #getPivotY()
8600     * @see #setRotationY(float)
8601     *
8602     * @return The degrees of Y rotation.
8603     */
8604    @ViewDebug.ExportedProperty(category = "drawing")
8605    public float getRotationY() {
8606        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8607    }
8608
8609    /**
8610     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8611     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8612     * down the y axis.
8613     *
8614     * When rotating large views, it is recommended to adjust the camera distance
8615     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8616     *
8617     * @param rotationY The degrees of Y rotation.
8618     *
8619     * @see #getRotationY()
8620     * @see #getPivotX()
8621     * @see #getPivotY()
8622     * @see #setRotation(float)
8623     * @see #setRotationX(float)
8624     * @see #setCameraDistance(float)
8625     *
8626     * @attr ref android.R.styleable#View_rotationY
8627     */
8628    public void setRotationY(float rotationY) {
8629        ensureTransformationInfo();
8630        final TransformationInfo info = mTransformationInfo;
8631        if (info.mRotationY != rotationY) {
8632            invalidateViewProperty(true, false);
8633            info.mRotationY = rotationY;
8634            info.mMatrixDirty = true;
8635            invalidateViewProperty(false, true);
8636            if (mDisplayList != null) {
8637                mDisplayList.setRotationY(rotationY);
8638            }
8639        }
8640    }
8641
8642    /**
8643     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8644     *
8645     * @see #getPivotX()
8646     * @see #getPivotY()
8647     * @see #setRotationX(float)
8648     *
8649     * @return The degrees of X rotation.
8650     */
8651    @ViewDebug.ExportedProperty(category = "drawing")
8652    public float getRotationX() {
8653        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8654    }
8655
8656    /**
8657     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8658     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8659     * x axis.
8660     *
8661     * When rotating large views, it is recommended to adjust the camera distance
8662     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8663     *
8664     * @param rotationX The degrees of X rotation.
8665     *
8666     * @see #getRotationX()
8667     * @see #getPivotX()
8668     * @see #getPivotY()
8669     * @see #setRotation(float)
8670     * @see #setRotationY(float)
8671     * @see #setCameraDistance(float)
8672     *
8673     * @attr ref android.R.styleable#View_rotationX
8674     */
8675    public void setRotationX(float rotationX) {
8676        ensureTransformationInfo();
8677        final TransformationInfo info = mTransformationInfo;
8678        if (info.mRotationX != rotationX) {
8679            invalidateViewProperty(true, false);
8680            info.mRotationX = rotationX;
8681            info.mMatrixDirty = true;
8682            invalidateViewProperty(false, true);
8683            if (mDisplayList != null) {
8684                mDisplayList.setRotationX(rotationX);
8685            }
8686        }
8687    }
8688
8689    /**
8690     * The amount that the view is scaled in x around the pivot point, as a proportion of
8691     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8692     *
8693     * <p>By default, this is 1.0f.
8694     *
8695     * @see #getPivotX()
8696     * @see #getPivotY()
8697     * @return The scaling factor.
8698     */
8699    @ViewDebug.ExportedProperty(category = "drawing")
8700    public float getScaleX() {
8701        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8702    }
8703
8704    /**
8705     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8706     * the view's unscaled width. A value of 1 means that no scaling is applied.
8707     *
8708     * @param scaleX The scaling factor.
8709     * @see #getPivotX()
8710     * @see #getPivotY()
8711     *
8712     * @attr ref android.R.styleable#View_scaleX
8713     */
8714    public void setScaleX(float scaleX) {
8715        ensureTransformationInfo();
8716        final TransformationInfo info = mTransformationInfo;
8717        if (info.mScaleX != scaleX) {
8718            invalidateViewProperty(true, false);
8719            info.mScaleX = scaleX;
8720            info.mMatrixDirty = true;
8721            invalidateViewProperty(false, true);
8722            if (mDisplayList != null) {
8723                mDisplayList.setScaleX(scaleX);
8724            }
8725        }
8726    }
8727
8728    /**
8729     * The amount that the view is scaled in y around the pivot point, as a proportion of
8730     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8731     *
8732     * <p>By default, this is 1.0f.
8733     *
8734     * @see #getPivotX()
8735     * @see #getPivotY()
8736     * @return The scaling factor.
8737     */
8738    @ViewDebug.ExportedProperty(category = "drawing")
8739    public float getScaleY() {
8740        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8741    }
8742
8743    /**
8744     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8745     * the view's unscaled width. A value of 1 means that no scaling is applied.
8746     *
8747     * @param scaleY The scaling factor.
8748     * @see #getPivotX()
8749     * @see #getPivotY()
8750     *
8751     * @attr ref android.R.styleable#View_scaleY
8752     */
8753    public void setScaleY(float scaleY) {
8754        ensureTransformationInfo();
8755        final TransformationInfo info = mTransformationInfo;
8756        if (info.mScaleY != scaleY) {
8757            invalidateViewProperty(true, false);
8758            info.mScaleY = scaleY;
8759            info.mMatrixDirty = true;
8760            invalidateViewProperty(false, true);
8761            if (mDisplayList != null) {
8762                mDisplayList.setScaleY(scaleY);
8763            }
8764        }
8765    }
8766
8767    /**
8768     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8769     * and {@link #setScaleX(float) scaled}.
8770     *
8771     * @see #getRotation()
8772     * @see #getScaleX()
8773     * @see #getScaleY()
8774     * @see #getPivotY()
8775     * @return The x location of the pivot point.
8776     *
8777     * @attr ref android.R.styleable#View_transformPivotX
8778     */
8779    @ViewDebug.ExportedProperty(category = "drawing")
8780    public float getPivotX() {
8781        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8782    }
8783
8784    /**
8785     * Sets the x location of the point around which the view is
8786     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8787     * By default, the pivot point is centered on the object.
8788     * Setting this property disables this behavior and causes the view to use only the
8789     * explicitly set pivotX and pivotY values.
8790     *
8791     * @param pivotX The x location of the pivot point.
8792     * @see #getRotation()
8793     * @see #getScaleX()
8794     * @see #getScaleY()
8795     * @see #getPivotY()
8796     *
8797     * @attr ref android.R.styleable#View_transformPivotX
8798     */
8799    public void setPivotX(float pivotX) {
8800        ensureTransformationInfo();
8801        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8802        final TransformationInfo info = mTransformationInfo;
8803        if (info.mPivotX != pivotX) {
8804            invalidateViewProperty(true, false);
8805            info.mPivotX = pivotX;
8806            info.mMatrixDirty = true;
8807            invalidateViewProperty(false, true);
8808            if (mDisplayList != null) {
8809                mDisplayList.setPivotX(pivotX);
8810            }
8811        }
8812    }
8813
8814    /**
8815     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8816     * and {@link #setScaleY(float) scaled}.
8817     *
8818     * @see #getRotation()
8819     * @see #getScaleX()
8820     * @see #getScaleY()
8821     * @see #getPivotY()
8822     * @return The y location of the pivot point.
8823     *
8824     * @attr ref android.R.styleable#View_transformPivotY
8825     */
8826    @ViewDebug.ExportedProperty(category = "drawing")
8827    public float getPivotY() {
8828        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8829    }
8830
8831    /**
8832     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8833     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8834     * Setting this property disables this behavior and causes the view to use only the
8835     * explicitly set pivotX and pivotY values.
8836     *
8837     * @param pivotY The y location of the pivot point.
8838     * @see #getRotation()
8839     * @see #getScaleX()
8840     * @see #getScaleY()
8841     * @see #getPivotY()
8842     *
8843     * @attr ref android.R.styleable#View_transformPivotY
8844     */
8845    public void setPivotY(float pivotY) {
8846        ensureTransformationInfo();
8847        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8848        final TransformationInfo info = mTransformationInfo;
8849        if (info.mPivotY != pivotY) {
8850            invalidateViewProperty(true, false);
8851            info.mPivotY = pivotY;
8852            info.mMatrixDirty = true;
8853            invalidateViewProperty(false, true);
8854            if (mDisplayList != null) {
8855                mDisplayList.setPivotY(pivotY);
8856            }
8857        }
8858    }
8859
8860    /**
8861     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8862     * completely transparent and 1 means the view is completely opaque.
8863     *
8864     * <p>By default this is 1.0f.
8865     * @return The opacity of the view.
8866     */
8867    @ViewDebug.ExportedProperty(category = "drawing")
8868    public float getAlpha() {
8869        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8870    }
8871
8872    /**
8873     * Returns whether this View has content which overlaps. This function, intended to be
8874     * overridden by specific View types, is an optimization when alpha is set on a view. If
8875     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8876     * and then composited it into place, which can be expensive. If the view has no overlapping
8877     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8878     * An example of overlapping rendering is a TextView with a background image, such as a
8879     * Button. An example of non-overlapping rendering is a TextView with no background, or
8880     * an ImageView with only the foreground image. The default implementation returns true;
8881     * subclasses should override if they have cases which can be optimized.
8882     *
8883     * @return true if the content in this view might overlap, false otherwise.
8884     */
8885    public boolean hasOverlappingRendering() {
8886        return true;
8887    }
8888
8889    /**
8890     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8891     * completely transparent and 1 means the view is completely opaque.</p>
8892     *
8893     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8894     * responsible for applying the opacity itself. Otherwise, calling this method is
8895     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8896     * setting a hardware layer.</p>
8897     *
8898     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8899     * performance implications. It is generally best to use the alpha property sparingly and
8900     * transiently, as in the case of fading animations.</p>
8901     *
8902     * @param alpha The opacity of the view.
8903     *
8904     * @see #setLayerType(int, android.graphics.Paint)
8905     *
8906     * @attr ref android.R.styleable#View_alpha
8907     */
8908    public void setAlpha(float alpha) {
8909        ensureTransformationInfo();
8910        if (mTransformationInfo.mAlpha != alpha) {
8911            mTransformationInfo.mAlpha = alpha;
8912            if (onSetAlpha((int) (alpha * 255))) {
8913                mPrivateFlags |= ALPHA_SET;
8914                // subclass is handling alpha - don't optimize rendering cache invalidation
8915                invalidateParentCaches();
8916                invalidate(true);
8917            } else {
8918                mPrivateFlags &= ~ALPHA_SET;
8919                invalidateViewProperty(true, false);
8920                if (mDisplayList != null) {
8921                    mDisplayList.setAlpha(alpha);
8922                }
8923            }
8924        }
8925    }
8926
8927    /**
8928     * Faster version of setAlpha() which performs the same steps except there are
8929     * no calls to invalidate(). The caller of this function should perform proper invalidation
8930     * on the parent and this object. The return value indicates whether the subclass handles
8931     * alpha (the return value for onSetAlpha()).
8932     *
8933     * @param alpha The new value for the alpha property
8934     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8935     *         the new value for the alpha property is different from the old value
8936     */
8937    boolean setAlphaNoInvalidation(float alpha) {
8938        ensureTransformationInfo();
8939        if (mTransformationInfo.mAlpha != alpha) {
8940            mTransformationInfo.mAlpha = alpha;
8941            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8942            if (subclassHandlesAlpha) {
8943                mPrivateFlags |= ALPHA_SET;
8944                return true;
8945            } else {
8946                mPrivateFlags &= ~ALPHA_SET;
8947                if (mDisplayList != null) {
8948                    mDisplayList.setAlpha(alpha);
8949                }
8950            }
8951        }
8952        return false;
8953    }
8954
8955    /**
8956     * Top position of this view relative to its parent.
8957     *
8958     * @return The top of this view, in pixels.
8959     */
8960    @ViewDebug.CapturedViewProperty
8961    public final int getTop() {
8962        return mTop;
8963    }
8964
8965    /**
8966     * Sets the top position of this view relative to its parent. This method is meant to be called
8967     * by the layout system and should not generally be called otherwise, because the property
8968     * may be changed at any time by the layout.
8969     *
8970     * @param top The top of this view, in pixels.
8971     */
8972    public final void setTop(int top) {
8973        if (top != mTop) {
8974            updateMatrix();
8975            final boolean matrixIsIdentity = mTransformationInfo == null
8976                    || mTransformationInfo.mMatrixIsIdentity;
8977            if (matrixIsIdentity) {
8978                if (mAttachInfo != null) {
8979                    int minTop;
8980                    int yLoc;
8981                    if (top < mTop) {
8982                        minTop = top;
8983                        yLoc = top - mTop;
8984                    } else {
8985                        minTop = mTop;
8986                        yLoc = 0;
8987                    }
8988                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8989                }
8990            } else {
8991                // Double-invalidation is necessary to capture view's old and new areas
8992                invalidate(true);
8993            }
8994
8995            int width = mRight - mLeft;
8996            int oldHeight = mBottom - mTop;
8997
8998            mTop = top;
8999            if (mDisplayList != null) {
9000                mDisplayList.setTop(mTop);
9001            }
9002
9003            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9004
9005            if (!matrixIsIdentity) {
9006                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9007                    // A change in dimension means an auto-centered pivot point changes, too
9008                    mTransformationInfo.mMatrixDirty = true;
9009                }
9010                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9011                invalidate(true);
9012            }
9013            mBackgroundSizeChanged = true;
9014            invalidateParentIfNeeded();
9015        }
9016    }
9017
9018    /**
9019     * Bottom position of this view relative to its parent.
9020     *
9021     * @return The bottom of this view, in pixels.
9022     */
9023    @ViewDebug.CapturedViewProperty
9024    public final int getBottom() {
9025        return mBottom;
9026    }
9027
9028    /**
9029     * True if this view has changed since the last time being drawn.
9030     *
9031     * @return The dirty state of this view.
9032     */
9033    public boolean isDirty() {
9034        return (mPrivateFlags & DIRTY_MASK) != 0;
9035    }
9036
9037    /**
9038     * Sets the bottom position of this view relative to its parent. This method is meant to be
9039     * called by the layout system and should not generally be called otherwise, because the
9040     * property may be changed at any time by the layout.
9041     *
9042     * @param bottom The bottom of this view, in pixels.
9043     */
9044    public final void setBottom(int bottom) {
9045        if (bottom != mBottom) {
9046            updateMatrix();
9047            final boolean matrixIsIdentity = mTransformationInfo == null
9048                    || mTransformationInfo.mMatrixIsIdentity;
9049            if (matrixIsIdentity) {
9050                if (mAttachInfo != null) {
9051                    int maxBottom;
9052                    if (bottom < mBottom) {
9053                        maxBottom = mBottom;
9054                    } else {
9055                        maxBottom = bottom;
9056                    }
9057                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9058                }
9059            } else {
9060                // Double-invalidation is necessary to capture view's old and new areas
9061                invalidate(true);
9062            }
9063
9064            int width = mRight - mLeft;
9065            int oldHeight = mBottom - mTop;
9066
9067            mBottom = bottom;
9068            if (mDisplayList != null) {
9069                mDisplayList.setBottom(mBottom);
9070            }
9071
9072            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9073
9074            if (!matrixIsIdentity) {
9075                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9076                    // A change in dimension means an auto-centered pivot point changes, too
9077                    mTransformationInfo.mMatrixDirty = true;
9078                }
9079                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9080                invalidate(true);
9081            }
9082            mBackgroundSizeChanged = true;
9083            invalidateParentIfNeeded();
9084        }
9085    }
9086
9087    /**
9088     * Left position of this view relative to its parent.
9089     *
9090     * @return The left edge of this view, in pixels.
9091     */
9092    @ViewDebug.CapturedViewProperty
9093    public final int getLeft() {
9094        return mLeft;
9095    }
9096
9097    /**
9098     * Sets the left position of this view relative to its parent. This method is meant to be called
9099     * by the layout system and should not generally be called otherwise, because the property
9100     * may be changed at any time by the layout.
9101     *
9102     * @param left The bottom of this view, in pixels.
9103     */
9104    public final void setLeft(int left) {
9105        if (left != mLeft) {
9106            updateMatrix();
9107            final boolean matrixIsIdentity = mTransformationInfo == null
9108                    || mTransformationInfo.mMatrixIsIdentity;
9109            if (matrixIsIdentity) {
9110                if (mAttachInfo != null) {
9111                    int minLeft;
9112                    int xLoc;
9113                    if (left < mLeft) {
9114                        minLeft = left;
9115                        xLoc = left - mLeft;
9116                    } else {
9117                        minLeft = mLeft;
9118                        xLoc = 0;
9119                    }
9120                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9121                }
9122            } else {
9123                // Double-invalidation is necessary to capture view's old and new areas
9124                invalidate(true);
9125            }
9126
9127            int oldWidth = mRight - mLeft;
9128            int height = mBottom - mTop;
9129
9130            mLeft = left;
9131            if (mDisplayList != null) {
9132                mDisplayList.setLeft(left);
9133            }
9134
9135            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9136
9137            if (!matrixIsIdentity) {
9138                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9139                    // A change in dimension means an auto-centered pivot point changes, too
9140                    mTransformationInfo.mMatrixDirty = true;
9141                }
9142                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9143                invalidate(true);
9144            }
9145            mBackgroundSizeChanged = true;
9146            invalidateParentIfNeeded();
9147        }
9148    }
9149
9150    /**
9151     * Right position of this view relative to its parent.
9152     *
9153     * @return The right edge of this view, in pixels.
9154     */
9155    @ViewDebug.CapturedViewProperty
9156    public final int getRight() {
9157        return mRight;
9158    }
9159
9160    /**
9161     * Sets the right position of this view relative to its parent. This method is meant to be called
9162     * by the layout system and should not generally be called otherwise, because the property
9163     * may be changed at any time by the layout.
9164     *
9165     * @param right The bottom of this view, in pixels.
9166     */
9167    public final void setRight(int right) {
9168        if (right != mRight) {
9169            updateMatrix();
9170            final boolean matrixIsIdentity = mTransformationInfo == null
9171                    || mTransformationInfo.mMatrixIsIdentity;
9172            if (matrixIsIdentity) {
9173                if (mAttachInfo != null) {
9174                    int maxRight;
9175                    if (right < mRight) {
9176                        maxRight = mRight;
9177                    } else {
9178                        maxRight = right;
9179                    }
9180                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9181                }
9182            } else {
9183                // Double-invalidation is necessary to capture view's old and new areas
9184                invalidate(true);
9185            }
9186
9187            int oldWidth = mRight - mLeft;
9188            int height = mBottom - mTop;
9189
9190            mRight = right;
9191            if (mDisplayList != null) {
9192                mDisplayList.setRight(mRight);
9193            }
9194
9195            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9196
9197            if (!matrixIsIdentity) {
9198                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9199                    // A change in dimension means an auto-centered pivot point changes, too
9200                    mTransformationInfo.mMatrixDirty = true;
9201                }
9202                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9203                invalidate(true);
9204            }
9205            mBackgroundSizeChanged = true;
9206            invalidateParentIfNeeded();
9207        }
9208    }
9209
9210    /**
9211     * The visual x position of this view, in pixels. This is equivalent to the
9212     * {@link #setTranslationX(float) translationX} property plus the current
9213     * {@link #getLeft() left} property.
9214     *
9215     * @return The visual x position of this view, in pixels.
9216     */
9217    @ViewDebug.ExportedProperty(category = "drawing")
9218    public float getX() {
9219        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9220    }
9221
9222    /**
9223     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9224     * {@link #setTranslationX(float) translationX} property to be the difference between
9225     * the x value passed in and the current {@link #getLeft() left} property.
9226     *
9227     * @param x The visual x position of this view, in pixels.
9228     */
9229    public void setX(float x) {
9230        setTranslationX(x - mLeft);
9231    }
9232
9233    /**
9234     * The visual y position of this view, in pixels. This is equivalent to the
9235     * {@link #setTranslationY(float) translationY} property plus the current
9236     * {@link #getTop() top} property.
9237     *
9238     * @return The visual y position of this view, in pixels.
9239     */
9240    @ViewDebug.ExportedProperty(category = "drawing")
9241    public float getY() {
9242        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9243    }
9244
9245    /**
9246     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9247     * {@link #setTranslationY(float) translationY} property to be the difference between
9248     * the y value passed in and the current {@link #getTop() top} property.
9249     *
9250     * @param y The visual y position of this view, in pixels.
9251     */
9252    public void setY(float y) {
9253        setTranslationY(y - mTop);
9254    }
9255
9256
9257    /**
9258     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9259     * This position is post-layout, in addition to wherever the object's
9260     * layout placed it.
9261     *
9262     * @return The horizontal position of this view relative to its left position, in pixels.
9263     */
9264    @ViewDebug.ExportedProperty(category = "drawing")
9265    public float getTranslationX() {
9266        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9267    }
9268
9269    /**
9270     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9271     * This effectively positions the object post-layout, in addition to wherever the object's
9272     * layout placed it.
9273     *
9274     * @param translationX The horizontal position of this view relative to its left position,
9275     * in pixels.
9276     *
9277     * @attr ref android.R.styleable#View_translationX
9278     */
9279    public void setTranslationX(float translationX) {
9280        ensureTransformationInfo();
9281        final TransformationInfo info = mTransformationInfo;
9282        if (info.mTranslationX != translationX) {
9283            // Double-invalidation is necessary to capture view's old and new areas
9284            invalidateViewProperty(true, false);
9285            info.mTranslationX = translationX;
9286            info.mMatrixDirty = true;
9287            invalidateViewProperty(false, true);
9288            if (mDisplayList != null) {
9289                mDisplayList.setTranslationX(translationX);
9290            }
9291        }
9292    }
9293
9294    /**
9295     * The horizontal location of this view relative to its {@link #getTop() top} position.
9296     * This position is post-layout, in addition to wherever the object's
9297     * layout placed it.
9298     *
9299     * @return The vertical position of this view relative to its top position,
9300     * in pixels.
9301     */
9302    @ViewDebug.ExportedProperty(category = "drawing")
9303    public float getTranslationY() {
9304        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9305    }
9306
9307    /**
9308     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9309     * This effectively positions the object post-layout, in addition to wherever the object's
9310     * layout placed it.
9311     *
9312     * @param translationY The vertical position of this view relative to its top position,
9313     * in pixels.
9314     *
9315     * @attr ref android.R.styleable#View_translationY
9316     */
9317    public void setTranslationY(float translationY) {
9318        ensureTransformationInfo();
9319        final TransformationInfo info = mTransformationInfo;
9320        if (info.mTranslationY != translationY) {
9321            invalidateViewProperty(true, false);
9322            info.mTranslationY = translationY;
9323            info.mMatrixDirty = true;
9324            invalidateViewProperty(false, true);
9325            if (mDisplayList != null) {
9326                mDisplayList.setTranslationY(translationY);
9327            }
9328        }
9329    }
9330
9331    /**
9332     * Hit rectangle in parent's coordinates
9333     *
9334     * @param outRect The hit rectangle of the view.
9335     */
9336    public void getHitRect(Rect outRect) {
9337        updateMatrix();
9338        final TransformationInfo info = mTransformationInfo;
9339        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9340            outRect.set(mLeft, mTop, mRight, mBottom);
9341        } else {
9342            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9343            tmpRect.set(-info.mPivotX, -info.mPivotY,
9344                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9345            info.mMatrix.mapRect(tmpRect);
9346            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9347                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9348        }
9349    }
9350
9351    /**
9352     * Determines whether the given point, in local coordinates is inside the view.
9353     */
9354    /*package*/ final boolean pointInView(float localX, float localY) {
9355        return localX >= 0 && localX < (mRight - mLeft)
9356                && localY >= 0 && localY < (mBottom - mTop);
9357    }
9358
9359    /**
9360     * Utility method to determine whether the given point, in local coordinates,
9361     * is inside the view, where the area of the view is expanded by the slop factor.
9362     * This method is called while processing touch-move events to determine if the event
9363     * is still within the view.
9364     */
9365    private boolean pointInView(float localX, float localY, float slop) {
9366        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9367                localY < ((mBottom - mTop) + slop);
9368    }
9369
9370    /**
9371     * When a view has focus and the user navigates away from it, the next view is searched for
9372     * starting from the rectangle filled in by this method.
9373     *
9374     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9375     * of the view.  However, if your view maintains some idea of internal selection,
9376     * such as a cursor, or a selected row or column, you should override this method and
9377     * fill in a more specific rectangle.
9378     *
9379     * @param r The rectangle to fill in, in this view's coordinates.
9380     */
9381    public void getFocusedRect(Rect r) {
9382        getDrawingRect(r);
9383    }
9384
9385    /**
9386     * If some part of this view is not clipped by any of its parents, then
9387     * return that area in r in global (root) coordinates. To convert r to local
9388     * coordinates (without taking possible View rotations into account), offset
9389     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9390     * If the view is completely clipped or translated out, return false.
9391     *
9392     * @param r If true is returned, r holds the global coordinates of the
9393     *        visible portion of this view.
9394     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9395     *        between this view and its root. globalOffet may be null.
9396     * @return true if r is non-empty (i.e. part of the view is visible at the
9397     *         root level.
9398     */
9399    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9400        int width = mRight - mLeft;
9401        int height = mBottom - mTop;
9402        if (width > 0 && height > 0) {
9403            r.set(0, 0, width, height);
9404            if (globalOffset != null) {
9405                globalOffset.set(-mScrollX, -mScrollY);
9406            }
9407            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9408        }
9409        return false;
9410    }
9411
9412    public final boolean getGlobalVisibleRect(Rect r) {
9413        return getGlobalVisibleRect(r, null);
9414    }
9415
9416    public final boolean getLocalVisibleRect(Rect r) {
9417        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9418        if (getGlobalVisibleRect(r, offset)) {
9419            r.offset(-offset.x, -offset.y); // make r local
9420            return true;
9421        }
9422        return false;
9423    }
9424
9425    /**
9426     * Offset this view's vertical location by the specified number of pixels.
9427     *
9428     * @param offset the number of pixels to offset the view by
9429     */
9430    public void offsetTopAndBottom(int offset) {
9431        if (offset != 0) {
9432            updateMatrix();
9433            final boolean matrixIsIdentity = mTransformationInfo == null
9434                    || mTransformationInfo.mMatrixIsIdentity;
9435            if (matrixIsIdentity) {
9436                if (mDisplayList != null) {
9437                    invalidateViewProperty(false, false);
9438                } else {
9439                    final ViewParent p = mParent;
9440                    if (p != null && mAttachInfo != null) {
9441                        final Rect r = mAttachInfo.mTmpInvalRect;
9442                        int minTop;
9443                        int maxBottom;
9444                        int yLoc;
9445                        if (offset < 0) {
9446                            minTop = mTop + offset;
9447                            maxBottom = mBottom;
9448                            yLoc = offset;
9449                        } else {
9450                            minTop = mTop;
9451                            maxBottom = mBottom + offset;
9452                            yLoc = 0;
9453                        }
9454                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9455                        p.invalidateChild(this, r);
9456                    }
9457                }
9458            } else {
9459                invalidateViewProperty(false, false);
9460            }
9461
9462            mTop += offset;
9463            mBottom += offset;
9464            if (mDisplayList != null) {
9465                mDisplayList.offsetTopBottom(offset);
9466                invalidateViewProperty(false, false);
9467            } else {
9468                if (!matrixIsIdentity) {
9469                    invalidateViewProperty(false, true);
9470                }
9471                invalidateParentIfNeeded();
9472            }
9473        }
9474    }
9475
9476    /**
9477     * Offset this view's horizontal location by the specified amount of pixels.
9478     *
9479     * @param offset the numer of pixels to offset the view by
9480     */
9481    public void offsetLeftAndRight(int offset) {
9482        if (offset != 0) {
9483            updateMatrix();
9484            final boolean matrixIsIdentity = mTransformationInfo == null
9485                    || mTransformationInfo.mMatrixIsIdentity;
9486            if (matrixIsIdentity) {
9487                if (mDisplayList != null) {
9488                    invalidateViewProperty(false, false);
9489                } else {
9490                    final ViewParent p = mParent;
9491                    if (p != null && mAttachInfo != null) {
9492                        final Rect r = mAttachInfo.mTmpInvalRect;
9493                        int minLeft;
9494                        int maxRight;
9495                        if (offset < 0) {
9496                            minLeft = mLeft + offset;
9497                            maxRight = mRight;
9498                        } else {
9499                            minLeft = mLeft;
9500                            maxRight = mRight + offset;
9501                        }
9502                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9503                        p.invalidateChild(this, r);
9504                    }
9505                }
9506            } else {
9507                invalidateViewProperty(false, false);
9508            }
9509
9510            mLeft += offset;
9511            mRight += offset;
9512            if (mDisplayList != null) {
9513                mDisplayList.offsetLeftRight(offset);
9514                invalidateViewProperty(false, false);
9515            } else {
9516                if (!matrixIsIdentity) {
9517                    invalidateViewProperty(false, true);
9518                }
9519                invalidateParentIfNeeded();
9520            }
9521        }
9522    }
9523
9524    /**
9525     * Get the LayoutParams associated with this view. All views should have
9526     * layout parameters. These supply parameters to the <i>parent</i> of this
9527     * view specifying how it should be arranged. There are many subclasses of
9528     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9529     * of ViewGroup that are responsible for arranging their children.
9530     *
9531     * This method may return null if this View is not attached to a parent
9532     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9533     * was not invoked successfully. When a View is attached to a parent
9534     * ViewGroup, this method must not return null.
9535     *
9536     * @return The LayoutParams associated with this view, or null if no
9537     *         parameters have been set yet
9538     */
9539    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9540    public ViewGroup.LayoutParams getLayoutParams() {
9541        return mLayoutParams;
9542    }
9543
9544    /**
9545     * Set the layout parameters associated with this view. These supply
9546     * parameters to the <i>parent</i> of this view specifying how it should be
9547     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9548     * correspond to the different subclasses of ViewGroup that are responsible
9549     * for arranging their children.
9550     *
9551     * @param params The layout parameters for this view, cannot be null
9552     */
9553    public void setLayoutParams(ViewGroup.LayoutParams params) {
9554        if (params == null) {
9555            throw new NullPointerException("Layout parameters cannot be null");
9556        }
9557        mLayoutParams = params;
9558        if (mParent instanceof ViewGroup) {
9559            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9560        }
9561        requestLayout();
9562    }
9563
9564    /**
9565     * Set the scrolled position of your view. This will cause a call to
9566     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9567     * invalidated.
9568     * @param x the x position to scroll to
9569     * @param y the y position to scroll to
9570     */
9571    public void scrollTo(int x, int y) {
9572        if (mScrollX != x || mScrollY != y) {
9573            int oldX = mScrollX;
9574            int oldY = mScrollY;
9575            mScrollX = x;
9576            mScrollY = y;
9577            invalidateParentCaches();
9578            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9579            if (!awakenScrollBars()) {
9580                postInvalidateOnAnimation();
9581            }
9582        }
9583    }
9584
9585    /**
9586     * Move the scrolled position of your view. This will cause a call to
9587     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9588     * invalidated.
9589     * @param x the amount of pixels to scroll by horizontally
9590     * @param y the amount of pixels to scroll by vertically
9591     */
9592    public void scrollBy(int x, int y) {
9593        scrollTo(mScrollX + x, mScrollY + y);
9594    }
9595
9596    /**
9597     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9598     * animation to fade the scrollbars out after a default delay. If a subclass
9599     * provides animated scrolling, the start delay should equal the duration
9600     * of the scrolling animation.</p>
9601     *
9602     * <p>The animation starts only if at least one of the scrollbars is
9603     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9604     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9605     * this method returns true, and false otherwise. If the animation is
9606     * started, this method calls {@link #invalidate()}; in that case the
9607     * caller should not call {@link #invalidate()}.</p>
9608     *
9609     * <p>This method should be invoked every time a subclass directly updates
9610     * the scroll parameters.</p>
9611     *
9612     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9613     * and {@link #scrollTo(int, int)}.</p>
9614     *
9615     * @return true if the animation is played, false otherwise
9616     *
9617     * @see #awakenScrollBars(int)
9618     * @see #scrollBy(int, int)
9619     * @see #scrollTo(int, int)
9620     * @see #isHorizontalScrollBarEnabled()
9621     * @see #isVerticalScrollBarEnabled()
9622     * @see #setHorizontalScrollBarEnabled(boolean)
9623     * @see #setVerticalScrollBarEnabled(boolean)
9624     */
9625    protected boolean awakenScrollBars() {
9626        return mScrollCache != null &&
9627                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9628    }
9629
9630    /**
9631     * Trigger the scrollbars to draw.
9632     * This method differs from awakenScrollBars() only in its default duration.
9633     * initialAwakenScrollBars() will show the scroll bars for longer than
9634     * usual to give the user more of a chance to notice them.
9635     *
9636     * @return true if the animation is played, false otherwise.
9637     */
9638    private boolean initialAwakenScrollBars() {
9639        return mScrollCache != null &&
9640                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9641    }
9642
9643    /**
9644     * <p>
9645     * Trigger the scrollbars to draw. When invoked this method starts an
9646     * animation to fade the scrollbars out after a fixed delay. If a subclass
9647     * provides animated scrolling, the start delay should equal the duration of
9648     * the scrolling animation.
9649     * </p>
9650     *
9651     * <p>
9652     * The animation starts only if at least one of the scrollbars is enabled,
9653     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9654     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9655     * this method returns true, and false otherwise. If the animation is
9656     * started, this method calls {@link #invalidate()}; in that case the caller
9657     * should not call {@link #invalidate()}.
9658     * </p>
9659     *
9660     * <p>
9661     * This method should be invoked everytime a subclass directly updates the
9662     * scroll parameters.
9663     * </p>
9664     *
9665     * @param startDelay the delay, in milliseconds, after which the animation
9666     *        should start; when the delay is 0, the animation starts
9667     *        immediately
9668     * @return true if the animation is played, false otherwise
9669     *
9670     * @see #scrollBy(int, int)
9671     * @see #scrollTo(int, int)
9672     * @see #isHorizontalScrollBarEnabled()
9673     * @see #isVerticalScrollBarEnabled()
9674     * @see #setHorizontalScrollBarEnabled(boolean)
9675     * @see #setVerticalScrollBarEnabled(boolean)
9676     */
9677    protected boolean awakenScrollBars(int startDelay) {
9678        return awakenScrollBars(startDelay, true);
9679    }
9680
9681    /**
9682     * <p>
9683     * Trigger the scrollbars to draw. When invoked this method starts an
9684     * animation to fade the scrollbars out after a fixed delay. If a subclass
9685     * provides animated scrolling, the start delay should equal the duration of
9686     * the scrolling animation.
9687     * </p>
9688     *
9689     * <p>
9690     * The animation starts only if at least one of the scrollbars is enabled,
9691     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9692     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9693     * this method returns true, and false otherwise. If the animation is
9694     * started, this method calls {@link #invalidate()} if the invalidate parameter
9695     * is set to true; in that case the caller
9696     * should not call {@link #invalidate()}.
9697     * </p>
9698     *
9699     * <p>
9700     * This method should be invoked everytime a subclass directly updates the
9701     * scroll parameters.
9702     * </p>
9703     *
9704     * @param startDelay the delay, in milliseconds, after which the animation
9705     *        should start; when the delay is 0, the animation starts
9706     *        immediately
9707     *
9708     * @param invalidate Wheter this method should call invalidate
9709     *
9710     * @return true if the animation is played, false otherwise
9711     *
9712     * @see #scrollBy(int, int)
9713     * @see #scrollTo(int, int)
9714     * @see #isHorizontalScrollBarEnabled()
9715     * @see #isVerticalScrollBarEnabled()
9716     * @see #setHorizontalScrollBarEnabled(boolean)
9717     * @see #setVerticalScrollBarEnabled(boolean)
9718     */
9719    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9720        final ScrollabilityCache scrollCache = mScrollCache;
9721
9722        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9723            return false;
9724        }
9725
9726        if (scrollCache.scrollBar == null) {
9727            scrollCache.scrollBar = new ScrollBarDrawable();
9728        }
9729
9730        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9731
9732            if (invalidate) {
9733                // Invalidate to show the scrollbars
9734                postInvalidateOnAnimation();
9735            }
9736
9737            if (scrollCache.state == ScrollabilityCache.OFF) {
9738                // FIXME: this is copied from WindowManagerService.
9739                // We should get this value from the system when it
9740                // is possible to do so.
9741                final int KEY_REPEAT_FIRST_DELAY = 750;
9742                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9743            }
9744
9745            // Tell mScrollCache when we should start fading. This may
9746            // extend the fade start time if one was already scheduled
9747            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9748            scrollCache.fadeStartTime = fadeStartTime;
9749            scrollCache.state = ScrollabilityCache.ON;
9750
9751            // Schedule our fader to run, unscheduling any old ones first
9752            if (mAttachInfo != null) {
9753                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9754                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9755            }
9756
9757            return true;
9758        }
9759
9760        return false;
9761    }
9762
9763    /**
9764     * Do not invalidate views which are not visible and which are not running an animation. They
9765     * will not get drawn and they should not set dirty flags as if they will be drawn
9766     */
9767    private boolean skipInvalidate() {
9768        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9769                (!(mParent instanceof ViewGroup) ||
9770                        !((ViewGroup) mParent).isViewTransitioning(this));
9771    }
9772    /**
9773     * Mark the area defined by dirty as needing to be drawn. If the view is
9774     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9775     * in the future. This must be called from a UI thread. To call from a non-UI
9776     * thread, call {@link #postInvalidate()}.
9777     *
9778     * WARNING: This method is destructive to dirty.
9779     * @param dirty the rectangle representing the bounds of the dirty region
9780     */
9781    public void invalidate(Rect dirty) {
9782        if (ViewDebug.TRACE_HIERARCHY) {
9783            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9784        }
9785
9786        if (skipInvalidate()) {
9787            return;
9788        }
9789        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9790                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9791                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9792            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9793            mPrivateFlags |= INVALIDATED;
9794            mPrivateFlags |= DIRTY;
9795            final ViewParent p = mParent;
9796            final AttachInfo ai = mAttachInfo;
9797            //noinspection PointlessBooleanExpression,ConstantConditions
9798            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9799                if (p != null && ai != null && ai.mHardwareAccelerated) {
9800                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9801                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9802                    p.invalidateChild(this, null);
9803                    return;
9804                }
9805            }
9806            if (p != null && ai != null) {
9807                final int scrollX = mScrollX;
9808                final int scrollY = mScrollY;
9809                final Rect r = ai.mTmpInvalRect;
9810                r.set(dirty.left - scrollX, dirty.top - scrollY,
9811                        dirty.right - scrollX, dirty.bottom - scrollY);
9812                mParent.invalidateChild(this, r);
9813            }
9814        }
9815    }
9816
9817    /**
9818     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9819     * The coordinates of the dirty rect are relative to the view.
9820     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9821     * will be called at some point in the future. This must be called from
9822     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9823     * @param l the left position of the dirty region
9824     * @param t the top position of the dirty region
9825     * @param r the right position of the dirty region
9826     * @param b the bottom position of the dirty region
9827     */
9828    public void invalidate(int l, int t, int r, int b) {
9829        if (ViewDebug.TRACE_HIERARCHY) {
9830            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9831        }
9832
9833        if (skipInvalidate()) {
9834            return;
9835        }
9836        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9837                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9838                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9839            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9840            mPrivateFlags |= INVALIDATED;
9841            mPrivateFlags |= DIRTY;
9842            final ViewParent p = mParent;
9843            final AttachInfo ai = mAttachInfo;
9844            //noinspection PointlessBooleanExpression,ConstantConditions
9845            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9846                if (p != null && ai != null && ai.mHardwareAccelerated) {
9847                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9848                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9849                    p.invalidateChild(this, null);
9850                    return;
9851                }
9852            }
9853            if (p != null && ai != null && l < r && t < b) {
9854                final int scrollX = mScrollX;
9855                final int scrollY = mScrollY;
9856                final Rect tmpr = ai.mTmpInvalRect;
9857                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9858                p.invalidateChild(this, tmpr);
9859            }
9860        }
9861    }
9862
9863    /**
9864     * Invalidate the whole view. If the view is visible,
9865     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9866     * the future. This must be called from a UI thread. To call from a non-UI thread,
9867     * call {@link #postInvalidate()}.
9868     */
9869    public void invalidate() {
9870        invalidate(true);
9871    }
9872
9873    /**
9874     * This is where the invalidate() work actually happens. A full invalidate()
9875     * causes the drawing cache to be invalidated, but this function can be called with
9876     * invalidateCache set to false to skip that invalidation step for cases that do not
9877     * need it (for example, a component that remains at the same dimensions with the same
9878     * content).
9879     *
9880     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9881     * well. This is usually true for a full invalidate, but may be set to false if the
9882     * View's contents or dimensions have not changed.
9883     */
9884    void invalidate(boolean invalidateCache) {
9885        if (ViewDebug.TRACE_HIERARCHY) {
9886            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9887        }
9888
9889        if (skipInvalidate()) {
9890            return;
9891        }
9892        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9893                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9894                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9895            mLastIsOpaque = isOpaque();
9896            mPrivateFlags &= ~DRAWN;
9897            mPrivateFlags |= DIRTY;
9898            if (invalidateCache) {
9899                mPrivateFlags |= INVALIDATED;
9900                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9901            }
9902            final AttachInfo ai = mAttachInfo;
9903            final ViewParent p = mParent;
9904            //noinspection PointlessBooleanExpression,ConstantConditions
9905            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9906                if (p != null && ai != null && ai.mHardwareAccelerated) {
9907                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9908                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9909                    p.invalidateChild(this, null);
9910                    return;
9911                }
9912            }
9913
9914            if (p != null && ai != null) {
9915                final Rect r = ai.mTmpInvalRect;
9916                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9917                // Don't call invalidate -- we don't want to internally scroll
9918                // our own bounds
9919                p.invalidateChild(this, r);
9920            }
9921        }
9922    }
9923
9924    /**
9925     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9926     * set any flags or handle all of the cases handled by the default invalidation methods.
9927     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9928     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9929     * walk up the hierarchy, transforming the dirty rect as necessary.
9930     *
9931     * The method also handles normal invalidation logic if display list properties are not
9932     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9933     * backup approach, to handle these cases used in the various property-setting methods.
9934     *
9935     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9936     * are not being used in this view
9937     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9938     * list properties are not being used in this view
9939     */
9940    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9941        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9942            if (invalidateParent) {
9943                invalidateParentCaches();
9944            }
9945            if (forceRedraw) {
9946                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9947            }
9948            invalidate(false);
9949        } else {
9950            final AttachInfo ai = mAttachInfo;
9951            final ViewParent p = mParent;
9952            if (p != null && ai != null) {
9953                final Rect r = ai.mTmpInvalRect;
9954                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9955                if (mParent instanceof ViewGroup) {
9956                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9957                } else {
9958                    mParent.invalidateChild(this, r);
9959                }
9960            }
9961        }
9962    }
9963
9964    /**
9965     * Utility method to transform a given Rect by the current matrix of this view.
9966     */
9967    void transformRect(final Rect rect) {
9968        if (!getMatrix().isIdentity()) {
9969            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9970            boundingRect.set(rect);
9971            getMatrix().mapRect(boundingRect);
9972            rect.set((int) (boundingRect.left - 0.5f),
9973                    (int) (boundingRect.top - 0.5f),
9974                    (int) (boundingRect.right + 0.5f),
9975                    (int) (boundingRect.bottom + 0.5f));
9976        }
9977    }
9978
9979    /**
9980     * Used to indicate that the parent of this view should clear its caches. This functionality
9981     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9982     * which is necessary when various parent-managed properties of the view change, such as
9983     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9984     * clears the parent caches and does not causes an invalidate event.
9985     *
9986     * @hide
9987     */
9988    protected void invalidateParentCaches() {
9989        if (mParent instanceof View) {
9990            ((View) mParent).mPrivateFlags |= INVALIDATED;
9991        }
9992    }
9993
9994    /**
9995     * Used to indicate that the parent of this view should be invalidated. This functionality
9996     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9997     * which is necessary when various parent-managed properties of the view change, such as
9998     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9999     * an invalidation event to the parent.
10000     *
10001     * @hide
10002     */
10003    protected void invalidateParentIfNeeded() {
10004        if (isHardwareAccelerated() && mParent instanceof View) {
10005            ((View) mParent).invalidate(true);
10006        }
10007    }
10008
10009    /**
10010     * Indicates whether this View is opaque. An opaque View guarantees that it will
10011     * draw all the pixels overlapping its bounds using a fully opaque color.
10012     *
10013     * Subclasses of View should override this method whenever possible to indicate
10014     * whether an instance is opaque. Opaque Views are treated in a special way by
10015     * the View hierarchy, possibly allowing it to perform optimizations during
10016     * invalidate/draw passes.
10017     *
10018     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10019     */
10020    @ViewDebug.ExportedProperty(category = "drawing")
10021    public boolean isOpaque() {
10022        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10023                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10024                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10025    }
10026
10027    /**
10028     * @hide
10029     */
10030    protected void computeOpaqueFlags() {
10031        // Opaque if:
10032        //   - Has a background
10033        //   - Background is opaque
10034        //   - Doesn't have scrollbars or scrollbars are inside overlay
10035
10036        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10037            mPrivateFlags |= OPAQUE_BACKGROUND;
10038        } else {
10039            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10040        }
10041
10042        final int flags = mViewFlags;
10043        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10044                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10045            mPrivateFlags |= OPAQUE_SCROLLBARS;
10046        } else {
10047            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10048        }
10049    }
10050
10051    /**
10052     * @hide
10053     */
10054    protected boolean hasOpaqueScrollbars() {
10055        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10056    }
10057
10058    /**
10059     * @return A handler associated with the thread running the View. This
10060     * handler can be used to pump events in the UI events queue.
10061     */
10062    public Handler getHandler() {
10063        if (mAttachInfo != null) {
10064            return mAttachInfo.mHandler;
10065        }
10066        return null;
10067    }
10068
10069    /**
10070     * Gets the view root associated with the View.
10071     * @return The view root, or null if none.
10072     * @hide
10073     */
10074    public ViewRootImpl getViewRootImpl() {
10075        if (mAttachInfo != null) {
10076            return mAttachInfo.mViewRootImpl;
10077        }
10078        return null;
10079    }
10080
10081    /**
10082     * <p>Causes the Runnable to be added to the message queue.
10083     * The runnable will be run on the user interface thread.</p>
10084     *
10085     * <p>This method can be invoked from outside of the UI thread
10086     * only when this View is attached to a window.</p>
10087     *
10088     * @param action The Runnable that will be executed.
10089     *
10090     * @return Returns true if the Runnable was successfully placed in to the
10091     *         message queue.  Returns false on failure, usually because the
10092     *         looper processing the message queue is exiting.
10093     *
10094     * @see #postDelayed
10095     * @see #removeCallbacks
10096     */
10097    public boolean post(Runnable action) {
10098        final AttachInfo attachInfo = mAttachInfo;
10099        if (attachInfo != null) {
10100            return attachInfo.mHandler.post(action);
10101        }
10102        // Assume that post will succeed later
10103        ViewRootImpl.getRunQueue().post(action);
10104        return true;
10105    }
10106
10107    /**
10108     * <p>Causes the Runnable to be added to the message queue, to be run
10109     * after the specified amount of time elapses.
10110     * The runnable will be run on the user interface thread.</p>
10111     *
10112     * <p>This method can be invoked from outside of the UI thread
10113     * only when this View is attached to a window.</p>
10114     *
10115     * @param action The Runnable that will be executed.
10116     * @param delayMillis The delay (in milliseconds) until the Runnable
10117     *        will be executed.
10118     *
10119     * @return true if the Runnable was successfully placed in to the
10120     *         message queue.  Returns false on failure, usually because the
10121     *         looper processing the message queue is exiting.  Note that a
10122     *         result of true does not mean the Runnable will be processed --
10123     *         if the looper is quit before the delivery time of the message
10124     *         occurs then the message will be dropped.
10125     *
10126     * @see #post
10127     * @see #removeCallbacks
10128     */
10129    public boolean postDelayed(Runnable action, long delayMillis) {
10130        final AttachInfo attachInfo = mAttachInfo;
10131        if (attachInfo != null) {
10132            return attachInfo.mHandler.postDelayed(action, delayMillis);
10133        }
10134        // Assume that post will succeed later
10135        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10136        return true;
10137    }
10138
10139    /**
10140     * <p>Causes the Runnable to execute on the next animation time step.
10141     * The runnable will be run on the user interface thread.</p>
10142     *
10143     * <p>This method can be invoked from outside of the UI thread
10144     * only when this View is attached to a window.</p>
10145     *
10146     * @param action The Runnable that will be executed.
10147     *
10148     * @see #postOnAnimationDelayed
10149     * @see #removeCallbacks
10150     */
10151    public void postOnAnimation(Runnable action) {
10152        final AttachInfo attachInfo = mAttachInfo;
10153        if (attachInfo != null) {
10154            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10155                    Choreographer.CALLBACK_ANIMATION, action, null);
10156        } else {
10157            // Assume that post will succeed later
10158            ViewRootImpl.getRunQueue().post(action);
10159        }
10160    }
10161
10162    /**
10163     * <p>Causes the Runnable to execute on the next animation time step,
10164     * after the specified amount of time elapses.
10165     * The runnable will be run on the user interface thread.</p>
10166     *
10167     * <p>This method can be invoked from outside of the UI thread
10168     * only when this View is attached to a window.</p>
10169     *
10170     * @param action The Runnable that will be executed.
10171     * @param delayMillis The delay (in milliseconds) until the Runnable
10172     *        will be executed.
10173     *
10174     * @see #postOnAnimation
10175     * @see #removeCallbacks
10176     */
10177    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10178        final AttachInfo attachInfo = mAttachInfo;
10179        if (attachInfo != null) {
10180            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10181                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10182        } else {
10183            // Assume that post will succeed later
10184            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10185        }
10186    }
10187
10188    /**
10189     * <p>Removes the specified Runnable from the message queue.</p>
10190     *
10191     * <p>This method can be invoked from outside of the UI thread
10192     * only when this View is attached to a window.</p>
10193     *
10194     * @param action The Runnable to remove from the message handling queue
10195     *
10196     * @return true if this view could ask the Handler to remove the Runnable,
10197     *         false otherwise. When the returned value is true, the Runnable
10198     *         may or may not have been actually removed from the message queue
10199     *         (for instance, if the Runnable was not in the queue already.)
10200     *
10201     * @see #post
10202     * @see #postDelayed
10203     * @see #postOnAnimation
10204     * @see #postOnAnimationDelayed
10205     */
10206    public boolean removeCallbacks(Runnable action) {
10207        if (action != null) {
10208            final AttachInfo attachInfo = mAttachInfo;
10209            if (attachInfo != null) {
10210                attachInfo.mHandler.removeCallbacks(action);
10211                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10212                        Choreographer.CALLBACK_ANIMATION, action, null);
10213            } else {
10214                // Assume that post will succeed later
10215                ViewRootImpl.getRunQueue().removeCallbacks(action);
10216            }
10217        }
10218        return true;
10219    }
10220
10221    /**
10222     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10223     * Use this to invalidate the View from a non-UI thread.</p>
10224     *
10225     * <p>This method can be invoked from outside of the UI thread
10226     * only when this View is attached to a window.</p>
10227     *
10228     * @see #invalidate()
10229     * @see #postInvalidateDelayed(long)
10230     */
10231    public void postInvalidate() {
10232        postInvalidateDelayed(0);
10233    }
10234
10235    /**
10236     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10237     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10238     *
10239     * <p>This method can be invoked from outside of the UI thread
10240     * only when this View is attached to a window.</p>
10241     *
10242     * @param left The left coordinate of the rectangle to invalidate.
10243     * @param top The top coordinate of the rectangle to invalidate.
10244     * @param right The right coordinate of the rectangle to invalidate.
10245     * @param bottom The bottom coordinate of the rectangle to invalidate.
10246     *
10247     * @see #invalidate(int, int, int, int)
10248     * @see #invalidate(Rect)
10249     * @see #postInvalidateDelayed(long, int, int, int, int)
10250     */
10251    public void postInvalidate(int left, int top, int right, int bottom) {
10252        postInvalidateDelayed(0, left, top, right, bottom);
10253    }
10254
10255    /**
10256     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10257     * loop. Waits for the specified amount of time.</p>
10258     *
10259     * <p>This method can be invoked from outside of the UI thread
10260     * only when this View is attached to a window.</p>
10261     *
10262     * @param delayMilliseconds the duration in milliseconds to delay the
10263     *         invalidation by
10264     *
10265     * @see #invalidate()
10266     * @see #postInvalidate()
10267     */
10268    public void postInvalidateDelayed(long delayMilliseconds) {
10269        // We try only with the AttachInfo because there's no point in invalidating
10270        // if we are not attached to our window
10271        final AttachInfo attachInfo = mAttachInfo;
10272        if (attachInfo != null) {
10273            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10274        }
10275    }
10276
10277    /**
10278     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10279     * through the event loop. Waits for the specified amount of time.</p>
10280     *
10281     * <p>This method can be invoked from outside of the UI thread
10282     * only when this View is attached to a window.</p>
10283     *
10284     * @param delayMilliseconds the duration in milliseconds to delay the
10285     *         invalidation by
10286     * @param left The left coordinate of the rectangle to invalidate.
10287     * @param top The top coordinate of the rectangle to invalidate.
10288     * @param right The right coordinate of the rectangle to invalidate.
10289     * @param bottom The bottom coordinate of the rectangle to invalidate.
10290     *
10291     * @see #invalidate(int, int, int, int)
10292     * @see #invalidate(Rect)
10293     * @see #postInvalidate(int, int, int, int)
10294     */
10295    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10296            int right, int bottom) {
10297
10298        // We try only with the AttachInfo because there's no point in invalidating
10299        // if we are not attached to our window
10300        final AttachInfo attachInfo = mAttachInfo;
10301        if (attachInfo != null) {
10302            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10303            info.target = this;
10304            info.left = left;
10305            info.top = top;
10306            info.right = right;
10307            info.bottom = bottom;
10308
10309            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10310        }
10311    }
10312
10313    /**
10314     * <p>Cause an invalidate to happen on the next animation time step, typically the
10315     * next display frame.</p>
10316     *
10317     * <p>This method can be invoked from outside of the UI thread
10318     * only when this View is attached to a window.</p>
10319     *
10320     * @see #invalidate()
10321     */
10322    public void postInvalidateOnAnimation() {
10323        // We try only with the AttachInfo because there's no point in invalidating
10324        // if we are not attached to our window
10325        final AttachInfo attachInfo = mAttachInfo;
10326        if (attachInfo != null) {
10327            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10328        }
10329    }
10330
10331    /**
10332     * <p>Cause an invalidate of the specified area to happen on the next animation
10333     * time step, typically the next display frame.</p>
10334     *
10335     * <p>This method can be invoked from outside of the UI thread
10336     * only when this View is attached to a window.</p>
10337     *
10338     * @param left The left coordinate of the rectangle to invalidate.
10339     * @param top The top coordinate of the rectangle to invalidate.
10340     * @param right The right coordinate of the rectangle to invalidate.
10341     * @param bottom The bottom coordinate of the rectangle to invalidate.
10342     *
10343     * @see #invalidate(int, int, int, int)
10344     * @see #invalidate(Rect)
10345     */
10346    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10347        // We try only with the AttachInfo because there's no point in invalidating
10348        // if we are not attached to our window
10349        final AttachInfo attachInfo = mAttachInfo;
10350        if (attachInfo != null) {
10351            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10352            info.target = this;
10353            info.left = left;
10354            info.top = top;
10355            info.right = right;
10356            info.bottom = bottom;
10357
10358            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10359        }
10360    }
10361
10362    /**
10363     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10364     * This event is sent at most once every
10365     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10366     */
10367    private void postSendViewScrolledAccessibilityEventCallback() {
10368        if (mSendViewScrolledAccessibilityEvent == null) {
10369            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10370        }
10371        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10372            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10373            postDelayed(mSendViewScrolledAccessibilityEvent,
10374                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10375        }
10376    }
10377
10378    /**
10379     * Called by a parent to request that a child update its values for mScrollX
10380     * and mScrollY if necessary. This will typically be done if the child is
10381     * animating a scroll using a {@link android.widget.Scroller Scroller}
10382     * object.
10383     */
10384    public void computeScroll() {
10385    }
10386
10387    /**
10388     * <p>Indicate whether the horizontal edges are faded when the view is
10389     * scrolled horizontally.</p>
10390     *
10391     * @return true if the horizontal edges should are faded on scroll, false
10392     *         otherwise
10393     *
10394     * @see #setHorizontalFadingEdgeEnabled(boolean)
10395     *
10396     * @attr ref android.R.styleable#View_requiresFadingEdge
10397     */
10398    public boolean isHorizontalFadingEdgeEnabled() {
10399        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10400    }
10401
10402    /**
10403     * <p>Define whether the horizontal edges should be faded when this view
10404     * is scrolled horizontally.</p>
10405     *
10406     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10407     *                                    be faded when the view is scrolled
10408     *                                    horizontally
10409     *
10410     * @see #isHorizontalFadingEdgeEnabled()
10411     *
10412     * @attr ref android.R.styleable#View_requiresFadingEdge
10413     */
10414    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10415        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10416            if (horizontalFadingEdgeEnabled) {
10417                initScrollCache();
10418            }
10419
10420            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10421        }
10422    }
10423
10424    /**
10425     * <p>Indicate whether the vertical edges are faded when the view is
10426     * scrolled horizontally.</p>
10427     *
10428     * @return true if the vertical edges should are faded on scroll, false
10429     *         otherwise
10430     *
10431     * @see #setVerticalFadingEdgeEnabled(boolean)
10432     *
10433     * @attr ref android.R.styleable#View_requiresFadingEdge
10434     */
10435    public boolean isVerticalFadingEdgeEnabled() {
10436        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10437    }
10438
10439    /**
10440     * <p>Define whether the vertical edges should be faded when this view
10441     * is scrolled vertically.</p>
10442     *
10443     * @param verticalFadingEdgeEnabled true if the vertical edges should
10444     *                                  be faded when the view is scrolled
10445     *                                  vertically
10446     *
10447     * @see #isVerticalFadingEdgeEnabled()
10448     *
10449     * @attr ref android.R.styleable#View_requiresFadingEdge
10450     */
10451    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10452        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10453            if (verticalFadingEdgeEnabled) {
10454                initScrollCache();
10455            }
10456
10457            mViewFlags ^= FADING_EDGE_VERTICAL;
10458        }
10459    }
10460
10461    /**
10462     * Returns the strength, or intensity, of the top faded edge. The strength is
10463     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10464     * returns 0.0 or 1.0 but no value in between.
10465     *
10466     * Subclasses should override this method to provide a smoother fade transition
10467     * when scrolling occurs.
10468     *
10469     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10470     */
10471    protected float getTopFadingEdgeStrength() {
10472        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10473    }
10474
10475    /**
10476     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10477     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10478     * returns 0.0 or 1.0 but no value in between.
10479     *
10480     * Subclasses should override this method to provide a smoother fade transition
10481     * when scrolling occurs.
10482     *
10483     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10484     */
10485    protected float getBottomFadingEdgeStrength() {
10486        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10487                computeVerticalScrollRange() ? 1.0f : 0.0f;
10488    }
10489
10490    /**
10491     * Returns the strength, or intensity, of the left faded edge. The strength is
10492     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10493     * returns 0.0 or 1.0 but no value in between.
10494     *
10495     * Subclasses should override this method to provide a smoother fade transition
10496     * when scrolling occurs.
10497     *
10498     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10499     */
10500    protected float getLeftFadingEdgeStrength() {
10501        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10502    }
10503
10504    /**
10505     * Returns the strength, or intensity, of the right faded edge. The strength is
10506     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10507     * returns 0.0 or 1.0 but no value in between.
10508     *
10509     * Subclasses should override this method to provide a smoother fade transition
10510     * when scrolling occurs.
10511     *
10512     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10513     */
10514    protected float getRightFadingEdgeStrength() {
10515        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10516                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10517    }
10518
10519    /**
10520     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10521     * scrollbar is not drawn by default.</p>
10522     *
10523     * @return true if the horizontal scrollbar should be painted, false
10524     *         otherwise
10525     *
10526     * @see #setHorizontalScrollBarEnabled(boolean)
10527     */
10528    public boolean isHorizontalScrollBarEnabled() {
10529        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10530    }
10531
10532    /**
10533     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10534     * scrollbar is not drawn by default.</p>
10535     *
10536     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10537     *                                   be painted
10538     *
10539     * @see #isHorizontalScrollBarEnabled()
10540     */
10541    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10542        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10543            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10544            computeOpaqueFlags();
10545            resolvePadding();
10546        }
10547    }
10548
10549    /**
10550     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10551     * scrollbar is not drawn by default.</p>
10552     *
10553     * @return true if the vertical scrollbar should be painted, false
10554     *         otherwise
10555     *
10556     * @see #setVerticalScrollBarEnabled(boolean)
10557     */
10558    public boolean isVerticalScrollBarEnabled() {
10559        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10560    }
10561
10562    /**
10563     * <p>Define whether the vertical scrollbar should be drawn or not. The
10564     * scrollbar is not drawn by default.</p>
10565     *
10566     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10567     *                                 be painted
10568     *
10569     * @see #isVerticalScrollBarEnabled()
10570     */
10571    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10572        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10573            mViewFlags ^= SCROLLBARS_VERTICAL;
10574            computeOpaqueFlags();
10575            resolvePadding();
10576        }
10577    }
10578
10579    /**
10580     * @hide
10581     */
10582    protected void recomputePadding() {
10583        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10584    }
10585
10586    /**
10587     * Define whether scrollbars will fade when the view is not scrolling.
10588     *
10589     * @param fadeScrollbars wheter to enable fading
10590     *
10591     * @attr ref android.R.styleable#View_fadeScrollbars
10592     */
10593    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10594        initScrollCache();
10595        final ScrollabilityCache scrollabilityCache = mScrollCache;
10596        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10597        if (fadeScrollbars) {
10598            scrollabilityCache.state = ScrollabilityCache.OFF;
10599        } else {
10600            scrollabilityCache.state = ScrollabilityCache.ON;
10601        }
10602    }
10603
10604    /**
10605     *
10606     * Returns true if scrollbars will fade when this view is not scrolling
10607     *
10608     * @return true if scrollbar fading is enabled
10609     *
10610     * @attr ref android.R.styleable#View_fadeScrollbars
10611     */
10612    public boolean isScrollbarFadingEnabled() {
10613        return mScrollCache != null && mScrollCache.fadeScrollBars;
10614    }
10615
10616    /**
10617     *
10618     * Returns the delay before scrollbars fade.
10619     *
10620     * @return the delay before scrollbars fade
10621     *
10622     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10623     */
10624    public int getScrollBarDefaultDelayBeforeFade() {
10625        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10626                mScrollCache.scrollBarDefaultDelayBeforeFade;
10627    }
10628
10629    /**
10630     * Define the delay before scrollbars fade.
10631     *
10632     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10633     *
10634     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10635     */
10636    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10637        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10638    }
10639
10640    /**
10641     *
10642     * Returns the scrollbar fade duration.
10643     *
10644     * @return the scrollbar fade duration
10645     *
10646     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10647     */
10648    public int getScrollBarFadeDuration() {
10649        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10650                mScrollCache.scrollBarFadeDuration;
10651    }
10652
10653    /**
10654     * Define the scrollbar fade duration.
10655     *
10656     * @param scrollBarFadeDuration - the scrollbar fade duration
10657     *
10658     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10659     */
10660    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10661        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10662    }
10663
10664    /**
10665     *
10666     * Returns the scrollbar size.
10667     *
10668     * @return the scrollbar size
10669     *
10670     * @attr ref android.R.styleable#View_scrollbarSize
10671     */
10672    public int getScrollBarSize() {
10673        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10674                mScrollCache.scrollBarSize;
10675    }
10676
10677    /**
10678     * Define the scrollbar size.
10679     *
10680     * @param scrollBarSize - the scrollbar size
10681     *
10682     * @attr ref android.R.styleable#View_scrollbarSize
10683     */
10684    public void setScrollBarSize(int scrollBarSize) {
10685        getScrollCache().scrollBarSize = scrollBarSize;
10686    }
10687
10688    /**
10689     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10690     * inset. When inset, they add to the padding of the view. And the scrollbars
10691     * can be drawn inside the padding area or on the edge of the view. For example,
10692     * if a view has a background drawable and you want to draw the scrollbars
10693     * inside the padding specified by the drawable, you can use
10694     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10695     * appear at the edge of the view, ignoring the padding, then you can use
10696     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10697     * @param style the style of the scrollbars. Should be one of
10698     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10699     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10700     * @see #SCROLLBARS_INSIDE_OVERLAY
10701     * @see #SCROLLBARS_INSIDE_INSET
10702     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10703     * @see #SCROLLBARS_OUTSIDE_INSET
10704     *
10705     * @attr ref android.R.styleable#View_scrollbarStyle
10706     */
10707    public void setScrollBarStyle(int style) {
10708        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10709            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10710            computeOpaqueFlags();
10711            resolvePadding();
10712        }
10713    }
10714
10715    /**
10716     * <p>Returns the current scrollbar style.</p>
10717     * @return the current scrollbar style
10718     * @see #SCROLLBARS_INSIDE_OVERLAY
10719     * @see #SCROLLBARS_INSIDE_INSET
10720     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10721     * @see #SCROLLBARS_OUTSIDE_INSET
10722     *
10723     * @attr ref android.R.styleable#View_scrollbarStyle
10724     */
10725    @ViewDebug.ExportedProperty(mapping = {
10726            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10727            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10728            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10729            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10730    })
10731    public int getScrollBarStyle() {
10732        return mViewFlags & SCROLLBARS_STYLE_MASK;
10733    }
10734
10735    /**
10736     * <p>Compute the horizontal range that the horizontal scrollbar
10737     * represents.</p>
10738     *
10739     * <p>The range is expressed in arbitrary units that must be the same as the
10740     * units used by {@link #computeHorizontalScrollExtent()} and
10741     * {@link #computeHorizontalScrollOffset()}.</p>
10742     *
10743     * <p>The default range is the drawing width of this view.</p>
10744     *
10745     * @return the total horizontal range represented by the horizontal
10746     *         scrollbar
10747     *
10748     * @see #computeHorizontalScrollExtent()
10749     * @see #computeHorizontalScrollOffset()
10750     * @see android.widget.ScrollBarDrawable
10751     */
10752    protected int computeHorizontalScrollRange() {
10753        return getWidth();
10754    }
10755
10756    /**
10757     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10758     * within the horizontal range. This value is used to compute the position
10759     * of the thumb within the scrollbar's track.</p>
10760     *
10761     * <p>The range is expressed in arbitrary units that must be the same as the
10762     * units used by {@link #computeHorizontalScrollRange()} and
10763     * {@link #computeHorizontalScrollExtent()}.</p>
10764     *
10765     * <p>The default offset is the scroll offset of this view.</p>
10766     *
10767     * @return the horizontal offset of the scrollbar's thumb
10768     *
10769     * @see #computeHorizontalScrollRange()
10770     * @see #computeHorizontalScrollExtent()
10771     * @see android.widget.ScrollBarDrawable
10772     */
10773    protected int computeHorizontalScrollOffset() {
10774        return mScrollX;
10775    }
10776
10777    /**
10778     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10779     * within the horizontal range. This value is used to compute the length
10780     * of the thumb within the scrollbar's track.</p>
10781     *
10782     * <p>The range is expressed in arbitrary units that must be the same as the
10783     * units used by {@link #computeHorizontalScrollRange()} and
10784     * {@link #computeHorizontalScrollOffset()}.</p>
10785     *
10786     * <p>The default extent is the drawing width of this view.</p>
10787     *
10788     * @return the horizontal extent of the scrollbar's thumb
10789     *
10790     * @see #computeHorizontalScrollRange()
10791     * @see #computeHorizontalScrollOffset()
10792     * @see android.widget.ScrollBarDrawable
10793     */
10794    protected int computeHorizontalScrollExtent() {
10795        return getWidth();
10796    }
10797
10798    /**
10799     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10800     *
10801     * <p>The range is expressed in arbitrary units that must be the same as the
10802     * units used by {@link #computeVerticalScrollExtent()} and
10803     * {@link #computeVerticalScrollOffset()}.</p>
10804     *
10805     * @return the total vertical range represented by the vertical scrollbar
10806     *
10807     * <p>The default range is the drawing height of this view.</p>
10808     *
10809     * @see #computeVerticalScrollExtent()
10810     * @see #computeVerticalScrollOffset()
10811     * @see android.widget.ScrollBarDrawable
10812     */
10813    protected int computeVerticalScrollRange() {
10814        return getHeight();
10815    }
10816
10817    /**
10818     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10819     * within the horizontal range. This value is used to compute the position
10820     * of the thumb within the scrollbar's track.</p>
10821     *
10822     * <p>The range is expressed in arbitrary units that must be the same as the
10823     * units used by {@link #computeVerticalScrollRange()} and
10824     * {@link #computeVerticalScrollExtent()}.</p>
10825     *
10826     * <p>The default offset is the scroll offset of this view.</p>
10827     *
10828     * @return the vertical offset of the scrollbar's thumb
10829     *
10830     * @see #computeVerticalScrollRange()
10831     * @see #computeVerticalScrollExtent()
10832     * @see android.widget.ScrollBarDrawable
10833     */
10834    protected int computeVerticalScrollOffset() {
10835        return mScrollY;
10836    }
10837
10838    /**
10839     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10840     * within the vertical range. This value is used to compute the length
10841     * of the thumb within the scrollbar's track.</p>
10842     *
10843     * <p>The range is expressed in arbitrary units that must be the same as the
10844     * units used by {@link #computeVerticalScrollRange()} and
10845     * {@link #computeVerticalScrollOffset()}.</p>
10846     *
10847     * <p>The default extent is the drawing height of this view.</p>
10848     *
10849     * @return the vertical extent of the scrollbar's thumb
10850     *
10851     * @see #computeVerticalScrollRange()
10852     * @see #computeVerticalScrollOffset()
10853     * @see android.widget.ScrollBarDrawable
10854     */
10855    protected int computeVerticalScrollExtent() {
10856        return getHeight();
10857    }
10858
10859    /**
10860     * Check if this view can be scrolled horizontally in a certain direction.
10861     *
10862     * @param direction Negative to check scrolling left, positive to check scrolling right.
10863     * @return true if this view can be scrolled in the specified direction, false otherwise.
10864     */
10865    public boolean canScrollHorizontally(int direction) {
10866        final int offset = computeHorizontalScrollOffset();
10867        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10868        if (range == 0) return false;
10869        if (direction < 0) {
10870            return offset > 0;
10871        } else {
10872            return offset < range - 1;
10873        }
10874    }
10875
10876    /**
10877     * Check if this view can be scrolled vertically in a certain direction.
10878     *
10879     * @param direction Negative to check scrolling up, positive to check scrolling down.
10880     * @return true if this view can be scrolled in the specified direction, false otherwise.
10881     */
10882    public boolean canScrollVertically(int direction) {
10883        final int offset = computeVerticalScrollOffset();
10884        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10885        if (range == 0) return false;
10886        if (direction < 0) {
10887            return offset > 0;
10888        } else {
10889            return offset < range - 1;
10890        }
10891    }
10892
10893    /**
10894     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10895     * scrollbars are painted only if they have been awakened first.</p>
10896     *
10897     * @param canvas the canvas on which to draw the scrollbars
10898     *
10899     * @see #awakenScrollBars(int)
10900     */
10901    protected final void onDrawScrollBars(Canvas canvas) {
10902        // scrollbars are drawn only when the animation is running
10903        final ScrollabilityCache cache = mScrollCache;
10904        if (cache != null) {
10905
10906            int state = cache.state;
10907
10908            if (state == ScrollabilityCache.OFF) {
10909                return;
10910            }
10911
10912            boolean invalidate = false;
10913
10914            if (state == ScrollabilityCache.FADING) {
10915                // We're fading -- get our fade interpolation
10916                if (cache.interpolatorValues == null) {
10917                    cache.interpolatorValues = new float[1];
10918                }
10919
10920                float[] values = cache.interpolatorValues;
10921
10922                // Stops the animation if we're done
10923                if (cache.scrollBarInterpolator.timeToValues(values) ==
10924                        Interpolator.Result.FREEZE_END) {
10925                    cache.state = ScrollabilityCache.OFF;
10926                } else {
10927                    cache.scrollBar.setAlpha(Math.round(values[0]));
10928                }
10929
10930                // This will make the scroll bars inval themselves after
10931                // drawing. We only want this when we're fading so that
10932                // we prevent excessive redraws
10933                invalidate = true;
10934            } else {
10935                // We're just on -- but we may have been fading before so
10936                // reset alpha
10937                cache.scrollBar.setAlpha(255);
10938            }
10939
10940
10941            final int viewFlags = mViewFlags;
10942
10943            final boolean drawHorizontalScrollBar =
10944                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10945            final boolean drawVerticalScrollBar =
10946                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10947                && !isVerticalScrollBarHidden();
10948
10949            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10950                final int width = mRight - mLeft;
10951                final int height = mBottom - mTop;
10952
10953                final ScrollBarDrawable scrollBar = cache.scrollBar;
10954
10955                final int scrollX = mScrollX;
10956                final int scrollY = mScrollY;
10957                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10958
10959                int left, top, right, bottom;
10960
10961                if (drawHorizontalScrollBar) {
10962                    int size = scrollBar.getSize(false);
10963                    if (size <= 0) {
10964                        size = cache.scrollBarSize;
10965                    }
10966
10967                    scrollBar.setParameters(computeHorizontalScrollRange(),
10968                                            computeHorizontalScrollOffset(),
10969                                            computeHorizontalScrollExtent(), false);
10970                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10971                            getVerticalScrollbarWidth() : 0;
10972                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10973                    left = scrollX + (mPaddingLeft & inside);
10974                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10975                    bottom = top + size;
10976                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10977                    if (invalidate) {
10978                        invalidate(left, top, right, bottom);
10979                    }
10980                }
10981
10982                if (drawVerticalScrollBar) {
10983                    int size = scrollBar.getSize(true);
10984                    if (size <= 0) {
10985                        size = cache.scrollBarSize;
10986                    }
10987
10988                    scrollBar.setParameters(computeVerticalScrollRange(),
10989                                            computeVerticalScrollOffset(),
10990                                            computeVerticalScrollExtent(), true);
10991                    switch (mVerticalScrollbarPosition) {
10992                        default:
10993                        case SCROLLBAR_POSITION_DEFAULT:
10994                        case SCROLLBAR_POSITION_RIGHT:
10995                            left = scrollX + width - size - (mUserPaddingRight & inside);
10996                            break;
10997                        case SCROLLBAR_POSITION_LEFT:
10998                            left = scrollX + (mUserPaddingLeft & inside);
10999                            break;
11000                    }
11001                    top = scrollY + (mPaddingTop & inside);
11002                    right = left + size;
11003                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11004                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11005                    if (invalidate) {
11006                        invalidate(left, top, right, bottom);
11007                    }
11008                }
11009            }
11010        }
11011    }
11012
11013    /**
11014     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11015     * FastScroller is visible.
11016     * @return whether to temporarily hide the vertical scrollbar
11017     * @hide
11018     */
11019    protected boolean isVerticalScrollBarHidden() {
11020        return false;
11021    }
11022
11023    /**
11024     * <p>Draw the horizontal scrollbar if
11025     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11026     *
11027     * @param canvas the canvas on which to draw the scrollbar
11028     * @param scrollBar the scrollbar's drawable
11029     *
11030     * @see #isHorizontalScrollBarEnabled()
11031     * @see #computeHorizontalScrollRange()
11032     * @see #computeHorizontalScrollExtent()
11033     * @see #computeHorizontalScrollOffset()
11034     * @see android.widget.ScrollBarDrawable
11035     * @hide
11036     */
11037    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11038            int l, int t, int r, int b) {
11039        scrollBar.setBounds(l, t, r, b);
11040        scrollBar.draw(canvas);
11041    }
11042
11043    /**
11044     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11045     * returns true.</p>
11046     *
11047     * @param canvas the canvas on which to draw the scrollbar
11048     * @param scrollBar the scrollbar's drawable
11049     *
11050     * @see #isVerticalScrollBarEnabled()
11051     * @see #computeVerticalScrollRange()
11052     * @see #computeVerticalScrollExtent()
11053     * @see #computeVerticalScrollOffset()
11054     * @see android.widget.ScrollBarDrawable
11055     * @hide
11056     */
11057    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11058            int l, int t, int r, int b) {
11059        scrollBar.setBounds(l, t, r, b);
11060        scrollBar.draw(canvas);
11061    }
11062
11063    /**
11064     * Implement this to do your drawing.
11065     *
11066     * @param canvas the canvas on which the background will be drawn
11067     */
11068    protected void onDraw(Canvas canvas) {
11069    }
11070
11071    /*
11072     * Caller is responsible for calling requestLayout if necessary.
11073     * (This allows addViewInLayout to not request a new layout.)
11074     */
11075    void assignParent(ViewParent parent) {
11076        if (mParent == null) {
11077            mParent = parent;
11078        } else if (parent == null) {
11079            mParent = null;
11080        } else {
11081            throw new RuntimeException("view " + this + " being added, but"
11082                    + " it already has a parent");
11083        }
11084    }
11085
11086    /**
11087     * This is called when the view is attached to a window.  At this point it
11088     * has a Surface and will start drawing.  Note that this function is
11089     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11090     * however it may be called any time before the first onDraw -- including
11091     * before or after {@link #onMeasure(int, int)}.
11092     *
11093     * @see #onDetachedFromWindow()
11094     */
11095    protected void onAttachedToWindow() {
11096        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11097            mParent.requestTransparentRegion(this);
11098        }
11099
11100        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11101            initialAwakenScrollBars();
11102            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11103        }
11104
11105        jumpDrawablesToCurrentState();
11106
11107        // Order is important here: LayoutDirection MUST be resolved before Padding
11108        // and TextDirection
11109        resolveLayoutDirection();
11110        resolvePadding();
11111        resolveTextDirection();
11112        resolveTextAlignment();
11113
11114        clearAccessibilityFocus();
11115        if (isFocused()) {
11116            InputMethodManager imm = InputMethodManager.peekInstance();
11117            imm.focusIn(this);
11118        }
11119
11120        if (mAttachInfo != null && mDisplayList != null) {
11121            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11122        }
11123    }
11124
11125    /**
11126     * @see #onScreenStateChanged(int)
11127     */
11128    void dispatchScreenStateChanged(int screenState) {
11129        onScreenStateChanged(screenState);
11130    }
11131
11132    /**
11133     * This method is called whenever the state of the screen this view is
11134     * attached to changes. A state change will usually occurs when the screen
11135     * turns on or off (whether it happens automatically or the user does it
11136     * manually.)
11137     *
11138     * @param screenState The new state of the screen. Can be either
11139     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11140     */
11141    public void onScreenStateChanged(int screenState) {
11142    }
11143
11144    /**
11145     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11146     */
11147    private boolean hasRtlSupport() {
11148        return mContext.getApplicationInfo().hasRtlSupport();
11149    }
11150
11151    /**
11152     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11153     * that the parent directionality can and will be resolved before its children.
11154     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11155     * @hide
11156     */
11157    public void resolveLayoutDirection() {
11158        // Clear any previous layout direction resolution
11159        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11160
11161        if (hasRtlSupport()) {
11162            // Set resolved depending on layout direction
11163            switch (getLayoutDirection()) {
11164                case LAYOUT_DIRECTION_INHERIT:
11165                    // If this is root view, no need to look at parent's layout dir.
11166                    if (canResolveLayoutDirection()) {
11167                        ViewGroup viewGroup = ((ViewGroup) mParent);
11168
11169                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11170                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11171                        }
11172                    } else {
11173                        // Nothing to do, LTR by default
11174                    }
11175                    break;
11176                case LAYOUT_DIRECTION_RTL:
11177                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11178                    break;
11179                case LAYOUT_DIRECTION_LOCALE:
11180                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11181                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11182                    }
11183                    break;
11184                default:
11185                    // Nothing to do, LTR by default
11186            }
11187        }
11188
11189        // Set to resolved
11190        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11191        onResolvedLayoutDirectionChanged();
11192        // Resolve padding
11193        resolvePadding();
11194    }
11195
11196    /**
11197     * Called when layout direction has been resolved.
11198     *
11199     * The default implementation does nothing.
11200     * @hide
11201     */
11202    public void onResolvedLayoutDirectionChanged() {
11203    }
11204
11205    /**
11206     * Resolve padding depending on layout direction.
11207     * @hide
11208     */
11209    public void resolvePadding() {
11210        // If the user specified the absolute padding (either with android:padding or
11211        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11212        // use the default padding or the padding from the background drawable
11213        // (stored at this point in mPadding*)
11214        int resolvedLayoutDirection = getResolvedLayoutDirection();
11215        switch (resolvedLayoutDirection) {
11216            case LAYOUT_DIRECTION_RTL:
11217                // Start user padding override Right user padding. Otherwise, if Right user
11218                // padding is not defined, use the default Right padding. If Right user padding
11219                // is defined, just use it.
11220                if (mUserPaddingStart >= 0) {
11221                    mUserPaddingRight = mUserPaddingStart;
11222                } else if (mUserPaddingRight < 0) {
11223                    mUserPaddingRight = mPaddingRight;
11224                }
11225                if (mUserPaddingEnd >= 0) {
11226                    mUserPaddingLeft = mUserPaddingEnd;
11227                } else if (mUserPaddingLeft < 0) {
11228                    mUserPaddingLeft = mPaddingLeft;
11229                }
11230                break;
11231            case LAYOUT_DIRECTION_LTR:
11232            default:
11233                // Start user padding override Left user padding. Otherwise, if Left user
11234                // padding is not defined, use the default left padding. If Left user padding
11235                // is defined, just use it.
11236                if (mUserPaddingStart >= 0) {
11237                    mUserPaddingLeft = mUserPaddingStart;
11238                } else if (mUserPaddingLeft < 0) {
11239                    mUserPaddingLeft = mPaddingLeft;
11240                }
11241                if (mUserPaddingEnd >= 0) {
11242                    mUserPaddingRight = mUserPaddingEnd;
11243                } else if (mUserPaddingRight < 0) {
11244                    mUserPaddingRight = mPaddingRight;
11245                }
11246        }
11247
11248        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11249
11250        if(isPaddingRelative()) {
11251            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11252        } else {
11253            recomputePadding();
11254        }
11255        onPaddingChanged(resolvedLayoutDirection);
11256    }
11257
11258    /**
11259     * Resolve padding depending on the layout direction. Subclasses that care about
11260     * padding resolution should override this method. The default implementation does
11261     * nothing.
11262     *
11263     * @param layoutDirection the direction of the layout
11264     *
11265     * @see {@link #LAYOUT_DIRECTION_LTR}
11266     * @see {@link #LAYOUT_DIRECTION_RTL}
11267     * @hide
11268     */
11269    public void onPaddingChanged(int layoutDirection) {
11270    }
11271
11272    /**
11273     * Check if layout direction resolution can be done.
11274     *
11275     * @return true if layout direction resolution can be done otherwise return false.
11276     * @hide
11277     */
11278    public boolean canResolveLayoutDirection() {
11279        switch (getLayoutDirection()) {
11280            case LAYOUT_DIRECTION_INHERIT:
11281                return (mParent != null) && (mParent instanceof ViewGroup);
11282            default:
11283                return true;
11284        }
11285    }
11286
11287    /**
11288     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11289     * when reset is done.
11290     * @hide
11291     */
11292    public void resetResolvedLayoutDirection() {
11293        // Reset the current resolved bits
11294        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11295        onResolvedLayoutDirectionReset();
11296        // Reset also the text direction
11297        resetResolvedTextDirection();
11298    }
11299
11300    /**
11301     * Called during reset of resolved layout direction.
11302     *
11303     * Subclasses need to override this method to clear cached information that depends on the
11304     * resolved layout direction, or to inform child views that inherit their layout direction.
11305     *
11306     * The default implementation does nothing.
11307     * @hide
11308     */
11309    public void onResolvedLayoutDirectionReset() {
11310    }
11311
11312    /**
11313     * Check if a Locale uses an RTL script.
11314     *
11315     * @param locale Locale to check
11316     * @return true if the Locale uses an RTL script.
11317     * @hide
11318     */
11319    protected static boolean isLayoutDirectionRtl(Locale locale) {
11320        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11321    }
11322
11323    /**
11324     * This is called when the view is detached from a window.  At this point it
11325     * no longer has a surface for drawing.
11326     *
11327     * @see #onAttachedToWindow()
11328     */
11329    protected void onDetachedFromWindow() {
11330        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11331
11332        removeUnsetPressCallback();
11333        removeLongPressCallback();
11334        removePerformClickCallback();
11335        removeSendViewScrolledAccessibilityEventCallback();
11336
11337        destroyDrawingCache();
11338
11339        destroyLayer(false);
11340
11341        if (mAttachInfo != null) {
11342            if (mDisplayList != null) {
11343                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11344            }
11345            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11346        } else {
11347            if (mDisplayList != null) {
11348                // Should never happen
11349                mDisplayList.invalidate();
11350            }
11351        }
11352
11353        mCurrentAnimation = null;
11354
11355        resetResolvedLayoutDirection();
11356        resetResolvedTextAlignment();
11357        resetAccessibilityStateChanged();
11358    }
11359
11360    /**
11361     * @return The number of times this view has been attached to a window
11362     */
11363    protected int getWindowAttachCount() {
11364        return mWindowAttachCount;
11365    }
11366
11367    /**
11368     * Retrieve a unique token identifying the window this view is attached to.
11369     * @return Return the window's token for use in
11370     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11371     */
11372    public IBinder getWindowToken() {
11373        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11374    }
11375
11376    /**
11377     * Retrieve a unique token identifying the top-level "real" window of
11378     * the window that this view is attached to.  That is, this is like
11379     * {@link #getWindowToken}, except if the window this view in is a panel
11380     * window (attached to another containing window), then the token of
11381     * the containing window is returned instead.
11382     *
11383     * @return Returns the associated window token, either
11384     * {@link #getWindowToken()} or the containing window's token.
11385     */
11386    public IBinder getApplicationWindowToken() {
11387        AttachInfo ai = mAttachInfo;
11388        if (ai != null) {
11389            IBinder appWindowToken = ai.mPanelParentWindowToken;
11390            if (appWindowToken == null) {
11391                appWindowToken = ai.mWindowToken;
11392            }
11393            return appWindowToken;
11394        }
11395        return null;
11396    }
11397
11398    /**
11399     * Retrieve private session object this view hierarchy is using to
11400     * communicate with the window manager.
11401     * @return the session object to communicate with the window manager
11402     */
11403    /*package*/ IWindowSession getWindowSession() {
11404        return mAttachInfo != null ? mAttachInfo.mSession : null;
11405    }
11406
11407    /**
11408     * @param info the {@link android.view.View.AttachInfo} to associated with
11409     *        this view
11410     */
11411    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11412        //System.out.println("Attached! " + this);
11413        mAttachInfo = info;
11414        mWindowAttachCount++;
11415        // We will need to evaluate the drawable state at least once.
11416        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11417        if (mFloatingTreeObserver != null) {
11418            info.mTreeObserver.merge(mFloatingTreeObserver);
11419            mFloatingTreeObserver = null;
11420        }
11421        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11422            mAttachInfo.mScrollContainers.add(this);
11423            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11424        }
11425        performCollectViewAttributes(mAttachInfo, visibility);
11426        onAttachedToWindow();
11427
11428        ListenerInfo li = mListenerInfo;
11429        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11430                li != null ? li.mOnAttachStateChangeListeners : null;
11431        if (listeners != null && listeners.size() > 0) {
11432            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11433            // perform the dispatching. The iterator is a safe guard against listeners that
11434            // could mutate the list by calling the various add/remove methods. This prevents
11435            // the array from being modified while we iterate it.
11436            for (OnAttachStateChangeListener listener : listeners) {
11437                listener.onViewAttachedToWindow(this);
11438            }
11439        }
11440
11441        int vis = info.mWindowVisibility;
11442        if (vis != GONE) {
11443            onWindowVisibilityChanged(vis);
11444        }
11445        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11446            // If nobody has evaluated the drawable state yet, then do it now.
11447            refreshDrawableState();
11448        }
11449    }
11450
11451    void dispatchDetachedFromWindow() {
11452        AttachInfo info = mAttachInfo;
11453        if (info != null) {
11454            int vis = info.mWindowVisibility;
11455            if (vis != GONE) {
11456                onWindowVisibilityChanged(GONE);
11457            }
11458        }
11459
11460        onDetachedFromWindow();
11461
11462        ListenerInfo li = mListenerInfo;
11463        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11464                li != null ? li.mOnAttachStateChangeListeners : null;
11465        if (listeners != null && listeners.size() > 0) {
11466            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11467            // perform the dispatching. The iterator is a safe guard against listeners that
11468            // could mutate the list by calling the various add/remove methods. This prevents
11469            // the array from being modified while we iterate it.
11470            for (OnAttachStateChangeListener listener : listeners) {
11471                listener.onViewDetachedFromWindow(this);
11472            }
11473        }
11474
11475        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11476            mAttachInfo.mScrollContainers.remove(this);
11477            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11478        }
11479
11480        mAttachInfo = null;
11481    }
11482
11483    /**
11484     * Store this view hierarchy's frozen state into the given container.
11485     *
11486     * @param container The SparseArray in which to save the view's state.
11487     *
11488     * @see #restoreHierarchyState(android.util.SparseArray)
11489     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11490     * @see #onSaveInstanceState()
11491     */
11492    public void saveHierarchyState(SparseArray<Parcelable> container) {
11493        dispatchSaveInstanceState(container);
11494    }
11495
11496    /**
11497     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11498     * this view and its children. May be overridden to modify how freezing happens to a
11499     * view's children; for example, some views may want to not store state for their children.
11500     *
11501     * @param container The SparseArray in which to save the view's state.
11502     *
11503     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11504     * @see #saveHierarchyState(android.util.SparseArray)
11505     * @see #onSaveInstanceState()
11506     */
11507    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11508        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11509            mPrivateFlags &= ~SAVE_STATE_CALLED;
11510            Parcelable state = onSaveInstanceState();
11511            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11512                throw new IllegalStateException(
11513                        "Derived class did not call super.onSaveInstanceState()");
11514            }
11515            if (state != null) {
11516                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11517                // + ": " + state);
11518                container.put(mID, state);
11519            }
11520        }
11521    }
11522
11523    /**
11524     * Hook allowing a view to generate a representation of its internal state
11525     * that can later be used to create a new instance with that same state.
11526     * This state should only contain information that is not persistent or can
11527     * not be reconstructed later. For example, you will never store your
11528     * current position on screen because that will be computed again when a
11529     * new instance of the view is placed in its view hierarchy.
11530     * <p>
11531     * Some examples of things you may store here: the current cursor position
11532     * in a text view (but usually not the text itself since that is stored in a
11533     * content provider or other persistent storage), the currently selected
11534     * item in a list view.
11535     *
11536     * @return Returns a Parcelable object containing the view's current dynamic
11537     *         state, or null if there is nothing interesting to save. The
11538     *         default implementation returns null.
11539     * @see #onRestoreInstanceState(android.os.Parcelable)
11540     * @see #saveHierarchyState(android.util.SparseArray)
11541     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11542     * @see #setSaveEnabled(boolean)
11543     */
11544    protected Parcelable onSaveInstanceState() {
11545        mPrivateFlags |= SAVE_STATE_CALLED;
11546        return BaseSavedState.EMPTY_STATE;
11547    }
11548
11549    /**
11550     * Restore this view hierarchy's frozen state from the given container.
11551     *
11552     * @param container The SparseArray which holds previously frozen states.
11553     *
11554     * @see #saveHierarchyState(android.util.SparseArray)
11555     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11556     * @see #onRestoreInstanceState(android.os.Parcelable)
11557     */
11558    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11559        dispatchRestoreInstanceState(container);
11560    }
11561
11562    /**
11563     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11564     * state for this view and its children. May be overridden to modify how restoring
11565     * happens to a view's children; for example, some views may want to not store state
11566     * for their children.
11567     *
11568     * @param container The SparseArray which holds previously saved state.
11569     *
11570     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11571     * @see #restoreHierarchyState(android.util.SparseArray)
11572     * @see #onRestoreInstanceState(android.os.Parcelable)
11573     */
11574    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11575        if (mID != NO_ID) {
11576            Parcelable state = container.get(mID);
11577            if (state != null) {
11578                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11579                // + ": " + state);
11580                mPrivateFlags &= ~SAVE_STATE_CALLED;
11581                onRestoreInstanceState(state);
11582                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11583                    throw new IllegalStateException(
11584                            "Derived class did not call super.onRestoreInstanceState()");
11585                }
11586            }
11587        }
11588    }
11589
11590    /**
11591     * Hook allowing a view to re-apply a representation of its internal state that had previously
11592     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11593     * null state.
11594     *
11595     * @param state The frozen state that had previously been returned by
11596     *        {@link #onSaveInstanceState}.
11597     *
11598     * @see #onSaveInstanceState()
11599     * @see #restoreHierarchyState(android.util.SparseArray)
11600     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11601     */
11602    protected void onRestoreInstanceState(Parcelable state) {
11603        mPrivateFlags |= SAVE_STATE_CALLED;
11604        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11605            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11606                    + "received " + state.getClass().toString() + " instead. This usually happens "
11607                    + "when two views of different type have the same id in the same hierarchy. "
11608                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11609                    + "other views do not use the same id.");
11610        }
11611    }
11612
11613    /**
11614     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11615     *
11616     * @return the drawing start time in milliseconds
11617     */
11618    public long getDrawingTime() {
11619        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11620    }
11621
11622    /**
11623     * <p>Enables or disables the duplication of the parent's state into this view. When
11624     * duplication is enabled, this view gets its drawable state from its parent rather
11625     * than from its own internal properties.</p>
11626     *
11627     * <p>Note: in the current implementation, setting this property to true after the
11628     * view was added to a ViewGroup might have no effect at all. This property should
11629     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11630     *
11631     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11632     * property is enabled, an exception will be thrown.</p>
11633     *
11634     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11635     * parent, these states should not be affected by this method.</p>
11636     *
11637     * @param enabled True to enable duplication of the parent's drawable state, false
11638     *                to disable it.
11639     *
11640     * @see #getDrawableState()
11641     * @see #isDuplicateParentStateEnabled()
11642     */
11643    public void setDuplicateParentStateEnabled(boolean enabled) {
11644        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11645    }
11646
11647    /**
11648     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11649     *
11650     * @return True if this view's drawable state is duplicated from the parent,
11651     *         false otherwise
11652     *
11653     * @see #getDrawableState()
11654     * @see #setDuplicateParentStateEnabled(boolean)
11655     */
11656    public boolean isDuplicateParentStateEnabled() {
11657        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11658    }
11659
11660    /**
11661     * <p>Specifies the type of layer backing this view. The layer can be
11662     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11663     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11664     *
11665     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11666     * instance that controls how the layer is composed on screen. The following
11667     * properties of the paint are taken into account when composing the layer:</p>
11668     * <ul>
11669     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11670     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11671     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11672     * </ul>
11673     *
11674     * <p>If this view has an alpha value set to < 1.0 by calling
11675     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11676     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11677     * equivalent to setting a hardware layer on this view and providing a paint with
11678     * the desired alpha value.<p>
11679     *
11680     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11681     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11682     * for more information on when and how to use layers.</p>
11683     *
11684     * @param layerType The ype of layer to use with this view, must be one of
11685     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11686     *        {@link #LAYER_TYPE_HARDWARE}
11687     * @param paint The paint used to compose the layer. This argument is optional
11688     *        and can be null. It is ignored when the layer type is
11689     *        {@link #LAYER_TYPE_NONE}
11690     *
11691     * @see #getLayerType()
11692     * @see #LAYER_TYPE_NONE
11693     * @see #LAYER_TYPE_SOFTWARE
11694     * @see #LAYER_TYPE_HARDWARE
11695     * @see #setAlpha(float)
11696     *
11697     * @attr ref android.R.styleable#View_layerType
11698     */
11699    public void setLayerType(int layerType, Paint paint) {
11700        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11701            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11702                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11703        }
11704
11705        if (layerType == mLayerType) {
11706            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11707                mLayerPaint = paint == null ? new Paint() : paint;
11708                invalidateParentCaches();
11709                invalidate(true);
11710            }
11711            return;
11712        }
11713
11714        // Destroy any previous software drawing cache if needed
11715        switch (mLayerType) {
11716            case LAYER_TYPE_HARDWARE:
11717                destroyLayer(false);
11718                // fall through - non-accelerated views may use software layer mechanism instead
11719            case LAYER_TYPE_SOFTWARE:
11720                destroyDrawingCache();
11721                break;
11722            default:
11723                break;
11724        }
11725
11726        mLayerType = layerType;
11727        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11728        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11729        mLocalDirtyRect = layerDisabled ? null : new Rect();
11730
11731        invalidateParentCaches();
11732        invalidate(true);
11733    }
11734
11735    /**
11736     * Indicates whether this view has a static layer. A view with layer type
11737     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11738     * dynamic.
11739     */
11740    boolean hasStaticLayer() {
11741        return true;
11742    }
11743
11744    /**
11745     * Indicates what type of layer is currently associated with this view. By default
11746     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11747     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11748     * for more information on the different types of layers.
11749     *
11750     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11751     *         {@link #LAYER_TYPE_HARDWARE}
11752     *
11753     * @see #setLayerType(int, android.graphics.Paint)
11754     * @see #buildLayer()
11755     * @see #LAYER_TYPE_NONE
11756     * @see #LAYER_TYPE_SOFTWARE
11757     * @see #LAYER_TYPE_HARDWARE
11758     */
11759    public int getLayerType() {
11760        return mLayerType;
11761    }
11762
11763    /**
11764     * Forces this view's layer to be created and this view to be rendered
11765     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11766     * invoking this method will have no effect.
11767     *
11768     * This method can for instance be used to render a view into its layer before
11769     * starting an animation. If this view is complex, rendering into the layer
11770     * before starting the animation will avoid skipping frames.
11771     *
11772     * @throws IllegalStateException If this view is not attached to a window
11773     *
11774     * @see #setLayerType(int, android.graphics.Paint)
11775     */
11776    public void buildLayer() {
11777        if (mLayerType == LAYER_TYPE_NONE) return;
11778
11779        if (mAttachInfo == null) {
11780            throw new IllegalStateException("This view must be attached to a window first");
11781        }
11782
11783        switch (mLayerType) {
11784            case LAYER_TYPE_HARDWARE:
11785                if (mAttachInfo.mHardwareRenderer != null &&
11786                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11787                        mAttachInfo.mHardwareRenderer.validate()) {
11788                    getHardwareLayer();
11789                }
11790                break;
11791            case LAYER_TYPE_SOFTWARE:
11792                buildDrawingCache(true);
11793                break;
11794        }
11795    }
11796
11797    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11798    void flushLayer() {
11799        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11800            mHardwareLayer.flush();
11801        }
11802    }
11803
11804    /**
11805     * <p>Returns a hardware layer that can be used to draw this view again
11806     * without executing its draw method.</p>
11807     *
11808     * @return A HardwareLayer ready to render, or null if an error occurred.
11809     */
11810    HardwareLayer getHardwareLayer() {
11811        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11812                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11813            return null;
11814        }
11815
11816        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11817
11818        final int width = mRight - mLeft;
11819        final int height = mBottom - mTop;
11820
11821        if (width == 0 || height == 0) {
11822            return null;
11823        }
11824
11825        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11826            if (mHardwareLayer == null) {
11827                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11828                        width, height, isOpaque());
11829                mLocalDirtyRect.set(0, 0, width, height);
11830            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11831                mHardwareLayer.resize(width, height);
11832                mLocalDirtyRect.set(0, 0, width, height);
11833            }
11834
11835            // The layer is not valid if the underlying GPU resources cannot be allocated
11836            if (!mHardwareLayer.isValid()) {
11837                return null;
11838            }
11839
11840            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11841            mLocalDirtyRect.setEmpty();
11842        }
11843
11844        return mHardwareLayer;
11845    }
11846
11847    /**
11848     * Destroys this View's hardware layer if possible.
11849     *
11850     * @return True if the layer was destroyed, false otherwise.
11851     *
11852     * @see #setLayerType(int, android.graphics.Paint)
11853     * @see #LAYER_TYPE_HARDWARE
11854     */
11855    boolean destroyLayer(boolean valid) {
11856        if (mHardwareLayer != null) {
11857            AttachInfo info = mAttachInfo;
11858            if (info != null && info.mHardwareRenderer != null &&
11859                    info.mHardwareRenderer.isEnabled() &&
11860                    (valid || info.mHardwareRenderer.validate())) {
11861                mHardwareLayer.destroy();
11862                mHardwareLayer = null;
11863
11864                invalidate(true);
11865                invalidateParentCaches();
11866            }
11867            return true;
11868        }
11869        return false;
11870    }
11871
11872    /**
11873     * Destroys all hardware rendering resources. This method is invoked
11874     * when the system needs to reclaim resources. Upon execution of this
11875     * method, you should free any OpenGL resources created by the view.
11876     *
11877     * Note: you <strong>must</strong> call
11878     * <code>super.destroyHardwareResources()</code> when overriding
11879     * this method.
11880     *
11881     * @hide
11882     */
11883    protected void destroyHardwareResources() {
11884        destroyLayer(true);
11885    }
11886
11887    /**
11888     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11889     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11890     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11891     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11892     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11893     * null.</p>
11894     *
11895     * <p>Enabling the drawing cache is similar to
11896     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11897     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11898     * drawing cache has no effect on rendering because the system uses a different mechanism
11899     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11900     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11901     * for information on how to enable software and hardware layers.</p>
11902     *
11903     * <p>This API can be used to manually generate
11904     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11905     * {@link #getDrawingCache()}.</p>
11906     *
11907     * @param enabled true to enable the drawing cache, false otherwise
11908     *
11909     * @see #isDrawingCacheEnabled()
11910     * @see #getDrawingCache()
11911     * @see #buildDrawingCache()
11912     * @see #setLayerType(int, android.graphics.Paint)
11913     */
11914    public void setDrawingCacheEnabled(boolean enabled) {
11915        mCachingFailed = false;
11916        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11917    }
11918
11919    /**
11920     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11921     *
11922     * @return true if the drawing cache is enabled
11923     *
11924     * @see #setDrawingCacheEnabled(boolean)
11925     * @see #getDrawingCache()
11926     */
11927    @ViewDebug.ExportedProperty(category = "drawing")
11928    public boolean isDrawingCacheEnabled() {
11929        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11930    }
11931
11932    /**
11933     * Debugging utility which recursively outputs the dirty state of a view and its
11934     * descendants.
11935     *
11936     * @hide
11937     */
11938    @SuppressWarnings({"UnusedDeclaration"})
11939    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11940        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11941                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11942                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11943                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11944        if (clear) {
11945            mPrivateFlags &= clearMask;
11946        }
11947        if (this instanceof ViewGroup) {
11948            ViewGroup parent = (ViewGroup) this;
11949            final int count = parent.getChildCount();
11950            for (int i = 0; i < count; i++) {
11951                final View child = parent.getChildAt(i);
11952                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11953            }
11954        }
11955    }
11956
11957    /**
11958     * This method is used by ViewGroup to cause its children to restore or recreate their
11959     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11960     * to recreate its own display list, which would happen if it went through the normal
11961     * draw/dispatchDraw mechanisms.
11962     *
11963     * @hide
11964     */
11965    protected void dispatchGetDisplayList() {}
11966
11967    /**
11968     * A view that is not attached or hardware accelerated cannot create a display list.
11969     * This method checks these conditions and returns the appropriate result.
11970     *
11971     * @return true if view has the ability to create a display list, false otherwise.
11972     *
11973     * @hide
11974     */
11975    public boolean canHaveDisplayList() {
11976        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11977    }
11978
11979    /**
11980     * @return The HardwareRenderer associated with that view or null if hardware rendering
11981     * is not supported or this this has not been attached to a window.
11982     *
11983     * @hide
11984     */
11985    public HardwareRenderer getHardwareRenderer() {
11986        if (mAttachInfo != null) {
11987            return mAttachInfo.mHardwareRenderer;
11988        }
11989        return null;
11990    }
11991
11992    /**
11993     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11994     * Otherwise, the same display list will be returned (after having been rendered into
11995     * along the way, depending on the invalidation state of the view).
11996     *
11997     * @param displayList The previous version of this displayList, could be null.
11998     * @param isLayer Whether the requester of the display list is a layer. If so,
11999     * the view will avoid creating a layer inside the resulting display list.
12000     * @return A new or reused DisplayList object.
12001     */
12002    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12003        if (!canHaveDisplayList()) {
12004            return null;
12005        }
12006
12007        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12008                displayList == null || !displayList.isValid() ||
12009                (!isLayer && mRecreateDisplayList))) {
12010            // Don't need to recreate the display list, just need to tell our
12011            // children to restore/recreate theirs
12012            if (displayList != null && displayList.isValid() &&
12013                    !isLayer && !mRecreateDisplayList) {
12014                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12015                mPrivateFlags &= ~DIRTY_MASK;
12016                dispatchGetDisplayList();
12017
12018                return displayList;
12019            }
12020
12021            if (!isLayer) {
12022                // If we got here, we're recreating it. Mark it as such to ensure that
12023                // we copy in child display lists into ours in drawChild()
12024                mRecreateDisplayList = true;
12025            }
12026            if (displayList == null) {
12027                final String name = getClass().getSimpleName();
12028                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12029                // If we're creating a new display list, make sure our parent gets invalidated
12030                // since they will need to recreate their display list to account for this
12031                // new child display list.
12032                invalidateParentCaches();
12033            }
12034
12035            boolean caching = false;
12036            final HardwareCanvas canvas = displayList.start();
12037            int width = mRight - mLeft;
12038            int height = mBottom - mTop;
12039
12040            try {
12041                canvas.setViewport(width, height);
12042                // The dirty rect should always be null for a display list
12043                canvas.onPreDraw(null);
12044                int layerType = (
12045                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12046                        getLayerType() : LAYER_TYPE_NONE;
12047                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12048                    if (layerType == LAYER_TYPE_HARDWARE) {
12049                        final HardwareLayer layer = getHardwareLayer();
12050                        if (layer != null && layer.isValid()) {
12051                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12052                        } else {
12053                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12054                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12055                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12056                        }
12057                        caching = true;
12058                    } else {
12059                        buildDrawingCache(true);
12060                        Bitmap cache = getDrawingCache(true);
12061                        if (cache != null) {
12062                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12063                            caching = true;
12064                        }
12065                    }
12066                } else {
12067
12068                    computeScroll();
12069
12070                    canvas.translate(-mScrollX, -mScrollY);
12071                    if (!isLayer) {
12072                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12073                        mPrivateFlags &= ~DIRTY_MASK;
12074                    }
12075
12076                    // Fast path for layouts with no backgrounds
12077                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12078                        dispatchDraw(canvas);
12079                    } else {
12080                        draw(canvas);
12081                    }
12082                }
12083            } finally {
12084                canvas.onPostDraw();
12085
12086                displayList.end();
12087                displayList.setCaching(caching);
12088                if (isLayer) {
12089                    displayList.setLeftTopRightBottom(0, 0, width, height);
12090                } else {
12091                    setDisplayListProperties(displayList);
12092                }
12093            }
12094        } else if (!isLayer) {
12095            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12096            mPrivateFlags &= ~DIRTY_MASK;
12097        }
12098
12099        return displayList;
12100    }
12101
12102    /**
12103     * Get the DisplayList for the HardwareLayer
12104     *
12105     * @param layer The HardwareLayer whose DisplayList we want
12106     * @return A DisplayList fopr the specified HardwareLayer
12107     */
12108    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12109        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12110        layer.setDisplayList(displayList);
12111        return displayList;
12112    }
12113
12114
12115    /**
12116     * <p>Returns a display list that can be used to draw this view again
12117     * without executing its draw method.</p>
12118     *
12119     * @return A DisplayList ready to replay, or null if caching is not enabled.
12120     *
12121     * @hide
12122     */
12123    public DisplayList getDisplayList() {
12124        mDisplayList = getDisplayList(mDisplayList, false);
12125        return mDisplayList;
12126    }
12127
12128    /**
12129     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12130     *
12131     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12132     *
12133     * @see #getDrawingCache(boolean)
12134     */
12135    public Bitmap getDrawingCache() {
12136        return getDrawingCache(false);
12137    }
12138
12139    /**
12140     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12141     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12142     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12143     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12144     * request the drawing cache by calling this method and draw it on screen if the
12145     * returned bitmap is not null.</p>
12146     *
12147     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12148     * this method will create a bitmap of the same size as this view. Because this bitmap
12149     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12150     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12151     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12152     * size than the view. This implies that your application must be able to handle this
12153     * size.</p>
12154     *
12155     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12156     *        the current density of the screen when the application is in compatibility
12157     *        mode.
12158     *
12159     * @return A bitmap representing this view or null if cache is disabled.
12160     *
12161     * @see #setDrawingCacheEnabled(boolean)
12162     * @see #isDrawingCacheEnabled()
12163     * @see #buildDrawingCache(boolean)
12164     * @see #destroyDrawingCache()
12165     */
12166    public Bitmap getDrawingCache(boolean autoScale) {
12167        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12168            return null;
12169        }
12170        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12171            buildDrawingCache(autoScale);
12172        }
12173        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12174    }
12175
12176    /**
12177     * <p>Frees the resources used by the drawing cache. If you call
12178     * {@link #buildDrawingCache()} manually without calling
12179     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12180     * should cleanup the cache with this method afterwards.</p>
12181     *
12182     * @see #setDrawingCacheEnabled(boolean)
12183     * @see #buildDrawingCache()
12184     * @see #getDrawingCache()
12185     */
12186    public void destroyDrawingCache() {
12187        if (mDrawingCache != null) {
12188            mDrawingCache.recycle();
12189            mDrawingCache = null;
12190        }
12191        if (mUnscaledDrawingCache != null) {
12192            mUnscaledDrawingCache.recycle();
12193            mUnscaledDrawingCache = null;
12194        }
12195    }
12196
12197    /**
12198     * Setting a solid background color for the drawing cache's bitmaps will improve
12199     * performance and memory usage. Note, though that this should only be used if this
12200     * view will always be drawn on top of a solid color.
12201     *
12202     * @param color The background color to use for the drawing cache's bitmap
12203     *
12204     * @see #setDrawingCacheEnabled(boolean)
12205     * @see #buildDrawingCache()
12206     * @see #getDrawingCache()
12207     */
12208    public void setDrawingCacheBackgroundColor(int color) {
12209        if (color != mDrawingCacheBackgroundColor) {
12210            mDrawingCacheBackgroundColor = color;
12211            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12212        }
12213    }
12214
12215    /**
12216     * @see #setDrawingCacheBackgroundColor(int)
12217     *
12218     * @return The background color to used for the drawing cache's bitmap
12219     */
12220    public int getDrawingCacheBackgroundColor() {
12221        return mDrawingCacheBackgroundColor;
12222    }
12223
12224    /**
12225     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12226     *
12227     * @see #buildDrawingCache(boolean)
12228     */
12229    public void buildDrawingCache() {
12230        buildDrawingCache(false);
12231    }
12232
12233    /**
12234     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12235     *
12236     * <p>If you call {@link #buildDrawingCache()} manually without calling
12237     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12238     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12239     *
12240     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12241     * this method will create a bitmap of the same size as this view. Because this bitmap
12242     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12243     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12244     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12245     * size than the view. This implies that your application must be able to handle this
12246     * size.</p>
12247     *
12248     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12249     * you do not need the drawing cache bitmap, calling this method will increase memory
12250     * usage and cause the view to be rendered in software once, thus negatively impacting
12251     * performance.</p>
12252     *
12253     * @see #getDrawingCache()
12254     * @see #destroyDrawingCache()
12255     */
12256    public void buildDrawingCache(boolean autoScale) {
12257        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12258                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12259            mCachingFailed = false;
12260
12261            if (ViewDebug.TRACE_HIERARCHY) {
12262                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
12263            }
12264
12265            int width = mRight - mLeft;
12266            int height = mBottom - mTop;
12267
12268            final AttachInfo attachInfo = mAttachInfo;
12269            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12270
12271            if (autoScale && scalingRequired) {
12272                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12273                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12274            }
12275
12276            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12277            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12278            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12279
12280            if (width <= 0 || height <= 0 ||
12281                     // Projected bitmap size in bytes
12282                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12283                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12284                destroyDrawingCache();
12285                mCachingFailed = true;
12286                return;
12287            }
12288
12289            boolean clear = true;
12290            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12291
12292            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12293                Bitmap.Config quality;
12294                if (!opaque) {
12295                    // Never pick ARGB_4444 because it looks awful
12296                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12297                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12298                        case DRAWING_CACHE_QUALITY_AUTO:
12299                            quality = Bitmap.Config.ARGB_8888;
12300                            break;
12301                        case DRAWING_CACHE_QUALITY_LOW:
12302                            quality = Bitmap.Config.ARGB_8888;
12303                            break;
12304                        case DRAWING_CACHE_QUALITY_HIGH:
12305                            quality = Bitmap.Config.ARGB_8888;
12306                            break;
12307                        default:
12308                            quality = Bitmap.Config.ARGB_8888;
12309                            break;
12310                    }
12311                } else {
12312                    // Optimization for translucent windows
12313                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12314                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12315                }
12316
12317                // Try to cleanup memory
12318                if (bitmap != null) bitmap.recycle();
12319
12320                try {
12321                    bitmap = Bitmap.createBitmap(width, height, quality);
12322                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12323                    if (autoScale) {
12324                        mDrawingCache = bitmap;
12325                    } else {
12326                        mUnscaledDrawingCache = bitmap;
12327                    }
12328                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12329                } catch (OutOfMemoryError e) {
12330                    // If there is not enough memory to create the bitmap cache, just
12331                    // ignore the issue as bitmap caches are not required to draw the
12332                    // view hierarchy
12333                    if (autoScale) {
12334                        mDrawingCache = null;
12335                    } else {
12336                        mUnscaledDrawingCache = null;
12337                    }
12338                    mCachingFailed = true;
12339                    return;
12340                }
12341
12342                clear = drawingCacheBackgroundColor != 0;
12343            }
12344
12345            Canvas canvas;
12346            if (attachInfo != null) {
12347                canvas = attachInfo.mCanvas;
12348                if (canvas == null) {
12349                    canvas = new Canvas();
12350                }
12351                canvas.setBitmap(bitmap);
12352                // Temporarily clobber the cached Canvas in case one of our children
12353                // is also using a drawing cache. Without this, the children would
12354                // steal the canvas by attaching their own bitmap to it and bad, bad
12355                // thing would happen (invisible views, corrupted drawings, etc.)
12356                attachInfo.mCanvas = null;
12357            } else {
12358                // This case should hopefully never or seldom happen
12359                canvas = new Canvas(bitmap);
12360            }
12361
12362            if (clear) {
12363                bitmap.eraseColor(drawingCacheBackgroundColor);
12364            }
12365
12366            computeScroll();
12367            final int restoreCount = canvas.save();
12368
12369            if (autoScale && scalingRequired) {
12370                final float scale = attachInfo.mApplicationScale;
12371                canvas.scale(scale, scale);
12372            }
12373
12374            canvas.translate(-mScrollX, -mScrollY);
12375
12376            mPrivateFlags |= DRAWN;
12377            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12378                    mLayerType != LAYER_TYPE_NONE) {
12379                mPrivateFlags |= DRAWING_CACHE_VALID;
12380            }
12381
12382            // Fast path for layouts with no backgrounds
12383            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12384                if (ViewDebug.TRACE_HIERARCHY) {
12385                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12386                }
12387                mPrivateFlags &= ~DIRTY_MASK;
12388                dispatchDraw(canvas);
12389            } else {
12390                draw(canvas);
12391            }
12392
12393            canvas.restoreToCount(restoreCount);
12394            canvas.setBitmap(null);
12395
12396            if (attachInfo != null) {
12397                // Restore the cached Canvas for our siblings
12398                attachInfo.mCanvas = canvas;
12399            }
12400        }
12401    }
12402
12403    /**
12404     * Create a snapshot of the view into a bitmap.  We should probably make
12405     * some form of this public, but should think about the API.
12406     */
12407    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12408        int width = mRight - mLeft;
12409        int height = mBottom - mTop;
12410
12411        final AttachInfo attachInfo = mAttachInfo;
12412        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12413        width = (int) ((width * scale) + 0.5f);
12414        height = (int) ((height * scale) + 0.5f);
12415
12416        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12417        if (bitmap == null) {
12418            throw new OutOfMemoryError();
12419        }
12420
12421        Resources resources = getResources();
12422        if (resources != null) {
12423            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12424        }
12425
12426        Canvas canvas;
12427        if (attachInfo != null) {
12428            canvas = attachInfo.mCanvas;
12429            if (canvas == null) {
12430                canvas = new Canvas();
12431            }
12432            canvas.setBitmap(bitmap);
12433            // Temporarily clobber the cached Canvas in case one of our children
12434            // is also using a drawing cache. Without this, the children would
12435            // steal the canvas by attaching their own bitmap to it and bad, bad
12436            // things would happen (invisible views, corrupted drawings, etc.)
12437            attachInfo.mCanvas = null;
12438        } else {
12439            // This case should hopefully never or seldom happen
12440            canvas = new Canvas(bitmap);
12441        }
12442
12443        if ((backgroundColor & 0xff000000) != 0) {
12444            bitmap.eraseColor(backgroundColor);
12445        }
12446
12447        computeScroll();
12448        final int restoreCount = canvas.save();
12449        canvas.scale(scale, scale);
12450        canvas.translate(-mScrollX, -mScrollY);
12451
12452        // Temporarily remove the dirty mask
12453        int flags = mPrivateFlags;
12454        mPrivateFlags &= ~DIRTY_MASK;
12455
12456        // Fast path for layouts with no backgrounds
12457        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12458            dispatchDraw(canvas);
12459        } else {
12460            draw(canvas);
12461        }
12462
12463        mPrivateFlags = flags;
12464
12465        canvas.restoreToCount(restoreCount);
12466        canvas.setBitmap(null);
12467
12468        if (attachInfo != null) {
12469            // Restore the cached Canvas for our siblings
12470            attachInfo.mCanvas = canvas;
12471        }
12472
12473        return bitmap;
12474    }
12475
12476    /**
12477     * Indicates whether this View is currently in edit mode. A View is usually
12478     * in edit mode when displayed within a developer tool. For instance, if
12479     * this View is being drawn by a visual user interface builder, this method
12480     * should return true.
12481     *
12482     * Subclasses should check the return value of this method to provide
12483     * different behaviors if their normal behavior might interfere with the
12484     * host environment. For instance: the class spawns a thread in its
12485     * constructor, the drawing code relies on device-specific features, etc.
12486     *
12487     * This method is usually checked in the drawing code of custom widgets.
12488     *
12489     * @return True if this View is in edit mode, false otherwise.
12490     */
12491    public boolean isInEditMode() {
12492        return false;
12493    }
12494
12495    /**
12496     * If the View draws content inside its padding and enables fading edges,
12497     * it needs to support padding offsets. Padding offsets are added to the
12498     * fading edges to extend the length of the fade so that it covers pixels
12499     * drawn inside the padding.
12500     *
12501     * Subclasses of this class should override this method if they need
12502     * to draw content inside the padding.
12503     *
12504     * @return True if padding offset must be applied, false otherwise.
12505     *
12506     * @see #getLeftPaddingOffset()
12507     * @see #getRightPaddingOffset()
12508     * @see #getTopPaddingOffset()
12509     * @see #getBottomPaddingOffset()
12510     *
12511     * @since CURRENT
12512     */
12513    protected boolean isPaddingOffsetRequired() {
12514        return false;
12515    }
12516
12517    /**
12518     * Amount by which to extend the left fading region. Called only when
12519     * {@link #isPaddingOffsetRequired()} returns true.
12520     *
12521     * @return The left padding offset in pixels.
12522     *
12523     * @see #isPaddingOffsetRequired()
12524     *
12525     * @since CURRENT
12526     */
12527    protected int getLeftPaddingOffset() {
12528        return 0;
12529    }
12530
12531    /**
12532     * Amount by which to extend the right fading region. Called only when
12533     * {@link #isPaddingOffsetRequired()} returns true.
12534     *
12535     * @return The right padding offset in pixels.
12536     *
12537     * @see #isPaddingOffsetRequired()
12538     *
12539     * @since CURRENT
12540     */
12541    protected int getRightPaddingOffset() {
12542        return 0;
12543    }
12544
12545    /**
12546     * Amount by which to extend the top fading region. Called only when
12547     * {@link #isPaddingOffsetRequired()} returns true.
12548     *
12549     * @return The top padding offset in pixels.
12550     *
12551     * @see #isPaddingOffsetRequired()
12552     *
12553     * @since CURRENT
12554     */
12555    protected int getTopPaddingOffset() {
12556        return 0;
12557    }
12558
12559    /**
12560     * Amount by which to extend the bottom fading region. Called only when
12561     * {@link #isPaddingOffsetRequired()} returns true.
12562     *
12563     * @return The bottom padding offset in pixels.
12564     *
12565     * @see #isPaddingOffsetRequired()
12566     *
12567     * @since CURRENT
12568     */
12569    protected int getBottomPaddingOffset() {
12570        return 0;
12571    }
12572
12573    /**
12574     * @hide
12575     * @param offsetRequired
12576     */
12577    protected int getFadeTop(boolean offsetRequired) {
12578        int top = mPaddingTop;
12579        if (offsetRequired) top += getTopPaddingOffset();
12580        return top;
12581    }
12582
12583    /**
12584     * @hide
12585     * @param offsetRequired
12586     */
12587    protected int getFadeHeight(boolean offsetRequired) {
12588        int padding = mPaddingTop;
12589        if (offsetRequired) padding += getTopPaddingOffset();
12590        return mBottom - mTop - mPaddingBottom - padding;
12591    }
12592
12593    /**
12594     * <p>Indicates whether this view is attached to a hardware accelerated
12595     * window or not.</p>
12596     *
12597     * <p>Even if this method returns true, it does not mean that every call
12598     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12599     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12600     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12601     * window is hardware accelerated,
12602     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12603     * return false, and this method will return true.</p>
12604     *
12605     * @return True if the view is attached to a window and the window is
12606     *         hardware accelerated; false in any other case.
12607     */
12608    public boolean isHardwareAccelerated() {
12609        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12610    }
12611
12612    /**
12613     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12614     * case of an active Animation being run on the view.
12615     */
12616    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12617            Animation a, boolean scalingRequired) {
12618        Transformation invalidationTransform;
12619        final int flags = parent.mGroupFlags;
12620        final boolean initialized = a.isInitialized();
12621        if (!initialized) {
12622            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12623            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12624            onAnimationStart();
12625        }
12626
12627        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12628        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12629            if (parent.mInvalidationTransformation == null) {
12630                parent.mInvalidationTransformation = new Transformation();
12631            }
12632            invalidationTransform = parent.mInvalidationTransformation;
12633            a.getTransformation(drawingTime, invalidationTransform, 1f);
12634        } else {
12635            invalidationTransform = parent.mChildTransformation;
12636        }
12637        if (more) {
12638            if (!a.willChangeBounds()) {
12639                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12640                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12641                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12642                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12643                    // The child need to draw an animation, potentially offscreen, so
12644                    // make sure we do not cancel invalidate requests
12645                    parent.mPrivateFlags |= DRAW_ANIMATION;
12646                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12647                }
12648            } else {
12649                if (parent.mInvalidateRegion == null) {
12650                    parent.mInvalidateRegion = new RectF();
12651                }
12652                final RectF region = parent.mInvalidateRegion;
12653                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12654                        invalidationTransform);
12655
12656                // The child need to draw an animation, potentially offscreen, so
12657                // make sure we do not cancel invalidate requests
12658                parent.mPrivateFlags |= DRAW_ANIMATION;
12659
12660                final int left = mLeft + (int) region.left;
12661                final int top = mTop + (int) region.top;
12662                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12663                        top + (int) (region.height() + .5f));
12664            }
12665        }
12666        return more;
12667    }
12668
12669    /**
12670     * This method is called by getDisplayList() when a display list is created or re-rendered.
12671     * It sets or resets the current value of all properties on that display list (resetting is
12672     * necessary when a display list is being re-created, because we need to make sure that
12673     * previously-set transform values
12674     */
12675    void setDisplayListProperties(DisplayList displayList) {
12676        if (displayList != null) {
12677            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12678            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12679            if (mParent instanceof ViewGroup) {
12680                displayList.setClipChildren(
12681                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12682            }
12683            float alpha = 1;
12684            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12685                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12686                ViewGroup parentVG = (ViewGroup) mParent;
12687                final boolean hasTransform =
12688                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12689                if (hasTransform) {
12690                    Transformation transform = parentVG.mChildTransformation;
12691                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12692                    if (transformType != Transformation.TYPE_IDENTITY) {
12693                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12694                            alpha = transform.getAlpha();
12695                        }
12696                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12697                            displayList.setStaticMatrix(transform.getMatrix());
12698                        }
12699                    }
12700                }
12701            }
12702            if (mTransformationInfo != null) {
12703                alpha *= mTransformationInfo.mAlpha;
12704                if (alpha < 1) {
12705                    final int multipliedAlpha = (int) (255 * alpha);
12706                    if (onSetAlpha(multipliedAlpha)) {
12707                        alpha = 1;
12708                    }
12709                }
12710                displayList.setTransformationInfo(alpha,
12711                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12712                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12713                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12714                        mTransformationInfo.mScaleY);
12715                if (mTransformationInfo.mCamera == null) {
12716                    mTransformationInfo.mCamera = new Camera();
12717                    mTransformationInfo.matrix3D = new Matrix();
12718                }
12719                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12720                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12721                    displayList.setPivotX(getPivotX());
12722                    displayList.setPivotY(getPivotY());
12723                }
12724            } else if (alpha < 1) {
12725                displayList.setAlpha(alpha);
12726            }
12727        }
12728    }
12729
12730    /**
12731     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12732     * This draw() method is an implementation detail and is not intended to be overridden or
12733     * to be called from anywhere else other than ViewGroup.drawChild().
12734     */
12735    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12736        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12737        boolean more = false;
12738        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12739        final int flags = parent.mGroupFlags;
12740
12741        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12742            parent.mChildTransformation.clear();
12743            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12744        }
12745
12746        Transformation transformToApply = null;
12747        boolean concatMatrix = false;
12748
12749        boolean scalingRequired = false;
12750        boolean caching;
12751        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12752
12753        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12754        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12755                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12756            caching = true;
12757            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12758            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12759        } else {
12760            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12761        }
12762
12763        final Animation a = getAnimation();
12764        if (a != null) {
12765            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12766            concatMatrix = a.willChangeTransformationMatrix();
12767            transformToApply = parent.mChildTransformation;
12768        } else if (!useDisplayListProperties &&
12769                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12770            final boolean hasTransform =
12771                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12772            if (hasTransform) {
12773                final int transformType = parent.mChildTransformation.getTransformationType();
12774                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12775                        parent.mChildTransformation : null;
12776                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12777            }
12778        }
12779
12780        concatMatrix |= !childHasIdentityMatrix;
12781
12782        // Sets the flag as early as possible to allow draw() implementations
12783        // to call invalidate() successfully when doing animations
12784        mPrivateFlags |= DRAWN;
12785
12786        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12787                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12788            return more;
12789        }
12790
12791        if (hardwareAccelerated) {
12792            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12793            // retain the flag's value temporarily in the mRecreateDisplayList flag
12794            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12795            mPrivateFlags &= ~INVALIDATED;
12796        }
12797
12798        computeScroll();
12799
12800        final int sx = mScrollX;
12801        final int sy = mScrollY;
12802
12803        DisplayList displayList = null;
12804        Bitmap cache = null;
12805        boolean hasDisplayList = false;
12806        if (caching) {
12807            if (!hardwareAccelerated) {
12808                if (layerType != LAYER_TYPE_NONE) {
12809                    layerType = LAYER_TYPE_SOFTWARE;
12810                    buildDrawingCache(true);
12811                }
12812                cache = getDrawingCache(true);
12813            } else {
12814                switch (layerType) {
12815                    case LAYER_TYPE_SOFTWARE:
12816                        if (useDisplayListProperties) {
12817                            hasDisplayList = canHaveDisplayList();
12818                        } else {
12819                            buildDrawingCache(true);
12820                            cache = getDrawingCache(true);
12821                        }
12822                        break;
12823                    case LAYER_TYPE_HARDWARE:
12824                        if (useDisplayListProperties) {
12825                            hasDisplayList = canHaveDisplayList();
12826                        }
12827                        break;
12828                    case LAYER_TYPE_NONE:
12829                        // Delay getting the display list until animation-driven alpha values are
12830                        // set up and possibly passed on to the view
12831                        hasDisplayList = canHaveDisplayList();
12832                        break;
12833                }
12834            }
12835        }
12836        useDisplayListProperties &= hasDisplayList;
12837        if (useDisplayListProperties) {
12838            displayList = getDisplayList();
12839            if (!displayList.isValid()) {
12840                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12841                // to getDisplayList(), the display list will be marked invalid and we should not
12842                // try to use it again.
12843                displayList = null;
12844                hasDisplayList = false;
12845                useDisplayListProperties = false;
12846            }
12847        }
12848
12849        final boolean hasNoCache = cache == null || hasDisplayList;
12850        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12851                layerType != LAYER_TYPE_HARDWARE;
12852
12853        int restoreTo = -1;
12854        if (!useDisplayListProperties || transformToApply != null) {
12855            restoreTo = canvas.save();
12856        }
12857        if (offsetForScroll) {
12858            canvas.translate(mLeft - sx, mTop - sy);
12859        } else {
12860            if (!useDisplayListProperties) {
12861                canvas.translate(mLeft, mTop);
12862            }
12863            if (scalingRequired) {
12864                if (useDisplayListProperties) {
12865                    // TODO: Might not need this if we put everything inside the DL
12866                    restoreTo = canvas.save();
12867                }
12868                // mAttachInfo cannot be null, otherwise scalingRequired == false
12869                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12870                canvas.scale(scale, scale);
12871            }
12872        }
12873
12874        float alpha = useDisplayListProperties ? 1 : getAlpha();
12875        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12876            if (transformToApply != null || !childHasIdentityMatrix) {
12877                int transX = 0;
12878                int transY = 0;
12879
12880                if (offsetForScroll) {
12881                    transX = -sx;
12882                    transY = -sy;
12883                }
12884
12885                if (transformToApply != null) {
12886                    if (concatMatrix) {
12887                        if (useDisplayListProperties) {
12888                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12889                        } else {
12890                            // Undo the scroll translation, apply the transformation matrix,
12891                            // then redo the scroll translate to get the correct result.
12892                            canvas.translate(-transX, -transY);
12893                            canvas.concat(transformToApply.getMatrix());
12894                            canvas.translate(transX, transY);
12895                        }
12896                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12897                    }
12898
12899                    float transformAlpha = transformToApply.getAlpha();
12900                    if (transformAlpha < 1) {
12901                        alpha *= transformToApply.getAlpha();
12902                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12903                    }
12904                }
12905
12906                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12907                    canvas.translate(-transX, -transY);
12908                    canvas.concat(getMatrix());
12909                    canvas.translate(transX, transY);
12910                }
12911            }
12912
12913            if (alpha < 1) {
12914                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12915                if (hasNoCache) {
12916                    final int multipliedAlpha = (int) (255 * alpha);
12917                    if (!onSetAlpha(multipliedAlpha)) {
12918                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12919                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12920                                layerType != LAYER_TYPE_NONE) {
12921                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12922                        }
12923                        if (useDisplayListProperties) {
12924                            displayList.setAlpha(alpha * getAlpha());
12925                        } else  if (layerType == LAYER_TYPE_NONE) {
12926                            final int scrollX = hasDisplayList ? 0 : sx;
12927                            final int scrollY = hasDisplayList ? 0 : sy;
12928                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12929                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12930                        }
12931                    } else {
12932                        // Alpha is handled by the child directly, clobber the layer's alpha
12933                        mPrivateFlags |= ALPHA_SET;
12934                    }
12935                }
12936            }
12937        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12938            onSetAlpha(255);
12939            mPrivateFlags &= ~ALPHA_SET;
12940        }
12941
12942        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12943                !useDisplayListProperties) {
12944            if (offsetForScroll) {
12945                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12946            } else {
12947                if (!scalingRequired || cache == null) {
12948                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12949                } else {
12950                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12951                }
12952            }
12953        }
12954
12955        if (!useDisplayListProperties && hasDisplayList) {
12956            displayList = getDisplayList();
12957            if (!displayList.isValid()) {
12958                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12959                // to getDisplayList(), the display list will be marked invalid and we should not
12960                // try to use it again.
12961                displayList = null;
12962                hasDisplayList = false;
12963            }
12964        }
12965
12966        if (hasNoCache) {
12967            boolean layerRendered = false;
12968            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12969                final HardwareLayer layer = getHardwareLayer();
12970                if (layer != null && layer.isValid()) {
12971                    mLayerPaint.setAlpha((int) (alpha * 255));
12972                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12973                    layerRendered = true;
12974                } else {
12975                    final int scrollX = hasDisplayList ? 0 : sx;
12976                    final int scrollY = hasDisplayList ? 0 : sy;
12977                    canvas.saveLayer(scrollX, scrollY,
12978                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12979                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12980                }
12981            }
12982
12983            if (!layerRendered) {
12984                if (!hasDisplayList) {
12985                    // Fast path for layouts with no backgrounds
12986                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12987                        if (ViewDebug.TRACE_HIERARCHY) {
12988                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12989                        }
12990                        mPrivateFlags &= ~DIRTY_MASK;
12991                        dispatchDraw(canvas);
12992                    } else {
12993                        draw(canvas);
12994                    }
12995                } else {
12996                    mPrivateFlags &= ~DIRTY_MASK;
12997                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
12998                }
12999            }
13000        } else if (cache != null) {
13001            mPrivateFlags &= ~DIRTY_MASK;
13002            Paint cachePaint;
13003
13004            if (layerType == LAYER_TYPE_NONE) {
13005                cachePaint = parent.mCachePaint;
13006                if (cachePaint == null) {
13007                    cachePaint = new Paint();
13008                    cachePaint.setDither(false);
13009                    parent.mCachePaint = cachePaint;
13010                }
13011                if (alpha < 1) {
13012                    cachePaint.setAlpha((int) (alpha * 255));
13013                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13014                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13015                    cachePaint.setAlpha(255);
13016                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13017                }
13018            } else {
13019                cachePaint = mLayerPaint;
13020                cachePaint.setAlpha((int) (alpha * 255));
13021            }
13022            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13023        }
13024
13025        if (restoreTo >= 0) {
13026            canvas.restoreToCount(restoreTo);
13027        }
13028
13029        if (a != null && !more) {
13030            if (!hardwareAccelerated && !a.getFillAfter()) {
13031                onSetAlpha(255);
13032            }
13033            parent.finishAnimatingView(this, a);
13034        }
13035
13036        if (more && hardwareAccelerated) {
13037            // invalidation is the trigger to recreate display lists, so if we're using
13038            // display lists to render, force an invalidate to allow the animation to
13039            // continue drawing another frame
13040            parent.invalidate(true);
13041            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13042                // alpha animations should cause the child to recreate its display list
13043                invalidate(true);
13044            }
13045        }
13046
13047        mRecreateDisplayList = false;
13048
13049        return more;
13050    }
13051
13052    /**
13053     * Manually render this view (and all of its children) to the given Canvas.
13054     * The view must have already done a full layout before this function is
13055     * called.  When implementing a view, implement
13056     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13057     * If you do need to override this method, call the superclass version.
13058     *
13059     * @param canvas The Canvas to which the View is rendered.
13060     */
13061    public void draw(Canvas canvas) {
13062        if (ViewDebug.TRACE_HIERARCHY) {
13063            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
13064        }
13065
13066        final int privateFlags = mPrivateFlags;
13067        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13068                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13069        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13070
13071        /*
13072         * Draw traversal performs several drawing steps which must be executed
13073         * in the appropriate order:
13074         *
13075         *      1. Draw the background
13076         *      2. If necessary, save the canvas' layers to prepare for fading
13077         *      3. Draw view's content
13078         *      4. Draw children
13079         *      5. If necessary, draw the fading edges and restore layers
13080         *      6. Draw decorations (scrollbars for instance)
13081         */
13082
13083        // Step 1, draw the background, if needed
13084        int saveCount;
13085
13086        if (!dirtyOpaque) {
13087            final Drawable background = mBackground;
13088            if (background != null) {
13089                final int scrollX = mScrollX;
13090                final int scrollY = mScrollY;
13091
13092                if (mBackgroundSizeChanged) {
13093                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13094                    mBackgroundSizeChanged = false;
13095                }
13096
13097                if ((scrollX | scrollY) == 0) {
13098                    background.draw(canvas);
13099                } else {
13100                    canvas.translate(scrollX, scrollY);
13101                    background.draw(canvas);
13102                    canvas.translate(-scrollX, -scrollY);
13103                }
13104            }
13105        }
13106
13107        // skip step 2 & 5 if possible (common case)
13108        final int viewFlags = mViewFlags;
13109        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13110        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13111        if (!verticalEdges && !horizontalEdges) {
13112            // Step 3, draw the content
13113            if (!dirtyOpaque) onDraw(canvas);
13114
13115            // Step 4, draw the children
13116            dispatchDraw(canvas);
13117
13118            // Step 6, draw decorations (scrollbars)
13119            onDrawScrollBars(canvas);
13120
13121            // we're done...
13122            return;
13123        }
13124
13125        /*
13126         * Here we do the full fledged routine...
13127         * (this is an uncommon case where speed matters less,
13128         * this is why we repeat some of the tests that have been
13129         * done above)
13130         */
13131
13132        boolean drawTop = false;
13133        boolean drawBottom = false;
13134        boolean drawLeft = false;
13135        boolean drawRight = false;
13136
13137        float topFadeStrength = 0.0f;
13138        float bottomFadeStrength = 0.0f;
13139        float leftFadeStrength = 0.0f;
13140        float rightFadeStrength = 0.0f;
13141
13142        // Step 2, save the canvas' layers
13143        int paddingLeft = mPaddingLeft;
13144
13145        final boolean offsetRequired = isPaddingOffsetRequired();
13146        if (offsetRequired) {
13147            paddingLeft += getLeftPaddingOffset();
13148        }
13149
13150        int left = mScrollX + paddingLeft;
13151        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13152        int top = mScrollY + getFadeTop(offsetRequired);
13153        int bottom = top + getFadeHeight(offsetRequired);
13154
13155        if (offsetRequired) {
13156            right += getRightPaddingOffset();
13157            bottom += getBottomPaddingOffset();
13158        }
13159
13160        final ScrollabilityCache scrollabilityCache = mScrollCache;
13161        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13162        int length = (int) fadeHeight;
13163
13164        // clip the fade length if top and bottom fades overlap
13165        // overlapping fades produce odd-looking artifacts
13166        if (verticalEdges && (top + length > bottom - length)) {
13167            length = (bottom - top) / 2;
13168        }
13169
13170        // also clip horizontal fades if necessary
13171        if (horizontalEdges && (left + length > right - length)) {
13172            length = (right - left) / 2;
13173        }
13174
13175        if (verticalEdges) {
13176            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13177            drawTop = topFadeStrength * fadeHeight > 1.0f;
13178            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13179            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13180        }
13181
13182        if (horizontalEdges) {
13183            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13184            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13185            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13186            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13187        }
13188
13189        saveCount = canvas.getSaveCount();
13190
13191        int solidColor = getSolidColor();
13192        if (solidColor == 0) {
13193            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13194
13195            if (drawTop) {
13196                canvas.saveLayer(left, top, right, top + length, null, flags);
13197            }
13198
13199            if (drawBottom) {
13200                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13201            }
13202
13203            if (drawLeft) {
13204                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13205            }
13206
13207            if (drawRight) {
13208                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13209            }
13210        } else {
13211            scrollabilityCache.setFadeColor(solidColor);
13212        }
13213
13214        // Step 3, draw the content
13215        if (!dirtyOpaque) onDraw(canvas);
13216
13217        // Step 4, draw the children
13218        dispatchDraw(canvas);
13219
13220        // Step 5, draw the fade effect and restore layers
13221        final Paint p = scrollabilityCache.paint;
13222        final Matrix matrix = scrollabilityCache.matrix;
13223        final Shader fade = scrollabilityCache.shader;
13224
13225        if (drawTop) {
13226            matrix.setScale(1, fadeHeight * topFadeStrength);
13227            matrix.postTranslate(left, top);
13228            fade.setLocalMatrix(matrix);
13229            canvas.drawRect(left, top, right, top + length, p);
13230        }
13231
13232        if (drawBottom) {
13233            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13234            matrix.postRotate(180);
13235            matrix.postTranslate(left, bottom);
13236            fade.setLocalMatrix(matrix);
13237            canvas.drawRect(left, bottom - length, right, bottom, p);
13238        }
13239
13240        if (drawLeft) {
13241            matrix.setScale(1, fadeHeight * leftFadeStrength);
13242            matrix.postRotate(-90);
13243            matrix.postTranslate(left, top);
13244            fade.setLocalMatrix(matrix);
13245            canvas.drawRect(left, top, left + length, bottom, p);
13246        }
13247
13248        if (drawRight) {
13249            matrix.setScale(1, fadeHeight * rightFadeStrength);
13250            matrix.postRotate(90);
13251            matrix.postTranslate(right, top);
13252            fade.setLocalMatrix(matrix);
13253            canvas.drawRect(right - length, top, right, bottom, p);
13254        }
13255
13256        canvas.restoreToCount(saveCount);
13257
13258        // Step 6, draw decorations (scrollbars)
13259        onDrawScrollBars(canvas);
13260    }
13261
13262    /**
13263     * Override this if your view is known to always be drawn on top of a solid color background,
13264     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13265     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13266     * should be set to 0xFF.
13267     *
13268     * @see #setVerticalFadingEdgeEnabled(boolean)
13269     * @see #setHorizontalFadingEdgeEnabled(boolean)
13270     *
13271     * @return The known solid color background for this view, or 0 if the color may vary
13272     */
13273    @ViewDebug.ExportedProperty(category = "drawing")
13274    public int getSolidColor() {
13275        return 0;
13276    }
13277
13278    /**
13279     * Build a human readable string representation of the specified view flags.
13280     *
13281     * @param flags the view flags to convert to a string
13282     * @return a String representing the supplied flags
13283     */
13284    private static String printFlags(int flags) {
13285        String output = "";
13286        int numFlags = 0;
13287        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13288            output += "TAKES_FOCUS";
13289            numFlags++;
13290        }
13291
13292        switch (flags & VISIBILITY_MASK) {
13293        case INVISIBLE:
13294            if (numFlags > 0) {
13295                output += " ";
13296            }
13297            output += "INVISIBLE";
13298            // USELESS HERE numFlags++;
13299            break;
13300        case GONE:
13301            if (numFlags > 0) {
13302                output += " ";
13303            }
13304            output += "GONE";
13305            // USELESS HERE numFlags++;
13306            break;
13307        default:
13308            break;
13309        }
13310        return output;
13311    }
13312
13313    /**
13314     * Build a human readable string representation of the specified private
13315     * view flags.
13316     *
13317     * @param privateFlags the private view flags to convert to a string
13318     * @return a String representing the supplied flags
13319     */
13320    private static String printPrivateFlags(int privateFlags) {
13321        String output = "";
13322        int numFlags = 0;
13323
13324        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13325            output += "WANTS_FOCUS";
13326            numFlags++;
13327        }
13328
13329        if ((privateFlags & FOCUSED) == FOCUSED) {
13330            if (numFlags > 0) {
13331                output += " ";
13332            }
13333            output += "FOCUSED";
13334            numFlags++;
13335        }
13336
13337        if ((privateFlags & SELECTED) == SELECTED) {
13338            if (numFlags > 0) {
13339                output += " ";
13340            }
13341            output += "SELECTED";
13342            numFlags++;
13343        }
13344
13345        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13346            if (numFlags > 0) {
13347                output += " ";
13348            }
13349            output += "IS_ROOT_NAMESPACE";
13350            numFlags++;
13351        }
13352
13353        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13354            if (numFlags > 0) {
13355                output += " ";
13356            }
13357            output += "HAS_BOUNDS";
13358            numFlags++;
13359        }
13360
13361        if ((privateFlags & DRAWN) == DRAWN) {
13362            if (numFlags > 0) {
13363                output += " ";
13364            }
13365            output += "DRAWN";
13366            // USELESS HERE numFlags++;
13367        }
13368        return output;
13369    }
13370
13371    /**
13372     * <p>Indicates whether or not this view's layout will be requested during
13373     * the next hierarchy layout pass.</p>
13374     *
13375     * @return true if the layout will be forced during next layout pass
13376     */
13377    public boolean isLayoutRequested() {
13378        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13379    }
13380
13381    /**
13382     * Assign a size and position to a view and all of its
13383     * descendants
13384     *
13385     * <p>This is the second phase of the layout mechanism.
13386     * (The first is measuring). In this phase, each parent calls
13387     * layout on all of its children to position them.
13388     * This is typically done using the child measurements
13389     * that were stored in the measure pass().</p>
13390     *
13391     * <p>Derived classes should not override this method.
13392     * Derived classes with children should override
13393     * onLayout. In that method, they should
13394     * call layout on each of their children.</p>
13395     *
13396     * @param l Left position, relative to parent
13397     * @param t Top position, relative to parent
13398     * @param r Right position, relative to parent
13399     * @param b Bottom position, relative to parent
13400     */
13401    @SuppressWarnings({"unchecked"})
13402    public void layout(int l, int t, int r, int b) {
13403        int oldL = mLeft;
13404        int oldT = mTop;
13405        int oldB = mBottom;
13406        int oldR = mRight;
13407        boolean changed = setFrame(l, t, r, b);
13408        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13409            if (ViewDebug.TRACE_HIERARCHY) {
13410                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13411            }
13412
13413            onLayout(changed, l, t, r, b);
13414            mPrivateFlags &= ~LAYOUT_REQUIRED;
13415
13416            ListenerInfo li = mListenerInfo;
13417            if (li != null && li.mOnLayoutChangeListeners != null) {
13418                ArrayList<OnLayoutChangeListener> listenersCopy =
13419                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13420                int numListeners = listenersCopy.size();
13421                for (int i = 0; i < numListeners; ++i) {
13422                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13423                }
13424            }
13425        }
13426        mPrivateFlags &= ~FORCE_LAYOUT;
13427    }
13428
13429    /**
13430     * Called from layout when this view should
13431     * assign a size and position to each of its children.
13432     *
13433     * Derived classes with children should override
13434     * this method and call layout on each of
13435     * their children.
13436     * @param changed This is a new size or position for this view
13437     * @param left Left position, relative to parent
13438     * @param top Top position, relative to parent
13439     * @param right Right position, relative to parent
13440     * @param bottom Bottom position, relative to parent
13441     */
13442    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13443    }
13444
13445    /**
13446     * Assign a size and position to this view.
13447     *
13448     * This is called from layout.
13449     *
13450     * @param left Left position, relative to parent
13451     * @param top Top position, relative to parent
13452     * @param right Right position, relative to parent
13453     * @param bottom Bottom position, relative to parent
13454     * @return true if the new size and position are different than the
13455     *         previous ones
13456     * {@hide}
13457     */
13458    protected boolean setFrame(int left, int top, int right, int bottom) {
13459        boolean changed = false;
13460
13461        if (DBG) {
13462            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13463                    + right + "," + bottom + ")");
13464        }
13465
13466        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13467            changed = true;
13468
13469            // Remember our drawn bit
13470            int drawn = mPrivateFlags & DRAWN;
13471
13472            int oldWidth = mRight - mLeft;
13473            int oldHeight = mBottom - mTop;
13474            int newWidth = right - left;
13475            int newHeight = bottom - top;
13476            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13477
13478            // Invalidate our old position
13479            invalidate(sizeChanged);
13480
13481            mLeft = left;
13482            mTop = top;
13483            mRight = right;
13484            mBottom = bottom;
13485            if (mDisplayList != null) {
13486                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13487            }
13488
13489            mPrivateFlags |= HAS_BOUNDS;
13490
13491
13492            if (sizeChanged) {
13493                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13494                    // A change in dimension means an auto-centered pivot point changes, too
13495                    if (mTransformationInfo != null) {
13496                        mTransformationInfo.mMatrixDirty = true;
13497                    }
13498                }
13499                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13500            }
13501
13502            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13503                // If we are visible, force the DRAWN bit to on so that
13504                // this invalidate will go through (at least to our parent).
13505                // This is because someone may have invalidated this view
13506                // before this call to setFrame came in, thereby clearing
13507                // the DRAWN bit.
13508                mPrivateFlags |= DRAWN;
13509                invalidate(sizeChanged);
13510                // parent display list may need to be recreated based on a change in the bounds
13511                // of any child
13512                invalidateParentCaches();
13513            }
13514
13515            // Reset drawn bit to original value (invalidate turns it off)
13516            mPrivateFlags |= drawn;
13517
13518            mBackgroundSizeChanged = true;
13519        }
13520        return changed;
13521    }
13522
13523    /**
13524     * Finalize inflating a view from XML.  This is called as the last phase
13525     * of inflation, after all child views have been added.
13526     *
13527     * <p>Even if the subclass overrides onFinishInflate, they should always be
13528     * sure to call the super method, so that we get called.
13529     */
13530    protected void onFinishInflate() {
13531    }
13532
13533    /**
13534     * Returns the resources associated with this view.
13535     *
13536     * @return Resources object.
13537     */
13538    public Resources getResources() {
13539        return mResources;
13540    }
13541
13542    /**
13543     * Invalidates the specified Drawable.
13544     *
13545     * @param drawable the drawable to invalidate
13546     */
13547    public void invalidateDrawable(Drawable drawable) {
13548        if (verifyDrawable(drawable)) {
13549            final Rect dirty = drawable.getBounds();
13550            final int scrollX = mScrollX;
13551            final int scrollY = mScrollY;
13552
13553            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13554                    dirty.right + scrollX, dirty.bottom + scrollY);
13555        }
13556    }
13557
13558    /**
13559     * Schedules an action on a drawable to occur at a specified time.
13560     *
13561     * @param who the recipient of the action
13562     * @param what the action to run on the drawable
13563     * @param when the time at which the action must occur. Uses the
13564     *        {@link SystemClock#uptimeMillis} timebase.
13565     */
13566    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13567        if (verifyDrawable(who) && what != null) {
13568            final long delay = when - SystemClock.uptimeMillis();
13569            if (mAttachInfo != null) {
13570                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13571                        Choreographer.CALLBACK_ANIMATION, what, who,
13572                        Choreographer.subtractFrameDelay(delay));
13573            } else {
13574                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13575            }
13576        }
13577    }
13578
13579    /**
13580     * Cancels a scheduled action on a drawable.
13581     *
13582     * @param who the recipient of the action
13583     * @param what the action to cancel
13584     */
13585    public void unscheduleDrawable(Drawable who, Runnable what) {
13586        if (verifyDrawable(who) && what != null) {
13587            if (mAttachInfo != null) {
13588                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13589                        Choreographer.CALLBACK_ANIMATION, what, who);
13590            } else {
13591                ViewRootImpl.getRunQueue().removeCallbacks(what);
13592            }
13593        }
13594    }
13595
13596    /**
13597     * Unschedule any events associated with the given Drawable.  This can be
13598     * used when selecting a new Drawable into a view, so that the previous
13599     * one is completely unscheduled.
13600     *
13601     * @param who The Drawable to unschedule.
13602     *
13603     * @see #drawableStateChanged
13604     */
13605    public void unscheduleDrawable(Drawable who) {
13606        if (mAttachInfo != null && who != null) {
13607            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13608                    Choreographer.CALLBACK_ANIMATION, null, who);
13609        }
13610    }
13611
13612    /**
13613    * Return the layout direction of a given Drawable.
13614    *
13615    * @param who the Drawable to query
13616    * @hide
13617    */
13618    public int getResolvedLayoutDirection(Drawable who) {
13619        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13620    }
13621
13622    /**
13623     * If your view subclass is displaying its own Drawable objects, it should
13624     * override this function and return true for any Drawable it is
13625     * displaying.  This allows animations for those drawables to be
13626     * scheduled.
13627     *
13628     * <p>Be sure to call through to the super class when overriding this
13629     * function.
13630     *
13631     * @param who The Drawable to verify.  Return true if it is one you are
13632     *            displaying, else return the result of calling through to the
13633     *            super class.
13634     *
13635     * @return boolean If true than the Drawable is being displayed in the
13636     *         view; else false and it is not allowed to animate.
13637     *
13638     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13639     * @see #drawableStateChanged()
13640     */
13641    protected boolean verifyDrawable(Drawable who) {
13642        return who == mBackground;
13643    }
13644
13645    /**
13646     * This function is called whenever the state of the view changes in such
13647     * a way that it impacts the state of drawables being shown.
13648     *
13649     * <p>Be sure to call through to the superclass when overriding this
13650     * function.
13651     *
13652     * @see Drawable#setState(int[])
13653     */
13654    protected void drawableStateChanged() {
13655        Drawable d = mBackground;
13656        if (d != null && d.isStateful()) {
13657            d.setState(getDrawableState());
13658        }
13659    }
13660
13661    /**
13662     * Call this to force a view to update its drawable state. This will cause
13663     * drawableStateChanged to be called on this view. Views that are interested
13664     * in the new state should call getDrawableState.
13665     *
13666     * @see #drawableStateChanged
13667     * @see #getDrawableState
13668     */
13669    public void refreshDrawableState() {
13670        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13671        drawableStateChanged();
13672
13673        ViewParent parent = mParent;
13674        if (parent != null) {
13675            parent.childDrawableStateChanged(this);
13676        }
13677    }
13678
13679    /**
13680     * Return an array of resource IDs of the drawable states representing the
13681     * current state of the view.
13682     *
13683     * @return The current drawable state
13684     *
13685     * @see Drawable#setState(int[])
13686     * @see #drawableStateChanged()
13687     * @see #onCreateDrawableState(int)
13688     */
13689    public final int[] getDrawableState() {
13690        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13691            return mDrawableState;
13692        } else {
13693            mDrawableState = onCreateDrawableState(0);
13694            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13695            return mDrawableState;
13696        }
13697    }
13698
13699    /**
13700     * Generate the new {@link android.graphics.drawable.Drawable} state for
13701     * this view. This is called by the view
13702     * system when the cached Drawable state is determined to be invalid.  To
13703     * retrieve the current state, you should use {@link #getDrawableState}.
13704     *
13705     * @param extraSpace if non-zero, this is the number of extra entries you
13706     * would like in the returned array in which you can place your own
13707     * states.
13708     *
13709     * @return Returns an array holding the current {@link Drawable} state of
13710     * the view.
13711     *
13712     * @see #mergeDrawableStates(int[], int[])
13713     */
13714    protected int[] onCreateDrawableState(int extraSpace) {
13715        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13716                mParent instanceof View) {
13717            return ((View) mParent).onCreateDrawableState(extraSpace);
13718        }
13719
13720        int[] drawableState;
13721
13722        int privateFlags = mPrivateFlags;
13723
13724        int viewStateIndex = 0;
13725        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13726        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13727        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13728        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13729        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13730        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13731        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13732                HardwareRenderer.isAvailable()) {
13733            // This is set if HW acceleration is requested, even if the current
13734            // process doesn't allow it.  This is just to allow app preview
13735            // windows to better match their app.
13736            viewStateIndex |= VIEW_STATE_ACCELERATED;
13737        }
13738        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13739
13740        final int privateFlags2 = mPrivateFlags2;
13741        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13742        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13743
13744        drawableState = VIEW_STATE_SETS[viewStateIndex];
13745
13746        //noinspection ConstantIfStatement
13747        if (false) {
13748            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13749            Log.i("View", toString()
13750                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13751                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13752                    + " fo=" + hasFocus()
13753                    + " sl=" + ((privateFlags & SELECTED) != 0)
13754                    + " wf=" + hasWindowFocus()
13755                    + ": " + Arrays.toString(drawableState));
13756        }
13757
13758        if (extraSpace == 0) {
13759            return drawableState;
13760        }
13761
13762        final int[] fullState;
13763        if (drawableState != null) {
13764            fullState = new int[drawableState.length + extraSpace];
13765            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13766        } else {
13767            fullState = new int[extraSpace];
13768        }
13769
13770        return fullState;
13771    }
13772
13773    /**
13774     * Merge your own state values in <var>additionalState</var> into the base
13775     * state values <var>baseState</var> that were returned by
13776     * {@link #onCreateDrawableState(int)}.
13777     *
13778     * @param baseState The base state values returned by
13779     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13780     * own additional state values.
13781     *
13782     * @param additionalState The additional state values you would like
13783     * added to <var>baseState</var>; this array is not modified.
13784     *
13785     * @return As a convenience, the <var>baseState</var> array you originally
13786     * passed into the function is returned.
13787     *
13788     * @see #onCreateDrawableState(int)
13789     */
13790    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13791        final int N = baseState.length;
13792        int i = N - 1;
13793        while (i >= 0 && baseState[i] == 0) {
13794            i--;
13795        }
13796        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13797        return baseState;
13798    }
13799
13800    /**
13801     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13802     * on all Drawable objects associated with this view.
13803     */
13804    public void jumpDrawablesToCurrentState() {
13805        if (mBackground != null) {
13806            mBackground.jumpToCurrentState();
13807        }
13808    }
13809
13810    /**
13811     * Sets the background color for this view.
13812     * @param color the color of the background
13813     */
13814    @RemotableViewMethod
13815    public void setBackgroundColor(int color) {
13816        if (mBackground instanceof ColorDrawable) {
13817            ((ColorDrawable) mBackground).setColor(color);
13818        } else {
13819            setBackground(new ColorDrawable(color));
13820        }
13821    }
13822
13823    /**
13824     * Set the background to a given resource. The resource should refer to
13825     * a Drawable object or 0 to remove the background.
13826     * @param resid The identifier of the resource.
13827     *
13828     * @attr ref android.R.styleable#View_background
13829     */
13830    @RemotableViewMethod
13831    public void setBackgroundResource(int resid) {
13832        if (resid != 0 && resid == mBackgroundResource) {
13833            return;
13834        }
13835
13836        Drawable d= null;
13837        if (resid != 0) {
13838            d = mResources.getDrawable(resid);
13839        }
13840        setBackground(d);
13841
13842        mBackgroundResource = resid;
13843    }
13844
13845    /**
13846     * Set the background to a given Drawable, or remove the background. If the
13847     * background has padding, this View's padding is set to the background's
13848     * padding. However, when a background is removed, this View's padding isn't
13849     * touched. If setting the padding is desired, please use
13850     * {@link #setPadding(int, int, int, int)}.
13851     *
13852     * @param background The Drawable to use as the background, or null to remove the
13853     *        background
13854     */
13855    public void setBackground(Drawable background) {
13856        //noinspection deprecation
13857        setBackgroundDrawable(background);
13858    }
13859
13860    /**
13861     * @deprecated use {@link #setBackground(Drawable)} instead
13862     */
13863    @Deprecated
13864    public void setBackgroundDrawable(Drawable background) {
13865        if (background == mBackground) {
13866            return;
13867        }
13868
13869        boolean requestLayout = false;
13870
13871        mBackgroundResource = 0;
13872
13873        /*
13874         * Regardless of whether we're setting a new background or not, we want
13875         * to clear the previous drawable.
13876         */
13877        if (mBackground != null) {
13878            mBackground.setCallback(null);
13879            unscheduleDrawable(mBackground);
13880        }
13881
13882        if (background != null) {
13883            Rect padding = sThreadLocal.get();
13884            if (padding == null) {
13885                padding = new Rect();
13886                sThreadLocal.set(padding);
13887            }
13888            if (background.getPadding(padding)) {
13889                switch (background.getResolvedLayoutDirectionSelf()) {
13890                    case LAYOUT_DIRECTION_RTL:
13891                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13892                        break;
13893                    case LAYOUT_DIRECTION_LTR:
13894                    default:
13895                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13896                }
13897            }
13898
13899            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13900            // if it has a different minimum size, we should layout again
13901            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13902                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13903                requestLayout = true;
13904            }
13905
13906            background.setCallback(this);
13907            if (background.isStateful()) {
13908                background.setState(getDrawableState());
13909            }
13910            background.setVisible(getVisibility() == VISIBLE, false);
13911            mBackground = background;
13912
13913            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13914                mPrivateFlags &= ~SKIP_DRAW;
13915                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13916                requestLayout = true;
13917            }
13918        } else {
13919            /* Remove the background */
13920            mBackground = null;
13921
13922            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13923                /*
13924                 * This view ONLY drew the background before and we're removing
13925                 * the background, so now it won't draw anything
13926                 * (hence we SKIP_DRAW)
13927                 */
13928                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13929                mPrivateFlags |= SKIP_DRAW;
13930            }
13931
13932            /*
13933             * When the background is set, we try to apply its padding to this
13934             * View. When the background is removed, we don't touch this View's
13935             * padding. This is noted in the Javadocs. Hence, we don't need to
13936             * requestLayout(), the invalidate() below is sufficient.
13937             */
13938
13939            // The old background's minimum size could have affected this
13940            // View's layout, so let's requestLayout
13941            requestLayout = true;
13942        }
13943
13944        computeOpaqueFlags();
13945
13946        if (requestLayout) {
13947            requestLayout();
13948        }
13949
13950        mBackgroundSizeChanged = true;
13951        invalidate(true);
13952    }
13953
13954    /**
13955     * Gets the background drawable
13956     *
13957     * @return The drawable used as the background for this view, if any.
13958     *
13959     * @see #setBackground(Drawable)
13960     *
13961     * @attr ref android.R.styleable#View_background
13962     */
13963    public Drawable getBackground() {
13964        return mBackground;
13965    }
13966
13967    /**
13968     * Sets the padding. The view may add on the space required to display
13969     * the scrollbars, depending on the style and visibility of the scrollbars.
13970     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13971     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13972     * from the values set in this call.
13973     *
13974     * @attr ref android.R.styleable#View_padding
13975     * @attr ref android.R.styleable#View_paddingBottom
13976     * @attr ref android.R.styleable#View_paddingLeft
13977     * @attr ref android.R.styleable#View_paddingRight
13978     * @attr ref android.R.styleable#View_paddingTop
13979     * @param left the left padding in pixels
13980     * @param top the top padding in pixels
13981     * @param right the right padding in pixels
13982     * @param bottom the bottom padding in pixels
13983     */
13984    public void setPadding(int left, int top, int right, int bottom) {
13985        mUserPaddingStart = -1;
13986        mUserPaddingEnd = -1;
13987        mUserPaddingRelative = false;
13988
13989        internalSetPadding(left, top, right, bottom);
13990    }
13991
13992    private void internalSetPadding(int left, int top, int right, int bottom) {
13993        mUserPaddingLeft = left;
13994        mUserPaddingRight = right;
13995        mUserPaddingBottom = bottom;
13996
13997        final int viewFlags = mViewFlags;
13998        boolean changed = false;
13999
14000        // Common case is there are no scroll bars.
14001        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14002            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14003                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14004                        ? 0 : getVerticalScrollbarWidth();
14005                switch (mVerticalScrollbarPosition) {
14006                    case SCROLLBAR_POSITION_DEFAULT:
14007                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14008                            left += offset;
14009                        } else {
14010                            right += offset;
14011                        }
14012                        break;
14013                    case SCROLLBAR_POSITION_RIGHT:
14014                        right += offset;
14015                        break;
14016                    case SCROLLBAR_POSITION_LEFT:
14017                        left += offset;
14018                        break;
14019                }
14020            }
14021            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14022                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14023                        ? 0 : getHorizontalScrollbarHeight();
14024            }
14025        }
14026
14027        if (mPaddingLeft != left) {
14028            changed = true;
14029            mPaddingLeft = left;
14030        }
14031        if (mPaddingTop != top) {
14032            changed = true;
14033            mPaddingTop = top;
14034        }
14035        if (mPaddingRight != right) {
14036            changed = true;
14037            mPaddingRight = right;
14038        }
14039        if (mPaddingBottom != bottom) {
14040            changed = true;
14041            mPaddingBottom = bottom;
14042        }
14043
14044        if (changed) {
14045            requestLayout();
14046        }
14047    }
14048
14049    /**
14050     * Sets the relative padding. The view may add on the space required to display
14051     * the scrollbars, depending on the style and visibility of the scrollbars.
14052     * from the values set in this call.
14053     *
14054     * @param start the start padding in pixels
14055     * @param top the top padding in pixels
14056     * @param end the end padding in pixels
14057     * @param bottom the bottom padding in pixels
14058     * @hide
14059     */
14060    public void setPaddingRelative(int start, int top, int end, int bottom) {
14061        mUserPaddingStart = start;
14062        mUserPaddingEnd = end;
14063        mUserPaddingRelative = true;
14064
14065        switch(getResolvedLayoutDirection()) {
14066            case LAYOUT_DIRECTION_RTL:
14067                internalSetPadding(end, top, start, bottom);
14068                break;
14069            case LAYOUT_DIRECTION_LTR:
14070            default:
14071                internalSetPadding(start, top, end, bottom);
14072        }
14073    }
14074
14075    /**
14076     * Returns the top padding of this view.
14077     *
14078     * @return the top padding in pixels
14079     */
14080    public int getPaddingTop() {
14081        return mPaddingTop;
14082    }
14083
14084    /**
14085     * Returns the bottom padding of this view. If there are inset and enabled
14086     * scrollbars, this value may include the space required to display the
14087     * scrollbars as well.
14088     *
14089     * @return the bottom padding in pixels
14090     */
14091    public int getPaddingBottom() {
14092        return mPaddingBottom;
14093    }
14094
14095    /**
14096     * Returns the left padding of this view. If there are inset and enabled
14097     * scrollbars, this value may include the space required to display the
14098     * scrollbars as well.
14099     *
14100     * @return the left padding in pixels
14101     */
14102    public int getPaddingLeft() {
14103        return mPaddingLeft;
14104    }
14105
14106    /**
14107     * Returns the start padding of this view depending on its resolved layout direction.
14108     * If there are inset and enabled scrollbars, this value may include the space
14109     * required to display the scrollbars as well.
14110     *
14111     * @return the start padding in pixels
14112     * @hide
14113     */
14114    public int getPaddingStart() {
14115        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14116                mPaddingRight : mPaddingLeft;
14117    }
14118
14119    /**
14120     * Returns the right padding of this view. If there are inset and enabled
14121     * scrollbars, this value may include the space required to display the
14122     * scrollbars as well.
14123     *
14124     * @return the right padding in pixels
14125     */
14126    public int getPaddingRight() {
14127        return mPaddingRight;
14128    }
14129
14130    /**
14131     * Returns the end padding of this view depending on its resolved layout direction.
14132     * If there are inset and enabled scrollbars, this value may include the space
14133     * required to display the scrollbars as well.
14134     *
14135     * @return the end padding in pixels
14136     * @hide
14137     */
14138    public int getPaddingEnd() {
14139        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14140                mPaddingLeft : mPaddingRight;
14141    }
14142
14143    /**
14144     * Return if the padding as been set thru relative values
14145     * {@link #setPaddingRelative(int, int, int, int)}
14146     *
14147     * @return true if the padding is relative or false if it is not.
14148     * @hide
14149     */
14150    public boolean isPaddingRelative() {
14151        return mUserPaddingRelative;
14152    }
14153
14154    /**
14155     * @hide
14156     */
14157    public Insets getOpticalInsets() {
14158        if (mLayoutInsets == null) {
14159            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14160        }
14161        return mLayoutInsets;
14162    }
14163
14164    /**
14165     * @hide
14166     */
14167    public void setLayoutInsets(Insets layoutInsets) {
14168        mLayoutInsets = layoutInsets;
14169    }
14170
14171    /**
14172     * Changes the selection state of this view. A view can be selected or not.
14173     * Note that selection is not the same as focus. Views are typically
14174     * selected in the context of an AdapterView like ListView or GridView;
14175     * the selected view is the view that is highlighted.
14176     *
14177     * @param selected true if the view must be selected, false otherwise
14178     */
14179    public void setSelected(boolean selected) {
14180        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14181            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14182            if (!selected) resetPressedState();
14183            invalidate(true);
14184            refreshDrawableState();
14185            dispatchSetSelected(selected);
14186            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14187                notifyAccessibilityStateChanged();
14188            }
14189        }
14190    }
14191
14192    /**
14193     * Dispatch setSelected to all of this View's children.
14194     *
14195     * @see #setSelected(boolean)
14196     *
14197     * @param selected The new selected state
14198     */
14199    protected void dispatchSetSelected(boolean selected) {
14200    }
14201
14202    /**
14203     * Indicates the selection state of this view.
14204     *
14205     * @return true if the view is selected, false otherwise
14206     */
14207    @ViewDebug.ExportedProperty
14208    public boolean isSelected() {
14209        return (mPrivateFlags & SELECTED) != 0;
14210    }
14211
14212    /**
14213     * Changes the activated state of this view. A view can be activated or not.
14214     * Note that activation is not the same as selection.  Selection is
14215     * a transient property, representing the view (hierarchy) the user is
14216     * currently interacting with.  Activation is a longer-term state that the
14217     * user can move views in and out of.  For example, in a list view with
14218     * single or multiple selection enabled, the views in the current selection
14219     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14220     * here.)  The activated state is propagated down to children of the view it
14221     * is set on.
14222     *
14223     * @param activated true if the view must be activated, false otherwise
14224     */
14225    public void setActivated(boolean activated) {
14226        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14227            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14228            invalidate(true);
14229            refreshDrawableState();
14230            dispatchSetActivated(activated);
14231        }
14232    }
14233
14234    /**
14235     * Dispatch setActivated to all of this View's children.
14236     *
14237     * @see #setActivated(boolean)
14238     *
14239     * @param activated The new activated state
14240     */
14241    protected void dispatchSetActivated(boolean activated) {
14242    }
14243
14244    /**
14245     * Indicates the activation state of this view.
14246     *
14247     * @return true if the view is activated, false otherwise
14248     */
14249    @ViewDebug.ExportedProperty
14250    public boolean isActivated() {
14251        return (mPrivateFlags & ACTIVATED) != 0;
14252    }
14253
14254    /**
14255     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14256     * observer can be used to get notifications when global events, like
14257     * layout, happen.
14258     *
14259     * The returned ViewTreeObserver observer is not guaranteed to remain
14260     * valid for the lifetime of this View. If the caller of this method keeps
14261     * a long-lived reference to ViewTreeObserver, it should always check for
14262     * the return value of {@link ViewTreeObserver#isAlive()}.
14263     *
14264     * @return The ViewTreeObserver for this view's hierarchy.
14265     */
14266    public ViewTreeObserver getViewTreeObserver() {
14267        if (mAttachInfo != null) {
14268            return mAttachInfo.mTreeObserver;
14269        }
14270        if (mFloatingTreeObserver == null) {
14271            mFloatingTreeObserver = new ViewTreeObserver();
14272        }
14273        return mFloatingTreeObserver;
14274    }
14275
14276    /**
14277     * <p>Finds the topmost view in the current view hierarchy.</p>
14278     *
14279     * @return the topmost view containing this view
14280     */
14281    public View getRootView() {
14282        if (mAttachInfo != null) {
14283            final View v = mAttachInfo.mRootView;
14284            if (v != null) {
14285                return v;
14286            }
14287        }
14288
14289        View parent = this;
14290
14291        while (parent.mParent != null && parent.mParent instanceof View) {
14292            parent = (View) parent.mParent;
14293        }
14294
14295        return parent;
14296    }
14297
14298    /**
14299     * <p>Computes the coordinates of this view on the screen. The argument
14300     * must be an array of two integers. After the method returns, the array
14301     * contains the x and y location in that order.</p>
14302     *
14303     * @param location an array of two integers in which to hold the coordinates
14304     */
14305    public void getLocationOnScreen(int[] location) {
14306        getLocationInWindow(location);
14307
14308        final AttachInfo info = mAttachInfo;
14309        if (info != null) {
14310            location[0] += info.mWindowLeft;
14311            location[1] += info.mWindowTop;
14312        }
14313    }
14314
14315    /**
14316     * <p>Computes the coordinates of this view in its window. The argument
14317     * must be an array of two integers. After the method returns, the array
14318     * contains the x and y location in that order.</p>
14319     *
14320     * @param location an array of two integers in which to hold the coordinates
14321     */
14322    public void getLocationInWindow(int[] location) {
14323        if (location == null || location.length < 2) {
14324            throw new IllegalArgumentException("location must be an array of two integers");
14325        }
14326
14327        if (mAttachInfo == null) {
14328            // When the view is not attached to a window, this method does not make sense
14329            location[0] = location[1] = 0;
14330            return;
14331        }
14332
14333        float[] position = mAttachInfo.mTmpTransformLocation;
14334        position[0] = position[1] = 0.0f;
14335
14336        if (!hasIdentityMatrix()) {
14337            getMatrix().mapPoints(position);
14338        }
14339
14340        position[0] += mLeft;
14341        position[1] += mTop;
14342
14343        ViewParent viewParent = mParent;
14344        while (viewParent instanceof View) {
14345            final View view = (View) viewParent;
14346
14347            position[0] -= view.mScrollX;
14348            position[1] -= view.mScrollY;
14349
14350            if (!view.hasIdentityMatrix()) {
14351                view.getMatrix().mapPoints(position);
14352            }
14353
14354            position[0] += view.mLeft;
14355            position[1] += view.mTop;
14356
14357            viewParent = view.mParent;
14358         }
14359
14360        if (viewParent instanceof ViewRootImpl) {
14361            // *cough*
14362            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14363            position[1] -= vr.mCurScrollY;
14364        }
14365
14366        location[0] = (int) (position[0] + 0.5f);
14367        location[1] = (int) (position[1] + 0.5f);
14368    }
14369
14370    /**
14371     * {@hide}
14372     * @param id the id of the view to be found
14373     * @return the view of the specified id, null if cannot be found
14374     */
14375    protected View findViewTraversal(int id) {
14376        if (id == mID) {
14377            return this;
14378        }
14379        return null;
14380    }
14381
14382    /**
14383     * {@hide}
14384     * @param tag the tag of the view to be found
14385     * @return the view of specified tag, null if cannot be found
14386     */
14387    protected View findViewWithTagTraversal(Object tag) {
14388        if (tag != null && tag.equals(mTag)) {
14389            return this;
14390        }
14391        return null;
14392    }
14393
14394    /**
14395     * {@hide}
14396     * @param predicate The predicate to evaluate.
14397     * @param childToSkip If not null, ignores this child during the recursive traversal.
14398     * @return The first view that matches the predicate or null.
14399     */
14400    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14401        if (predicate.apply(this)) {
14402            return this;
14403        }
14404        return null;
14405    }
14406
14407    /**
14408     * Look for a child view with the given id.  If this view has the given
14409     * id, return this view.
14410     *
14411     * @param id The id to search for.
14412     * @return The view that has the given id in the hierarchy or null
14413     */
14414    public final View findViewById(int id) {
14415        if (id < 0) {
14416            return null;
14417        }
14418        return findViewTraversal(id);
14419    }
14420
14421    /**
14422     * Finds a view by its unuque and stable accessibility id.
14423     *
14424     * @param accessibilityId The searched accessibility id.
14425     * @return The found view.
14426     */
14427    final View findViewByAccessibilityId(int accessibilityId) {
14428        if (accessibilityId < 0) {
14429            return null;
14430        }
14431        return findViewByAccessibilityIdTraversal(accessibilityId);
14432    }
14433
14434    /**
14435     * Performs the traversal to find a view by its unuque and stable accessibility id.
14436     *
14437     * <strong>Note:</strong>This method does not stop at the root namespace
14438     * boundary since the user can touch the screen at an arbitrary location
14439     * potentially crossing the root namespace bounday which will send an
14440     * accessibility event to accessibility services and they should be able
14441     * to obtain the event source. Also accessibility ids are guaranteed to be
14442     * unique in the window.
14443     *
14444     * @param accessibilityId The accessibility id.
14445     * @return The found view.
14446     */
14447    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14448        if (getAccessibilityViewId() == accessibilityId) {
14449            return this;
14450        }
14451        return null;
14452    }
14453
14454    /**
14455     * Look for a child view with the given tag.  If this view has the given
14456     * tag, return this view.
14457     *
14458     * @param tag The tag to search for, using "tag.equals(getTag())".
14459     * @return The View that has the given tag in the hierarchy or null
14460     */
14461    public final View findViewWithTag(Object tag) {
14462        if (tag == null) {
14463            return null;
14464        }
14465        return findViewWithTagTraversal(tag);
14466    }
14467
14468    /**
14469     * {@hide}
14470     * Look for a child view that matches the specified predicate.
14471     * If this view matches the predicate, return this view.
14472     *
14473     * @param predicate The predicate to evaluate.
14474     * @return The first view that matches the predicate or null.
14475     */
14476    public final View findViewByPredicate(Predicate<View> predicate) {
14477        return findViewByPredicateTraversal(predicate, null);
14478    }
14479
14480    /**
14481     * {@hide}
14482     * Look for a child view that matches the specified predicate,
14483     * starting with the specified view and its descendents and then
14484     * recusively searching the ancestors and siblings of that view
14485     * until this view is reached.
14486     *
14487     * This method is useful in cases where the predicate does not match
14488     * a single unique view (perhaps multiple views use the same id)
14489     * and we are trying to find the view that is "closest" in scope to the
14490     * starting view.
14491     *
14492     * @param start The view to start from.
14493     * @param predicate The predicate to evaluate.
14494     * @return The first view that matches the predicate or null.
14495     */
14496    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14497        View childToSkip = null;
14498        for (;;) {
14499            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14500            if (view != null || start == this) {
14501                return view;
14502            }
14503
14504            ViewParent parent = start.getParent();
14505            if (parent == null || !(parent instanceof View)) {
14506                return null;
14507            }
14508
14509            childToSkip = start;
14510            start = (View) parent;
14511        }
14512    }
14513
14514    /**
14515     * Sets the identifier for this view. The identifier does not have to be
14516     * unique in this view's hierarchy. The identifier should be a positive
14517     * number.
14518     *
14519     * @see #NO_ID
14520     * @see #getId()
14521     * @see #findViewById(int)
14522     *
14523     * @param id a number used to identify the view
14524     *
14525     * @attr ref android.R.styleable#View_id
14526     */
14527    public void setId(int id) {
14528        mID = id;
14529    }
14530
14531    /**
14532     * {@hide}
14533     *
14534     * @param isRoot true if the view belongs to the root namespace, false
14535     *        otherwise
14536     */
14537    public void setIsRootNamespace(boolean isRoot) {
14538        if (isRoot) {
14539            mPrivateFlags |= IS_ROOT_NAMESPACE;
14540        } else {
14541            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14542        }
14543    }
14544
14545    /**
14546     * {@hide}
14547     *
14548     * @return true if the view belongs to the root namespace, false otherwise
14549     */
14550    public boolean isRootNamespace() {
14551        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14552    }
14553
14554    /**
14555     * Returns this view's identifier.
14556     *
14557     * @return a positive integer used to identify the view or {@link #NO_ID}
14558     *         if the view has no ID
14559     *
14560     * @see #setId(int)
14561     * @see #findViewById(int)
14562     * @attr ref android.R.styleable#View_id
14563     */
14564    @ViewDebug.CapturedViewProperty
14565    public int getId() {
14566        return mID;
14567    }
14568
14569    /**
14570     * Returns this view's tag.
14571     *
14572     * @return the Object stored in this view as a tag
14573     *
14574     * @see #setTag(Object)
14575     * @see #getTag(int)
14576     */
14577    @ViewDebug.ExportedProperty
14578    public Object getTag() {
14579        return mTag;
14580    }
14581
14582    /**
14583     * Sets the tag associated with this view. A tag can be used to mark
14584     * a view in its hierarchy and does not have to be unique within the
14585     * hierarchy. Tags can also be used to store data within a view without
14586     * resorting to another data structure.
14587     *
14588     * @param tag an Object to tag the view with
14589     *
14590     * @see #getTag()
14591     * @see #setTag(int, Object)
14592     */
14593    public void setTag(final Object tag) {
14594        mTag = tag;
14595    }
14596
14597    /**
14598     * Returns the tag associated with this view and the specified key.
14599     *
14600     * @param key The key identifying the tag
14601     *
14602     * @return the Object stored in this view as a tag
14603     *
14604     * @see #setTag(int, Object)
14605     * @see #getTag()
14606     */
14607    public Object getTag(int key) {
14608        if (mKeyedTags != null) return mKeyedTags.get(key);
14609        return null;
14610    }
14611
14612    /**
14613     * Sets a tag associated with this view and a key. A tag can be used
14614     * to mark a view in its hierarchy and does not have to be unique within
14615     * the hierarchy. Tags can also be used to store data within a view
14616     * without resorting to another data structure.
14617     *
14618     * The specified key should be an id declared in the resources of the
14619     * application to ensure it is unique (see the <a
14620     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14621     * Keys identified as belonging to
14622     * the Android framework or not associated with any package will cause
14623     * an {@link IllegalArgumentException} to be thrown.
14624     *
14625     * @param key The key identifying the tag
14626     * @param tag An Object to tag the view with
14627     *
14628     * @throws IllegalArgumentException If they specified key is not valid
14629     *
14630     * @see #setTag(Object)
14631     * @see #getTag(int)
14632     */
14633    public void setTag(int key, final Object tag) {
14634        // If the package id is 0x00 or 0x01, it's either an undefined package
14635        // or a framework id
14636        if ((key >>> 24) < 2) {
14637            throw new IllegalArgumentException("The key must be an application-specific "
14638                    + "resource id.");
14639        }
14640
14641        setKeyedTag(key, tag);
14642    }
14643
14644    /**
14645     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14646     * framework id.
14647     *
14648     * @hide
14649     */
14650    public void setTagInternal(int key, Object tag) {
14651        if ((key >>> 24) != 0x1) {
14652            throw new IllegalArgumentException("The key must be a framework-specific "
14653                    + "resource id.");
14654        }
14655
14656        setKeyedTag(key, tag);
14657    }
14658
14659    private void setKeyedTag(int key, Object tag) {
14660        if (mKeyedTags == null) {
14661            mKeyedTags = new SparseArray<Object>();
14662        }
14663
14664        mKeyedTags.put(key, tag);
14665    }
14666
14667    /**
14668     * @param consistency The type of consistency. See ViewDebug for more information.
14669     *
14670     * @hide
14671     */
14672    protected boolean dispatchConsistencyCheck(int consistency) {
14673        return onConsistencyCheck(consistency);
14674    }
14675
14676    /**
14677     * Method that subclasses should implement to check their consistency. The type of
14678     * consistency check is indicated by the bit field passed as a parameter.
14679     *
14680     * @param consistency The type of consistency. See ViewDebug for more information.
14681     *
14682     * @throws IllegalStateException if the view is in an inconsistent state.
14683     *
14684     * @hide
14685     */
14686    protected boolean onConsistencyCheck(int consistency) {
14687        boolean result = true;
14688
14689        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14690        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14691
14692        if (checkLayout) {
14693            if (getParent() == null) {
14694                result = false;
14695                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14696                        "View " + this + " does not have a parent.");
14697            }
14698
14699            if (mAttachInfo == null) {
14700                result = false;
14701                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14702                        "View " + this + " is not attached to a window.");
14703            }
14704        }
14705
14706        if (checkDrawing) {
14707            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14708            // from their draw() method
14709
14710            if ((mPrivateFlags & DRAWN) != DRAWN &&
14711                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14712                result = false;
14713                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14714                        "View " + this + " was invalidated but its drawing cache is valid.");
14715            }
14716        }
14717
14718        return result;
14719    }
14720
14721    /**
14722     * Prints information about this view in the log output, with the tag
14723     * {@link #VIEW_LOG_TAG}.
14724     *
14725     * @hide
14726     */
14727    public void debug() {
14728        debug(0);
14729    }
14730
14731    /**
14732     * Prints information about this view in the log output, with the tag
14733     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14734     * indentation defined by the <code>depth</code>.
14735     *
14736     * @param depth the indentation level
14737     *
14738     * @hide
14739     */
14740    protected void debug(int depth) {
14741        String output = debugIndent(depth - 1);
14742
14743        output += "+ " + this;
14744        int id = getId();
14745        if (id != -1) {
14746            output += " (id=" + id + ")";
14747        }
14748        Object tag = getTag();
14749        if (tag != null) {
14750            output += " (tag=" + tag + ")";
14751        }
14752        Log.d(VIEW_LOG_TAG, output);
14753
14754        if ((mPrivateFlags & FOCUSED) != 0) {
14755            output = debugIndent(depth) + " FOCUSED";
14756            Log.d(VIEW_LOG_TAG, output);
14757        }
14758
14759        output = debugIndent(depth);
14760        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14761                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14762                + "} ";
14763        Log.d(VIEW_LOG_TAG, output);
14764
14765        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14766                || mPaddingBottom != 0) {
14767            output = debugIndent(depth);
14768            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14769                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14770            Log.d(VIEW_LOG_TAG, output);
14771        }
14772
14773        output = debugIndent(depth);
14774        output += "mMeasureWidth=" + mMeasuredWidth +
14775                " mMeasureHeight=" + mMeasuredHeight;
14776        Log.d(VIEW_LOG_TAG, output);
14777
14778        output = debugIndent(depth);
14779        if (mLayoutParams == null) {
14780            output += "BAD! no layout params";
14781        } else {
14782            output = mLayoutParams.debug(output);
14783        }
14784        Log.d(VIEW_LOG_TAG, output);
14785
14786        output = debugIndent(depth);
14787        output += "flags={";
14788        output += View.printFlags(mViewFlags);
14789        output += "}";
14790        Log.d(VIEW_LOG_TAG, output);
14791
14792        output = debugIndent(depth);
14793        output += "privateFlags={";
14794        output += View.printPrivateFlags(mPrivateFlags);
14795        output += "}";
14796        Log.d(VIEW_LOG_TAG, output);
14797    }
14798
14799    /**
14800     * Creates a string of whitespaces used for indentation.
14801     *
14802     * @param depth the indentation level
14803     * @return a String containing (depth * 2 + 3) * 2 white spaces
14804     *
14805     * @hide
14806     */
14807    protected static String debugIndent(int depth) {
14808        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14809        for (int i = 0; i < (depth * 2) + 3; i++) {
14810            spaces.append(' ').append(' ');
14811        }
14812        return spaces.toString();
14813    }
14814
14815    /**
14816     * <p>Return the offset of the widget's text baseline from the widget's top
14817     * boundary. If this widget does not support baseline alignment, this
14818     * method returns -1. </p>
14819     *
14820     * @return the offset of the baseline within the widget's bounds or -1
14821     *         if baseline alignment is not supported
14822     */
14823    @ViewDebug.ExportedProperty(category = "layout")
14824    public int getBaseline() {
14825        return -1;
14826    }
14827
14828    /**
14829     * Call this when something has changed which has invalidated the
14830     * layout of this view. This will schedule a layout pass of the view
14831     * tree.
14832     */
14833    public void requestLayout() {
14834        if (ViewDebug.TRACE_HIERARCHY) {
14835            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14836        }
14837
14838        mPrivateFlags |= FORCE_LAYOUT;
14839        mPrivateFlags |= INVALIDATED;
14840
14841        if (mLayoutParams != null) {
14842            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14843        }
14844
14845        if (mParent != null && !mParent.isLayoutRequested()) {
14846            mParent.requestLayout();
14847        }
14848    }
14849
14850    /**
14851     * Forces this view to be laid out during the next layout pass.
14852     * This method does not call requestLayout() or forceLayout()
14853     * on the parent.
14854     */
14855    public void forceLayout() {
14856        mPrivateFlags |= FORCE_LAYOUT;
14857        mPrivateFlags |= INVALIDATED;
14858    }
14859
14860    /**
14861     * <p>
14862     * This is called to find out how big a view should be. The parent
14863     * supplies constraint information in the width and height parameters.
14864     * </p>
14865     *
14866     * <p>
14867     * The actual measurement work of a view is performed in
14868     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14869     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14870     * </p>
14871     *
14872     *
14873     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14874     *        parent
14875     * @param heightMeasureSpec Vertical space requirements as imposed by the
14876     *        parent
14877     *
14878     * @see #onMeasure(int, int)
14879     */
14880    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14881        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14882                widthMeasureSpec != mOldWidthMeasureSpec ||
14883                heightMeasureSpec != mOldHeightMeasureSpec) {
14884
14885            // first clears the measured dimension flag
14886            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14887
14888            if (ViewDebug.TRACE_HIERARCHY) {
14889                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14890            }
14891
14892            // measure ourselves, this should set the measured dimension flag back
14893            onMeasure(widthMeasureSpec, heightMeasureSpec);
14894
14895            // flag not set, setMeasuredDimension() was not invoked, we raise
14896            // an exception to warn the developer
14897            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14898                throw new IllegalStateException("onMeasure() did not set the"
14899                        + " measured dimension by calling"
14900                        + " setMeasuredDimension()");
14901            }
14902
14903            mPrivateFlags |= LAYOUT_REQUIRED;
14904        }
14905
14906        mOldWidthMeasureSpec = widthMeasureSpec;
14907        mOldHeightMeasureSpec = heightMeasureSpec;
14908    }
14909
14910    /**
14911     * <p>
14912     * Measure the view and its content to determine the measured width and the
14913     * measured height. This method is invoked by {@link #measure(int, int)} and
14914     * should be overriden by subclasses to provide accurate and efficient
14915     * measurement of their contents.
14916     * </p>
14917     *
14918     * <p>
14919     * <strong>CONTRACT:</strong> When overriding this method, you
14920     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14921     * measured width and height of this view. Failure to do so will trigger an
14922     * <code>IllegalStateException</code>, thrown by
14923     * {@link #measure(int, int)}. Calling the superclass'
14924     * {@link #onMeasure(int, int)} is a valid use.
14925     * </p>
14926     *
14927     * <p>
14928     * The base class implementation of measure defaults to the background size,
14929     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14930     * override {@link #onMeasure(int, int)} to provide better measurements of
14931     * their content.
14932     * </p>
14933     *
14934     * <p>
14935     * If this method is overridden, it is the subclass's responsibility to make
14936     * sure the measured height and width are at least the view's minimum height
14937     * and width ({@link #getSuggestedMinimumHeight()} and
14938     * {@link #getSuggestedMinimumWidth()}).
14939     * </p>
14940     *
14941     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14942     *                         The requirements are encoded with
14943     *                         {@link android.view.View.MeasureSpec}.
14944     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14945     *                         The requirements are encoded with
14946     *                         {@link android.view.View.MeasureSpec}.
14947     *
14948     * @see #getMeasuredWidth()
14949     * @see #getMeasuredHeight()
14950     * @see #setMeasuredDimension(int, int)
14951     * @see #getSuggestedMinimumHeight()
14952     * @see #getSuggestedMinimumWidth()
14953     * @see android.view.View.MeasureSpec#getMode(int)
14954     * @see android.view.View.MeasureSpec#getSize(int)
14955     */
14956    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14957        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14958                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14959    }
14960
14961    /**
14962     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14963     * measured width and measured height. Failing to do so will trigger an
14964     * exception at measurement time.</p>
14965     *
14966     * @param measuredWidth The measured width of this view.  May be a complex
14967     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14968     * {@link #MEASURED_STATE_TOO_SMALL}.
14969     * @param measuredHeight The measured height of this view.  May be a complex
14970     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14971     * {@link #MEASURED_STATE_TOO_SMALL}.
14972     */
14973    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14974        mMeasuredWidth = measuredWidth;
14975        mMeasuredHeight = measuredHeight;
14976
14977        mPrivateFlags |= MEASURED_DIMENSION_SET;
14978    }
14979
14980    /**
14981     * Merge two states as returned by {@link #getMeasuredState()}.
14982     * @param curState The current state as returned from a view or the result
14983     * of combining multiple views.
14984     * @param newState The new view state to combine.
14985     * @return Returns a new integer reflecting the combination of the two
14986     * states.
14987     */
14988    public static int combineMeasuredStates(int curState, int newState) {
14989        return curState | newState;
14990    }
14991
14992    /**
14993     * Version of {@link #resolveSizeAndState(int, int, int)}
14994     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14995     */
14996    public static int resolveSize(int size, int measureSpec) {
14997        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14998    }
14999
15000    /**
15001     * Utility to reconcile a desired size and state, with constraints imposed
15002     * by a MeasureSpec.  Will take the desired size, unless a different size
15003     * is imposed by the constraints.  The returned value is a compound integer,
15004     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15005     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15006     * size is smaller than the size the view wants to be.
15007     *
15008     * @param size How big the view wants to be
15009     * @param measureSpec Constraints imposed by the parent
15010     * @return Size information bit mask as defined by
15011     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15012     */
15013    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15014        int result = size;
15015        int specMode = MeasureSpec.getMode(measureSpec);
15016        int specSize =  MeasureSpec.getSize(measureSpec);
15017        switch (specMode) {
15018        case MeasureSpec.UNSPECIFIED:
15019            result = size;
15020            break;
15021        case MeasureSpec.AT_MOST:
15022            if (specSize < size) {
15023                result = specSize | MEASURED_STATE_TOO_SMALL;
15024            } else {
15025                result = size;
15026            }
15027            break;
15028        case MeasureSpec.EXACTLY:
15029            result = specSize;
15030            break;
15031        }
15032        return result | (childMeasuredState&MEASURED_STATE_MASK);
15033    }
15034
15035    /**
15036     * Utility to return a default size. Uses the supplied size if the
15037     * MeasureSpec imposed no constraints. Will get larger if allowed
15038     * by the MeasureSpec.
15039     *
15040     * @param size Default size for this view
15041     * @param measureSpec Constraints imposed by the parent
15042     * @return The size this view should be.
15043     */
15044    public static int getDefaultSize(int size, int measureSpec) {
15045        int result = size;
15046        int specMode = MeasureSpec.getMode(measureSpec);
15047        int specSize = MeasureSpec.getSize(measureSpec);
15048
15049        switch (specMode) {
15050        case MeasureSpec.UNSPECIFIED:
15051            result = size;
15052            break;
15053        case MeasureSpec.AT_MOST:
15054        case MeasureSpec.EXACTLY:
15055            result = specSize;
15056            break;
15057        }
15058        return result;
15059    }
15060
15061    /**
15062     * Returns the suggested minimum height that the view should use. This
15063     * returns the maximum of the view's minimum height
15064     * and the background's minimum height
15065     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15066     * <p>
15067     * When being used in {@link #onMeasure(int, int)}, the caller should still
15068     * ensure the returned height is within the requirements of the parent.
15069     *
15070     * @return The suggested minimum height of the view.
15071     */
15072    protected int getSuggestedMinimumHeight() {
15073        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15074
15075    }
15076
15077    /**
15078     * Returns the suggested minimum width that the view should use. This
15079     * returns the maximum of the view's minimum width)
15080     * and the background's minimum width
15081     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15082     * <p>
15083     * When being used in {@link #onMeasure(int, int)}, the caller should still
15084     * ensure the returned width is within the requirements of the parent.
15085     *
15086     * @return The suggested minimum width of the view.
15087     */
15088    protected int getSuggestedMinimumWidth() {
15089        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15090    }
15091
15092    /**
15093     * Returns the minimum height of the view.
15094     *
15095     * @return the minimum height the view will try to be.
15096     *
15097     * @see #setMinimumHeight(int)
15098     *
15099     * @attr ref android.R.styleable#View_minHeight
15100     */
15101    public int getMinimumHeight() {
15102        return mMinHeight;
15103    }
15104
15105    /**
15106     * Sets the minimum height of the view. It is not guaranteed the view will
15107     * be able to achieve this minimum height (for example, if its parent layout
15108     * constrains it with less available height).
15109     *
15110     * @param minHeight The minimum height the view will try to be.
15111     *
15112     * @see #getMinimumHeight()
15113     *
15114     * @attr ref android.R.styleable#View_minHeight
15115     */
15116    public void setMinimumHeight(int minHeight) {
15117        mMinHeight = minHeight;
15118        requestLayout();
15119    }
15120
15121    /**
15122     * Returns the minimum width of the view.
15123     *
15124     * @return the minimum width the view will try to be.
15125     *
15126     * @see #setMinimumWidth(int)
15127     *
15128     * @attr ref android.R.styleable#View_minWidth
15129     */
15130    public int getMinimumWidth() {
15131        return mMinWidth;
15132    }
15133
15134    /**
15135     * Sets the minimum width of the view. It is not guaranteed the view will
15136     * be able to achieve this minimum width (for example, if its parent layout
15137     * constrains it with less available width).
15138     *
15139     * @param minWidth The minimum width the view will try to be.
15140     *
15141     * @see #getMinimumWidth()
15142     *
15143     * @attr ref android.R.styleable#View_minWidth
15144     */
15145    public void setMinimumWidth(int minWidth) {
15146        mMinWidth = minWidth;
15147        requestLayout();
15148
15149    }
15150
15151    /**
15152     * Get the animation currently associated with this view.
15153     *
15154     * @return The animation that is currently playing or
15155     *         scheduled to play for this view.
15156     */
15157    public Animation getAnimation() {
15158        return mCurrentAnimation;
15159    }
15160
15161    /**
15162     * Start the specified animation now.
15163     *
15164     * @param animation the animation to start now
15165     */
15166    public void startAnimation(Animation animation) {
15167        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15168        setAnimation(animation);
15169        invalidateParentCaches();
15170        invalidate(true);
15171    }
15172
15173    /**
15174     * Cancels any animations for this view.
15175     */
15176    public void clearAnimation() {
15177        if (mCurrentAnimation != null) {
15178            mCurrentAnimation.detach();
15179        }
15180        mCurrentAnimation = null;
15181        invalidateParentIfNeeded();
15182    }
15183
15184    /**
15185     * Sets the next animation to play for this view.
15186     * If you want the animation to play immediately, use
15187     * startAnimation. This method provides allows fine-grained
15188     * control over the start time and invalidation, but you
15189     * must make sure that 1) the animation has a start time set, and
15190     * 2) the view will be invalidated when the animation is supposed to
15191     * start.
15192     *
15193     * @param animation The next animation, or null.
15194     */
15195    public void setAnimation(Animation animation) {
15196        mCurrentAnimation = animation;
15197
15198        if (animation != null) {
15199            // If the screen is off assume the animation start time is now instead of
15200            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15201            // would cause the animation to start when the screen turns back on
15202            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15203                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15204                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15205            }
15206            animation.reset();
15207        }
15208    }
15209
15210    /**
15211     * Invoked by a parent ViewGroup to notify the start of the animation
15212     * currently associated with this view. If you override this method,
15213     * always call super.onAnimationStart();
15214     *
15215     * @see #setAnimation(android.view.animation.Animation)
15216     * @see #getAnimation()
15217     */
15218    protected void onAnimationStart() {
15219        mPrivateFlags |= ANIMATION_STARTED;
15220    }
15221
15222    /**
15223     * Invoked by a parent ViewGroup to notify the end of the animation
15224     * currently associated with this view. If you override this method,
15225     * always call super.onAnimationEnd();
15226     *
15227     * @see #setAnimation(android.view.animation.Animation)
15228     * @see #getAnimation()
15229     */
15230    protected void onAnimationEnd() {
15231        mPrivateFlags &= ~ANIMATION_STARTED;
15232    }
15233
15234    /**
15235     * Invoked if there is a Transform that involves alpha. Subclass that can
15236     * draw themselves with the specified alpha should return true, and then
15237     * respect that alpha when their onDraw() is called. If this returns false
15238     * then the view may be redirected to draw into an offscreen buffer to
15239     * fulfill the request, which will look fine, but may be slower than if the
15240     * subclass handles it internally. The default implementation returns false.
15241     *
15242     * @param alpha The alpha (0..255) to apply to the view's drawing
15243     * @return true if the view can draw with the specified alpha.
15244     */
15245    protected boolean onSetAlpha(int alpha) {
15246        return false;
15247    }
15248
15249    /**
15250     * This is used by the RootView to perform an optimization when
15251     * the view hierarchy contains one or several SurfaceView.
15252     * SurfaceView is always considered transparent, but its children are not,
15253     * therefore all View objects remove themselves from the global transparent
15254     * region (passed as a parameter to this function).
15255     *
15256     * @param region The transparent region for this ViewAncestor (window).
15257     *
15258     * @return Returns true if the effective visibility of the view at this
15259     * point is opaque, regardless of the transparent region; returns false
15260     * if it is possible for underlying windows to be seen behind the view.
15261     *
15262     * {@hide}
15263     */
15264    public boolean gatherTransparentRegion(Region region) {
15265        final AttachInfo attachInfo = mAttachInfo;
15266        if (region != null && attachInfo != null) {
15267            final int pflags = mPrivateFlags;
15268            if ((pflags & SKIP_DRAW) == 0) {
15269                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15270                // remove it from the transparent region.
15271                final int[] location = attachInfo.mTransparentLocation;
15272                getLocationInWindow(location);
15273                region.op(location[0], location[1], location[0] + mRight - mLeft,
15274                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15275            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15276                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15277                // exists, so we remove the background drawable's non-transparent
15278                // parts from this transparent region.
15279                applyDrawableToTransparentRegion(mBackground, region);
15280            }
15281        }
15282        return true;
15283    }
15284
15285    /**
15286     * Play a sound effect for this view.
15287     *
15288     * <p>The framework will play sound effects for some built in actions, such as
15289     * clicking, but you may wish to play these effects in your widget,
15290     * for instance, for internal navigation.
15291     *
15292     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15293     * {@link #isSoundEffectsEnabled()} is true.
15294     *
15295     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15296     */
15297    public void playSoundEffect(int soundConstant) {
15298        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15299            return;
15300        }
15301        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15302    }
15303
15304    /**
15305     * BZZZTT!!1!
15306     *
15307     * <p>Provide haptic feedback to the user for this view.
15308     *
15309     * <p>The framework will provide haptic feedback for some built in actions,
15310     * such as long presses, but you may wish to provide feedback for your
15311     * own widget.
15312     *
15313     * <p>The feedback will only be performed if
15314     * {@link #isHapticFeedbackEnabled()} is true.
15315     *
15316     * @param feedbackConstant One of the constants defined in
15317     * {@link HapticFeedbackConstants}
15318     */
15319    public boolean performHapticFeedback(int feedbackConstant) {
15320        return performHapticFeedback(feedbackConstant, 0);
15321    }
15322
15323    /**
15324     * BZZZTT!!1!
15325     *
15326     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15327     *
15328     * @param feedbackConstant One of the constants defined in
15329     * {@link HapticFeedbackConstants}
15330     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15331     */
15332    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15333        if (mAttachInfo == null) {
15334            return false;
15335        }
15336        //noinspection SimplifiableIfStatement
15337        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15338                && !isHapticFeedbackEnabled()) {
15339            return false;
15340        }
15341        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15342                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15343    }
15344
15345    /**
15346     * Request that the visibility of the status bar or other screen/window
15347     * decorations be changed.
15348     *
15349     * <p>This method is used to put the over device UI into temporary modes
15350     * where the user's attention is focused more on the application content,
15351     * by dimming or hiding surrounding system affordances.  This is typically
15352     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15353     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15354     * to be placed behind the action bar (and with these flags other system
15355     * affordances) so that smooth transitions between hiding and showing them
15356     * can be done.
15357     *
15358     * <p>Two representative examples of the use of system UI visibility is
15359     * implementing a content browsing application (like a magazine reader)
15360     * and a video playing application.
15361     *
15362     * <p>The first code shows a typical implementation of a View in a content
15363     * browsing application.  In this implementation, the application goes
15364     * into a content-oriented mode by hiding the status bar and action bar,
15365     * and putting the navigation elements into lights out mode.  The user can
15366     * then interact with content while in this mode.  Such an application should
15367     * provide an easy way for the user to toggle out of the mode (such as to
15368     * check information in the status bar or access notifications).  In the
15369     * implementation here, this is done simply by tapping on the content.
15370     *
15371     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15372     *      content}
15373     *
15374     * <p>This second code sample shows a typical implementation of a View
15375     * in a video playing application.  In this situation, while the video is
15376     * playing the application would like to go into a complete full-screen mode,
15377     * to use as much of the display as possible for the video.  When in this state
15378     * the user can not interact with the application; the system intercepts
15379     * touching on the screen to pop the UI out of full screen mode.
15380     *
15381     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15382     *      content}
15383     *
15384     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15385     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15386     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15387     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15388     */
15389    public void setSystemUiVisibility(int visibility) {
15390        if (visibility != mSystemUiVisibility) {
15391            mSystemUiVisibility = visibility;
15392            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15393                mParent.recomputeViewAttributes(this);
15394            }
15395        }
15396    }
15397
15398    /**
15399     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15400     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15401     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15402     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15403     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15404     */
15405    public int getSystemUiVisibility() {
15406        return mSystemUiVisibility;
15407    }
15408
15409    /**
15410     * Returns the current system UI visibility that is currently set for
15411     * the entire window.  This is the combination of the
15412     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15413     * views in the window.
15414     */
15415    public int getWindowSystemUiVisibility() {
15416        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15417    }
15418
15419    /**
15420     * Override to find out when the window's requested system UI visibility
15421     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15422     * This is different from the callbacks recieved through
15423     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15424     * in that this is only telling you about the local request of the window,
15425     * not the actual values applied by the system.
15426     */
15427    public void onWindowSystemUiVisibilityChanged(int visible) {
15428    }
15429
15430    /**
15431     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15432     * the view hierarchy.
15433     */
15434    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15435        onWindowSystemUiVisibilityChanged(visible);
15436    }
15437
15438    /**
15439     * Set a listener to receive callbacks when the visibility of the system bar changes.
15440     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15441     */
15442    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15443        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15444        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15445            mParent.recomputeViewAttributes(this);
15446        }
15447    }
15448
15449    /**
15450     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15451     * the view hierarchy.
15452     */
15453    public void dispatchSystemUiVisibilityChanged(int visibility) {
15454        ListenerInfo li = mListenerInfo;
15455        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15456            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15457                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15458        }
15459    }
15460
15461    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15462        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15463        if (val != mSystemUiVisibility) {
15464            setSystemUiVisibility(val);
15465        }
15466    }
15467
15468    /** @hide */
15469    public void setDisabledSystemUiVisibility(int flags) {
15470        if (mAttachInfo != null) {
15471            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15472                mAttachInfo.mDisabledSystemUiVisibility = flags;
15473                if (mParent != null) {
15474                    mParent.recomputeViewAttributes(this);
15475                }
15476            }
15477        }
15478    }
15479
15480    /**
15481     * Creates an image that the system displays during the drag and drop
15482     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15483     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15484     * appearance as the given View. The default also positions the center of the drag shadow
15485     * directly under the touch point. If no View is provided (the constructor with no parameters
15486     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15487     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15488     * default is an invisible drag shadow.
15489     * <p>
15490     * You are not required to use the View you provide to the constructor as the basis of the
15491     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15492     * anything you want as the drag shadow.
15493     * </p>
15494     * <p>
15495     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15496     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15497     *  size and position of the drag shadow. It uses this data to construct a
15498     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15499     *  so that your application can draw the shadow image in the Canvas.
15500     * </p>
15501     *
15502     * <div class="special reference">
15503     * <h3>Developer Guides</h3>
15504     * <p>For a guide to implementing drag and drop features, read the
15505     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15506     * </div>
15507     */
15508    public static class DragShadowBuilder {
15509        private final WeakReference<View> mView;
15510
15511        /**
15512         * Constructs a shadow image builder based on a View. By default, the resulting drag
15513         * shadow will have the same appearance and dimensions as the View, with the touch point
15514         * over the center of the View.
15515         * @param view A View. Any View in scope can be used.
15516         */
15517        public DragShadowBuilder(View view) {
15518            mView = new WeakReference<View>(view);
15519        }
15520
15521        /**
15522         * Construct a shadow builder object with no associated View.  This
15523         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15524         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15525         * to supply the drag shadow's dimensions and appearance without
15526         * reference to any View object. If they are not overridden, then the result is an
15527         * invisible drag shadow.
15528         */
15529        public DragShadowBuilder() {
15530            mView = new WeakReference<View>(null);
15531        }
15532
15533        /**
15534         * Returns the View object that had been passed to the
15535         * {@link #View.DragShadowBuilder(View)}
15536         * constructor.  If that View parameter was {@code null} or if the
15537         * {@link #View.DragShadowBuilder()}
15538         * constructor was used to instantiate the builder object, this method will return
15539         * null.
15540         *
15541         * @return The View object associate with this builder object.
15542         */
15543        @SuppressWarnings({"JavadocReference"})
15544        final public View getView() {
15545            return mView.get();
15546        }
15547
15548        /**
15549         * Provides the metrics for the shadow image. These include the dimensions of
15550         * the shadow image, and the point within that shadow that should
15551         * be centered under the touch location while dragging.
15552         * <p>
15553         * The default implementation sets the dimensions of the shadow to be the
15554         * same as the dimensions of the View itself and centers the shadow under
15555         * the touch point.
15556         * </p>
15557         *
15558         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15559         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15560         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15561         * image.
15562         *
15563         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15564         * shadow image that should be underneath the touch point during the drag and drop
15565         * operation. Your application must set {@link android.graphics.Point#x} to the
15566         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15567         */
15568        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15569            final View view = mView.get();
15570            if (view != null) {
15571                shadowSize.set(view.getWidth(), view.getHeight());
15572                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15573            } else {
15574                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15575            }
15576        }
15577
15578        /**
15579         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15580         * based on the dimensions it received from the
15581         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15582         *
15583         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15584         */
15585        public void onDrawShadow(Canvas canvas) {
15586            final View view = mView.get();
15587            if (view != null) {
15588                view.draw(canvas);
15589            } else {
15590                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15591            }
15592        }
15593    }
15594
15595    /**
15596     * Starts a drag and drop operation. When your application calls this method, it passes a
15597     * {@link android.view.View.DragShadowBuilder} object to the system. The
15598     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15599     * to get metrics for the drag shadow, and then calls the object's
15600     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15601     * <p>
15602     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15603     *  drag events to all the View objects in your application that are currently visible. It does
15604     *  this either by calling the View object's drag listener (an implementation of
15605     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15606     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15607     *  Both are passed a {@link android.view.DragEvent} object that has a
15608     *  {@link android.view.DragEvent#getAction()} value of
15609     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15610     * </p>
15611     * <p>
15612     * Your application can invoke startDrag() on any attached View object. The View object does not
15613     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15614     * be related to the View the user selected for dragging.
15615     * </p>
15616     * @param data A {@link android.content.ClipData} object pointing to the data to be
15617     * transferred by the drag and drop operation.
15618     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15619     * drag shadow.
15620     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15621     * drop operation. This Object is put into every DragEvent object sent by the system during the
15622     * current drag.
15623     * <p>
15624     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15625     * to the target Views. For example, it can contain flags that differentiate between a
15626     * a copy operation and a move operation.
15627     * </p>
15628     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15629     * so the parameter should be set to 0.
15630     * @return {@code true} if the method completes successfully, or
15631     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15632     * do a drag, and so no drag operation is in progress.
15633     */
15634    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15635            Object myLocalState, int flags) {
15636        if (ViewDebug.DEBUG_DRAG) {
15637            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15638        }
15639        boolean okay = false;
15640
15641        Point shadowSize = new Point();
15642        Point shadowTouchPoint = new Point();
15643        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15644
15645        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15646                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15647            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15648        }
15649
15650        if (ViewDebug.DEBUG_DRAG) {
15651            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15652                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15653        }
15654        Surface surface = new Surface();
15655        try {
15656            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15657                    flags, shadowSize.x, shadowSize.y, surface);
15658            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15659                    + " surface=" + surface);
15660            if (token != null) {
15661                Canvas canvas = surface.lockCanvas(null);
15662                try {
15663                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15664                    shadowBuilder.onDrawShadow(canvas);
15665                } finally {
15666                    surface.unlockCanvasAndPost(canvas);
15667                }
15668
15669                final ViewRootImpl root = getViewRootImpl();
15670
15671                // Cache the local state object for delivery with DragEvents
15672                root.setLocalDragState(myLocalState);
15673
15674                // repurpose 'shadowSize' for the last touch point
15675                root.getLastTouchPoint(shadowSize);
15676
15677                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15678                        shadowSize.x, shadowSize.y,
15679                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15680                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15681
15682                // Off and running!  Release our local surface instance; the drag
15683                // shadow surface is now managed by the system process.
15684                surface.release();
15685            }
15686        } catch (Exception e) {
15687            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15688            surface.destroy();
15689        }
15690
15691        return okay;
15692    }
15693
15694    /**
15695     * Handles drag events sent by the system following a call to
15696     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15697     *<p>
15698     * When the system calls this method, it passes a
15699     * {@link android.view.DragEvent} object. A call to
15700     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15701     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15702     * operation.
15703     * @param event The {@link android.view.DragEvent} sent by the system.
15704     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15705     * in DragEvent, indicating the type of drag event represented by this object.
15706     * @return {@code true} if the method was successful, otherwise {@code false}.
15707     * <p>
15708     *  The method should return {@code true} in response to an action type of
15709     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15710     *  operation.
15711     * </p>
15712     * <p>
15713     *  The method should also return {@code true} in response to an action type of
15714     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15715     *  {@code false} if it didn't.
15716     * </p>
15717     */
15718    public boolean onDragEvent(DragEvent event) {
15719        return false;
15720    }
15721
15722    /**
15723     * Detects if this View is enabled and has a drag event listener.
15724     * If both are true, then it calls the drag event listener with the
15725     * {@link android.view.DragEvent} it received. If the drag event listener returns
15726     * {@code true}, then dispatchDragEvent() returns {@code true}.
15727     * <p>
15728     * For all other cases, the method calls the
15729     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15730     * method and returns its result.
15731     * </p>
15732     * <p>
15733     * This ensures that a drag event is always consumed, even if the View does not have a drag
15734     * event listener. However, if the View has a listener and the listener returns true, then
15735     * onDragEvent() is not called.
15736     * </p>
15737     */
15738    public boolean dispatchDragEvent(DragEvent event) {
15739        //noinspection SimplifiableIfStatement
15740        ListenerInfo li = mListenerInfo;
15741        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15742                && li.mOnDragListener.onDrag(this, event)) {
15743            return true;
15744        }
15745        return onDragEvent(event);
15746    }
15747
15748    boolean canAcceptDrag() {
15749        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15750    }
15751
15752    /**
15753     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15754     * it is ever exposed at all.
15755     * @hide
15756     */
15757    public void onCloseSystemDialogs(String reason) {
15758    }
15759
15760    /**
15761     * Given a Drawable whose bounds have been set to draw into this view,
15762     * update a Region being computed for
15763     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15764     * that any non-transparent parts of the Drawable are removed from the
15765     * given transparent region.
15766     *
15767     * @param dr The Drawable whose transparency is to be applied to the region.
15768     * @param region A Region holding the current transparency information,
15769     * where any parts of the region that are set are considered to be
15770     * transparent.  On return, this region will be modified to have the
15771     * transparency information reduced by the corresponding parts of the
15772     * Drawable that are not transparent.
15773     * {@hide}
15774     */
15775    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15776        if (DBG) {
15777            Log.i("View", "Getting transparent region for: " + this);
15778        }
15779        final Region r = dr.getTransparentRegion();
15780        final Rect db = dr.getBounds();
15781        final AttachInfo attachInfo = mAttachInfo;
15782        if (r != null && attachInfo != null) {
15783            final int w = getRight()-getLeft();
15784            final int h = getBottom()-getTop();
15785            if (db.left > 0) {
15786                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15787                r.op(0, 0, db.left, h, Region.Op.UNION);
15788            }
15789            if (db.right < w) {
15790                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15791                r.op(db.right, 0, w, h, Region.Op.UNION);
15792            }
15793            if (db.top > 0) {
15794                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15795                r.op(0, 0, w, db.top, Region.Op.UNION);
15796            }
15797            if (db.bottom < h) {
15798                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15799                r.op(0, db.bottom, w, h, Region.Op.UNION);
15800            }
15801            final int[] location = attachInfo.mTransparentLocation;
15802            getLocationInWindow(location);
15803            r.translate(location[0], location[1]);
15804            region.op(r, Region.Op.INTERSECT);
15805        } else {
15806            region.op(db, Region.Op.DIFFERENCE);
15807        }
15808    }
15809
15810    private void checkForLongClick(int delayOffset) {
15811        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15812            mHasPerformedLongPress = false;
15813
15814            if (mPendingCheckForLongPress == null) {
15815                mPendingCheckForLongPress = new CheckForLongPress();
15816            }
15817            mPendingCheckForLongPress.rememberWindowAttachCount();
15818            postDelayed(mPendingCheckForLongPress,
15819                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15820        }
15821    }
15822
15823    /**
15824     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15825     * LayoutInflater} class, which provides a full range of options for view inflation.
15826     *
15827     * @param context The Context object for your activity or application.
15828     * @param resource The resource ID to inflate
15829     * @param root A view group that will be the parent.  Used to properly inflate the
15830     * layout_* parameters.
15831     * @see LayoutInflater
15832     */
15833    public static View inflate(Context context, int resource, ViewGroup root) {
15834        LayoutInflater factory = LayoutInflater.from(context);
15835        return factory.inflate(resource, root);
15836    }
15837
15838    /**
15839     * Scroll the view with standard behavior for scrolling beyond the normal
15840     * content boundaries. Views that call this method should override
15841     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15842     * results of an over-scroll operation.
15843     *
15844     * Views can use this method to handle any touch or fling-based scrolling.
15845     *
15846     * @param deltaX Change in X in pixels
15847     * @param deltaY Change in Y in pixels
15848     * @param scrollX Current X scroll value in pixels before applying deltaX
15849     * @param scrollY Current Y scroll value in pixels before applying deltaY
15850     * @param scrollRangeX Maximum content scroll range along the X axis
15851     * @param scrollRangeY Maximum content scroll range along the Y axis
15852     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15853     *          along the X axis.
15854     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15855     *          along the Y axis.
15856     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15857     * @return true if scrolling was clamped to an over-scroll boundary along either
15858     *          axis, false otherwise.
15859     */
15860    @SuppressWarnings({"UnusedParameters"})
15861    protected boolean overScrollBy(int deltaX, int deltaY,
15862            int scrollX, int scrollY,
15863            int scrollRangeX, int scrollRangeY,
15864            int maxOverScrollX, int maxOverScrollY,
15865            boolean isTouchEvent) {
15866        final int overScrollMode = mOverScrollMode;
15867        final boolean canScrollHorizontal =
15868                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15869        final boolean canScrollVertical =
15870                computeVerticalScrollRange() > computeVerticalScrollExtent();
15871        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15872                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15873        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15874                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15875
15876        int newScrollX = scrollX + deltaX;
15877        if (!overScrollHorizontal) {
15878            maxOverScrollX = 0;
15879        }
15880
15881        int newScrollY = scrollY + deltaY;
15882        if (!overScrollVertical) {
15883            maxOverScrollY = 0;
15884        }
15885
15886        // Clamp values if at the limits and record
15887        final int left = -maxOverScrollX;
15888        final int right = maxOverScrollX + scrollRangeX;
15889        final int top = -maxOverScrollY;
15890        final int bottom = maxOverScrollY + scrollRangeY;
15891
15892        boolean clampedX = false;
15893        if (newScrollX > right) {
15894            newScrollX = right;
15895            clampedX = true;
15896        } else if (newScrollX < left) {
15897            newScrollX = left;
15898            clampedX = true;
15899        }
15900
15901        boolean clampedY = false;
15902        if (newScrollY > bottom) {
15903            newScrollY = bottom;
15904            clampedY = true;
15905        } else if (newScrollY < top) {
15906            newScrollY = top;
15907            clampedY = true;
15908        }
15909
15910        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15911
15912        return clampedX || clampedY;
15913    }
15914
15915    /**
15916     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15917     * respond to the results of an over-scroll operation.
15918     *
15919     * @param scrollX New X scroll value in pixels
15920     * @param scrollY New Y scroll value in pixels
15921     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15922     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15923     */
15924    protected void onOverScrolled(int scrollX, int scrollY,
15925            boolean clampedX, boolean clampedY) {
15926        // Intentionally empty.
15927    }
15928
15929    /**
15930     * Returns the over-scroll mode for this view. The result will be
15931     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15932     * (allow over-scrolling only if the view content is larger than the container),
15933     * or {@link #OVER_SCROLL_NEVER}.
15934     *
15935     * @return This view's over-scroll mode.
15936     */
15937    public int getOverScrollMode() {
15938        return mOverScrollMode;
15939    }
15940
15941    /**
15942     * Set the over-scroll mode for this view. Valid over-scroll modes are
15943     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15944     * (allow over-scrolling only if the view content is larger than the container),
15945     * or {@link #OVER_SCROLL_NEVER}.
15946     *
15947     * Setting the over-scroll mode of a view will have an effect only if the
15948     * view is capable of scrolling.
15949     *
15950     * @param overScrollMode The new over-scroll mode for this view.
15951     */
15952    public void setOverScrollMode(int overScrollMode) {
15953        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15954                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15955                overScrollMode != OVER_SCROLL_NEVER) {
15956            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15957        }
15958        mOverScrollMode = overScrollMode;
15959    }
15960
15961    /**
15962     * Gets a scale factor that determines the distance the view should scroll
15963     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15964     * @return The vertical scroll scale factor.
15965     * @hide
15966     */
15967    protected float getVerticalScrollFactor() {
15968        if (mVerticalScrollFactor == 0) {
15969            TypedValue outValue = new TypedValue();
15970            if (!mContext.getTheme().resolveAttribute(
15971                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15972                throw new IllegalStateException(
15973                        "Expected theme to define listPreferredItemHeight.");
15974            }
15975            mVerticalScrollFactor = outValue.getDimension(
15976                    mContext.getResources().getDisplayMetrics());
15977        }
15978        return mVerticalScrollFactor;
15979    }
15980
15981    /**
15982     * Gets a scale factor that determines the distance the view should scroll
15983     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15984     * @return The horizontal scroll scale factor.
15985     * @hide
15986     */
15987    protected float getHorizontalScrollFactor() {
15988        // TODO: Should use something else.
15989        return getVerticalScrollFactor();
15990    }
15991
15992    /**
15993     * Return the value specifying the text direction or policy that was set with
15994     * {@link #setTextDirection(int)}.
15995     *
15996     * @return the defined text direction. It can be one of:
15997     *
15998     * {@link #TEXT_DIRECTION_INHERIT},
15999     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16000     * {@link #TEXT_DIRECTION_ANY_RTL},
16001     * {@link #TEXT_DIRECTION_LTR},
16002     * {@link #TEXT_DIRECTION_RTL},
16003     * {@link #TEXT_DIRECTION_LOCALE}
16004     * @hide
16005     */
16006    @ViewDebug.ExportedProperty(category = "text", mapping = {
16007            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16008            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16009            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16010            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16011            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16012            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16013    })
16014    public int getTextDirection() {
16015        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16016    }
16017
16018    /**
16019     * Set the text direction.
16020     *
16021     * @param textDirection the direction to set. Should be one of:
16022     *
16023     * {@link #TEXT_DIRECTION_INHERIT},
16024     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16025     * {@link #TEXT_DIRECTION_ANY_RTL},
16026     * {@link #TEXT_DIRECTION_LTR},
16027     * {@link #TEXT_DIRECTION_RTL},
16028     * {@link #TEXT_DIRECTION_LOCALE}
16029     * @hide
16030     */
16031    public void setTextDirection(int textDirection) {
16032        if (getTextDirection() != textDirection) {
16033            // Reset the current text direction and the resolved one
16034            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16035            resetResolvedTextDirection();
16036            // Set the new text direction
16037            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16038            // Refresh
16039            requestLayout();
16040            invalidate(true);
16041        }
16042    }
16043
16044    /**
16045     * Return the resolved text direction.
16046     *
16047     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16048     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16049     * up the parent chain of the view. if there is no parent, then it will return the default
16050     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16051     *
16052     * @return the resolved text direction. Returns one of:
16053     *
16054     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16055     * {@link #TEXT_DIRECTION_ANY_RTL},
16056     * {@link #TEXT_DIRECTION_LTR},
16057     * {@link #TEXT_DIRECTION_RTL},
16058     * {@link #TEXT_DIRECTION_LOCALE}
16059     * @hide
16060     */
16061    public int getResolvedTextDirection() {
16062        // The text direction will be resolved only if needed
16063        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16064            resolveTextDirection();
16065        }
16066        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16067    }
16068
16069    /**
16070     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16071     * resolution is done.
16072     * @hide
16073     */
16074    public void resolveTextDirection() {
16075        // Reset any previous text direction resolution
16076        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16077
16078        if (hasRtlSupport()) {
16079            // Set resolved text direction flag depending on text direction flag
16080            final int textDirection = getTextDirection();
16081            switch(textDirection) {
16082                case TEXT_DIRECTION_INHERIT:
16083                    if (canResolveTextDirection()) {
16084                        ViewGroup viewGroup = ((ViewGroup) mParent);
16085
16086                        // Set current resolved direction to the same value as the parent's one
16087                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16088                        switch (parentResolvedDirection) {
16089                            case TEXT_DIRECTION_FIRST_STRONG:
16090                            case TEXT_DIRECTION_ANY_RTL:
16091                            case TEXT_DIRECTION_LTR:
16092                            case TEXT_DIRECTION_RTL:
16093                            case TEXT_DIRECTION_LOCALE:
16094                                mPrivateFlags2 |=
16095                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16096                                break;
16097                            default:
16098                                // Default resolved direction is "first strong" heuristic
16099                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16100                        }
16101                    } else {
16102                        // We cannot do the resolution if there is no parent, so use the default one
16103                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16104                    }
16105                    break;
16106                case TEXT_DIRECTION_FIRST_STRONG:
16107                case TEXT_DIRECTION_ANY_RTL:
16108                case TEXT_DIRECTION_LTR:
16109                case TEXT_DIRECTION_RTL:
16110                case TEXT_DIRECTION_LOCALE:
16111                    // Resolved direction is the same as text direction
16112                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16113                    break;
16114                default:
16115                    // Default resolved direction is "first strong" heuristic
16116                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16117            }
16118        } else {
16119            // Default resolved direction is "first strong" heuristic
16120            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16121        }
16122
16123        // Set to resolved
16124        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16125        onResolvedTextDirectionChanged();
16126    }
16127
16128    /**
16129     * Called when text direction has been resolved. Subclasses that care about text direction
16130     * resolution should override this method.
16131     *
16132     * The default implementation does nothing.
16133     * @hide
16134     */
16135    public void onResolvedTextDirectionChanged() {
16136    }
16137
16138    /**
16139     * Check if text direction resolution can be done.
16140     *
16141     * @return true if text direction resolution can be done otherwise return false.
16142     * @hide
16143     */
16144    public boolean canResolveTextDirection() {
16145        switch (getTextDirection()) {
16146            case TEXT_DIRECTION_INHERIT:
16147                return (mParent != null) && (mParent instanceof ViewGroup);
16148            default:
16149                return true;
16150        }
16151    }
16152
16153    /**
16154     * Reset resolved text direction. Text direction can be resolved with a call to
16155     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16156     * reset is done.
16157     * @hide
16158     */
16159    public void resetResolvedTextDirection() {
16160        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16161        onResolvedTextDirectionReset();
16162    }
16163
16164    /**
16165     * Called when text direction is reset. Subclasses that care about text direction reset should
16166     * override this method and do a reset of the text direction of their children. The default
16167     * implementation does nothing.
16168     * @hide
16169     */
16170    public void onResolvedTextDirectionReset() {
16171    }
16172
16173    /**
16174     * Return the value specifying the text alignment or policy that was set with
16175     * {@link #setTextAlignment(int)}.
16176     *
16177     * @return the defined text alignment. It can be one of:
16178     *
16179     * {@link #TEXT_ALIGNMENT_INHERIT},
16180     * {@link #TEXT_ALIGNMENT_GRAVITY},
16181     * {@link #TEXT_ALIGNMENT_CENTER},
16182     * {@link #TEXT_ALIGNMENT_TEXT_START},
16183     * {@link #TEXT_ALIGNMENT_TEXT_END},
16184     * {@link #TEXT_ALIGNMENT_VIEW_START},
16185     * {@link #TEXT_ALIGNMENT_VIEW_END}
16186     * @hide
16187     */
16188    @ViewDebug.ExportedProperty(category = "text", mapping = {
16189            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16190            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16191            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16192            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16193            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16194            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16195            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16196    })
16197    public int getTextAlignment() {
16198        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16199    }
16200
16201    /**
16202     * Set the text alignment.
16203     *
16204     * @param textAlignment The text alignment to set. Should be one of
16205     *
16206     * {@link #TEXT_ALIGNMENT_INHERIT},
16207     * {@link #TEXT_ALIGNMENT_GRAVITY},
16208     * {@link #TEXT_ALIGNMENT_CENTER},
16209     * {@link #TEXT_ALIGNMENT_TEXT_START},
16210     * {@link #TEXT_ALIGNMENT_TEXT_END},
16211     * {@link #TEXT_ALIGNMENT_VIEW_START},
16212     * {@link #TEXT_ALIGNMENT_VIEW_END}
16213     *
16214     * @attr ref android.R.styleable#View_textAlignment
16215     * @hide
16216     */
16217    public void setTextAlignment(int textAlignment) {
16218        if (textAlignment != getTextAlignment()) {
16219            // Reset the current and resolved text alignment
16220            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16221            resetResolvedTextAlignment();
16222            // Set the new text alignment
16223            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16224            // Refresh
16225            requestLayout();
16226            invalidate(true);
16227        }
16228    }
16229
16230    /**
16231     * Return the resolved text alignment.
16232     *
16233     * The resolved text alignment. This needs resolution if the value is
16234     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16235     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16236     *
16237     * @return the resolved text alignment. Returns one of:
16238     *
16239     * {@link #TEXT_ALIGNMENT_GRAVITY},
16240     * {@link #TEXT_ALIGNMENT_CENTER},
16241     * {@link #TEXT_ALIGNMENT_TEXT_START},
16242     * {@link #TEXT_ALIGNMENT_TEXT_END},
16243     * {@link #TEXT_ALIGNMENT_VIEW_START},
16244     * {@link #TEXT_ALIGNMENT_VIEW_END}
16245     * @hide
16246     */
16247    @ViewDebug.ExportedProperty(category = "text", mapping = {
16248            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16249            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16250            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16251            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16252            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16253            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16254            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16255    })
16256    public int getResolvedTextAlignment() {
16257        // If text alignment is not resolved, then resolve it
16258        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16259            resolveTextAlignment();
16260        }
16261        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16262    }
16263
16264    /**
16265     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16266     * resolution is done.
16267     * @hide
16268     */
16269    public void resolveTextAlignment() {
16270        // Reset any previous text alignment resolution
16271        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16272
16273        if (hasRtlSupport()) {
16274            // Set resolved text alignment flag depending on text alignment flag
16275            final int textAlignment = getTextAlignment();
16276            switch (textAlignment) {
16277                case TEXT_ALIGNMENT_INHERIT:
16278                    // Check if we can resolve the text alignment
16279                    if (canResolveLayoutDirection() && mParent instanceof View) {
16280                        View view = (View) mParent;
16281
16282                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16283                        switch (parentResolvedTextAlignment) {
16284                            case TEXT_ALIGNMENT_GRAVITY:
16285                            case TEXT_ALIGNMENT_TEXT_START:
16286                            case TEXT_ALIGNMENT_TEXT_END:
16287                            case TEXT_ALIGNMENT_CENTER:
16288                            case TEXT_ALIGNMENT_VIEW_START:
16289                            case TEXT_ALIGNMENT_VIEW_END:
16290                                // Resolved text alignment is the same as the parent resolved
16291                                // text alignment
16292                                mPrivateFlags2 |=
16293                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16294                                break;
16295                            default:
16296                                // Use default resolved text alignment
16297                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16298                        }
16299                    }
16300                    else {
16301                        // We cannot do the resolution if there is no parent so use the default
16302                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16303                    }
16304                    break;
16305                case TEXT_ALIGNMENT_GRAVITY:
16306                case TEXT_ALIGNMENT_TEXT_START:
16307                case TEXT_ALIGNMENT_TEXT_END:
16308                case TEXT_ALIGNMENT_CENTER:
16309                case TEXT_ALIGNMENT_VIEW_START:
16310                case TEXT_ALIGNMENT_VIEW_END:
16311                    // Resolved text alignment is the same as text alignment
16312                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16313                    break;
16314                default:
16315                    // Use default resolved text alignment
16316                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16317            }
16318        } else {
16319            // Use default resolved text alignment
16320            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16321        }
16322
16323        // Set the resolved
16324        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16325        onResolvedTextAlignmentChanged();
16326    }
16327
16328    /**
16329     * Check if text alignment resolution can be done.
16330     *
16331     * @return true if text alignment resolution can be done otherwise return false.
16332     * @hide
16333     */
16334    public boolean canResolveTextAlignment() {
16335        switch (getTextAlignment()) {
16336            case TEXT_DIRECTION_INHERIT:
16337                return (mParent != null);
16338            default:
16339                return true;
16340        }
16341    }
16342
16343    /**
16344     * Called when text alignment has been resolved. Subclasses that care about text alignment
16345     * resolution should override this method.
16346     *
16347     * The default implementation does nothing.
16348     * @hide
16349     */
16350    public void onResolvedTextAlignmentChanged() {
16351    }
16352
16353    /**
16354     * Reset resolved text alignment. Text alignment can be resolved with a call to
16355     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16356     * reset is done.
16357     * @hide
16358     */
16359    public void resetResolvedTextAlignment() {
16360        // Reset any previous text alignment resolution
16361        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16362        onResolvedTextAlignmentReset();
16363    }
16364
16365    /**
16366     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16367     * override this method and do a reset of the text alignment of their children. The default
16368     * implementation does nothing.
16369     * @hide
16370     */
16371    public void onResolvedTextAlignmentReset() {
16372    }
16373
16374    //
16375    // Properties
16376    //
16377    /**
16378     * A Property wrapper around the <code>alpha</code> functionality handled by the
16379     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16380     */
16381    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16382        @Override
16383        public void setValue(View object, float value) {
16384            object.setAlpha(value);
16385        }
16386
16387        @Override
16388        public Float get(View object) {
16389            return object.getAlpha();
16390        }
16391    };
16392
16393    /**
16394     * A Property wrapper around the <code>translationX</code> functionality handled by the
16395     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16396     */
16397    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16398        @Override
16399        public void setValue(View object, float value) {
16400            object.setTranslationX(value);
16401        }
16402
16403                @Override
16404        public Float get(View object) {
16405            return object.getTranslationX();
16406        }
16407    };
16408
16409    /**
16410     * A Property wrapper around the <code>translationY</code> functionality handled by the
16411     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16412     */
16413    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16414        @Override
16415        public void setValue(View object, float value) {
16416            object.setTranslationY(value);
16417        }
16418
16419        @Override
16420        public Float get(View object) {
16421            return object.getTranslationY();
16422        }
16423    };
16424
16425    /**
16426     * A Property wrapper around the <code>x</code> functionality handled by the
16427     * {@link View#setX(float)} and {@link View#getX()} methods.
16428     */
16429    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16430        @Override
16431        public void setValue(View object, float value) {
16432            object.setX(value);
16433        }
16434
16435        @Override
16436        public Float get(View object) {
16437            return object.getX();
16438        }
16439    };
16440
16441    /**
16442     * A Property wrapper around the <code>y</code> functionality handled by the
16443     * {@link View#setY(float)} and {@link View#getY()} methods.
16444     */
16445    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16446        @Override
16447        public void setValue(View object, float value) {
16448            object.setY(value);
16449        }
16450
16451        @Override
16452        public Float get(View object) {
16453            return object.getY();
16454        }
16455    };
16456
16457    /**
16458     * A Property wrapper around the <code>rotation</code> functionality handled by the
16459     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16460     */
16461    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16462        @Override
16463        public void setValue(View object, float value) {
16464            object.setRotation(value);
16465        }
16466
16467        @Override
16468        public Float get(View object) {
16469            return object.getRotation();
16470        }
16471    };
16472
16473    /**
16474     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16475     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16476     */
16477    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16478        @Override
16479        public void setValue(View object, float value) {
16480            object.setRotationX(value);
16481        }
16482
16483        @Override
16484        public Float get(View object) {
16485            return object.getRotationX();
16486        }
16487    };
16488
16489    /**
16490     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16491     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16492     */
16493    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16494        @Override
16495        public void setValue(View object, float value) {
16496            object.setRotationY(value);
16497        }
16498
16499        @Override
16500        public Float get(View object) {
16501            return object.getRotationY();
16502        }
16503    };
16504
16505    /**
16506     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16507     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16508     */
16509    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16510        @Override
16511        public void setValue(View object, float value) {
16512            object.setScaleX(value);
16513        }
16514
16515        @Override
16516        public Float get(View object) {
16517            return object.getScaleX();
16518        }
16519    };
16520
16521    /**
16522     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16523     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16524     */
16525    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16526        @Override
16527        public void setValue(View object, float value) {
16528            object.setScaleY(value);
16529        }
16530
16531        @Override
16532        public Float get(View object) {
16533            return object.getScaleY();
16534        }
16535    };
16536
16537    /**
16538     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16539     * Each MeasureSpec represents a requirement for either the width or the height.
16540     * A MeasureSpec is comprised of a size and a mode. There are three possible
16541     * modes:
16542     * <dl>
16543     * <dt>UNSPECIFIED</dt>
16544     * <dd>
16545     * The parent has not imposed any constraint on the child. It can be whatever size
16546     * it wants.
16547     * </dd>
16548     *
16549     * <dt>EXACTLY</dt>
16550     * <dd>
16551     * The parent has determined an exact size for the child. The child is going to be
16552     * given those bounds regardless of how big it wants to be.
16553     * </dd>
16554     *
16555     * <dt>AT_MOST</dt>
16556     * <dd>
16557     * The child can be as large as it wants up to the specified size.
16558     * </dd>
16559     * </dl>
16560     *
16561     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16562     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16563     */
16564    public static class MeasureSpec {
16565        private static final int MODE_SHIFT = 30;
16566        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16567
16568        /**
16569         * Measure specification mode: The parent has not imposed any constraint
16570         * on the child. It can be whatever size it wants.
16571         */
16572        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16573
16574        /**
16575         * Measure specification mode: The parent has determined an exact size
16576         * for the child. The child is going to be given those bounds regardless
16577         * of how big it wants to be.
16578         */
16579        public static final int EXACTLY     = 1 << MODE_SHIFT;
16580
16581        /**
16582         * Measure specification mode: The child can be as large as it wants up
16583         * to the specified size.
16584         */
16585        public static final int AT_MOST     = 2 << MODE_SHIFT;
16586
16587        /**
16588         * Creates a measure specification based on the supplied size and mode.
16589         *
16590         * The mode must always be one of the following:
16591         * <ul>
16592         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16593         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16594         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16595         * </ul>
16596         *
16597         * @param size the size of the measure specification
16598         * @param mode the mode of the measure specification
16599         * @return the measure specification based on size and mode
16600         */
16601        public static int makeMeasureSpec(int size, int mode) {
16602            return size + mode;
16603        }
16604
16605        /**
16606         * Extracts the mode from the supplied measure specification.
16607         *
16608         * @param measureSpec the measure specification to extract the mode from
16609         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16610         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16611         *         {@link android.view.View.MeasureSpec#EXACTLY}
16612         */
16613        public static int getMode(int measureSpec) {
16614            return (measureSpec & MODE_MASK);
16615        }
16616
16617        /**
16618         * Extracts the size from the supplied measure specification.
16619         *
16620         * @param measureSpec the measure specification to extract the size from
16621         * @return the size in pixels defined in the supplied measure specification
16622         */
16623        public static int getSize(int measureSpec) {
16624            return (measureSpec & ~MODE_MASK);
16625        }
16626
16627        /**
16628         * Returns a String representation of the specified measure
16629         * specification.
16630         *
16631         * @param measureSpec the measure specification to convert to a String
16632         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16633         */
16634        public static String toString(int measureSpec) {
16635            int mode = getMode(measureSpec);
16636            int size = getSize(measureSpec);
16637
16638            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16639
16640            if (mode == UNSPECIFIED)
16641                sb.append("UNSPECIFIED ");
16642            else if (mode == EXACTLY)
16643                sb.append("EXACTLY ");
16644            else if (mode == AT_MOST)
16645                sb.append("AT_MOST ");
16646            else
16647                sb.append(mode).append(" ");
16648
16649            sb.append(size);
16650            return sb.toString();
16651        }
16652    }
16653
16654    class CheckForLongPress implements Runnable {
16655
16656        private int mOriginalWindowAttachCount;
16657
16658        public void run() {
16659            if (isPressed() && (mParent != null)
16660                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16661                if (performLongClick()) {
16662                    mHasPerformedLongPress = true;
16663                }
16664            }
16665        }
16666
16667        public void rememberWindowAttachCount() {
16668            mOriginalWindowAttachCount = mWindowAttachCount;
16669        }
16670    }
16671
16672    private final class CheckForTap implements Runnable {
16673        public void run() {
16674            mPrivateFlags &= ~PREPRESSED;
16675            setPressed(true);
16676            checkForLongClick(ViewConfiguration.getTapTimeout());
16677        }
16678    }
16679
16680    private final class PerformClick implements Runnable {
16681        public void run() {
16682            performClick();
16683        }
16684    }
16685
16686    /** @hide */
16687    public void hackTurnOffWindowResizeAnim(boolean off) {
16688        mAttachInfo.mTurnOffWindowResizeAnim = off;
16689    }
16690
16691    /**
16692     * This method returns a ViewPropertyAnimator object, which can be used to animate
16693     * specific properties on this View.
16694     *
16695     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16696     */
16697    public ViewPropertyAnimator animate() {
16698        if (mAnimator == null) {
16699            mAnimator = new ViewPropertyAnimator(this);
16700        }
16701        return mAnimator;
16702    }
16703
16704    /**
16705     * Interface definition for a callback to be invoked when a key event is
16706     * dispatched to this view. The callback will be invoked before the key
16707     * event is given to the view.
16708     */
16709    public interface OnKeyListener {
16710        /**
16711         * Called when a key is dispatched to a view. This allows listeners to
16712         * get a chance to respond before the target view.
16713         *
16714         * @param v The view the key has been dispatched to.
16715         * @param keyCode The code for the physical key that was pressed
16716         * @param event The KeyEvent object containing full information about
16717         *        the event.
16718         * @return True if the listener has consumed the event, false otherwise.
16719         */
16720        boolean onKey(View v, int keyCode, KeyEvent event);
16721    }
16722
16723    /**
16724     * Interface definition for a callback to be invoked when a touch event is
16725     * dispatched to this view. The callback will be invoked before the touch
16726     * event is given to the view.
16727     */
16728    public interface OnTouchListener {
16729        /**
16730         * Called when a touch event is dispatched to a view. This allows listeners to
16731         * get a chance to respond before the target view.
16732         *
16733         * @param v The view the touch event has been dispatched to.
16734         * @param event The MotionEvent object containing full information about
16735         *        the event.
16736         * @return True if the listener has consumed the event, false otherwise.
16737         */
16738        boolean onTouch(View v, MotionEvent event);
16739    }
16740
16741    /**
16742     * Interface definition for a callback to be invoked when a hover event is
16743     * dispatched to this view. The callback will be invoked before the hover
16744     * event is given to the view.
16745     */
16746    public interface OnHoverListener {
16747        /**
16748         * Called when a hover event is dispatched to a view. This allows listeners to
16749         * get a chance to respond before the target view.
16750         *
16751         * @param v The view the hover event has been dispatched to.
16752         * @param event The MotionEvent object containing full information about
16753         *        the event.
16754         * @return True if the listener has consumed the event, false otherwise.
16755         */
16756        boolean onHover(View v, MotionEvent event);
16757    }
16758
16759    /**
16760     * Interface definition for a callback to be invoked when a generic motion event is
16761     * dispatched to this view. The callback will be invoked before the generic motion
16762     * event is given to the view.
16763     */
16764    public interface OnGenericMotionListener {
16765        /**
16766         * Called when a generic motion event is dispatched to a view. This allows listeners to
16767         * get a chance to respond before the target view.
16768         *
16769         * @param v The view the generic motion event has been dispatched to.
16770         * @param event The MotionEvent object containing full information about
16771         *        the event.
16772         * @return True if the listener has consumed the event, false otherwise.
16773         */
16774        boolean onGenericMotion(View v, MotionEvent event);
16775    }
16776
16777    /**
16778     * Interface definition for a callback to be invoked when a view has been clicked and held.
16779     */
16780    public interface OnLongClickListener {
16781        /**
16782         * Called when a view has been clicked and held.
16783         *
16784         * @param v The view that was clicked and held.
16785         *
16786         * @return true if the callback consumed the long click, false otherwise.
16787         */
16788        boolean onLongClick(View v);
16789    }
16790
16791    /**
16792     * Interface definition for a callback to be invoked when a drag is being dispatched
16793     * to this view.  The callback will be invoked before the hosting view's own
16794     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16795     * onDrag(event) behavior, it should return 'false' from this callback.
16796     *
16797     * <div class="special reference">
16798     * <h3>Developer Guides</h3>
16799     * <p>For a guide to implementing drag and drop features, read the
16800     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16801     * </div>
16802     */
16803    public interface OnDragListener {
16804        /**
16805         * Called when a drag event is dispatched to a view. This allows listeners
16806         * to get a chance to override base View behavior.
16807         *
16808         * @param v The View that received the drag event.
16809         * @param event The {@link android.view.DragEvent} object for the drag event.
16810         * @return {@code true} if the drag event was handled successfully, or {@code false}
16811         * if the drag event was not handled. Note that {@code false} will trigger the View
16812         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16813         */
16814        boolean onDrag(View v, DragEvent event);
16815    }
16816
16817    /**
16818     * Interface definition for a callback to be invoked when the focus state of
16819     * a view changed.
16820     */
16821    public interface OnFocusChangeListener {
16822        /**
16823         * Called when the focus state of a view has changed.
16824         *
16825         * @param v The view whose state has changed.
16826         * @param hasFocus The new focus state of v.
16827         */
16828        void onFocusChange(View v, boolean hasFocus);
16829    }
16830
16831    /**
16832     * Interface definition for a callback to be invoked when a view is clicked.
16833     */
16834    public interface OnClickListener {
16835        /**
16836         * Called when a view has been clicked.
16837         *
16838         * @param v The view that was clicked.
16839         */
16840        void onClick(View v);
16841    }
16842
16843    /**
16844     * Interface definition for a callback to be invoked when the context menu
16845     * for this view is being built.
16846     */
16847    public interface OnCreateContextMenuListener {
16848        /**
16849         * Called when the context menu for this view is being built. It is not
16850         * safe to hold onto the menu after this method returns.
16851         *
16852         * @param menu The context menu that is being built
16853         * @param v The view for which the context menu is being built
16854         * @param menuInfo Extra information about the item for which the
16855         *            context menu should be shown. This information will vary
16856         *            depending on the class of v.
16857         */
16858        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16859    }
16860
16861    /**
16862     * Interface definition for a callback to be invoked when the status bar changes
16863     * visibility.  This reports <strong>global</strong> changes to the system UI
16864     * state, not just what the application is requesting.
16865     *
16866     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16867     */
16868    public interface OnSystemUiVisibilityChangeListener {
16869        /**
16870         * Called when the status bar changes visibility because of a call to
16871         * {@link View#setSystemUiVisibility(int)}.
16872         *
16873         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16874         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16875         * <strong>global</strong> state of the UI visibility flags, not what your
16876         * app is currently applying.
16877         */
16878        public void onSystemUiVisibilityChange(int visibility);
16879    }
16880
16881    /**
16882     * Interface definition for a callback to be invoked when this view is attached
16883     * or detached from its window.
16884     */
16885    public interface OnAttachStateChangeListener {
16886        /**
16887         * Called when the view is attached to a window.
16888         * @param v The view that was attached
16889         */
16890        public void onViewAttachedToWindow(View v);
16891        /**
16892         * Called when the view is detached from a window.
16893         * @param v The view that was detached
16894         */
16895        public void onViewDetachedFromWindow(View v);
16896    }
16897
16898    private final class UnsetPressedState implements Runnable {
16899        public void run() {
16900            setPressed(false);
16901        }
16902    }
16903
16904    /**
16905     * Base class for derived classes that want to save and restore their own
16906     * state in {@link android.view.View#onSaveInstanceState()}.
16907     */
16908    public static class BaseSavedState extends AbsSavedState {
16909        /**
16910         * Constructor used when reading from a parcel. Reads the state of the superclass.
16911         *
16912         * @param source
16913         */
16914        public BaseSavedState(Parcel source) {
16915            super(source);
16916        }
16917
16918        /**
16919         * Constructor called by derived classes when creating their SavedState objects
16920         *
16921         * @param superState The state of the superclass of this view
16922         */
16923        public BaseSavedState(Parcelable superState) {
16924            super(superState);
16925        }
16926
16927        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16928                new Parcelable.Creator<BaseSavedState>() {
16929            public BaseSavedState createFromParcel(Parcel in) {
16930                return new BaseSavedState(in);
16931            }
16932
16933            public BaseSavedState[] newArray(int size) {
16934                return new BaseSavedState[size];
16935            }
16936        };
16937    }
16938
16939    /**
16940     * A set of information given to a view when it is attached to its parent
16941     * window.
16942     */
16943    static class AttachInfo {
16944        interface Callbacks {
16945            void playSoundEffect(int effectId);
16946            boolean performHapticFeedback(int effectId, boolean always);
16947        }
16948
16949        /**
16950         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16951         * to a Handler. This class contains the target (View) to invalidate and
16952         * the coordinates of the dirty rectangle.
16953         *
16954         * For performance purposes, this class also implements a pool of up to
16955         * POOL_LIMIT objects that get reused. This reduces memory allocations
16956         * whenever possible.
16957         */
16958        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16959            private static final int POOL_LIMIT = 10;
16960            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16961                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16962                        public InvalidateInfo newInstance() {
16963                            return new InvalidateInfo();
16964                        }
16965
16966                        public void onAcquired(InvalidateInfo element) {
16967                        }
16968
16969                        public void onReleased(InvalidateInfo element) {
16970                            element.target = null;
16971                        }
16972                    }, POOL_LIMIT)
16973            );
16974
16975            private InvalidateInfo mNext;
16976            private boolean mIsPooled;
16977
16978            View target;
16979
16980            int left;
16981            int top;
16982            int right;
16983            int bottom;
16984
16985            public void setNextPoolable(InvalidateInfo element) {
16986                mNext = element;
16987            }
16988
16989            public InvalidateInfo getNextPoolable() {
16990                return mNext;
16991            }
16992
16993            static InvalidateInfo acquire() {
16994                return sPool.acquire();
16995            }
16996
16997            void release() {
16998                sPool.release(this);
16999            }
17000
17001            public boolean isPooled() {
17002                return mIsPooled;
17003            }
17004
17005            public void setPooled(boolean isPooled) {
17006                mIsPooled = isPooled;
17007            }
17008        }
17009
17010        final IWindowSession mSession;
17011
17012        final IWindow mWindow;
17013
17014        final IBinder mWindowToken;
17015
17016        final Callbacks mRootCallbacks;
17017
17018        HardwareCanvas mHardwareCanvas;
17019
17020        /**
17021         * The top view of the hierarchy.
17022         */
17023        View mRootView;
17024
17025        IBinder mPanelParentWindowToken;
17026        Surface mSurface;
17027
17028        boolean mHardwareAccelerated;
17029        boolean mHardwareAccelerationRequested;
17030        HardwareRenderer mHardwareRenderer;
17031
17032        boolean mScreenOn;
17033
17034        /**
17035         * Scale factor used by the compatibility mode
17036         */
17037        float mApplicationScale;
17038
17039        /**
17040         * Indicates whether the application is in compatibility mode
17041         */
17042        boolean mScalingRequired;
17043
17044        /**
17045         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17046         */
17047        boolean mTurnOffWindowResizeAnim;
17048
17049        /**
17050         * Left position of this view's window
17051         */
17052        int mWindowLeft;
17053
17054        /**
17055         * Top position of this view's window
17056         */
17057        int mWindowTop;
17058
17059        /**
17060         * Indicates whether views need to use 32-bit drawing caches
17061         */
17062        boolean mUse32BitDrawingCache;
17063
17064        /**
17065         * Describes the parts of the window that are currently completely
17066         * obscured by system UI elements.
17067         */
17068        final Rect mSystemInsets = new Rect();
17069
17070        /**
17071         * For windows that are full-screen but using insets to layout inside
17072         * of the screen decorations, these are the current insets for the
17073         * content of the window.
17074         */
17075        final Rect mContentInsets = new Rect();
17076
17077        /**
17078         * For windows that are full-screen but using insets to layout inside
17079         * of the screen decorations, these are the current insets for the
17080         * actual visible parts of the window.
17081         */
17082        final Rect mVisibleInsets = new Rect();
17083
17084        /**
17085         * The internal insets given by this window.  This value is
17086         * supplied by the client (through
17087         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17088         * be given to the window manager when changed to be used in laying
17089         * out windows behind it.
17090         */
17091        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17092                = new ViewTreeObserver.InternalInsetsInfo();
17093
17094        /**
17095         * All views in the window's hierarchy that serve as scroll containers,
17096         * used to determine if the window can be resized or must be panned
17097         * to adjust for a soft input area.
17098         */
17099        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17100
17101        final KeyEvent.DispatcherState mKeyDispatchState
17102                = new KeyEvent.DispatcherState();
17103
17104        /**
17105         * Indicates whether the view's window currently has the focus.
17106         */
17107        boolean mHasWindowFocus;
17108
17109        /**
17110         * The current visibility of the window.
17111         */
17112        int mWindowVisibility;
17113
17114        /**
17115         * Indicates the time at which drawing started to occur.
17116         */
17117        long mDrawingTime;
17118
17119        /**
17120         * Indicates whether or not ignoring the DIRTY_MASK flags.
17121         */
17122        boolean mIgnoreDirtyState;
17123
17124        /**
17125         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17126         * to avoid clearing that flag prematurely.
17127         */
17128        boolean mSetIgnoreDirtyState = false;
17129
17130        /**
17131         * Indicates whether the view's window is currently in touch mode.
17132         */
17133        boolean mInTouchMode;
17134
17135        /**
17136         * Indicates that ViewAncestor should trigger a global layout change
17137         * the next time it performs a traversal
17138         */
17139        boolean mRecomputeGlobalAttributes;
17140
17141        /**
17142         * Always report new attributes at next traversal.
17143         */
17144        boolean mForceReportNewAttributes;
17145
17146        /**
17147         * Set during a traveral if any views want to keep the screen on.
17148         */
17149        boolean mKeepScreenOn;
17150
17151        /**
17152         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17153         */
17154        int mSystemUiVisibility;
17155
17156        /**
17157         * Hack to force certain system UI visibility flags to be cleared.
17158         */
17159        int mDisabledSystemUiVisibility;
17160
17161        /**
17162         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17163         * attached.
17164         */
17165        boolean mHasSystemUiListeners;
17166
17167        /**
17168         * Set if the visibility of any views has changed.
17169         */
17170        boolean mViewVisibilityChanged;
17171
17172        /**
17173         * Set to true if a view has been scrolled.
17174         */
17175        boolean mViewScrollChanged;
17176
17177        /**
17178         * Global to the view hierarchy used as a temporary for dealing with
17179         * x/y points in the transparent region computations.
17180         */
17181        final int[] mTransparentLocation = new int[2];
17182
17183        /**
17184         * Global to the view hierarchy used as a temporary for dealing with
17185         * x/y points in the ViewGroup.invalidateChild implementation.
17186         */
17187        final int[] mInvalidateChildLocation = new int[2];
17188
17189
17190        /**
17191         * Global to the view hierarchy used as a temporary for dealing with
17192         * x/y location when view is transformed.
17193         */
17194        final float[] mTmpTransformLocation = new float[2];
17195
17196        /**
17197         * The view tree observer used to dispatch global events like
17198         * layout, pre-draw, touch mode change, etc.
17199         */
17200        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17201
17202        /**
17203         * A Canvas used by the view hierarchy to perform bitmap caching.
17204         */
17205        Canvas mCanvas;
17206
17207        /**
17208         * The view root impl.
17209         */
17210        final ViewRootImpl mViewRootImpl;
17211
17212        /**
17213         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17214         * handler can be used to pump events in the UI events queue.
17215         */
17216        final Handler mHandler;
17217
17218        /**
17219         * Temporary for use in computing invalidate rectangles while
17220         * calling up the hierarchy.
17221         */
17222        final Rect mTmpInvalRect = new Rect();
17223
17224        /**
17225         * Temporary for use in computing hit areas with transformed views
17226         */
17227        final RectF mTmpTransformRect = new RectF();
17228
17229        /**
17230         * Temporary list for use in collecting focusable descendents of a view.
17231         */
17232        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17233
17234        /**
17235         * The id of the window for accessibility purposes.
17236         */
17237        int mAccessibilityWindowId = View.NO_ID;
17238
17239        /**
17240         * Whether to ingore not exposed for accessibility Views when
17241         * reporting the view tree to accessibility services.
17242         */
17243        boolean mIncludeNotImportantViews;
17244
17245        /**
17246         * The drawable for highlighting accessibility focus.
17247         */
17248        Drawable mAccessibilityFocusDrawable;
17249
17250        /**
17251         * Show where the margins, bounds and layout bounds are for each view.
17252         */
17253        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17254
17255        /**
17256         * Point used to compute visible regions.
17257         */
17258        final Point mPoint = new Point();
17259
17260        /**
17261         * Creates a new set of attachment information with the specified
17262         * events handler and thread.
17263         *
17264         * @param handler the events handler the view must use
17265         */
17266        AttachInfo(IWindowSession session, IWindow window,
17267                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17268            mSession = session;
17269            mWindow = window;
17270            mWindowToken = window.asBinder();
17271            mViewRootImpl = viewRootImpl;
17272            mHandler = handler;
17273            mRootCallbacks = effectPlayer;
17274        }
17275    }
17276
17277    /**
17278     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17279     * is supported. This avoids keeping too many unused fields in most
17280     * instances of View.</p>
17281     */
17282    private static class ScrollabilityCache implements Runnable {
17283
17284        /**
17285         * Scrollbars are not visible
17286         */
17287        public static final int OFF = 0;
17288
17289        /**
17290         * Scrollbars are visible
17291         */
17292        public static final int ON = 1;
17293
17294        /**
17295         * Scrollbars are fading away
17296         */
17297        public static final int FADING = 2;
17298
17299        public boolean fadeScrollBars;
17300
17301        public int fadingEdgeLength;
17302        public int scrollBarDefaultDelayBeforeFade;
17303        public int scrollBarFadeDuration;
17304
17305        public int scrollBarSize;
17306        public ScrollBarDrawable scrollBar;
17307        public float[] interpolatorValues;
17308        public View host;
17309
17310        public final Paint paint;
17311        public final Matrix matrix;
17312        public Shader shader;
17313
17314        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17315
17316        private static final float[] OPAQUE = { 255 };
17317        private static final float[] TRANSPARENT = { 0.0f };
17318
17319        /**
17320         * When fading should start. This time moves into the future every time
17321         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17322         */
17323        public long fadeStartTime;
17324
17325
17326        /**
17327         * The current state of the scrollbars: ON, OFF, or FADING
17328         */
17329        public int state = OFF;
17330
17331        private int mLastColor;
17332
17333        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17334            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17335            scrollBarSize = configuration.getScaledScrollBarSize();
17336            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17337            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17338
17339            paint = new Paint();
17340            matrix = new Matrix();
17341            // use use a height of 1, and then wack the matrix each time we
17342            // actually use it.
17343            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17344
17345            paint.setShader(shader);
17346            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17347            this.host = host;
17348        }
17349
17350        public void setFadeColor(int color) {
17351            if (color != 0 && color != mLastColor) {
17352                mLastColor = color;
17353                color |= 0xFF000000;
17354
17355                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17356                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17357
17358                paint.setShader(shader);
17359                // Restore the default transfer mode (src_over)
17360                paint.setXfermode(null);
17361            }
17362        }
17363
17364        public void run() {
17365            long now = AnimationUtils.currentAnimationTimeMillis();
17366            if (now >= fadeStartTime) {
17367
17368                // the animation fades the scrollbars out by changing
17369                // the opacity (alpha) from fully opaque to fully
17370                // transparent
17371                int nextFrame = (int) now;
17372                int framesCount = 0;
17373
17374                Interpolator interpolator = scrollBarInterpolator;
17375
17376                // Start opaque
17377                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17378
17379                // End transparent
17380                nextFrame += scrollBarFadeDuration;
17381                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17382
17383                state = FADING;
17384
17385                // Kick off the fade animation
17386                host.invalidate(true);
17387            }
17388        }
17389    }
17390
17391    /**
17392     * Resuable callback for sending
17393     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17394     */
17395    private class SendViewScrolledAccessibilityEvent implements Runnable {
17396        public volatile boolean mIsPending;
17397
17398        public void run() {
17399            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17400            mIsPending = false;
17401        }
17402    }
17403
17404    /**
17405     * <p>
17406     * This class represents a delegate that can be registered in a {@link View}
17407     * to enhance accessibility support via composition rather via inheritance.
17408     * It is specifically targeted to widget developers that extend basic View
17409     * classes i.e. classes in package android.view, that would like their
17410     * applications to be backwards compatible.
17411     * </p>
17412     * <div class="special reference">
17413     * <h3>Developer Guides</h3>
17414     * <p>For more information about making applications accessible, read the
17415     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17416     * developer guide.</p>
17417     * </div>
17418     * <p>
17419     * A scenario in which a developer would like to use an accessibility delegate
17420     * is overriding a method introduced in a later API version then the minimal API
17421     * version supported by the application. For example, the method
17422     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17423     * in API version 4 when the accessibility APIs were first introduced. If a
17424     * developer would like his application to run on API version 4 devices (assuming
17425     * all other APIs used by the application are version 4 or lower) and take advantage
17426     * of this method, instead of overriding the method which would break the application's
17427     * backwards compatibility, he can override the corresponding method in this
17428     * delegate and register the delegate in the target View if the API version of
17429     * the system is high enough i.e. the API version is same or higher to the API
17430     * version that introduced
17431     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17432     * </p>
17433     * <p>
17434     * Here is an example implementation:
17435     * </p>
17436     * <code><pre><p>
17437     * if (Build.VERSION.SDK_INT >= 14) {
17438     *     // If the API version is equal of higher than the version in
17439     *     // which onInitializeAccessibilityNodeInfo was introduced we
17440     *     // register a delegate with a customized implementation.
17441     *     View view = findViewById(R.id.view_id);
17442     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17443     *         public void onInitializeAccessibilityNodeInfo(View host,
17444     *                 AccessibilityNodeInfo info) {
17445     *             // Let the default implementation populate the info.
17446     *             super.onInitializeAccessibilityNodeInfo(host, info);
17447     *             // Set some other information.
17448     *             info.setEnabled(host.isEnabled());
17449     *         }
17450     *     });
17451     * }
17452     * </code></pre></p>
17453     * <p>
17454     * This delegate contains methods that correspond to the accessibility methods
17455     * in View. If a delegate has been specified the implementation in View hands
17456     * off handling to the corresponding method in this delegate. The default
17457     * implementation the delegate methods behaves exactly as the corresponding
17458     * method in View for the case of no accessibility delegate been set. Hence,
17459     * to customize the behavior of a View method, clients can override only the
17460     * corresponding delegate method without altering the behavior of the rest
17461     * accessibility related methods of the host view.
17462     * </p>
17463     */
17464    public static class AccessibilityDelegate {
17465
17466        /**
17467         * Sends an accessibility event of the given type. If accessibility is not
17468         * enabled this method has no effect.
17469         * <p>
17470         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17471         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17472         * been set.
17473         * </p>
17474         *
17475         * @param host The View hosting the delegate.
17476         * @param eventType The type of the event to send.
17477         *
17478         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17479         */
17480        public void sendAccessibilityEvent(View host, int eventType) {
17481            host.sendAccessibilityEventInternal(eventType);
17482        }
17483
17484        /**
17485         * Performs the specified accessibility action on the view. For
17486         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17487         * <p>
17488         * The default implementation behaves as
17489         * {@link View#performAccessibilityAction(int, Bundle)
17490         *  View#performAccessibilityAction(int, Bundle)} for the case of
17491         *  no accessibility delegate been set.
17492         * </p>
17493         *
17494         * @param action The action to perform.
17495         * @return Whether the action was performed.
17496         *
17497         * @see View#performAccessibilityAction(int, Bundle)
17498         *      View#performAccessibilityAction(int, Bundle)
17499         */
17500        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17501            return host.performAccessibilityActionInternal(action, args);
17502        }
17503
17504        /**
17505         * Sends an accessibility event. This method behaves exactly as
17506         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17507         * empty {@link AccessibilityEvent} and does not perform a check whether
17508         * accessibility is enabled.
17509         * <p>
17510         * The default implementation behaves as
17511         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17512         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17513         * the case of no accessibility delegate been set.
17514         * </p>
17515         *
17516         * @param host The View hosting the delegate.
17517         * @param event The event to send.
17518         *
17519         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17520         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17521         */
17522        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17523            host.sendAccessibilityEventUncheckedInternal(event);
17524        }
17525
17526        /**
17527         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17528         * to its children for adding their text content to the event.
17529         * <p>
17530         * The default implementation behaves as
17531         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17532         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17533         * the case of no accessibility delegate been set.
17534         * </p>
17535         *
17536         * @param host The View hosting the delegate.
17537         * @param event The event.
17538         * @return True if the event population was completed.
17539         *
17540         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17541         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17542         */
17543        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17544            return host.dispatchPopulateAccessibilityEventInternal(event);
17545        }
17546
17547        /**
17548         * Gives a chance to the host View to populate the accessibility event with its
17549         * text content.
17550         * <p>
17551         * The default implementation behaves as
17552         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17553         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17554         * the case of no accessibility delegate been set.
17555         * </p>
17556         *
17557         * @param host The View hosting the delegate.
17558         * @param event The accessibility event which to populate.
17559         *
17560         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17561         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17562         */
17563        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17564            host.onPopulateAccessibilityEventInternal(event);
17565        }
17566
17567        /**
17568         * Initializes an {@link AccessibilityEvent} with information about the
17569         * the host View which is the event source.
17570         * <p>
17571         * The default implementation behaves as
17572         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17573         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17574         * the case of no accessibility delegate been set.
17575         * </p>
17576         *
17577         * @param host The View hosting the delegate.
17578         * @param event The event to initialize.
17579         *
17580         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17581         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17582         */
17583        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17584            host.onInitializeAccessibilityEventInternal(event);
17585        }
17586
17587        /**
17588         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17589         * <p>
17590         * The default implementation behaves as
17591         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17592         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17593         * the case of no accessibility delegate been set.
17594         * </p>
17595         *
17596         * @param host The View hosting the delegate.
17597         * @param info The instance to initialize.
17598         *
17599         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17600         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17601         */
17602        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17603            host.onInitializeAccessibilityNodeInfoInternal(info);
17604        }
17605
17606        /**
17607         * Called when a child of the host View has requested sending an
17608         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17609         * to augment the event.
17610         * <p>
17611         * The default implementation behaves as
17612         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17613         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17614         * the case of no accessibility delegate been set.
17615         * </p>
17616         *
17617         * @param host The View hosting the delegate.
17618         * @param child The child which requests sending the event.
17619         * @param event The event to be sent.
17620         * @return True if the event should be sent
17621         *
17622         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17623         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17624         */
17625        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17626                AccessibilityEvent event) {
17627            return host.onRequestSendAccessibilityEventInternal(child, event);
17628        }
17629
17630        /**
17631         * Gets the provider for managing a virtual view hierarchy rooted at this View
17632         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17633         * that explore the window content.
17634         * <p>
17635         * The default implementation behaves as
17636         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17637         * the case of no accessibility delegate been set.
17638         * </p>
17639         *
17640         * @return The provider.
17641         *
17642         * @see AccessibilityNodeProvider
17643         */
17644        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17645            return null;
17646        }
17647    }
17648}
17649