View.java revision 1313b08011cfd4c89ab1101c0672f8dc8de2de23
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.util.AttributeSet;
51import android.util.FloatProperty;
52import android.util.LocaleUtil;
53import android.util.Log;
54import android.util.Pool;
55import android.util.Poolable;
56import android.util.PoolableManager;
57import android.util.Pools;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.widget.ScrollBarDrawable;
78
79import static android.os.Build.VERSION_CODES.*;
80import static java.lang.Math.max;
81
82import com.android.internal.R;
83import com.android.internal.util.Predicate;
84import com.android.internal.view.menu.MenuBuilder;
85
86import java.lang.ref.WeakReference;
87import java.lang.reflect.InvocationTargetException;
88import java.lang.reflect.Method;
89import java.util.ArrayList;
90import java.util.Arrays;
91import java.util.Locale;
92import java.util.concurrent.CopyOnWriteArrayList;
93
94/**
95 * <p>
96 * This class represents the basic building block for user interface components. A View
97 * occupies a rectangular area on the screen and is responsible for drawing and
98 * event handling. View is the base class for <em>widgets</em>, which are
99 * used to create interactive UI components (buttons, text fields, etc.). The
100 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
101 * are invisible containers that hold other Views (or other ViewGroups) and define
102 * their layout properties.
103 * </p>
104 *
105 * <div class="special reference">
106 * <h3>Developer Guides</h3>
107 * <p>For information about using this class to develop your application's user interface,
108 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
109 * </div>
110 *
111 * <a name="Using"></a>
112 * <h3>Using Views</h3>
113 * <p>
114 * All of the views in a window are arranged in a single tree. You can add views
115 * either from code or by specifying a tree of views in one or more XML layout
116 * files. There are many specialized subclasses of views that act as controls or
117 * are capable of displaying text, images, or other content.
118 * </p>
119 * <p>
120 * Once you have created a tree of views, there are typically a few types of
121 * common operations you may wish to perform:
122 * <ul>
123 * <li><strong>Set properties:</strong> for example setting the text of a
124 * {@link android.widget.TextView}. The available properties and the methods
125 * that set them will vary among the different subclasses of views. Note that
126 * properties that are known at build time can be set in the XML layout
127 * files.</li>
128 * <li><strong>Set focus:</strong> The framework will handled moving focus in
129 * response to user input. To force focus to a specific view, call
130 * {@link #requestFocus}.</li>
131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
132 * that will be notified when something interesting happens to the view. For
133 * example, all views will let you set a listener to be notified when the view
134 * gains or loses focus. You can register such a listener using
135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
136 * Other view subclasses offer more specialized listeners. For example, a Button
137 * exposes a listener to notify clients when the button is clicked.</li>
138 * <li><strong>Set visibility:</strong> You can hide or show views using
139 * {@link #setVisibility(int)}.</li>
140 * </ul>
141 * </p>
142 * <p><em>
143 * Note: The Android framework is responsible for measuring, laying out and
144 * drawing views. You should not call methods that perform these actions on
145 * views yourself unless you are actually implementing a
146 * {@link android.view.ViewGroup}.
147 * </em></p>
148 *
149 * <a name="Lifecycle"></a>
150 * <h3>Implementing a Custom View</h3>
151 *
152 * <p>
153 * To implement a custom view, you will usually begin by providing overrides for
154 * some of the standard methods that the framework calls on all views. You do
155 * not need to override all of these methods. In fact, you can start by just
156 * overriding {@link #onDraw(android.graphics.Canvas)}.
157 * <table border="2" width="85%" align="center" cellpadding="5">
158 *     <thead>
159 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
160 *     </thead>
161 *
162 *     <tbody>
163 *     <tr>
164 *         <td rowspan="2">Creation</td>
165 *         <td>Constructors</td>
166 *         <td>There is a form of the constructor that are called when the view
167 *         is created from code and a form that is called when the view is
168 *         inflated from a layout file. The second form should parse and apply
169 *         any attributes defined in the layout file.
170 *         </td>
171 *     </tr>
172 *     <tr>
173 *         <td><code>{@link #onFinishInflate()}</code></td>
174 *         <td>Called after a view and all of its children has been inflated
175 *         from XML.</td>
176 *     </tr>
177 *
178 *     <tr>
179 *         <td rowspan="3">Layout</td>
180 *         <td><code>{@link #onMeasure(int, int)}</code></td>
181 *         <td>Called to determine the size requirements for this view and all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
187 *         <td>Called when this view should assign a size and position to all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
193 *         <td>Called when the size of this view has changed.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td>Drawing</td>
199 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
200 *         <td>Called when the view should render its content.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td rowspan="4">Event processing</td>
206 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
207 *         <td>Called when a new key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a key up event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
217 *         <td>Called when a trackball motion event occurs.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
222 *         <td>Called when a touch screen motion event occurs.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="2">Focus</td>
228 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
229 *         <td>Called when the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
235 *         <td>Called when the window containing the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="3">Attaching</td>
241 *         <td><code>{@link #onAttachedToWindow()}</code></td>
242 *         <td>Called when the view is attached to a window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onDetachedFromWindow}</code></td>
248 *         <td>Called when the view is detached from its window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
254 *         <td>Called when the visibility of the window containing the view
255 *         has changed.
256 *         </td>
257 *     </tr>
258 *     </tbody>
259 *
260 * </table>
261 * </p>
262 *
263 * <a name="IDs"></a>
264 * <h3>IDs</h3>
265 * Views may have an integer id associated with them. These ids are typically
266 * assigned in the layout XML files, and are used to find specific views within
267 * the view tree. A common pattern is to:
268 * <ul>
269 * <li>Define a Button in the layout file and assign it a unique ID.
270 * <pre>
271 * &lt;Button
272 *     android:id="@+id/my_button"
273 *     android:layout_width="wrap_content"
274 *     android:layout_height="wrap_content"
275 *     android:text="@string/my_button_text"/&gt;
276 * </pre></li>
277 * <li>From the onCreate method of an Activity, find the Button
278 * <pre class="prettyprint">
279 *      Button myButton = (Button) findViewById(R.id.my_button);
280 * </pre></li>
281 * </ul>
282 * <p>
283 * View IDs need not be unique throughout the tree, but it is good practice to
284 * ensure that they are at least unique within the part of the tree you are
285 * searching.
286 * </p>
287 *
288 * <a name="Position"></a>
289 * <h3>Position</h3>
290 * <p>
291 * The geometry of a view is that of a rectangle. A view has a location,
292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
293 * two dimensions, expressed as a width and a height. The unit for location
294 * and dimensions is the pixel.
295 * </p>
296 *
297 * <p>
298 * It is possible to retrieve the location of a view by invoking the methods
299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
300 * coordinate of the rectangle representing the view. The latter returns the
301 * top, or Y, coordinate of the rectangle representing the view. These methods
302 * both return the location of the view relative to its parent. For instance,
303 * when getLeft() returns 20, that means the view is located 20 pixels to the
304 * right of the left edge of its direct parent.
305 * </p>
306 *
307 * <p>
308 * In addition, several convenience methods are offered to avoid unnecessary
309 * computations, namely {@link #getRight()} and {@link #getBottom()}.
310 * These methods return the coordinates of the right and bottom edges of the
311 * rectangle representing the view. For instance, calling {@link #getRight()}
312 * is similar to the following computation: <code>getLeft() + getWidth()</code>
313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
314 * </p>
315 *
316 * <a name="SizePaddingMargins"></a>
317 * <h3>Size, padding and margins</h3>
318 * <p>
319 * The size of a view is expressed with a width and a height. A view actually
320 * possess two pairs of width and height values.
321 * </p>
322 *
323 * <p>
324 * The first pair is known as <em>measured width</em> and
325 * <em>measured height</em>. These dimensions define how big a view wants to be
326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
328 * and {@link #getMeasuredHeight()}.
329 * </p>
330 *
331 * <p>
332 * The second pair is simply known as <em>width</em> and <em>height</em>, or
333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
334 * dimensions define the actual size of the view on screen, at drawing time and
335 * after layout. These values may, but do not have to, be different from the
336 * measured width and height. The width and height can be obtained by calling
337 * {@link #getWidth()} and {@link #getHeight()}.
338 * </p>
339 *
340 * <p>
341 * To measure its dimensions, a view takes into account its padding. The padding
342 * is expressed in pixels for the left, top, right and bottom parts of the view.
343 * Padding can be used to offset the content of the view by a specific amount of
344 * pixels. For instance, a left padding of 2 will push the view's content by
345 * 2 pixels to the right of the left edge. Padding can be set using the
346 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
347 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
348 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
349 * {@link #getPaddingEnd()}.
350 * </p>
351 *
352 * <p>
353 * Even though a view can define a padding, it does not provide any support for
354 * margins. However, view groups provide such a support. Refer to
355 * {@link android.view.ViewGroup} and
356 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
357 * </p>
358 *
359 * <a name="Layout"></a>
360 * <h3>Layout</h3>
361 * <p>
362 * Layout is a two pass process: a measure pass and a layout pass. The measuring
363 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
364 * of the view tree. Each view pushes dimension specifications down the tree
365 * during the recursion. At the end of the measure pass, every view has stored
366 * its measurements. The second pass happens in
367 * {@link #layout(int,int,int,int)} and is also top-down. During
368 * this pass each parent is responsible for positioning all of its children
369 * using the sizes computed in the measure pass.
370 * </p>
371 *
372 * <p>
373 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
374 * {@link #getMeasuredHeight()} values must be set, along with those for all of
375 * that view's descendants. A view's measured width and measured height values
376 * must respect the constraints imposed by the view's parents. This guarantees
377 * that at the end of the measure pass, all parents accept all of their
378 * children's measurements. A parent view may call measure() more than once on
379 * its children. For example, the parent may measure each child once with
380 * unspecified dimensions to find out how big they want to be, then call
381 * measure() on them again with actual numbers if the sum of all the children's
382 * unconstrained sizes is too big or too small.
383 * </p>
384 *
385 * <p>
386 * The measure pass uses two classes to communicate dimensions. The
387 * {@link MeasureSpec} class is used by views to tell their parents how they
388 * want to be measured and positioned. The base LayoutParams class just
389 * describes how big the view wants to be for both width and height. For each
390 * dimension, it can specify one of:
391 * <ul>
392 * <li> an exact number
393 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
394 * (minus padding)
395 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
396 * enclose its content (plus padding).
397 * </ul>
398 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
399 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
400 * an X and Y value.
401 * </p>
402 *
403 * <p>
404 * MeasureSpecs are used to push requirements down the tree from parent to
405 * child. A MeasureSpec can be in one of three modes:
406 * <ul>
407 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
408 * of a child view. For example, a LinearLayout may call measure() on its child
409 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
410 * tall the child view wants to be given a width of 240 pixels.
411 * <li>EXACTLY: This is used by the parent to impose an exact size on the
412 * child. The child must use this size, and guarantee that all of its
413 * descendants will fit within this size.
414 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
415 * child. The child must gurantee that it and all of its descendants will fit
416 * within this size.
417 * </ul>
418 * </p>
419 *
420 * <p>
421 * To intiate a layout, call {@link #requestLayout}. This method is typically
422 * called by a view on itself when it believes that is can no longer fit within
423 * its current bounds.
424 * </p>
425 *
426 * <a name="Drawing"></a>
427 * <h3>Drawing</h3>
428 * <p>
429 * Drawing is handled by walking the tree and rendering each view that
430 * intersects the invalid region. Because the tree is traversed in-order,
431 * this means that parents will draw before (i.e., behind) their children, with
432 * siblings drawn in the order they appear in the tree.
433 * If you set a background drawable for a View, then the View will draw it for you
434 * before calling back to its <code>onDraw()</code> method.
435 * </p>
436 *
437 * <p>
438 * Note that the framework will not draw views that are not in the invalid region.
439 * </p>
440 *
441 * <p>
442 * To force a view to draw, call {@link #invalidate()}.
443 * </p>
444 *
445 * <a name="EventHandlingThreading"></a>
446 * <h3>Event Handling and Threading</h3>
447 * <p>
448 * The basic cycle of a view is as follows:
449 * <ol>
450 * <li>An event comes in and is dispatched to the appropriate view. The view
451 * handles the event and notifies any listeners.</li>
452 * <li>If in the course of processing the event, the view's bounds may need
453 * to be changed, the view will call {@link #requestLayout()}.</li>
454 * <li>Similarly, if in the course of processing the event the view's appearance
455 * may need to be changed, the view will call {@link #invalidate()}.</li>
456 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
457 * the framework will take care of measuring, laying out, and drawing the tree
458 * as appropriate.</li>
459 * </ol>
460 * </p>
461 *
462 * <p><em>Note: The entire view tree is single threaded. You must always be on
463 * the UI thread when calling any method on any view.</em>
464 * If you are doing work on other threads and want to update the state of a view
465 * from that thread, you should use a {@link Handler}.
466 * </p>
467 *
468 * <a name="FocusHandling"></a>
469 * <h3>Focus Handling</h3>
470 * <p>
471 * The framework will handle routine focus movement in response to user input.
472 * This includes changing the focus as views are removed or hidden, or as new
473 * views become available. Views indicate their willingness to take focus
474 * through the {@link #isFocusable} method. To change whether a view can take
475 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
476 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
477 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
478 * </p>
479 * <p>
480 * Focus movement is based on an algorithm which finds the nearest neighbor in a
481 * given direction. In rare cases, the default algorithm may not match the
482 * intended behavior of the developer. In these situations, you can provide
483 * explicit overrides by using these XML attributes in the layout file:
484 * <pre>
485 * nextFocusDown
486 * nextFocusLeft
487 * nextFocusRight
488 * nextFocusUp
489 * </pre>
490 * </p>
491 *
492 *
493 * <p>
494 * To get a particular view to take focus, call {@link #requestFocus()}.
495 * </p>
496 *
497 * <a name="TouchMode"></a>
498 * <h3>Touch Mode</h3>
499 * <p>
500 * When a user is navigating a user interface via directional keys such as a D-pad, it is
501 * necessary to give focus to actionable items such as buttons so the user can see
502 * what will take input.  If the device has touch capabilities, however, and the user
503 * begins interacting with the interface by touching it, it is no longer necessary to
504 * always highlight, or give focus to, a particular view.  This motivates a mode
505 * for interaction named 'touch mode'.
506 * </p>
507 * <p>
508 * For a touch capable device, once the user touches the screen, the device
509 * will enter touch mode.  From this point onward, only views for which
510 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
511 * Other views that are touchable, like buttons, will not take focus when touched; they will
512 * only fire the on click listeners.
513 * </p>
514 * <p>
515 * Any time a user hits a directional key, such as a D-pad direction, the view device will
516 * exit touch mode, and find a view to take focus, so that the user may resume interacting
517 * with the user interface without touching the screen again.
518 * </p>
519 * <p>
520 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
521 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
522 * </p>
523 *
524 * <a name="Scrolling"></a>
525 * <h3>Scrolling</h3>
526 * <p>
527 * The framework provides basic support for views that wish to internally
528 * scroll their content. This includes keeping track of the X and Y scroll
529 * offset as well as mechanisms for drawing scrollbars. See
530 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
531 * {@link #awakenScrollBars()} for more details.
532 * </p>
533 *
534 * <a name="Tags"></a>
535 * <h3>Tags</h3>
536 * <p>
537 * Unlike IDs, tags are not used to identify views. Tags are essentially an
538 * extra piece of information that can be associated with a view. They are most
539 * often used as a convenience to store data related to views in the views
540 * themselves rather than by putting them in a separate structure.
541 * </p>
542 *
543 * <a name="Properties"></a>
544 * <h3>Properties</h3>
545 * <p>
546 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
547 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
548 * available both in the {@link Property} form as well as in similarly-named setter/getter
549 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
550 * be used to set persistent state associated with these rendering-related properties on the view.
551 * The properties and methods can also be used in conjunction with
552 * {@link android.animation.Animator Animator}-based animations, described more in the
553 * <a href="#Animation">Animation</a> section.
554 * </p>
555 *
556 * <a name="Animation"></a>
557 * <h3>Animation</h3>
558 * <p>
559 * Starting with Android 3.0, the preferred way of animating views is to use the
560 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
561 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
562 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
563 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
564 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
565 * makes animating these View properties particularly easy and efficient.
566 * </p>
567 * <p>
568 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
569 * You can attach an {@link Animation} object to a view using
570 * {@link #setAnimation(Animation)} or
571 * {@link #startAnimation(Animation)}. The animation can alter the scale,
572 * rotation, translation and alpha of a view over time. If the animation is
573 * attached to a view that has children, the animation will affect the entire
574 * subtree rooted by that node. When an animation is started, the framework will
575 * take care of redrawing the appropriate views until the animation completes.
576 * </p>
577 *
578 * <a name="Security"></a>
579 * <h3>Security</h3>
580 * <p>
581 * Sometimes it is essential that an application be able to verify that an action
582 * is being performed with the full knowledge and consent of the user, such as
583 * granting a permission request, making a purchase or clicking on an advertisement.
584 * Unfortunately, a malicious application could try to spoof the user into
585 * performing these actions, unaware, by concealing the intended purpose of the view.
586 * As a remedy, the framework offers a touch filtering mechanism that can be used to
587 * improve the security of views that provide access to sensitive functionality.
588 * </p><p>
589 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
590 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
591 * will discard touches that are received whenever the view's window is obscured by
592 * another visible window.  As a result, the view will not receive touches whenever a
593 * toast, dialog or other window appears above the view's window.
594 * </p><p>
595 * For more fine-grained control over security, consider overriding the
596 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
597 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
598 * </p>
599 *
600 * @attr ref android.R.styleable#View_alpha
601 * @attr ref android.R.styleable#View_background
602 * @attr ref android.R.styleable#View_clickable
603 * @attr ref android.R.styleable#View_contentDescription
604 * @attr ref android.R.styleable#View_drawingCacheQuality
605 * @attr ref android.R.styleable#View_duplicateParentState
606 * @attr ref android.R.styleable#View_id
607 * @attr ref android.R.styleable#View_requiresFadingEdge
608 * @attr ref android.R.styleable#View_fadeScrollbars
609 * @attr ref android.R.styleable#View_fadingEdgeLength
610 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
611 * @attr ref android.R.styleable#View_fitsSystemWindows
612 * @attr ref android.R.styleable#View_isScrollContainer
613 * @attr ref android.R.styleable#View_focusable
614 * @attr ref android.R.styleable#View_focusableInTouchMode
615 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
616 * @attr ref android.R.styleable#View_keepScreenOn
617 * @attr ref android.R.styleable#View_layerType
618 * @attr ref android.R.styleable#View_longClickable
619 * @attr ref android.R.styleable#View_minHeight
620 * @attr ref android.R.styleable#View_minWidth
621 * @attr ref android.R.styleable#View_nextFocusDown
622 * @attr ref android.R.styleable#View_nextFocusLeft
623 * @attr ref android.R.styleable#View_nextFocusRight
624 * @attr ref android.R.styleable#View_nextFocusUp
625 * @attr ref android.R.styleable#View_onClick
626 * @attr ref android.R.styleable#View_padding
627 * @attr ref android.R.styleable#View_paddingBottom
628 * @attr ref android.R.styleable#View_paddingLeft
629 * @attr ref android.R.styleable#View_paddingRight
630 * @attr ref android.R.styleable#View_paddingTop
631 * @attr ref android.R.styleable#View_paddingStart
632 * @attr ref android.R.styleable#View_paddingEnd
633 * @attr ref android.R.styleable#View_saveEnabled
634 * @attr ref android.R.styleable#View_rotation
635 * @attr ref android.R.styleable#View_rotationX
636 * @attr ref android.R.styleable#View_rotationY
637 * @attr ref android.R.styleable#View_scaleX
638 * @attr ref android.R.styleable#View_scaleY
639 * @attr ref android.R.styleable#View_scrollX
640 * @attr ref android.R.styleable#View_scrollY
641 * @attr ref android.R.styleable#View_scrollbarSize
642 * @attr ref android.R.styleable#View_scrollbarStyle
643 * @attr ref android.R.styleable#View_scrollbars
644 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
645 * @attr ref android.R.styleable#View_scrollbarFadeDuration
646 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
647 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
648 * @attr ref android.R.styleable#View_scrollbarThumbVertical
649 * @attr ref android.R.styleable#View_scrollbarTrackVertical
650 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
651 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
652 * @attr ref android.R.styleable#View_soundEffectsEnabled
653 * @attr ref android.R.styleable#View_tag
654 * @attr ref android.R.styleable#View_textAlignment
655 * @attr ref android.R.styleable#View_transformPivotX
656 * @attr ref android.R.styleable#View_transformPivotY
657 * @attr ref android.R.styleable#View_translationX
658 * @attr ref android.R.styleable#View_translationY
659 * @attr ref android.R.styleable#View_visibility
660 *
661 * @see android.view.ViewGroup
662 */
663public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
664        AccessibilityEventSource {
665    private static final boolean DBG = false;
666
667    /**
668     * The logging tag used by this class with android.util.Log.
669     */
670    protected static final String VIEW_LOG_TAG = "View";
671
672    /**
673     * When set to true, apps will draw debugging information about their layouts.
674     *
675     * @hide
676     */
677    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
678
679    /**
680     * Used to mark a View that has no ID.
681     */
682    public static final int NO_ID = -1;
683
684    /**
685     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
686     * calling setFlags.
687     */
688    private static final int NOT_FOCUSABLE = 0x00000000;
689
690    /**
691     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
692     * setFlags.
693     */
694    private static final int FOCUSABLE = 0x00000001;
695
696    /**
697     * Mask for use with setFlags indicating bits used for focus.
698     */
699    private static final int FOCUSABLE_MASK = 0x00000001;
700
701    /**
702     * This view will adjust its padding to fit sytem windows (e.g. status bar)
703     */
704    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
705
706    /**
707     * This view is visible.
708     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
709     * android:visibility}.
710     */
711    public static final int VISIBLE = 0x00000000;
712
713    /**
714     * This view is invisible, but it still takes up space for layout purposes.
715     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
716     * android:visibility}.
717     */
718    public static final int INVISIBLE = 0x00000004;
719
720    /**
721     * This view is invisible, and it doesn't take any space for layout
722     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
723     * android:visibility}.
724     */
725    public static final int GONE = 0x00000008;
726
727    /**
728     * Mask for use with setFlags indicating bits used for visibility.
729     * {@hide}
730     */
731    static final int VISIBILITY_MASK = 0x0000000C;
732
733    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
734
735    /**
736     * This view is enabled. Interpretation varies by subclass.
737     * Use with ENABLED_MASK when calling setFlags.
738     * {@hide}
739     */
740    static final int ENABLED = 0x00000000;
741
742    /**
743     * This view is disabled. Interpretation varies by subclass.
744     * Use with ENABLED_MASK when calling setFlags.
745     * {@hide}
746     */
747    static final int DISABLED = 0x00000020;
748
749   /**
750    * Mask for use with setFlags indicating bits used for indicating whether
751    * this view is enabled
752    * {@hide}
753    */
754    static final int ENABLED_MASK = 0x00000020;
755
756    /**
757     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
758     * called and further optimizations will be performed. It is okay to have
759     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
760     * {@hide}
761     */
762    static final int WILL_NOT_DRAW = 0x00000080;
763
764    /**
765     * Mask for use with setFlags indicating bits used for indicating whether
766     * this view is will draw
767     * {@hide}
768     */
769    static final int DRAW_MASK = 0x00000080;
770
771    /**
772     * <p>This view doesn't show scrollbars.</p>
773     * {@hide}
774     */
775    static final int SCROLLBARS_NONE = 0x00000000;
776
777    /**
778     * <p>This view shows horizontal scrollbars.</p>
779     * {@hide}
780     */
781    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
782
783    /**
784     * <p>This view shows vertical scrollbars.</p>
785     * {@hide}
786     */
787    static final int SCROLLBARS_VERTICAL = 0x00000200;
788
789    /**
790     * <p>Mask for use with setFlags indicating bits used for indicating which
791     * scrollbars are enabled.</p>
792     * {@hide}
793     */
794    static final int SCROLLBARS_MASK = 0x00000300;
795
796    /**
797     * Indicates that the view should filter touches when its window is obscured.
798     * Refer to the class comments for more information about this security feature.
799     * {@hide}
800     */
801    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
802
803    /**
804     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
805     * that they are optional and should be skipped if the window has
806     * requested system UI flags that ignore those insets for layout.
807     */
808    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
809
810    /**
811     * <p>This view doesn't show fading edges.</p>
812     * {@hide}
813     */
814    static final int FADING_EDGE_NONE = 0x00000000;
815
816    /**
817     * <p>This view shows horizontal fading edges.</p>
818     * {@hide}
819     */
820    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
821
822    /**
823     * <p>This view shows vertical fading edges.</p>
824     * {@hide}
825     */
826    static final int FADING_EDGE_VERTICAL = 0x00002000;
827
828    /**
829     * <p>Mask for use with setFlags indicating bits used for indicating which
830     * fading edges are enabled.</p>
831     * {@hide}
832     */
833    static final int FADING_EDGE_MASK = 0x00003000;
834
835    /**
836     * <p>Indicates this view can be clicked. When clickable, a View reacts
837     * to clicks by notifying the OnClickListener.<p>
838     * {@hide}
839     */
840    static final int CLICKABLE = 0x00004000;
841
842    /**
843     * <p>Indicates this view is caching its drawing into a bitmap.</p>
844     * {@hide}
845     */
846    static final int DRAWING_CACHE_ENABLED = 0x00008000;
847
848    /**
849     * <p>Indicates that no icicle should be saved for this view.<p>
850     * {@hide}
851     */
852    static final int SAVE_DISABLED = 0x000010000;
853
854    /**
855     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
856     * property.</p>
857     * {@hide}
858     */
859    static final int SAVE_DISABLED_MASK = 0x000010000;
860
861    /**
862     * <p>Indicates that no drawing cache should ever be created for this view.<p>
863     * {@hide}
864     */
865    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
866
867    /**
868     * <p>Indicates this view can take / keep focus when int touch mode.</p>
869     * {@hide}
870     */
871    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
872
873    /**
874     * <p>Enables low quality mode for the drawing cache.</p>
875     */
876    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
877
878    /**
879     * <p>Enables high quality mode for the drawing cache.</p>
880     */
881    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
882
883    /**
884     * <p>Enables automatic quality mode for the drawing cache.</p>
885     */
886    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
887
888    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
889            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
890    };
891
892    /**
893     * <p>Mask for use with setFlags indicating bits used for the cache
894     * quality property.</p>
895     * {@hide}
896     */
897    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
898
899    /**
900     * <p>
901     * Indicates this view can be long clicked. When long clickable, a View
902     * reacts to long clicks by notifying the OnLongClickListener or showing a
903     * context menu.
904     * </p>
905     * {@hide}
906     */
907    static final int LONG_CLICKABLE = 0x00200000;
908
909    /**
910     * <p>Indicates that this view gets its drawable states from its direct parent
911     * and ignores its original internal states.</p>
912     *
913     * @hide
914     */
915    static final int DUPLICATE_PARENT_STATE = 0x00400000;
916
917    /**
918     * The scrollbar style to display the scrollbars inside the content area,
919     * without increasing the padding. The scrollbars will be overlaid with
920     * translucency on the view's content.
921     */
922    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
923
924    /**
925     * The scrollbar style to display the scrollbars inside the padded area,
926     * increasing the padding of the view. The scrollbars will not overlap the
927     * content area of the view.
928     */
929    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
930
931    /**
932     * The scrollbar style to display the scrollbars at the edge of the view,
933     * without increasing the padding. The scrollbars will be overlaid with
934     * translucency.
935     */
936    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
937
938    /**
939     * The scrollbar style to display the scrollbars at the edge of the view,
940     * increasing the padding of the view. The scrollbars will only overlap the
941     * background, if any.
942     */
943    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
944
945    /**
946     * Mask to check if the scrollbar style is overlay or inset.
947     * {@hide}
948     */
949    static final int SCROLLBARS_INSET_MASK = 0x01000000;
950
951    /**
952     * Mask to check if the scrollbar style is inside or outside.
953     * {@hide}
954     */
955    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
956
957    /**
958     * Mask for scrollbar style.
959     * {@hide}
960     */
961    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
962
963    /**
964     * View flag indicating that the screen should remain on while the
965     * window containing this view is visible to the user.  This effectively
966     * takes care of automatically setting the WindowManager's
967     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
968     */
969    public static final int KEEP_SCREEN_ON = 0x04000000;
970
971    /**
972     * View flag indicating whether this view should have sound effects enabled
973     * for events such as clicking and touching.
974     */
975    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
976
977    /**
978     * View flag indicating whether this view should have haptic feedback
979     * enabled for events such as long presses.
980     */
981    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
982
983    /**
984     * <p>Indicates that the view hierarchy should stop saving state when
985     * it reaches this view.  If state saving is initiated immediately at
986     * the view, it will be allowed.
987     * {@hide}
988     */
989    static final int PARENT_SAVE_DISABLED = 0x20000000;
990
991    /**
992     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
993     * {@hide}
994     */
995    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
996
997    /**
998     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
999     * should add all focusable Views regardless if they are focusable in touch mode.
1000     */
1001    public static final int FOCUSABLES_ALL = 0x00000000;
1002
1003    /**
1004     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1005     * should add only Views focusable in touch mode.
1006     */
1007    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add only accessibility focusable Views.
1012     *
1013     * @hide
1014     */
1015    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1016
1017    /**
1018     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1019     * item.
1020     */
1021    public static final int FOCUS_BACKWARD = 0x00000001;
1022
1023    /**
1024     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1025     * item.
1026     */
1027    public static final int FOCUS_FORWARD = 0x00000002;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus to the left.
1031     */
1032    public static final int FOCUS_LEFT = 0x00000011;
1033
1034    /**
1035     * Use with {@link #focusSearch(int)}. Move focus up.
1036     */
1037    public static final int FOCUS_UP = 0x00000021;
1038
1039    /**
1040     * Use with {@link #focusSearch(int)}. Move focus to the right.
1041     */
1042    public static final int FOCUS_RIGHT = 0x00000042;
1043
1044    /**
1045     * Use with {@link #focusSearch(int)}. Move focus down.
1046     */
1047    public static final int FOCUS_DOWN = 0x00000082;
1048
1049    // Accessibility focus directions.
1050
1051    /**
1052     * The accessibility focus which is the current user position when
1053     * interacting with the accessibility framework.
1054     */
1055    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1056
1057    /**
1058     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1059     */
1060    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1061
1062    /**
1063     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1064     */
1065    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1066
1067    /**
1068     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1069     */
1070    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1071
1072    /**
1073     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1074     */
1075    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1076
1077    /**
1078     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1079     */
1080    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1081
1082    /**
1083     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1084     */
1085    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1086
1087    /**
1088     * Bits of {@link #getMeasuredWidthAndState()} and
1089     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1090     */
1091    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1092
1093    /**
1094     * Bits of {@link #getMeasuredWidthAndState()} and
1095     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1096     */
1097    public static final int MEASURED_STATE_MASK = 0xff000000;
1098
1099    /**
1100     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1101     * for functions that combine both width and height into a single int,
1102     * such as {@link #getMeasuredState()} and the childState argument of
1103     * {@link #resolveSizeAndState(int, int, int)}.
1104     */
1105    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1106
1107    /**
1108     * Bit of {@link #getMeasuredWidthAndState()} and
1109     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1110     * is smaller that the space the view would like to have.
1111     */
1112    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1113
1114    /**
1115     * Base View state sets
1116     */
1117    // Singles
1118    /**
1119     * Indicates the view has no states set. States are used with
1120     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1121     * view depending on its state.
1122     *
1123     * @see android.graphics.drawable.Drawable
1124     * @see #getDrawableState()
1125     */
1126    protected static final int[] EMPTY_STATE_SET;
1127    /**
1128     * Indicates the view is enabled. States are used with
1129     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1130     * view depending on its state.
1131     *
1132     * @see android.graphics.drawable.Drawable
1133     * @see #getDrawableState()
1134     */
1135    protected static final int[] ENABLED_STATE_SET;
1136    /**
1137     * Indicates the view is focused. States are used with
1138     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1139     * view depending on its state.
1140     *
1141     * @see android.graphics.drawable.Drawable
1142     * @see #getDrawableState()
1143     */
1144    protected static final int[] FOCUSED_STATE_SET;
1145    /**
1146     * Indicates the view is selected. States are used with
1147     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1148     * view depending on its state.
1149     *
1150     * @see android.graphics.drawable.Drawable
1151     * @see #getDrawableState()
1152     */
1153    protected static final int[] SELECTED_STATE_SET;
1154    /**
1155     * Indicates the view is pressed. States are used with
1156     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1157     * view depending on its state.
1158     *
1159     * @see android.graphics.drawable.Drawable
1160     * @see #getDrawableState()
1161     * @hide
1162     */
1163    protected static final int[] PRESSED_STATE_SET;
1164    /**
1165     * Indicates the view's window has focus. States are used with
1166     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1167     * view depending on its state.
1168     *
1169     * @see android.graphics.drawable.Drawable
1170     * @see #getDrawableState()
1171     */
1172    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1173    // Doubles
1174    /**
1175     * Indicates the view is enabled and has the focus.
1176     *
1177     * @see #ENABLED_STATE_SET
1178     * @see #FOCUSED_STATE_SET
1179     */
1180    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1181    /**
1182     * Indicates the view is enabled and selected.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #SELECTED_STATE_SET
1186     */
1187    protected static final int[] ENABLED_SELECTED_STATE_SET;
1188    /**
1189     * Indicates the view is enabled and that its window has focus.
1190     *
1191     * @see #ENABLED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is focused and selected.
1197     *
1198     * @see #FOCUSED_STATE_SET
1199     * @see #SELECTED_STATE_SET
1200     */
1201    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1202    /**
1203     * Indicates the view has the focus and that its window has the focus.
1204     *
1205     * @see #FOCUSED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is selected and that its window has the focus.
1211     *
1212     * @see #SELECTED_STATE_SET
1213     * @see #WINDOW_FOCUSED_STATE_SET
1214     */
1215    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1216    // Triples
1217    /**
1218     * Indicates the view is enabled, focused and selected.
1219     *
1220     * @see #ENABLED_STATE_SET
1221     * @see #FOCUSED_STATE_SET
1222     * @see #SELECTED_STATE_SET
1223     */
1224    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1225    /**
1226     * Indicates the view is enabled, focused and its window has the focus.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #FOCUSED_STATE_SET
1230     * @see #WINDOW_FOCUSED_STATE_SET
1231     */
1232    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1233    /**
1234     * Indicates the view is enabled, selected and its window has the focus.
1235     *
1236     * @see #ENABLED_STATE_SET
1237     * @see #SELECTED_STATE_SET
1238     * @see #WINDOW_FOCUSED_STATE_SET
1239     */
1240    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1241    /**
1242     * Indicates the view is focused, selected and its window has the focus.
1243     *
1244     * @see #FOCUSED_STATE_SET
1245     * @see #SELECTED_STATE_SET
1246     * @see #WINDOW_FOCUSED_STATE_SET
1247     */
1248    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1249    /**
1250     * Indicates the view is enabled, focused, selected and its window
1251     * has the focus.
1252     *
1253     * @see #ENABLED_STATE_SET
1254     * @see #FOCUSED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is pressed and its window has the focus.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #WINDOW_FOCUSED_STATE_SET
1264     */
1265    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1266    /**
1267     * Indicates the view is pressed and selected.
1268     *
1269     * @see #PRESSED_STATE_SET
1270     * @see #SELECTED_STATE_SET
1271     */
1272    protected static final int[] PRESSED_SELECTED_STATE_SET;
1273    /**
1274     * Indicates the view is pressed, selected and its window has the focus.
1275     *
1276     * @see #PRESSED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     * @see #WINDOW_FOCUSED_STATE_SET
1279     */
1280    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1281    /**
1282     * Indicates the view is pressed and focused.
1283     *
1284     * @see #PRESSED_STATE_SET
1285     * @see #FOCUSED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, focused and its window has the focus.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #FOCUSED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, focused and selected.
1298     *
1299     * @see #PRESSED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #FOCUSED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed, focused, selected and its window has the focus.
1306     *
1307     * @see #PRESSED_STATE_SET
1308     * @see #FOCUSED_STATE_SET
1309     * @see #SELECTED_STATE_SET
1310     * @see #WINDOW_FOCUSED_STATE_SET
1311     */
1312    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1313    /**
1314     * Indicates the view is pressed and enabled.
1315     *
1316     * @see #PRESSED_STATE_SET
1317     * @see #ENABLED_STATE_SET
1318     */
1319    protected static final int[] PRESSED_ENABLED_STATE_SET;
1320    /**
1321     * Indicates the view is pressed, enabled and its window has the focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled and selected.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     */
1335    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1336    /**
1337     * Indicates the view is pressed, enabled, selected and its window has the
1338     * focus.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #ENABLED_STATE_SET
1342     * @see #SELECTED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed, enabled and focused.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #ENABLED_STATE_SET
1351     * @see #FOCUSED_STATE_SET
1352     */
1353    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1354    /**
1355     * Indicates the view is pressed, enabled, focused and its window has the
1356     * focus.
1357     *
1358     * @see #PRESSED_STATE_SET
1359     * @see #ENABLED_STATE_SET
1360     * @see #FOCUSED_STATE_SET
1361     * @see #WINDOW_FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled, focused and selected.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     * @see #SELECTED_STATE_SET
1370     * @see #FOCUSED_STATE_SET
1371     */
1372    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1373    /**
1374     * Indicates the view is pressed, enabled, focused, selected and its window
1375     * has the focus.
1376     *
1377     * @see #PRESSED_STATE_SET
1378     * @see #ENABLED_STATE_SET
1379     * @see #SELECTED_STATE_SET
1380     * @see #FOCUSED_STATE_SET
1381     * @see #WINDOW_FOCUSED_STATE_SET
1382     */
1383    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1384
1385    /**
1386     * The order here is very important to {@link #getDrawableState()}
1387     */
1388    private static final int[][] VIEW_STATE_SETS;
1389
1390    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1391    static final int VIEW_STATE_SELECTED = 1 << 1;
1392    static final int VIEW_STATE_FOCUSED = 1 << 2;
1393    static final int VIEW_STATE_ENABLED = 1 << 3;
1394    static final int VIEW_STATE_PRESSED = 1 << 4;
1395    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1396    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1397    static final int VIEW_STATE_HOVERED = 1 << 7;
1398    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1399    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1400
1401    static final int[] VIEW_STATE_IDS = new int[] {
1402        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1403        R.attr.state_selected,          VIEW_STATE_SELECTED,
1404        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1405        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1406        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1407        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1408        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1409        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1410        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1411        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1412    };
1413
1414    static {
1415        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1416            throw new IllegalStateException(
1417                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1418        }
1419        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1420        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1421            int viewState = R.styleable.ViewDrawableStates[i];
1422            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1423                if (VIEW_STATE_IDS[j] == viewState) {
1424                    orderedIds[i * 2] = viewState;
1425                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1426                }
1427            }
1428        }
1429        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1430        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1431        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1432            int numBits = Integer.bitCount(i);
1433            int[] set = new int[numBits];
1434            int pos = 0;
1435            for (int j = 0; j < orderedIds.length; j += 2) {
1436                if ((i & orderedIds[j+1]) != 0) {
1437                    set[pos++] = orderedIds[j];
1438                }
1439            }
1440            VIEW_STATE_SETS[i] = set;
1441        }
1442
1443        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1444        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1445        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1446        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1448        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1449        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1451        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1453        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1455                | VIEW_STATE_FOCUSED];
1456        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1457        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1459        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1461        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1463                | VIEW_STATE_ENABLED];
1464        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1466        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_ENABLED];
1469        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED];
1472        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1474                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1475
1476        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1477        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1479        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1481        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1482                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1483                | VIEW_STATE_PRESSED];
1484        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1485                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1486        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1488                | VIEW_STATE_PRESSED];
1489        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1491                | VIEW_STATE_PRESSED];
1492        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1494                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1495        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1497        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1499                | VIEW_STATE_PRESSED];
1500        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1502                | VIEW_STATE_PRESSED];
1503        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1505                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1506        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1508                | VIEW_STATE_PRESSED];
1509        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1510                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1511                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1512        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1514                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1515        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1517                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1518                | VIEW_STATE_PRESSED];
1519    }
1520
1521    /**
1522     * Accessibility event types that are dispatched for text population.
1523     */
1524    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1525            AccessibilityEvent.TYPE_VIEW_CLICKED
1526            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1527            | AccessibilityEvent.TYPE_VIEW_SELECTED
1528            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1529            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1530            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1531            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1532            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1533            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1534            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1535            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1536
1537    /**
1538     * Temporary Rect currently for use in setBackground().  This will probably
1539     * be extended in the future to hold our own class with more than just
1540     * a Rect. :)
1541     */
1542    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1543
1544    /**
1545     * Map used to store views' tags.
1546     */
1547    private SparseArray<Object> mKeyedTags;
1548
1549    /**
1550     * The next available accessiiblity id.
1551     */
1552    private static int sNextAccessibilityViewId;
1553
1554    /**
1555     * The animation currently associated with this view.
1556     * @hide
1557     */
1558    protected Animation mCurrentAnimation = null;
1559
1560    /**
1561     * Width as measured during measure pass.
1562     * {@hide}
1563     */
1564    @ViewDebug.ExportedProperty(category = "measurement")
1565    int mMeasuredWidth;
1566
1567    /**
1568     * Height as measured during measure pass.
1569     * {@hide}
1570     */
1571    @ViewDebug.ExportedProperty(category = "measurement")
1572    int mMeasuredHeight;
1573
1574    /**
1575     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1576     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1577     * its display list. This flag, used only when hw accelerated, allows us to clear the
1578     * flag while retaining this information until it's needed (at getDisplayList() time and
1579     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1580     *
1581     * {@hide}
1582     */
1583    boolean mRecreateDisplayList = false;
1584
1585    /**
1586     * The view's identifier.
1587     * {@hide}
1588     *
1589     * @see #setId(int)
1590     * @see #getId()
1591     */
1592    @ViewDebug.ExportedProperty(resolveId = true)
1593    int mID = NO_ID;
1594
1595    /**
1596     * The stable ID of this view for accessibility purposes.
1597     */
1598    int mAccessibilityViewId = NO_ID;
1599
1600    /**
1601     * @hide
1602     */
1603    private int mAccessibilityCursorPosition = -1;
1604
1605    /**
1606     * The view's tag.
1607     * {@hide}
1608     *
1609     * @see #setTag(Object)
1610     * @see #getTag()
1611     */
1612    protected Object mTag;
1613
1614    // for mPrivateFlags:
1615    /** {@hide} */
1616    static final int WANTS_FOCUS                    = 0x00000001;
1617    /** {@hide} */
1618    static final int FOCUSED                        = 0x00000002;
1619    /** {@hide} */
1620    static final int SELECTED                       = 0x00000004;
1621    /** {@hide} */
1622    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1623    /** {@hide} */
1624    static final int HAS_BOUNDS                     = 0x00000010;
1625    /** {@hide} */
1626    static final int DRAWN                          = 0x00000020;
1627    /**
1628     * When this flag is set, this view is running an animation on behalf of its
1629     * children and should therefore not cancel invalidate requests, even if they
1630     * lie outside of this view's bounds.
1631     *
1632     * {@hide}
1633     */
1634    static final int DRAW_ANIMATION                 = 0x00000040;
1635    /** {@hide} */
1636    static final int SKIP_DRAW                      = 0x00000080;
1637    /** {@hide} */
1638    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1639    /** {@hide} */
1640    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1641    /** {@hide} */
1642    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1643    /** {@hide} */
1644    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1645    /** {@hide} */
1646    static final int FORCE_LAYOUT                   = 0x00001000;
1647    /** {@hide} */
1648    static final int LAYOUT_REQUIRED                = 0x00002000;
1649
1650    private static final int PRESSED                = 0x00004000;
1651
1652    /** {@hide} */
1653    static final int DRAWING_CACHE_VALID            = 0x00008000;
1654    /**
1655     * Flag used to indicate that this view should be drawn once more (and only once
1656     * more) after its animation has completed.
1657     * {@hide}
1658     */
1659    static final int ANIMATION_STARTED              = 0x00010000;
1660
1661    private static final int SAVE_STATE_CALLED      = 0x00020000;
1662
1663    /**
1664     * Indicates that the View returned true when onSetAlpha() was called and that
1665     * the alpha must be restored.
1666     * {@hide}
1667     */
1668    static final int ALPHA_SET                      = 0x00040000;
1669
1670    /**
1671     * Set by {@link #setScrollContainer(boolean)}.
1672     */
1673    static final int SCROLL_CONTAINER               = 0x00080000;
1674
1675    /**
1676     * Set by {@link #setScrollContainer(boolean)}.
1677     */
1678    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1679
1680    /**
1681     * View flag indicating whether this view was invalidated (fully or partially.)
1682     *
1683     * @hide
1684     */
1685    static final int DIRTY                          = 0x00200000;
1686
1687    /**
1688     * View flag indicating whether this view was invalidated by an opaque
1689     * invalidate request.
1690     *
1691     * @hide
1692     */
1693    static final int DIRTY_OPAQUE                   = 0x00400000;
1694
1695    /**
1696     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1697     *
1698     * @hide
1699     */
1700    static final int DIRTY_MASK                     = 0x00600000;
1701
1702    /**
1703     * Indicates whether the background is opaque.
1704     *
1705     * @hide
1706     */
1707    static final int OPAQUE_BACKGROUND              = 0x00800000;
1708
1709    /**
1710     * Indicates whether the scrollbars are opaque.
1711     *
1712     * @hide
1713     */
1714    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1715
1716    /**
1717     * Indicates whether the view is opaque.
1718     *
1719     * @hide
1720     */
1721    static final int OPAQUE_MASK                    = 0x01800000;
1722
1723    /**
1724     * Indicates a prepressed state;
1725     * the short time between ACTION_DOWN and recognizing
1726     * a 'real' press. Prepressed is used to recognize quick taps
1727     * even when they are shorter than ViewConfiguration.getTapTimeout().
1728     *
1729     * @hide
1730     */
1731    private static final int PREPRESSED             = 0x02000000;
1732
1733    /**
1734     * Indicates whether the view is temporarily detached.
1735     *
1736     * @hide
1737     */
1738    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1739
1740    /**
1741     * Indicates that we should awaken scroll bars once attached
1742     *
1743     * @hide
1744     */
1745    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1746
1747    /**
1748     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1749     * @hide
1750     */
1751    private static final int HOVERED              = 0x10000000;
1752
1753    /**
1754     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1755     * for transform operations
1756     *
1757     * @hide
1758     */
1759    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1760
1761    /** {@hide} */
1762    static final int ACTIVATED                    = 0x40000000;
1763
1764    /**
1765     * Indicates that this view was specifically invalidated, not just dirtied because some
1766     * child view was invalidated. The flag is used to determine when we need to recreate
1767     * a view's display list (as opposed to just returning a reference to its existing
1768     * display list).
1769     *
1770     * @hide
1771     */
1772    static final int INVALIDATED                  = 0x80000000;
1773
1774    /* Masks for mPrivateFlags2 */
1775
1776    /**
1777     * Indicates that this view has reported that it can accept the current drag's content.
1778     * Cleared when the drag operation concludes.
1779     * @hide
1780     */
1781    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1782
1783    /**
1784     * Indicates that this view is currently directly under the drag location in a
1785     * drag-and-drop operation involving content that it can accept.  Cleared when
1786     * the drag exits the view, or when the drag operation concludes.
1787     * @hide
1788     */
1789    static final int DRAG_HOVERED                 = 0x00000002;
1790
1791    /**
1792     * Horizontal layout direction of this view is from Left to Right.
1793     * Use with {@link #setLayoutDirection}.
1794     */
1795    public static final int LAYOUT_DIRECTION_LTR = 0;
1796
1797    /**
1798     * Horizontal layout direction of this view is from Right to Left.
1799     * Use with {@link #setLayoutDirection}.
1800     */
1801    public static final int LAYOUT_DIRECTION_RTL = 1;
1802
1803    /**
1804     * Horizontal layout direction of this view is inherited from its parent.
1805     * Use with {@link #setLayoutDirection}.
1806     */
1807    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1808
1809    /**
1810     * Horizontal layout direction of this view is from deduced from the default language
1811     * script for the locale. Use with {@link #setLayoutDirection}.
1812     */
1813    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1814
1815    /**
1816     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1817     * @hide
1818     */
1819    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1820
1821    /**
1822     * Mask for use with private flags indicating bits used for horizontal layout direction.
1823     * @hide
1824     */
1825    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1826
1827    /**
1828     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1829     * right-to-left direction.
1830     * @hide
1831     */
1832    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1833
1834    /**
1835     * Indicates whether the view horizontal layout direction has been resolved.
1836     * @hide
1837     */
1838    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1839
1840    /**
1841     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1842     * @hide
1843     */
1844    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1845
1846    /*
1847     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1848     * flag value.
1849     * @hide
1850     */
1851    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1852            LAYOUT_DIRECTION_LTR,
1853            LAYOUT_DIRECTION_RTL,
1854            LAYOUT_DIRECTION_INHERIT,
1855            LAYOUT_DIRECTION_LOCALE
1856    };
1857
1858    /**
1859     * Default horizontal layout direction.
1860     * @hide
1861     */
1862    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1863
1864    /**
1865     * Indicates that the view is tracking some sort of transient state
1866     * that the app should not need to be aware of, but that the framework
1867     * should take special care to preserve.
1868     *
1869     * @hide
1870     */
1871    static final int HAS_TRANSIENT_STATE = 0x00000100;
1872
1873
1874    /**
1875     * Text direction is inherited thru {@link ViewGroup}
1876     */
1877    public static final int TEXT_DIRECTION_INHERIT = 0;
1878
1879    /**
1880     * Text direction is using "first strong algorithm". The first strong directional character
1881     * determines the paragraph direction. If there is no strong directional character, the
1882     * paragraph direction is the view's resolved layout direction.
1883     */
1884    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1885
1886    /**
1887     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1888     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1889     * If there are neither, the paragraph direction is the view's resolved layout direction.
1890     */
1891    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1892
1893    /**
1894     * Text direction is forced to LTR.
1895     */
1896    public static final int TEXT_DIRECTION_LTR = 3;
1897
1898    /**
1899     * Text direction is forced to RTL.
1900     */
1901    public static final int TEXT_DIRECTION_RTL = 4;
1902
1903    /**
1904     * Text direction is coming from the system Locale.
1905     */
1906    public static final int TEXT_DIRECTION_LOCALE = 5;
1907
1908    /**
1909     * Default text direction is inherited
1910     */
1911    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1912
1913    /**
1914     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1915     * @hide
1916     */
1917    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1918
1919    /**
1920     * Mask for use with private flags indicating bits used for text direction.
1921     * @hide
1922     */
1923    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1924
1925    /**
1926     * Array of text direction flags for mapping attribute "textDirection" to correct
1927     * flag value.
1928     * @hide
1929     */
1930    private static final int[] TEXT_DIRECTION_FLAGS = {
1931            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1932            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1933            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1934            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1935            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1936            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1937    };
1938
1939    /**
1940     * Indicates whether the view text direction has been resolved.
1941     * @hide
1942     */
1943    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1944
1945    /**
1946     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1947     * @hide
1948     */
1949    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1950
1951    /**
1952     * Mask for use with private flags indicating bits used for resolved text direction.
1953     * @hide
1954     */
1955    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1956
1957    /**
1958     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1959     * @hide
1960     */
1961    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1962            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1963
1964    /*
1965     * Default text alignment. The text alignment of this View is inherited from its parent.
1966     * Use with {@link #setTextAlignment(int)}
1967     */
1968    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1969
1970    /**
1971     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1972     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1973     *
1974     * Use with {@link #setTextAlignment(int)}
1975     */
1976    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1977
1978    /**
1979     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1980     *
1981     * Use with {@link #setTextAlignment(int)}
1982     */
1983    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1984
1985    /**
1986     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1987     *
1988     * Use with {@link #setTextAlignment(int)}
1989     */
1990    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1991
1992    /**
1993     * Center the paragraph, e.g. ALIGN_CENTER.
1994     *
1995     * Use with {@link #setTextAlignment(int)}
1996     */
1997    public static final int TEXT_ALIGNMENT_CENTER = 4;
1998
1999    /**
2000     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2001     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2002     *
2003     * Use with {@link #setTextAlignment(int)}
2004     */
2005    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2006
2007    /**
2008     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2009     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2010     *
2011     * Use with {@link #setTextAlignment(int)}
2012     */
2013    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2014
2015    /**
2016     * Default text alignment is inherited
2017     */
2018    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2019
2020    /**
2021      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2022      * @hide
2023      */
2024    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2025
2026    /**
2027      * Mask for use with private flags indicating bits used for text alignment.
2028      * @hide
2029      */
2030    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2031
2032    /**
2033     * Array of text direction flags for mapping attribute "textAlignment" to correct
2034     * flag value.
2035     * @hide
2036     */
2037    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2038            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2039            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2040            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2041            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2042            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2043            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2044            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2045    };
2046
2047    /**
2048     * Indicates whether the view text alignment has been resolved.
2049     * @hide
2050     */
2051    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2052
2053    /**
2054     * Bit shift to get the resolved text alignment.
2055     * @hide
2056     */
2057    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2058
2059    /**
2060     * Mask for use with private flags indicating bits used for text alignment.
2061     * @hide
2062     */
2063    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2064
2065    /**
2066     * Indicates whether if the view text alignment has been resolved to gravity
2067     */
2068    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2069            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2070
2071    // Accessiblity constants for mPrivateFlags2
2072
2073    /**
2074     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2075     */
2076    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2077
2078    /**
2079     * Automatically determine whether a view is important for accessibility.
2080     */
2081    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2082
2083    /**
2084     * The view is important for accessibility.
2085     */
2086    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2087
2088    /**
2089     * The view is not important for accessibility.
2090     */
2091    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2092
2093    /**
2094     * The default whether the view is important for accessiblity.
2095     */
2096    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2097
2098    /**
2099     * Mask for obtainig the bits which specify how to determine
2100     * whether a view is important for accessibility.
2101     */
2102    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2103        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2104        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2105
2106    /**
2107     * Flag indicating whether a view has accessibility focus.
2108     */
2109    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2110
2111    /**
2112     * Flag indicating whether a view state for accessibility has changed.
2113     */
2114    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2115
2116    /* End of masks for mPrivateFlags2 */
2117
2118    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2119
2120    /**
2121     * Always allow a user to over-scroll this view, provided it is a
2122     * view that can scroll.
2123     *
2124     * @see #getOverScrollMode()
2125     * @see #setOverScrollMode(int)
2126     */
2127    public static final int OVER_SCROLL_ALWAYS = 0;
2128
2129    /**
2130     * Allow a user to over-scroll this view only if the content is large
2131     * enough to meaningfully scroll, provided it is a view that can scroll.
2132     *
2133     * @see #getOverScrollMode()
2134     * @see #setOverScrollMode(int)
2135     */
2136    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2137
2138    /**
2139     * Never allow a user to over-scroll this view.
2140     *
2141     * @see #getOverScrollMode()
2142     * @see #setOverScrollMode(int)
2143     */
2144    public static final int OVER_SCROLL_NEVER = 2;
2145
2146    /**
2147     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2148     * requested the system UI (status bar) to be visible (the default).
2149     *
2150     * @see #setSystemUiVisibility(int)
2151     */
2152    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2153
2154    /**
2155     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2156     * system UI to enter an unobtrusive "low profile" mode.
2157     *
2158     * <p>This is for use in games, book readers, video players, or any other
2159     * "immersive" application where the usual system chrome is deemed too distracting.
2160     *
2161     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2162     *
2163     * @see #setSystemUiVisibility(int)
2164     */
2165    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2166
2167    /**
2168     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2169     * system navigation be temporarily hidden.
2170     *
2171     * <p>This is an even less obtrusive state than that called for by
2172     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2173     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2174     * those to disappear. This is useful (in conjunction with the
2175     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2176     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2177     * window flags) for displaying content using every last pixel on the display.
2178     *
2179     * <p>There is a limitation: because navigation controls are so important, the least user
2180     * interaction will cause them to reappear immediately.  When this happens, both
2181     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2182     * so that both elements reappear at the same time.
2183     *
2184     * @see #setSystemUiVisibility(int)
2185     */
2186    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2187
2188    /**
2189     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2190     * into the normal fullscreen mode so that its content can take over the screen
2191     * while still allowing the user to interact with the application.
2192     *
2193     * <p>This has the same visual effect as
2194     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2195     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2196     * meaning that non-critical screen decorations (such as the status bar) will be
2197     * hidden while the user is in the View's window, focusing the experience on
2198     * that content.  Unlike the window flag, if you are using ActionBar in
2199     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2200     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2201     * hide the action bar.
2202     *
2203     * <p>This approach to going fullscreen is best used over the window flag when
2204     * it is a transient state -- that is, the application does this at certain
2205     * points in its user interaction where it wants to allow the user to focus
2206     * on content, but not as a continuous state.  For situations where the application
2207     * would like to simply stay full screen the entire time (such as a game that
2208     * wants to take over the screen), the
2209     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2210     * is usually a better approach.  The state set here will be removed by the system
2211     * in various situations (such as the user moving to another application) like
2212     * the other system UI states.
2213     *
2214     * <p>When using this flag, the application should provide some easy facility
2215     * for the user to go out of it.  A common example would be in an e-book
2216     * reader, where tapping on the screen brings back whatever screen and UI
2217     * decorations that had been hidden while the user was immersed in reading
2218     * the book.
2219     *
2220     * @see #setSystemUiVisibility(int)
2221     */
2222    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2223
2224    /**
2225     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2226     * flags, we would like a stable view of the content insets given to
2227     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2228     * will always represent the worst case that the application can expect
2229     * as a continue state.  In practice this means with any of system bar,
2230     * nav bar, and status bar shown, but not the space that would be needed
2231     * for an input method.
2232     *
2233     * <p>If you are using ActionBar in
2234     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2235     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2236     * insets it adds to those given to the application.
2237     */
2238    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2239
2240    /**
2241     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2242     * to be layed out as if it has requested
2243     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2244     * allows it to avoid artifacts when switching in and out of that mode, at
2245     * the expense that some of its user interface may be covered by screen
2246     * decorations when they are shown.  You can perform layout of your inner
2247     * UI elements to account for the navagation system UI through the
2248     * {@link #fitSystemWindows(Rect)} method.
2249     */
2250    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2251
2252    /**
2253     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2254     * to be layed out as if it has requested
2255     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2256     * allows it to avoid artifacts when switching in and out of that mode, at
2257     * the expense that some of its user interface may be covered by screen
2258     * decorations when they are shown.  You can perform layout of your inner
2259     * UI elements to account for non-fullscreen system UI through the
2260     * {@link #fitSystemWindows(Rect)} method.
2261     */
2262    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2263
2264    /**
2265     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2266     */
2267    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2268
2269    /**
2270     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2271     */
2272    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2273
2274    /**
2275     * @hide
2276     *
2277     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2278     * out of the public fields to keep the undefined bits out of the developer's way.
2279     *
2280     * Flag to make the status bar not expandable.  Unless you also
2281     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2282     */
2283    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2284
2285    /**
2286     * @hide
2287     *
2288     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2289     * out of the public fields to keep the undefined bits out of the developer's way.
2290     *
2291     * Flag to hide notification icons and scrolling ticker text.
2292     */
2293    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2294
2295    /**
2296     * @hide
2297     *
2298     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2299     * out of the public fields to keep the undefined bits out of the developer's way.
2300     *
2301     * Flag to disable incoming notification alerts.  This will not block
2302     * icons, but it will block sound, vibrating and other visual or aural notifications.
2303     */
2304    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2305
2306    /**
2307     * @hide
2308     *
2309     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2310     * out of the public fields to keep the undefined bits out of the developer's way.
2311     *
2312     * Flag to hide only the scrolling ticker.  Note that
2313     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2314     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2315     */
2316    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2317
2318    /**
2319     * @hide
2320     *
2321     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2322     * out of the public fields to keep the undefined bits out of the developer's way.
2323     *
2324     * Flag to hide the center system info area.
2325     */
2326    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2327
2328    /**
2329     * @hide
2330     *
2331     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2332     * out of the public fields to keep the undefined bits out of the developer's way.
2333     *
2334     * Flag to hide only the home button.  Don't use this
2335     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2336     */
2337    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2338
2339    /**
2340     * @hide
2341     *
2342     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2343     * out of the public fields to keep the undefined bits out of the developer's way.
2344     *
2345     * Flag to hide only the back button. Don't use this
2346     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2347     */
2348    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2349
2350    /**
2351     * @hide
2352     *
2353     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2354     * out of the public fields to keep the undefined bits out of the developer's way.
2355     *
2356     * Flag to hide only the clock.  You might use this if your activity has
2357     * its own clock making the status bar's clock redundant.
2358     */
2359    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2360
2361    /**
2362     * @hide
2363     *
2364     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2365     * out of the public fields to keep the undefined bits out of the developer's way.
2366     *
2367     * Flag to hide only the recent apps button. Don't use this
2368     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2369     */
2370    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2371
2372    /**
2373     * @hide
2374     */
2375    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2376
2377    /**
2378     * These are the system UI flags that can be cleared by events outside
2379     * of an application.  Currently this is just the ability to tap on the
2380     * screen while hiding the navigation bar to have it return.
2381     * @hide
2382     */
2383    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2384            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2385            | SYSTEM_UI_FLAG_FULLSCREEN;
2386
2387    /**
2388     * Flags that can impact the layout in relation to system UI.
2389     */
2390    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2391            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2392            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2393
2394    /**
2395     * Find views that render the specified text.
2396     *
2397     * @see #findViewsWithText(ArrayList, CharSequence, int)
2398     */
2399    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2400
2401    /**
2402     * Find find views that contain the specified content description.
2403     *
2404     * @see #findViewsWithText(ArrayList, CharSequence, int)
2405     */
2406    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2407
2408    /**
2409     * Find views that contain {@link AccessibilityNodeProvider}. Such
2410     * a View is a root of virtual view hierarchy and may contain the searched
2411     * text. If this flag is set Views with providers are automatically
2412     * added and it is a responsibility of the client to call the APIs of
2413     * the provider to determine whether the virtual tree rooted at this View
2414     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2415     * represeting the virtual views with this text.
2416     *
2417     * @see #findViewsWithText(ArrayList, CharSequence, int)
2418     *
2419     * @hide
2420     */
2421    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2422
2423    /**
2424     * Indicates that the screen has changed state and is now off.
2425     *
2426     * @see #onScreenStateChanged(int)
2427     */
2428    public static final int SCREEN_STATE_OFF = 0x0;
2429
2430    /**
2431     * Indicates that the screen has changed state and is now on.
2432     *
2433     * @see #onScreenStateChanged(int)
2434     */
2435    public static final int SCREEN_STATE_ON = 0x1;
2436
2437    /**
2438     * Controls the over-scroll mode for this view.
2439     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2440     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2441     * and {@link #OVER_SCROLL_NEVER}.
2442     */
2443    private int mOverScrollMode;
2444
2445    /**
2446     * The parent this view is attached to.
2447     * {@hide}
2448     *
2449     * @see #getParent()
2450     */
2451    protected ViewParent mParent;
2452
2453    /**
2454     * {@hide}
2455     */
2456    AttachInfo mAttachInfo;
2457
2458    /**
2459     * {@hide}
2460     */
2461    @ViewDebug.ExportedProperty(flagMapping = {
2462        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2463                name = "FORCE_LAYOUT"),
2464        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2465                name = "LAYOUT_REQUIRED"),
2466        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2467            name = "DRAWING_CACHE_INVALID", outputIf = false),
2468        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2469        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2470        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2471        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2472    })
2473    int mPrivateFlags;
2474    int mPrivateFlags2;
2475
2476    /**
2477     * This view's request for the visibility of the status bar.
2478     * @hide
2479     */
2480    @ViewDebug.ExportedProperty(flagMapping = {
2481        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2482                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2483                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2484        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2485                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2486                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2487        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2488                                equals = SYSTEM_UI_FLAG_VISIBLE,
2489                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2490    })
2491    int mSystemUiVisibility;
2492
2493    /**
2494     * Reference count for transient state.
2495     * @see #setHasTransientState(boolean)
2496     */
2497    int mTransientStateCount = 0;
2498
2499    /**
2500     * Count of how many windows this view has been attached to.
2501     */
2502    int mWindowAttachCount;
2503
2504    /**
2505     * The layout parameters associated with this view and used by the parent
2506     * {@link android.view.ViewGroup} to determine how this view should be
2507     * laid out.
2508     * {@hide}
2509     */
2510    protected ViewGroup.LayoutParams mLayoutParams;
2511
2512    /**
2513     * The view flags hold various views states.
2514     * {@hide}
2515     */
2516    @ViewDebug.ExportedProperty
2517    int mViewFlags;
2518
2519    static class TransformationInfo {
2520        /**
2521         * The transform matrix for the View. This transform is calculated internally
2522         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2523         * is used by default. Do *not* use this variable directly; instead call
2524         * getMatrix(), which will automatically recalculate the matrix if necessary
2525         * to get the correct matrix based on the latest rotation and scale properties.
2526         */
2527        private final Matrix mMatrix = new Matrix();
2528
2529        /**
2530         * The transform matrix for the View. This transform is calculated internally
2531         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2532         * is used by default. Do *not* use this variable directly; instead call
2533         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2534         * to get the correct matrix based on the latest rotation and scale properties.
2535         */
2536        private Matrix mInverseMatrix;
2537
2538        /**
2539         * An internal variable that tracks whether we need to recalculate the
2540         * transform matrix, based on whether the rotation or scaleX/Y properties
2541         * have changed since the matrix was last calculated.
2542         */
2543        boolean mMatrixDirty = false;
2544
2545        /**
2546         * An internal variable that tracks whether we need to recalculate the
2547         * transform matrix, based on whether the rotation or scaleX/Y properties
2548         * have changed since the matrix was last calculated.
2549         */
2550        private boolean mInverseMatrixDirty = true;
2551
2552        /**
2553         * A variable that tracks whether we need to recalculate the
2554         * transform matrix, based on whether the rotation or scaleX/Y properties
2555         * have changed since the matrix was last calculated. This variable
2556         * is only valid after a call to updateMatrix() or to a function that
2557         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2558         */
2559        private boolean mMatrixIsIdentity = true;
2560
2561        /**
2562         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2563         */
2564        private Camera mCamera = null;
2565
2566        /**
2567         * This matrix is used when computing the matrix for 3D rotations.
2568         */
2569        private Matrix matrix3D = null;
2570
2571        /**
2572         * These prev values are used to recalculate a centered pivot point when necessary. The
2573         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2574         * set), so thes values are only used then as well.
2575         */
2576        private int mPrevWidth = -1;
2577        private int mPrevHeight = -1;
2578
2579        /**
2580         * The degrees rotation around the vertical axis through the pivot point.
2581         */
2582        @ViewDebug.ExportedProperty
2583        float mRotationY = 0f;
2584
2585        /**
2586         * The degrees rotation around the horizontal axis through the pivot point.
2587         */
2588        @ViewDebug.ExportedProperty
2589        float mRotationX = 0f;
2590
2591        /**
2592         * The degrees rotation around the pivot point.
2593         */
2594        @ViewDebug.ExportedProperty
2595        float mRotation = 0f;
2596
2597        /**
2598         * The amount of translation of the object away from its left property (post-layout).
2599         */
2600        @ViewDebug.ExportedProperty
2601        float mTranslationX = 0f;
2602
2603        /**
2604         * The amount of translation of the object away from its top property (post-layout).
2605         */
2606        @ViewDebug.ExportedProperty
2607        float mTranslationY = 0f;
2608
2609        /**
2610         * The amount of scale in the x direction around the pivot point. A
2611         * value of 1 means no scaling is applied.
2612         */
2613        @ViewDebug.ExportedProperty
2614        float mScaleX = 1f;
2615
2616        /**
2617         * The amount of scale in the y direction around the pivot point. A
2618         * value of 1 means no scaling is applied.
2619         */
2620        @ViewDebug.ExportedProperty
2621        float mScaleY = 1f;
2622
2623        /**
2624         * The x location of the point around which the view is rotated and scaled.
2625         */
2626        @ViewDebug.ExportedProperty
2627        float mPivotX = 0f;
2628
2629        /**
2630         * The y location of the point around which the view is rotated and scaled.
2631         */
2632        @ViewDebug.ExportedProperty
2633        float mPivotY = 0f;
2634
2635        /**
2636         * The opacity of the View. This is a value from 0 to 1, where 0 means
2637         * completely transparent and 1 means completely opaque.
2638         */
2639        @ViewDebug.ExportedProperty
2640        float mAlpha = 1f;
2641    }
2642
2643    TransformationInfo mTransformationInfo;
2644
2645    private boolean mLastIsOpaque;
2646
2647    /**
2648     * Convenience value to check for float values that are close enough to zero to be considered
2649     * zero.
2650     */
2651    private static final float NONZERO_EPSILON = .001f;
2652
2653    /**
2654     * The distance in pixels from the left edge of this view's parent
2655     * to the left edge of this view.
2656     * {@hide}
2657     */
2658    @ViewDebug.ExportedProperty(category = "layout")
2659    protected int mLeft;
2660    /**
2661     * The distance in pixels from the left edge of this view's parent
2662     * to the right edge of this view.
2663     * {@hide}
2664     */
2665    @ViewDebug.ExportedProperty(category = "layout")
2666    protected int mRight;
2667    /**
2668     * The distance in pixels from the top edge of this view's parent
2669     * to the top edge of this view.
2670     * {@hide}
2671     */
2672    @ViewDebug.ExportedProperty(category = "layout")
2673    protected int mTop;
2674    /**
2675     * The distance in pixels from the top edge of this view's parent
2676     * to the bottom edge of this view.
2677     * {@hide}
2678     */
2679    @ViewDebug.ExportedProperty(category = "layout")
2680    protected int mBottom;
2681
2682    /**
2683     * The offset, in pixels, by which the content of this view is scrolled
2684     * horizontally.
2685     * {@hide}
2686     */
2687    @ViewDebug.ExportedProperty(category = "scrolling")
2688    protected int mScrollX;
2689    /**
2690     * The offset, in pixels, by which the content of this view is scrolled
2691     * vertically.
2692     * {@hide}
2693     */
2694    @ViewDebug.ExportedProperty(category = "scrolling")
2695    protected int mScrollY;
2696
2697    /**
2698     * The left padding in pixels, that is the distance in pixels between the
2699     * left edge of this view and the left edge of its content.
2700     * {@hide}
2701     */
2702    @ViewDebug.ExportedProperty(category = "padding")
2703    protected int mPaddingLeft;
2704    /**
2705     * The right padding in pixels, that is the distance in pixels between the
2706     * right edge of this view and the right edge of its content.
2707     * {@hide}
2708     */
2709    @ViewDebug.ExportedProperty(category = "padding")
2710    protected int mPaddingRight;
2711    /**
2712     * The top padding in pixels, that is the distance in pixels between the
2713     * top edge of this view and the top edge of its content.
2714     * {@hide}
2715     */
2716    @ViewDebug.ExportedProperty(category = "padding")
2717    protected int mPaddingTop;
2718    /**
2719     * The bottom padding in pixels, that is the distance in pixels between the
2720     * bottom edge of this view and the bottom edge of its content.
2721     * {@hide}
2722     */
2723    @ViewDebug.ExportedProperty(category = "padding")
2724    protected int mPaddingBottom;
2725
2726    /**
2727     * The layout insets in pixels, that is the distance in pixels between the
2728     * visible edges of this view its bounds.
2729     */
2730    private Insets mLayoutInsets;
2731
2732    /**
2733     * Briefly describes the view and is primarily used for accessibility support.
2734     */
2735    private CharSequence mContentDescription;
2736
2737    /**
2738     * Cache the paddingRight set by the user to append to the scrollbar's size.
2739     *
2740     * @hide
2741     */
2742    @ViewDebug.ExportedProperty(category = "padding")
2743    protected int mUserPaddingRight;
2744
2745    /**
2746     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2747     *
2748     * @hide
2749     */
2750    @ViewDebug.ExportedProperty(category = "padding")
2751    protected int mUserPaddingBottom;
2752
2753    /**
2754     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2755     *
2756     * @hide
2757     */
2758    @ViewDebug.ExportedProperty(category = "padding")
2759    protected int mUserPaddingLeft;
2760
2761    /**
2762     * Cache if the user padding is relative.
2763     *
2764     */
2765    @ViewDebug.ExportedProperty(category = "padding")
2766    boolean mUserPaddingRelative;
2767
2768    /**
2769     * Cache the paddingStart set by the user to append to the scrollbar's size.
2770     *
2771     */
2772    @ViewDebug.ExportedProperty(category = "padding")
2773    int mUserPaddingStart;
2774
2775    /**
2776     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2777     *
2778     */
2779    @ViewDebug.ExportedProperty(category = "padding")
2780    int mUserPaddingEnd;
2781
2782    /**
2783     * @hide
2784     */
2785    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2786    /**
2787     * @hide
2788     */
2789    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2790
2791    private Drawable mBackground;
2792
2793    private int mBackgroundResource;
2794    private boolean mBackgroundSizeChanged;
2795
2796    static class ListenerInfo {
2797        /**
2798         * Listener used to dispatch focus change events.
2799         * This field should be made private, so it is hidden from the SDK.
2800         * {@hide}
2801         */
2802        protected OnFocusChangeListener mOnFocusChangeListener;
2803
2804        /**
2805         * Listeners for layout change events.
2806         */
2807        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2808
2809        /**
2810         * Listeners for attach events.
2811         */
2812        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2813
2814        /**
2815         * Listener used to dispatch click events.
2816         * This field should be made private, so it is hidden from the SDK.
2817         * {@hide}
2818         */
2819        public OnClickListener mOnClickListener;
2820
2821        /**
2822         * Listener used to dispatch long click events.
2823         * This field should be made private, so it is hidden from the SDK.
2824         * {@hide}
2825         */
2826        protected OnLongClickListener mOnLongClickListener;
2827
2828        /**
2829         * Listener used to build the context menu.
2830         * This field should be made private, so it is hidden from the SDK.
2831         * {@hide}
2832         */
2833        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2834
2835        private OnKeyListener mOnKeyListener;
2836
2837        private OnTouchListener mOnTouchListener;
2838
2839        private OnHoverListener mOnHoverListener;
2840
2841        private OnGenericMotionListener mOnGenericMotionListener;
2842
2843        private OnDragListener mOnDragListener;
2844
2845        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2846    }
2847
2848    ListenerInfo mListenerInfo;
2849
2850    /**
2851     * The application environment this view lives in.
2852     * This field should be made private, so it is hidden from the SDK.
2853     * {@hide}
2854     */
2855    protected Context mContext;
2856
2857    private final Resources mResources;
2858
2859    private ScrollabilityCache mScrollCache;
2860
2861    private int[] mDrawableState = null;
2862
2863    /**
2864     * Set to true when drawing cache is enabled and cannot be created.
2865     *
2866     * @hide
2867     */
2868    public boolean mCachingFailed;
2869
2870    private Bitmap mDrawingCache;
2871    private Bitmap mUnscaledDrawingCache;
2872    private HardwareLayer mHardwareLayer;
2873    DisplayList mDisplayList;
2874
2875    /**
2876     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2877     * the user may specify which view to go to next.
2878     */
2879    private int mNextFocusLeftId = View.NO_ID;
2880
2881    /**
2882     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2883     * the user may specify which view to go to next.
2884     */
2885    private int mNextFocusRightId = View.NO_ID;
2886
2887    /**
2888     * When this view has focus and the next focus is {@link #FOCUS_UP},
2889     * the user may specify which view to go to next.
2890     */
2891    private int mNextFocusUpId = View.NO_ID;
2892
2893    /**
2894     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2895     * the user may specify which view to go to next.
2896     */
2897    private int mNextFocusDownId = View.NO_ID;
2898
2899    /**
2900     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2901     * the user may specify which view to go to next.
2902     */
2903    int mNextFocusForwardId = View.NO_ID;
2904
2905    private CheckForLongPress mPendingCheckForLongPress;
2906    private CheckForTap mPendingCheckForTap = null;
2907    private PerformClick mPerformClick;
2908    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2909
2910    private UnsetPressedState mUnsetPressedState;
2911
2912    /**
2913     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2914     * up event while a long press is invoked as soon as the long press duration is reached, so
2915     * a long press could be performed before the tap is checked, in which case the tap's action
2916     * should not be invoked.
2917     */
2918    private boolean mHasPerformedLongPress;
2919
2920    /**
2921     * The minimum height of the view. We'll try our best to have the height
2922     * of this view to at least this amount.
2923     */
2924    @ViewDebug.ExportedProperty(category = "measurement")
2925    private int mMinHeight;
2926
2927    /**
2928     * The minimum width of the view. We'll try our best to have the width
2929     * of this view to at least this amount.
2930     */
2931    @ViewDebug.ExportedProperty(category = "measurement")
2932    private int mMinWidth;
2933
2934    /**
2935     * The delegate to handle touch events that are physically in this view
2936     * but should be handled by another view.
2937     */
2938    private TouchDelegate mTouchDelegate = null;
2939
2940    /**
2941     * Solid color to use as a background when creating the drawing cache. Enables
2942     * the cache to use 16 bit bitmaps instead of 32 bit.
2943     */
2944    private int mDrawingCacheBackgroundColor = 0;
2945
2946    /**
2947     * Special tree observer used when mAttachInfo is null.
2948     */
2949    private ViewTreeObserver mFloatingTreeObserver;
2950
2951    /**
2952     * Cache the touch slop from the context that created the view.
2953     */
2954    private int mTouchSlop;
2955
2956    /**
2957     * Object that handles automatic animation of view properties.
2958     */
2959    private ViewPropertyAnimator mAnimator = null;
2960
2961    /**
2962     * Flag indicating that a drag can cross window boundaries.  When
2963     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2964     * with this flag set, all visible applications will be able to participate
2965     * in the drag operation and receive the dragged content.
2966     *
2967     * @hide
2968     */
2969    public static final int DRAG_FLAG_GLOBAL = 1;
2970
2971    /**
2972     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2973     */
2974    private float mVerticalScrollFactor;
2975
2976    /**
2977     * Position of the vertical scroll bar.
2978     */
2979    private int mVerticalScrollbarPosition;
2980
2981    /**
2982     * Position the scroll bar at the default position as determined by the system.
2983     */
2984    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2985
2986    /**
2987     * Position the scroll bar along the left edge.
2988     */
2989    public static final int SCROLLBAR_POSITION_LEFT = 1;
2990
2991    /**
2992     * Position the scroll bar along the right edge.
2993     */
2994    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2995
2996    /**
2997     * Indicates that the view does not have a layer.
2998     *
2999     * @see #getLayerType()
3000     * @see #setLayerType(int, android.graphics.Paint)
3001     * @see #LAYER_TYPE_SOFTWARE
3002     * @see #LAYER_TYPE_HARDWARE
3003     */
3004    public static final int LAYER_TYPE_NONE = 0;
3005
3006    /**
3007     * <p>Indicates that the view has a software layer. A software layer is backed
3008     * by a bitmap and causes the view to be rendered using Android's software
3009     * rendering pipeline, even if hardware acceleration is enabled.</p>
3010     *
3011     * <p>Software layers have various usages:</p>
3012     * <p>When the application is not using hardware acceleration, a software layer
3013     * is useful to apply a specific color filter and/or blending mode and/or
3014     * translucency to a view and all its children.</p>
3015     * <p>When the application is using hardware acceleration, a software layer
3016     * is useful to render drawing primitives not supported by the hardware
3017     * accelerated pipeline. It can also be used to cache a complex view tree
3018     * into a texture and reduce the complexity of drawing operations. For instance,
3019     * when animating a complex view tree with a translation, a software layer can
3020     * be used to render the view tree only once.</p>
3021     * <p>Software layers should be avoided when the affected view tree updates
3022     * often. Every update will require to re-render the software layer, which can
3023     * potentially be slow (particularly when hardware acceleration is turned on
3024     * since the layer will have to be uploaded into a hardware texture after every
3025     * update.)</p>
3026     *
3027     * @see #getLayerType()
3028     * @see #setLayerType(int, android.graphics.Paint)
3029     * @see #LAYER_TYPE_NONE
3030     * @see #LAYER_TYPE_HARDWARE
3031     */
3032    public static final int LAYER_TYPE_SOFTWARE = 1;
3033
3034    /**
3035     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3036     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3037     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3038     * rendering pipeline, but only if hardware acceleration is turned on for the
3039     * view hierarchy. When hardware acceleration is turned off, hardware layers
3040     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3041     *
3042     * <p>A hardware layer is useful to apply a specific color filter and/or
3043     * blending mode and/or translucency to a view and all its children.</p>
3044     * <p>A hardware layer can be used to cache a complex view tree into a
3045     * texture and reduce the complexity of drawing operations. For instance,
3046     * when animating a complex view tree with a translation, a hardware layer can
3047     * be used to render the view tree only once.</p>
3048     * <p>A hardware layer can also be used to increase the rendering quality when
3049     * rotation transformations are applied on a view. It can also be used to
3050     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3051     *
3052     * @see #getLayerType()
3053     * @see #setLayerType(int, android.graphics.Paint)
3054     * @see #LAYER_TYPE_NONE
3055     * @see #LAYER_TYPE_SOFTWARE
3056     */
3057    public static final int LAYER_TYPE_HARDWARE = 2;
3058
3059    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3060            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3061            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3062            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3063    })
3064    int mLayerType = LAYER_TYPE_NONE;
3065    Paint mLayerPaint;
3066    Rect mLocalDirtyRect;
3067
3068    /**
3069     * Set to true when the view is sending hover accessibility events because it
3070     * is the innermost hovered view.
3071     */
3072    private boolean mSendingHoverAccessibilityEvents;
3073
3074    /**
3075     * Simple constructor to use when creating a view from code.
3076     *
3077     * @param context The Context the view is running in, through which it can
3078     *        access the current theme, resources, etc.
3079     */
3080    public View(Context context) {
3081        mContext = context;
3082        mResources = context != null ? context.getResources() : null;
3083        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3084        // Set layout and text direction defaults
3085        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3086                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3087                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3088                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3089        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3090        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3091        mUserPaddingStart = -1;
3092        mUserPaddingEnd = -1;
3093        mUserPaddingRelative = false;
3094    }
3095
3096    /**
3097     * Delegate for injecting accessiblity functionality.
3098     */
3099    AccessibilityDelegate mAccessibilityDelegate;
3100
3101    /**
3102     * Consistency verifier for debugging purposes.
3103     * @hide
3104     */
3105    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3106            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3107                    new InputEventConsistencyVerifier(this, 0) : null;
3108
3109    /**
3110     * Constructor that is called when inflating a view from XML. This is called
3111     * when a view is being constructed from an XML file, supplying attributes
3112     * that were specified in the XML file. This version uses a default style of
3113     * 0, so the only attribute values applied are those in the Context's Theme
3114     * and the given AttributeSet.
3115     *
3116     * <p>
3117     * The method onFinishInflate() will be called after all children have been
3118     * added.
3119     *
3120     * @param context The Context the view is running in, through which it can
3121     *        access the current theme, resources, etc.
3122     * @param attrs The attributes of the XML tag that is inflating the view.
3123     * @see #View(Context, AttributeSet, int)
3124     */
3125    public View(Context context, AttributeSet attrs) {
3126        this(context, attrs, 0);
3127    }
3128
3129    /**
3130     * Perform inflation from XML and apply a class-specific base style. This
3131     * constructor of View allows subclasses to use their own base style when
3132     * they are inflating. For example, a Button class's constructor would call
3133     * this version of the super class constructor and supply
3134     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3135     * the theme's button style to modify all of the base view attributes (in
3136     * particular its background) as well as the Button class's attributes.
3137     *
3138     * @param context The Context the view is running in, through which it can
3139     *        access the current theme, resources, etc.
3140     * @param attrs The attributes of the XML tag that is inflating the view.
3141     * @param defStyle The default style to apply to this view. If 0, no style
3142     *        will be applied (beyond what is included in the theme). This may
3143     *        either be an attribute resource, whose value will be retrieved
3144     *        from the current theme, or an explicit style resource.
3145     * @see #View(Context, AttributeSet)
3146     */
3147    public View(Context context, AttributeSet attrs, int defStyle) {
3148        this(context);
3149
3150        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3151                defStyle, 0);
3152
3153        Drawable background = null;
3154
3155        int leftPadding = -1;
3156        int topPadding = -1;
3157        int rightPadding = -1;
3158        int bottomPadding = -1;
3159        int startPadding = -1;
3160        int endPadding = -1;
3161
3162        int padding = -1;
3163
3164        int viewFlagValues = 0;
3165        int viewFlagMasks = 0;
3166
3167        boolean setScrollContainer = false;
3168
3169        int x = 0;
3170        int y = 0;
3171
3172        float tx = 0;
3173        float ty = 0;
3174        float rotation = 0;
3175        float rotationX = 0;
3176        float rotationY = 0;
3177        float sx = 1f;
3178        float sy = 1f;
3179        boolean transformSet = false;
3180
3181        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3182
3183        int overScrollMode = mOverScrollMode;
3184        final int N = a.getIndexCount();
3185        for (int i = 0; i < N; i++) {
3186            int attr = a.getIndex(i);
3187            switch (attr) {
3188                case com.android.internal.R.styleable.View_background:
3189                    background = a.getDrawable(attr);
3190                    break;
3191                case com.android.internal.R.styleable.View_padding:
3192                    padding = a.getDimensionPixelSize(attr, -1);
3193                    break;
3194                 case com.android.internal.R.styleable.View_paddingLeft:
3195                    leftPadding = a.getDimensionPixelSize(attr, -1);
3196                    break;
3197                case com.android.internal.R.styleable.View_paddingTop:
3198                    topPadding = a.getDimensionPixelSize(attr, -1);
3199                    break;
3200                case com.android.internal.R.styleable.View_paddingRight:
3201                    rightPadding = a.getDimensionPixelSize(attr, -1);
3202                    break;
3203                case com.android.internal.R.styleable.View_paddingBottom:
3204                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3205                    break;
3206                case com.android.internal.R.styleable.View_paddingStart:
3207                    startPadding = a.getDimensionPixelSize(attr, -1);
3208                    break;
3209                case com.android.internal.R.styleable.View_paddingEnd:
3210                    endPadding = a.getDimensionPixelSize(attr, -1);
3211                    break;
3212                case com.android.internal.R.styleable.View_scrollX:
3213                    x = a.getDimensionPixelOffset(attr, 0);
3214                    break;
3215                case com.android.internal.R.styleable.View_scrollY:
3216                    y = a.getDimensionPixelOffset(attr, 0);
3217                    break;
3218                case com.android.internal.R.styleable.View_alpha:
3219                    setAlpha(a.getFloat(attr, 1f));
3220                    break;
3221                case com.android.internal.R.styleable.View_transformPivotX:
3222                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3223                    break;
3224                case com.android.internal.R.styleable.View_transformPivotY:
3225                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3226                    break;
3227                case com.android.internal.R.styleable.View_translationX:
3228                    tx = a.getDimensionPixelOffset(attr, 0);
3229                    transformSet = true;
3230                    break;
3231                case com.android.internal.R.styleable.View_translationY:
3232                    ty = a.getDimensionPixelOffset(attr, 0);
3233                    transformSet = true;
3234                    break;
3235                case com.android.internal.R.styleable.View_rotation:
3236                    rotation = a.getFloat(attr, 0);
3237                    transformSet = true;
3238                    break;
3239                case com.android.internal.R.styleable.View_rotationX:
3240                    rotationX = a.getFloat(attr, 0);
3241                    transformSet = true;
3242                    break;
3243                case com.android.internal.R.styleable.View_rotationY:
3244                    rotationY = a.getFloat(attr, 0);
3245                    transformSet = true;
3246                    break;
3247                case com.android.internal.R.styleable.View_scaleX:
3248                    sx = a.getFloat(attr, 1f);
3249                    transformSet = true;
3250                    break;
3251                case com.android.internal.R.styleable.View_scaleY:
3252                    sy = a.getFloat(attr, 1f);
3253                    transformSet = true;
3254                    break;
3255                case com.android.internal.R.styleable.View_id:
3256                    mID = a.getResourceId(attr, NO_ID);
3257                    break;
3258                case com.android.internal.R.styleable.View_tag:
3259                    mTag = a.getText(attr);
3260                    break;
3261                case com.android.internal.R.styleable.View_fitsSystemWindows:
3262                    if (a.getBoolean(attr, false)) {
3263                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3264                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3265                    }
3266                    break;
3267                case com.android.internal.R.styleable.View_focusable:
3268                    if (a.getBoolean(attr, false)) {
3269                        viewFlagValues |= FOCUSABLE;
3270                        viewFlagMasks |= FOCUSABLE_MASK;
3271                    }
3272                    break;
3273                case com.android.internal.R.styleable.View_focusableInTouchMode:
3274                    if (a.getBoolean(attr, false)) {
3275                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3276                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3277                    }
3278                    break;
3279                case com.android.internal.R.styleable.View_clickable:
3280                    if (a.getBoolean(attr, false)) {
3281                        viewFlagValues |= CLICKABLE;
3282                        viewFlagMasks |= CLICKABLE;
3283                    }
3284                    break;
3285                case com.android.internal.R.styleable.View_longClickable:
3286                    if (a.getBoolean(attr, false)) {
3287                        viewFlagValues |= LONG_CLICKABLE;
3288                        viewFlagMasks |= LONG_CLICKABLE;
3289                    }
3290                    break;
3291                case com.android.internal.R.styleable.View_saveEnabled:
3292                    if (!a.getBoolean(attr, true)) {
3293                        viewFlagValues |= SAVE_DISABLED;
3294                        viewFlagMasks |= SAVE_DISABLED_MASK;
3295                    }
3296                    break;
3297                case com.android.internal.R.styleable.View_duplicateParentState:
3298                    if (a.getBoolean(attr, false)) {
3299                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3300                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3301                    }
3302                    break;
3303                case com.android.internal.R.styleable.View_visibility:
3304                    final int visibility = a.getInt(attr, 0);
3305                    if (visibility != 0) {
3306                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3307                        viewFlagMasks |= VISIBILITY_MASK;
3308                    }
3309                    break;
3310                case com.android.internal.R.styleable.View_layoutDirection:
3311                    // Clear any layout direction flags (included resolved bits) already set
3312                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3313                    // Set the layout direction flags depending on the value of the attribute
3314                    final int layoutDirection = a.getInt(attr, -1);
3315                    final int value = (layoutDirection != -1) ?
3316                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3317                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3318                    break;
3319                case com.android.internal.R.styleable.View_drawingCacheQuality:
3320                    final int cacheQuality = a.getInt(attr, 0);
3321                    if (cacheQuality != 0) {
3322                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3323                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3324                    }
3325                    break;
3326                case com.android.internal.R.styleable.View_contentDescription:
3327                    mContentDescription = a.getString(attr);
3328                    break;
3329                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3330                    if (!a.getBoolean(attr, true)) {
3331                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3332                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3333                    }
3334                    break;
3335                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3336                    if (!a.getBoolean(attr, true)) {
3337                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3338                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3339                    }
3340                    break;
3341                case R.styleable.View_scrollbars:
3342                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3343                    if (scrollbars != SCROLLBARS_NONE) {
3344                        viewFlagValues |= scrollbars;
3345                        viewFlagMasks |= SCROLLBARS_MASK;
3346                        initializeScrollbars(a);
3347                    }
3348                    break;
3349                //noinspection deprecation
3350                case R.styleable.View_fadingEdge:
3351                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3352                        // Ignore the attribute starting with ICS
3353                        break;
3354                    }
3355                    // With builds < ICS, fall through and apply fading edges
3356                case R.styleable.View_requiresFadingEdge:
3357                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3358                    if (fadingEdge != FADING_EDGE_NONE) {
3359                        viewFlagValues |= fadingEdge;
3360                        viewFlagMasks |= FADING_EDGE_MASK;
3361                        initializeFadingEdge(a);
3362                    }
3363                    break;
3364                case R.styleable.View_scrollbarStyle:
3365                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3366                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3367                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3368                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3369                    }
3370                    break;
3371                case R.styleable.View_isScrollContainer:
3372                    setScrollContainer = true;
3373                    if (a.getBoolean(attr, false)) {
3374                        setScrollContainer(true);
3375                    }
3376                    break;
3377                case com.android.internal.R.styleable.View_keepScreenOn:
3378                    if (a.getBoolean(attr, false)) {
3379                        viewFlagValues |= KEEP_SCREEN_ON;
3380                        viewFlagMasks |= KEEP_SCREEN_ON;
3381                    }
3382                    break;
3383                case R.styleable.View_filterTouchesWhenObscured:
3384                    if (a.getBoolean(attr, false)) {
3385                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3386                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3387                    }
3388                    break;
3389                case R.styleable.View_nextFocusLeft:
3390                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3391                    break;
3392                case R.styleable.View_nextFocusRight:
3393                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3394                    break;
3395                case R.styleable.View_nextFocusUp:
3396                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3397                    break;
3398                case R.styleable.View_nextFocusDown:
3399                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3400                    break;
3401                case R.styleable.View_nextFocusForward:
3402                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3403                    break;
3404                case R.styleable.View_minWidth:
3405                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3406                    break;
3407                case R.styleable.View_minHeight:
3408                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3409                    break;
3410                case R.styleable.View_onClick:
3411                    if (context.isRestricted()) {
3412                        throw new IllegalStateException("The android:onClick attribute cannot "
3413                                + "be used within a restricted context");
3414                    }
3415
3416                    final String handlerName = a.getString(attr);
3417                    if (handlerName != null) {
3418                        setOnClickListener(new OnClickListener() {
3419                            private Method mHandler;
3420
3421                            public void onClick(View v) {
3422                                if (mHandler == null) {
3423                                    try {
3424                                        mHandler = getContext().getClass().getMethod(handlerName,
3425                                                View.class);
3426                                    } catch (NoSuchMethodException e) {
3427                                        int id = getId();
3428                                        String idText = id == NO_ID ? "" : " with id '"
3429                                                + getContext().getResources().getResourceEntryName(
3430                                                    id) + "'";
3431                                        throw new IllegalStateException("Could not find a method " +
3432                                                handlerName + "(View) in the activity "
3433                                                + getContext().getClass() + " for onClick handler"
3434                                                + " on view " + View.this.getClass() + idText, e);
3435                                    }
3436                                }
3437
3438                                try {
3439                                    mHandler.invoke(getContext(), View.this);
3440                                } catch (IllegalAccessException e) {
3441                                    throw new IllegalStateException("Could not execute non "
3442                                            + "public method of the activity", e);
3443                                } catch (InvocationTargetException e) {
3444                                    throw new IllegalStateException("Could not execute "
3445                                            + "method of the activity", e);
3446                                }
3447                            }
3448                        });
3449                    }
3450                    break;
3451                case R.styleable.View_overScrollMode:
3452                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3453                    break;
3454                case R.styleable.View_verticalScrollbarPosition:
3455                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3456                    break;
3457                case R.styleable.View_layerType:
3458                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3459                    break;
3460                case R.styleable.View_textDirection:
3461                    // Clear any text direction flag already set
3462                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3463                    // Set the text direction flags depending on the value of the attribute
3464                    final int textDirection = a.getInt(attr, -1);
3465                    if (textDirection != -1) {
3466                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3467                    }
3468                    break;
3469                case R.styleable.View_textAlignment:
3470                    // Clear any text alignment flag already set
3471                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3472                    // Set the text alignment flag depending on the value of the attribute
3473                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3474                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3475                    break;
3476                case R.styleable.View_importantForAccessibility:
3477                    setImportantForAccessibility(a.getInt(attr,
3478                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3479            }
3480        }
3481
3482        a.recycle();
3483
3484        setOverScrollMode(overScrollMode);
3485
3486        if (background != null) {
3487            setBackground(background);
3488        }
3489
3490        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3491        // layout direction). Those cached values will be used later during padding resolution.
3492        mUserPaddingStart = startPadding;
3493        mUserPaddingEnd = endPadding;
3494
3495        updateUserPaddingRelative();
3496
3497        if (padding >= 0) {
3498            leftPadding = padding;
3499            topPadding = padding;
3500            rightPadding = padding;
3501            bottomPadding = padding;
3502        }
3503
3504        // If the user specified the padding (either with android:padding or
3505        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3506        // use the default padding or the padding from the background drawable
3507        // (stored at this point in mPadding*)
3508        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3509                topPadding >= 0 ? topPadding : mPaddingTop,
3510                rightPadding >= 0 ? rightPadding : mPaddingRight,
3511                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3512
3513        if (viewFlagMasks != 0) {
3514            setFlags(viewFlagValues, viewFlagMasks);
3515        }
3516
3517        // Needs to be called after mViewFlags is set
3518        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3519            recomputePadding();
3520        }
3521
3522        if (x != 0 || y != 0) {
3523            scrollTo(x, y);
3524        }
3525
3526        if (transformSet) {
3527            setTranslationX(tx);
3528            setTranslationY(ty);
3529            setRotation(rotation);
3530            setRotationX(rotationX);
3531            setRotationY(rotationY);
3532            setScaleX(sx);
3533            setScaleY(sy);
3534        }
3535
3536        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3537            setScrollContainer(true);
3538        }
3539
3540        computeOpaqueFlags();
3541    }
3542
3543    private void updateUserPaddingRelative() {
3544        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3545    }
3546
3547    /**
3548     * Non-public constructor for use in testing
3549     */
3550    View() {
3551        mResources = null;
3552    }
3553
3554    /**
3555     * <p>
3556     * Initializes the fading edges from a given set of styled attributes. This
3557     * method should be called by subclasses that need fading edges and when an
3558     * instance of these subclasses is created programmatically rather than
3559     * being inflated from XML. This method is automatically called when the XML
3560     * is inflated.
3561     * </p>
3562     *
3563     * @param a the styled attributes set to initialize the fading edges from
3564     */
3565    protected void initializeFadingEdge(TypedArray a) {
3566        initScrollCache();
3567
3568        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3569                R.styleable.View_fadingEdgeLength,
3570                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3571    }
3572
3573    /**
3574     * Returns the size of the vertical faded edges used to indicate that more
3575     * content in this view is visible.
3576     *
3577     * @return The size in pixels of the vertical faded edge or 0 if vertical
3578     *         faded edges are not enabled for this view.
3579     * @attr ref android.R.styleable#View_fadingEdgeLength
3580     */
3581    public int getVerticalFadingEdgeLength() {
3582        if (isVerticalFadingEdgeEnabled()) {
3583            ScrollabilityCache cache = mScrollCache;
3584            if (cache != null) {
3585                return cache.fadingEdgeLength;
3586            }
3587        }
3588        return 0;
3589    }
3590
3591    /**
3592     * Set the size of the faded edge used to indicate that more content in this
3593     * view is available.  Will not change whether the fading edge is enabled; use
3594     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3595     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3596     * for the vertical or horizontal fading edges.
3597     *
3598     * @param length The size in pixels of the faded edge used to indicate that more
3599     *        content in this view is visible.
3600     */
3601    public void setFadingEdgeLength(int length) {
3602        initScrollCache();
3603        mScrollCache.fadingEdgeLength = length;
3604    }
3605
3606    /**
3607     * Returns the size of the horizontal faded edges used to indicate that more
3608     * content in this view is visible.
3609     *
3610     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3611     *         faded edges are not enabled for this view.
3612     * @attr ref android.R.styleable#View_fadingEdgeLength
3613     */
3614    public int getHorizontalFadingEdgeLength() {
3615        if (isHorizontalFadingEdgeEnabled()) {
3616            ScrollabilityCache cache = mScrollCache;
3617            if (cache != null) {
3618                return cache.fadingEdgeLength;
3619            }
3620        }
3621        return 0;
3622    }
3623
3624    /**
3625     * Returns the width of the vertical scrollbar.
3626     *
3627     * @return The width in pixels of the vertical scrollbar or 0 if there
3628     *         is no vertical scrollbar.
3629     */
3630    public int getVerticalScrollbarWidth() {
3631        ScrollabilityCache cache = mScrollCache;
3632        if (cache != null) {
3633            ScrollBarDrawable scrollBar = cache.scrollBar;
3634            if (scrollBar != null) {
3635                int size = scrollBar.getSize(true);
3636                if (size <= 0) {
3637                    size = cache.scrollBarSize;
3638                }
3639                return size;
3640            }
3641            return 0;
3642        }
3643        return 0;
3644    }
3645
3646    /**
3647     * Returns the height of the horizontal scrollbar.
3648     *
3649     * @return The height in pixels of the horizontal scrollbar or 0 if
3650     *         there is no horizontal scrollbar.
3651     */
3652    protected int getHorizontalScrollbarHeight() {
3653        ScrollabilityCache cache = mScrollCache;
3654        if (cache != null) {
3655            ScrollBarDrawable scrollBar = cache.scrollBar;
3656            if (scrollBar != null) {
3657                int size = scrollBar.getSize(false);
3658                if (size <= 0) {
3659                    size = cache.scrollBarSize;
3660                }
3661                return size;
3662            }
3663            return 0;
3664        }
3665        return 0;
3666    }
3667
3668    /**
3669     * <p>
3670     * Initializes the scrollbars from a given set of styled attributes. This
3671     * method should be called by subclasses that need scrollbars and when an
3672     * instance of these subclasses is created programmatically rather than
3673     * being inflated from XML. This method is automatically called when the XML
3674     * is inflated.
3675     * </p>
3676     *
3677     * @param a the styled attributes set to initialize the scrollbars from
3678     */
3679    protected void initializeScrollbars(TypedArray a) {
3680        initScrollCache();
3681
3682        final ScrollabilityCache scrollabilityCache = mScrollCache;
3683
3684        if (scrollabilityCache.scrollBar == null) {
3685            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3686        }
3687
3688        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3689
3690        if (!fadeScrollbars) {
3691            scrollabilityCache.state = ScrollabilityCache.ON;
3692        }
3693        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3694
3695
3696        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3697                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3698                        .getScrollBarFadeDuration());
3699        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3700                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3701                ViewConfiguration.getScrollDefaultDelay());
3702
3703
3704        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3705                com.android.internal.R.styleable.View_scrollbarSize,
3706                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3707
3708        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3709        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3710
3711        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3712        if (thumb != null) {
3713            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3714        }
3715
3716        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3717                false);
3718        if (alwaysDraw) {
3719            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3720        }
3721
3722        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3723        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3724
3725        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3726        if (thumb != null) {
3727            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3728        }
3729
3730        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3731                false);
3732        if (alwaysDraw) {
3733            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3734        }
3735
3736        // Re-apply user/background padding so that scrollbar(s) get added
3737        resolvePadding();
3738    }
3739
3740    /**
3741     * <p>
3742     * Initalizes the scrollability cache if necessary.
3743     * </p>
3744     */
3745    private void initScrollCache() {
3746        if (mScrollCache == null) {
3747            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3748        }
3749    }
3750
3751    private ScrollabilityCache getScrollCache() {
3752        initScrollCache();
3753        return mScrollCache;
3754    }
3755
3756    /**
3757     * Set the position of the vertical scroll bar. Should be one of
3758     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3759     * {@link #SCROLLBAR_POSITION_RIGHT}.
3760     *
3761     * @param position Where the vertical scroll bar should be positioned.
3762     */
3763    public void setVerticalScrollbarPosition(int position) {
3764        if (mVerticalScrollbarPosition != position) {
3765            mVerticalScrollbarPosition = position;
3766            computeOpaqueFlags();
3767            resolvePadding();
3768        }
3769    }
3770
3771    /**
3772     * @return The position where the vertical scroll bar will show, if applicable.
3773     * @see #setVerticalScrollbarPosition(int)
3774     */
3775    public int getVerticalScrollbarPosition() {
3776        return mVerticalScrollbarPosition;
3777    }
3778
3779    ListenerInfo getListenerInfo() {
3780        if (mListenerInfo != null) {
3781            return mListenerInfo;
3782        }
3783        mListenerInfo = new ListenerInfo();
3784        return mListenerInfo;
3785    }
3786
3787    /**
3788     * Register a callback to be invoked when focus of this view changed.
3789     *
3790     * @param l The callback that will run.
3791     */
3792    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3793        getListenerInfo().mOnFocusChangeListener = l;
3794    }
3795
3796    /**
3797     * Add a listener that will be called when the bounds of the view change due to
3798     * layout processing.
3799     *
3800     * @param listener The listener that will be called when layout bounds change.
3801     */
3802    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3803        ListenerInfo li = getListenerInfo();
3804        if (li.mOnLayoutChangeListeners == null) {
3805            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3806        }
3807        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3808            li.mOnLayoutChangeListeners.add(listener);
3809        }
3810    }
3811
3812    /**
3813     * Remove a listener for layout changes.
3814     *
3815     * @param listener The listener for layout bounds change.
3816     */
3817    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3818        ListenerInfo li = mListenerInfo;
3819        if (li == null || li.mOnLayoutChangeListeners == null) {
3820            return;
3821        }
3822        li.mOnLayoutChangeListeners.remove(listener);
3823    }
3824
3825    /**
3826     * Add a listener for attach state changes.
3827     *
3828     * This listener will be called whenever this view is attached or detached
3829     * from a window. Remove the listener using
3830     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3831     *
3832     * @param listener Listener to attach
3833     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3834     */
3835    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3836        ListenerInfo li = getListenerInfo();
3837        if (li.mOnAttachStateChangeListeners == null) {
3838            li.mOnAttachStateChangeListeners
3839                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3840        }
3841        li.mOnAttachStateChangeListeners.add(listener);
3842    }
3843
3844    /**
3845     * Remove a listener for attach state changes. The listener will receive no further
3846     * notification of window attach/detach events.
3847     *
3848     * @param listener Listener to remove
3849     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3850     */
3851    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3852        ListenerInfo li = mListenerInfo;
3853        if (li == null || li.mOnAttachStateChangeListeners == null) {
3854            return;
3855        }
3856        li.mOnAttachStateChangeListeners.remove(listener);
3857    }
3858
3859    /**
3860     * Returns the focus-change callback registered for this view.
3861     *
3862     * @return The callback, or null if one is not registered.
3863     */
3864    public OnFocusChangeListener getOnFocusChangeListener() {
3865        ListenerInfo li = mListenerInfo;
3866        return li != null ? li.mOnFocusChangeListener : null;
3867    }
3868
3869    /**
3870     * Register a callback to be invoked when this view is clicked. If this view is not
3871     * clickable, it becomes clickable.
3872     *
3873     * @param l The callback that will run
3874     *
3875     * @see #setClickable(boolean)
3876     */
3877    public void setOnClickListener(OnClickListener l) {
3878        if (!isClickable()) {
3879            setClickable(true);
3880        }
3881        getListenerInfo().mOnClickListener = l;
3882    }
3883
3884    /**
3885     * Return whether this view has an attached OnClickListener.  Returns
3886     * true if there is a listener, false if there is none.
3887     */
3888    public boolean hasOnClickListeners() {
3889        ListenerInfo li = mListenerInfo;
3890        return (li != null && li.mOnClickListener != null);
3891    }
3892
3893    /**
3894     * Register a callback to be invoked when this view is clicked and held. If this view is not
3895     * long clickable, it becomes long clickable.
3896     *
3897     * @param l The callback that will run
3898     *
3899     * @see #setLongClickable(boolean)
3900     */
3901    public void setOnLongClickListener(OnLongClickListener l) {
3902        if (!isLongClickable()) {
3903            setLongClickable(true);
3904        }
3905        getListenerInfo().mOnLongClickListener = l;
3906    }
3907
3908    /**
3909     * Register a callback to be invoked when the context menu for this view is
3910     * being built. If this view is not long clickable, it becomes long clickable.
3911     *
3912     * @param l The callback that will run
3913     *
3914     */
3915    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3916        if (!isLongClickable()) {
3917            setLongClickable(true);
3918        }
3919        getListenerInfo().mOnCreateContextMenuListener = l;
3920    }
3921
3922    /**
3923     * Call this view's OnClickListener, if it is defined.  Performs all normal
3924     * actions associated with clicking: reporting accessibility event, playing
3925     * a sound, etc.
3926     *
3927     * @return True there was an assigned OnClickListener that was called, false
3928     *         otherwise is returned.
3929     */
3930    public boolean performClick() {
3931        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3932
3933        ListenerInfo li = mListenerInfo;
3934        if (li != null && li.mOnClickListener != null) {
3935            playSoundEffect(SoundEffectConstants.CLICK);
3936            li.mOnClickListener.onClick(this);
3937            return true;
3938        }
3939
3940        return false;
3941    }
3942
3943    /**
3944     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3945     * this only calls the listener, and does not do any associated clicking
3946     * actions like reporting an accessibility event.
3947     *
3948     * @return True there was an assigned OnClickListener that was called, false
3949     *         otherwise is returned.
3950     */
3951    public boolean callOnClick() {
3952        ListenerInfo li = mListenerInfo;
3953        if (li != null && li.mOnClickListener != null) {
3954            li.mOnClickListener.onClick(this);
3955            return true;
3956        }
3957        return false;
3958    }
3959
3960    /**
3961     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3962     * OnLongClickListener did not consume the event.
3963     *
3964     * @return True if one of the above receivers consumed the event, false otherwise.
3965     */
3966    public boolean performLongClick() {
3967        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3968
3969        boolean handled = false;
3970        ListenerInfo li = mListenerInfo;
3971        if (li != null && li.mOnLongClickListener != null) {
3972            handled = li.mOnLongClickListener.onLongClick(View.this);
3973        }
3974        if (!handled) {
3975            handled = showContextMenu();
3976        }
3977        if (handled) {
3978            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3979        }
3980        return handled;
3981    }
3982
3983    /**
3984     * Performs button-related actions during a touch down event.
3985     *
3986     * @param event The event.
3987     * @return True if the down was consumed.
3988     *
3989     * @hide
3990     */
3991    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3992        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3993            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3994                return true;
3995            }
3996        }
3997        return false;
3998    }
3999
4000    /**
4001     * Bring up the context menu for this view.
4002     *
4003     * @return Whether a context menu was displayed.
4004     */
4005    public boolean showContextMenu() {
4006        return getParent().showContextMenuForChild(this);
4007    }
4008
4009    /**
4010     * Bring up the context menu for this view, referring to the item under the specified point.
4011     *
4012     * @param x The referenced x coordinate.
4013     * @param y The referenced y coordinate.
4014     * @param metaState The keyboard modifiers that were pressed.
4015     * @return Whether a context menu was displayed.
4016     *
4017     * @hide
4018     */
4019    public boolean showContextMenu(float x, float y, int metaState) {
4020        return showContextMenu();
4021    }
4022
4023    /**
4024     * Start an action mode.
4025     *
4026     * @param callback Callback that will control the lifecycle of the action mode
4027     * @return The new action mode if it is started, null otherwise
4028     *
4029     * @see ActionMode
4030     */
4031    public ActionMode startActionMode(ActionMode.Callback callback) {
4032        ViewParent parent = getParent();
4033        if (parent == null) return null;
4034        return parent.startActionModeForChild(this, callback);
4035    }
4036
4037    /**
4038     * Register a callback to be invoked when a key is pressed in this view.
4039     * @param l the key listener to attach to this view
4040     */
4041    public void setOnKeyListener(OnKeyListener l) {
4042        getListenerInfo().mOnKeyListener = l;
4043    }
4044
4045    /**
4046     * Register a callback to be invoked when a touch event is sent to this view.
4047     * @param l the touch listener to attach to this view
4048     */
4049    public void setOnTouchListener(OnTouchListener l) {
4050        getListenerInfo().mOnTouchListener = l;
4051    }
4052
4053    /**
4054     * Register a callback to be invoked when a generic motion event is sent to this view.
4055     * @param l the generic motion listener to attach to this view
4056     */
4057    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4058        getListenerInfo().mOnGenericMotionListener = l;
4059    }
4060
4061    /**
4062     * Register a callback to be invoked when a hover event is sent to this view.
4063     * @param l the hover listener to attach to this view
4064     */
4065    public void setOnHoverListener(OnHoverListener l) {
4066        getListenerInfo().mOnHoverListener = l;
4067    }
4068
4069    /**
4070     * Register a drag event listener callback object for this View. The parameter is
4071     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4072     * View, the system calls the
4073     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4074     * @param l An implementation of {@link android.view.View.OnDragListener}.
4075     */
4076    public void setOnDragListener(OnDragListener l) {
4077        getListenerInfo().mOnDragListener = l;
4078    }
4079
4080    /**
4081     * Give this view focus. This will cause
4082     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4083     *
4084     * Note: this does not check whether this {@link View} should get focus, it just
4085     * gives it focus no matter what.  It should only be called internally by framework
4086     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4087     *
4088     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4089     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4090     *        focus moved when requestFocus() is called. It may not always
4091     *        apply, in which case use the default View.FOCUS_DOWN.
4092     * @param previouslyFocusedRect The rectangle of the view that had focus
4093     *        prior in this View's coordinate system.
4094     */
4095    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4096        if (DBG) {
4097            System.out.println(this + " requestFocus()");
4098        }
4099
4100        if ((mPrivateFlags & FOCUSED) == 0) {
4101            mPrivateFlags |= FOCUSED;
4102
4103            if (mParent != null) {
4104                mParent.requestChildFocus(this, this);
4105            }
4106
4107            onFocusChanged(true, direction, previouslyFocusedRect);
4108            refreshDrawableState();
4109
4110            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4111                notifyAccessibilityStateChanged();
4112            }
4113        }
4114    }
4115
4116    /**
4117     * Request that a rectangle of this view be visible on the screen,
4118     * scrolling if necessary just enough.
4119     *
4120     * <p>A View should call this if it maintains some notion of which part
4121     * of its content is interesting.  For example, a text editing view
4122     * should call this when its cursor moves.
4123     *
4124     * @param rectangle The rectangle.
4125     * @return Whether any parent scrolled.
4126     */
4127    public boolean requestRectangleOnScreen(Rect rectangle) {
4128        return requestRectangleOnScreen(rectangle, false);
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     * <p>When <code>immediate</code> is set to true, scrolling will not be
4140     * animated.
4141     *
4142     * @param rectangle The rectangle.
4143     * @param immediate True to forbid animated scrolling, false otherwise
4144     * @return Whether any parent scrolled.
4145     */
4146    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4147        View child = this;
4148        ViewParent parent = mParent;
4149        boolean scrolled = false;
4150        while (parent != null) {
4151            scrolled |= parent.requestChildRectangleOnScreen(child,
4152                    rectangle, immediate);
4153
4154            // offset rect so next call has the rectangle in the
4155            // coordinate system of its direct child.
4156            rectangle.offset(child.getLeft(), child.getTop());
4157            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4158
4159            if (!(parent instanceof View)) {
4160                break;
4161            }
4162
4163            child = (View) parent;
4164            parent = child.getParent();
4165        }
4166        return scrolled;
4167    }
4168
4169    /**
4170     * Called when this view wants to give up focus. If focus is cleared
4171     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4172     * <p>
4173     * <strong>Note:</strong> When a View clears focus the framework is trying
4174     * to give focus to the first focusable View from the top. Hence, if this
4175     * View is the first from the top that can take focus, then all callbacks
4176     * related to clearing focus will be invoked after wich the framework will
4177     * give focus to this view.
4178     * </p>
4179     */
4180    public void clearFocus() {
4181        if (DBG) {
4182            System.out.println(this + " clearFocus()");
4183        }
4184
4185        if ((mPrivateFlags & FOCUSED) != 0) {
4186            mPrivateFlags &= ~FOCUSED;
4187
4188            if (mParent != null) {
4189                mParent.clearChildFocus(this);
4190            }
4191
4192            onFocusChanged(false, 0, null);
4193
4194            refreshDrawableState();
4195
4196            ensureInputFocusOnFirstFocusable();
4197
4198            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4199                notifyAccessibilityStateChanged();
4200            }
4201        }
4202    }
4203
4204    void ensureInputFocusOnFirstFocusable() {
4205        View root = getRootView();
4206        if (root != null) {
4207            root.requestFocus();
4208        }
4209    }
4210
4211    /**
4212     * Called internally by the view system when a new view is getting focus.
4213     * This is what clears the old focus.
4214     */
4215    void unFocus() {
4216        if (DBG) {
4217            System.out.println(this + " unFocus()");
4218        }
4219
4220        if ((mPrivateFlags & FOCUSED) != 0) {
4221            mPrivateFlags &= ~FOCUSED;
4222
4223            onFocusChanged(false, 0, null);
4224            refreshDrawableState();
4225
4226            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4227                notifyAccessibilityStateChanged();
4228            }
4229        }
4230    }
4231
4232    /**
4233     * Returns true if this view has focus iteself, or is the ancestor of the
4234     * view that has focus.
4235     *
4236     * @return True if this view has or contains focus, false otherwise.
4237     */
4238    @ViewDebug.ExportedProperty(category = "focus")
4239    public boolean hasFocus() {
4240        return (mPrivateFlags & FOCUSED) != 0;
4241    }
4242
4243    /**
4244     * Returns true if this view is focusable or if it contains a reachable View
4245     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4246     * is a View whose parents do not block descendants focus.
4247     *
4248     * Only {@link #VISIBLE} views are considered focusable.
4249     *
4250     * @return True if the view is focusable or if the view contains a focusable
4251     *         View, false otherwise.
4252     *
4253     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4254     */
4255    public boolean hasFocusable() {
4256        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4257    }
4258
4259    /**
4260     * Called by the view system when the focus state of this view changes.
4261     * When the focus change event is caused by directional navigation, direction
4262     * and previouslyFocusedRect provide insight into where the focus is coming from.
4263     * When overriding, be sure to call up through to the super class so that
4264     * the standard focus handling will occur.
4265     *
4266     * @param gainFocus True if the View has focus; false otherwise.
4267     * @param direction The direction focus has moved when requestFocus()
4268     *                  is called to give this view focus. Values are
4269     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4270     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4271     *                  It may not always apply, in which case use the default.
4272     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4273     *        system, of the previously focused view.  If applicable, this will be
4274     *        passed in as finer grained information about where the focus is coming
4275     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4276     */
4277    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4278        if (gainFocus) {
4279            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4280                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4281                requestAccessibilityFocus();
4282            }
4283        }
4284
4285        InputMethodManager imm = InputMethodManager.peekInstance();
4286        if (!gainFocus) {
4287            if (isPressed()) {
4288                setPressed(false);
4289            }
4290            if (imm != null && mAttachInfo != null
4291                    && mAttachInfo.mHasWindowFocus) {
4292                imm.focusOut(this);
4293            }
4294            onFocusLost();
4295        } else if (imm != null && mAttachInfo != null
4296                && mAttachInfo.mHasWindowFocus) {
4297            imm.focusIn(this);
4298        }
4299
4300        invalidate(true);
4301        ListenerInfo li = mListenerInfo;
4302        if (li != null && li.mOnFocusChangeListener != null) {
4303            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4304        }
4305
4306        if (mAttachInfo != null) {
4307            mAttachInfo.mKeyDispatchState.reset(this);
4308        }
4309    }
4310
4311    /**
4312     * Sends an accessibility event of the given type. If accessiiblity is
4313     * not enabled this method has no effect. The default implementation calls
4314     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4315     * to populate information about the event source (this View), then calls
4316     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4317     * populate the text content of the event source including its descendants,
4318     * and last calls
4319     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4320     * on its parent to resuest sending of the event to interested parties.
4321     * <p>
4322     * If an {@link AccessibilityDelegate} has been specified via calling
4323     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4324     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4325     * responsible for handling this call.
4326     * </p>
4327     *
4328     * @param eventType The type of the event to send, as defined by several types from
4329     * {@link android.view.accessibility.AccessibilityEvent}, such as
4330     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4331     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4332     *
4333     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4334     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4335     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4336     * @see AccessibilityDelegate
4337     */
4338    public void sendAccessibilityEvent(int eventType) {
4339        if (mAccessibilityDelegate != null) {
4340            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4341        } else {
4342            sendAccessibilityEventInternal(eventType);
4343        }
4344    }
4345
4346    /**
4347     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4348     * {@link AccessibilityEvent} to make an announcement which is related to some
4349     * sort of a context change for which none of the events representing UI transitions
4350     * is a good fit. For example, announcing a new page in a book. If accessibility
4351     * is not enabled this method does nothing.
4352     *
4353     * @param text The announcement text.
4354     */
4355    public void announceForAccessibility(CharSequence text) {
4356        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4357            AccessibilityEvent event = AccessibilityEvent.obtain(
4358                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4359            event.getText().add(text);
4360            sendAccessibilityEventUnchecked(event);
4361        }
4362    }
4363
4364    /**
4365     * @see #sendAccessibilityEvent(int)
4366     *
4367     * Note: Called from the default {@link AccessibilityDelegate}.
4368     */
4369    void sendAccessibilityEventInternal(int eventType) {
4370        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4371            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4372        }
4373    }
4374
4375    /**
4376     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4377     * takes as an argument an empty {@link AccessibilityEvent} and does not
4378     * perform a check whether accessibility is enabled.
4379     * <p>
4380     * If an {@link AccessibilityDelegate} has been specified via calling
4381     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4382     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4383     * is responsible for handling this call.
4384     * </p>
4385     *
4386     * @param event The event to send.
4387     *
4388     * @see #sendAccessibilityEvent(int)
4389     */
4390    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4391        if (mAccessibilityDelegate != null) {
4392            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4393        } else {
4394            sendAccessibilityEventUncheckedInternal(event);
4395        }
4396    }
4397
4398    /**
4399     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4400     *
4401     * Note: Called from the default {@link AccessibilityDelegate}.
4402     */
4403    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4404        if (!isShown()) {
4405            return;
4406        }
4407        onInitializeAccessibilityEvent(event);
4408        // Only a subset of accessibility events populates text content.
4409        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4410            dispatchPopulateAccessibilityEvent(event);
4411        }
4412        // Intercept accessibility focus events fired by virtual nodes to keep
4413        // track of accessibility focus position in such nodes.
4414        final int eventType = event.getEventType();
4415        switch (eventType) {
4416            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4417                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4418                        event.getSourceNodeId());
4419                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4420                    ViewRootImpl viewRootImpl = getViewRootImpl();
4421                    if (viewRootImpl != null) {
4422                        viewRootImpl.setAccessibilityFocusedHost(this);
4423                    }
4424                }
4425            } break;
4426            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4427                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4428                        event.getSourceNodeId());
4429                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4430                    ViewRootImpl viewRootImpl = getViewRootImpl();
4431                    if (viewRootImpl != null) {
4432                        viewRootImpl.setAccessibilityFocusedHost(null);
4433                    }
4434                }
4435            } break;
4436        }
4437        // In the beginning we called #isShown(), so we know that getParent() is not null.
4438        getParent().requestSendAccessibilityEvent(this, event);
4439    }
4440
4441    /**
4442     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4443     * to its children for adding their text content to the event. Note that the
4444     * event text is populated in a separate dispatch path since we add to the
4445     * event not only the text of the source but also the text of all its descendants.
4446     * A typical implementation will call
4447     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4448     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4449     * on each child. Override this method if custom population of the event text
4450     * content is required.
4451     * <p>
4452     * If an {@link AccessibilityDelegate} has been specified via calling
4453     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4454     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4455     * is responsible for handling this call.
4456     * </p>
4457     * <p>
4458     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4459     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4460     * </p>
4461     *
4462     * @param event The event.
4463     *
4464     * @return True if the event population was completed.
4465     */
4466    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4467        if (mAccessibilityDelegate != null) {
4468            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4469        } else {
4470            return dispatchPopulateAccessibilityEventInternal(event);
4471        }
4472    }
4473
4474    /**
4475     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4476     *
4477     * Note: Called from the default {@link AccessibilityDelegate}.
4478     */
4479    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4480        onPopulateAccessibilityEvent(event);
4481        return false;
4482    }
4483
4484    /**
4485     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4486     * giving a chance to this View to populate the accessibility event with its
4487     * text content. While this method is free to modify event
4488     * attributes other than text content, doing so should normally be performed in
4489     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4490     * <p>
4491     * Example: Adding formatted date string to an accessibility event in addition
4492     *          to the text added by the super implementation:
4493     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4494     *     super.onPopulateAccessibilityEvent(event);
4495     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4496     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4497     *         mCurrentDate.getTimeInMillis(), flags);
4498     *     event.getText().add(selectedDateUtterance);
4499     * }</pre>
4500     * <p>
4501     * If an {@link AccessibilityDelegate} has been specified via calling
4502     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4503     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4504     * is responsible for handling this call.
4505     * </p>
4506     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4507     * information to the event, in case the default implementation has basic information to add.
4508     * </p>
4509     *
4510     * @param event The accessibility event which to populate.
4511     *
4512     * @see #sendAccessibilityEvent(int)
4513     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4514     */
4515    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4516        if (mAccessibilityDelegate != null) {
4517            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4518        } else {
4519            onPopulateAccessibilityEventInternal(event);
4520        }
4521    }
4522
4523    /**
4524     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4525     *
4526     * Note: Called from the default {@link AccessibilityDelegate}.
4527     */
4528    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4529
4530    }
4531
4532    /**
4533     * Initializes an {@link AccessibilityEvent} with information about
4534     * this View which is the event source. In other words, the source of
4535     * an accessibility event is the view whose state change triggered firing
4536     * the event.
4537     * <p>
4538     * Example: Setting the password property of an event in addition
4539     *          to properties set by the super implementation:
4540     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4541     *     super.onInitializeAccessibilityEvent(event);
4542     *     event.setPassword(true);
4543     * }</pre>
4544     * <p>
4545     * If an {@link AccessibilityDelegate} has been specified via calling
4546     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4547     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4548     * is responsible for handling this call.
4549     * </p>
4550     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4551     * information to the event, in case the default implementation has basic information to add.
4552     * </p>
4553     * @param event The event to initialize.
4554     *
4555     * @see #sendAccessibilityEvent(int)
4556     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4557     */
4558    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4559        if (mAccessibilityDelegate != null) {
4560            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4561        } else {
4562            onInitializeAccessibilityEventInternal(event);
4563        }
4564    }
4565
4566    /**
4567     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4568     *
4569     * Note: Called from the default {@link AccessibilityDelegate}.
4570     */
4571    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4572        event.setSource(this);
4573        event.setClassName(View.class.getName());
4574        event.setPackageName(getContext().getPackageName());
4575        event.setEnabled(isEnabled());
4576        event.setContentDescription(mContentDescription);
4577
4578        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4579            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4580            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4581                    FOCUSABLES_ALL);
4582            event.setItemCount(focusablesTempList.size());
4583            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4584            focusablesTempList.clear();
4585        }
4586    }
4587
4588    /**
4589     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4590     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4591     * This method is responsible for obtaining an accessibility node info from a
4592     * pool of reusable instances and calling
4593     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4594     * initialize the former.
4595     * <p>
4596     * Note: The client is responsible for recycling the obtained instance by calling
4597     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4598     * </p>
4599     *
4600     * @return A populated {@link AccessibilityNodeInfo}.
4601     *
4602     * @see AccessibilityNodeInfo
4603     */
4604    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4605        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4606        if (provider != null) {
4607            return provider.createAccessibilityNodeInfo(View.NO_ID);
4608        } else {
4609            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4610            onInitializeAccessibilityNodeInfo(info);
4611            return info;
4612        }
4613    }
4614
4615    /**
4616     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4617     * The base implementation sets:
4618     * <ul>
4619     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4620     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4621     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4622     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4623     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4624     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4625     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4626     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4627     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4628     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4629     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4630     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4631     * </ul>
4632     * <p>
4633     * Subclasses should override this method, call the super implementation,
4634     * and set additional attributes.
4635     * </p>
4636     * <p>
4637     * If an {@link AccessibilityDelegate} has been specified via calling
4638     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4639     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4640     * is responsible for handling this call.
4641     * </p>
4642     *
4643     * @param info The instance to initialize.
4644     */
4645    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4646        if (mAccessibilityDelegate != null) {
4647            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4648        } else {
4649            onInitializeAccessibilityNodeInfoInternal(info);
4650        }
4651    }
4652
4653    /**
4654     * Gets the location of this view in screen coordintates.
4655     *
4656     * @param outRect The output location
4657     */
4658    private void getBoundsOnScreen(Rect outRect) {
4659        if (mAttachInfo == null) {
4660            return;
4661        }
4662
4663        RectF position = mAttachInfo.mTmpTransformRect;
4664        position.setEmpty();
4665
4666        if (!hasIdentityMatrix()) {
4667            getMatrix().mapRect(position);
4668        }
4669
4670        position.offset(mLeft, mRight);
4671
4672        ViewParent parent = mParent;
4673        while (parent instanceof View) {
4674            View parentView = (View) parent;
4675
4676            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4677
4678            if (!parentView.hasIdentityMatrix()) {
4679                parentView.getMatrix().mapRect(position);
4680            }
4681
4682            position.offset(parentView.mLeft, parentView.mTop);
4683
4684            parent = parentView.mParent;
4685        }
4686
4687        if (parent instanceof ViewRootImpl) {
4688            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4689            position.offset(0, -viewRootImpl.mCurScrollY);
4690        }
4691
4692        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4693
4694        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4695                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4696    }
4697
4698    /**
4699     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4700     *
4701     * Note: Called from the default {@link AccessibilityDelegate}.
4702     */
4703    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4704        Rect bounds = mAttachInfo.mTmpInvalRect;
4705        getDrawingRect(bounds);
4706        info.setBoundsInParent(bounds);
4707
4708        getBoundsOnScreen(bounds);
4709        info.setBoundsInScreen(bounds);
4710
4711        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4712            ViewParent parent = getParentForAccessibility();
4713            if (parent instanceof View) {
4714                info.setParent((View) parent);
4715            }
4716        }
4717
4718        info.setVisibleToUser(isVisibleToUser());
4719
4720        info.setPackageName(mContext.getPackageName());
4721        info.setClassName(View.class.getName());
4722        info.setContentDescription(getContentDescription());
4723
4724        info.setEnabled(isEnabled());
4725        info.setClickable(isClickable());
4726        info.setFocusable(isFocusable());
4727        info.setFocused(isFocused());
4728        info.setAccessibilityFocused(isAccessibilityFocused());
4729        info.setSelected(isSelected());
4730        info.setLongClickable(isLongClickable());
4731
4732        // TODO: These make sense only if we are in an AdapterView but all
4733        // views can be selected. Maybe from accessiiblity perspective
4734        // we should report as selectable view in an AdapterView.
4735        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4736        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4737
4738        if (isFocusable()) {
4739            if (isFocused()) {
4740                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4741            } else {
4742                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4743            }
4744        }
4745
4746        if (!isAccessibilityFocused()) {
4747            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4748        } else {
4749            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4750        }
4751
4752        if (isClickable()) {
4753            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4754        }
4755
4756        if (isLongClickable()) {
4757            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4758        }
4759
4760        if (mContentDescription != null && mContentDescription.length() > 0) {
4761            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4762            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4763            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4764                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4765                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4766        }
4767    }
4768
4769    /**
4770     * Computes whether this view is visible to the user. Such a view is
4771     * attached, visible, all its predecessors are visible, it is not clipped
4772     * entirely by its predecessors, and has an alpha greater than zero.
4773     *
4774     * @return Whether the view is visible on the screen.
4775     */
4776    private boolean isVisibleToUser() {
4777        // The first two checks are made also made by isShown() which
4778        // however traverses the tree up to the parent to catch that.
4779        // Therefore, we do some fail fast check to minimize the up
4780        // tree traversal.
4781        return (mAttachInfo != null
4782                && mAttachInfo.mWindowVisibility == View.VISIBLE
4783                && getAlpha() > 0
4784                && isShown()
4785                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
4786    }
4787
4788    /**
4789     * Sets a delegate for implementing accessibility support via compositon as
4790     * opposed to inheritance. The delegate's primary use is for implementing
4791     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4792     *
4793     * @param delegate The delegate instance.
4794     *
4795     * @see AccessibilityDelegate
4796     */
4797    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4798        mAccessibilityDelegate = delegate;
4799    }
4800
4801    /**
4802     * Gets the provider for managing a virtual view hierarchy rooted at this View
4803     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4804     * that explore the window content.
4805     * <p>
4806     * If this method returns an instance, this instance is responsible for managing
4807     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4808     * View including the one representing the View itself. Similarly the returned
4809     * instance is responsible for performing accessibility actions on any virtual
4810     * view or the root view itself.
4811     * </p>
4812     * <p>
4813     * If an {@link AccessibilityDelegate} has been specified via calling
4814     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4815     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4816     * is responsible for handling this call.
4817     * </p>
4818     *
4819     * @return The provider.
4820     *
4821     * @see AccessibilityNodeProvider
4822     */
4823    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4824        if (mAccessibilityDelegate != null) {
4825            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4826        } else {
4827            return null;
4828        }
4829    }
4830
4831    /**
4832     * Gets the unique identifier of this view on the screen for accessibility purposes.
4833     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4834     *
4835     * @return The view accessibility id.
4836     *
4837     * @hide
4838     */
4839    public int getAccessibilityViewId() {
4840        if (mAccessibilityViewId == NO_ID) {
4841            mAccessibilityViewId = sNextAccessibilityViewId++;
4842        }
4843        return mAccessibilityViewId;
4844    }
4845
4846    /**
4847     * Gets the unique identifier of the window in which this View reseides.
4848     *
4849     * @return The window accessibility id.
4850     *
4851     * @hide
4852     */
4853    public int getAccessibilityWindowId() {
4854        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4855    }
4856
4857    /**
4858     * Gets the {@link View} description. It briefly describes the view and is
4859     * primarily used for accessibility support. Set this property to enable
4860     * better accessibility support for your application. This is especially
4861     * true for views that do not have textual representation (For example,
4862     * ImageButton).
4863     *
4864     * @return The content description.
4865     *
4866     * @attr ref android.R.styleable#View_contentDescription
4867     */
4868    @ViewDebug.ExportedProperty(category = "accessibility")
4869    public CharSequence getContentDescription() {
4870        return mContentDescription;
4871    }
4872
4873    /**
4874     * Sets the {@link View} description. It briefly describes the view and is
4875     * primarily used for accessibility support. Set this property to enable
4876     * better accessibility support for your application. This is especially
4877     * true for views that do not have textual representation (For example,
4878     * ImageButton).
4879     *
4880     * @param contentDescription The content description.
4881     *
4882     * @attr ref android.R.styleable#View_contentDescription
4883     */
4884    @RemotableViewMethod
4885    public void setContentDescription(CharSequence contentDescription) {
4886        mContentDescription = contentDescription;
4887    }
4888
4889    /**
4890     * Invoked whenever this view loses focus, either by losing window focus or by losing
4891     * focus within its window. This method can be used to clear any state tied to the
4892     * focus. For instance, if a button is held pressed with the trackball and the window
4893     * loses focus, this method can be used to cancel the press.
4894     *
4895     * Subclasses of View overriding this method should always call super.onFocusLost().
4896     *
4897     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4898     * @see #onWindowFocusChanged(boolean)
4899     *
4900     * @hide pending API council approval
4901     */
4902    protected void onFocusLost() {
4903        resetPressedState();
4904    }
4905
4906    private void resetPressedState() {
4907        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4908            return;
4909        }
4910
4911        if (isPressed()) {
4912            setPressed(false);
4913
4914            if (!mHasPerformedLongPress) {
4915                removeLongPressCallback();
4916            }
4917        }
4918    }
4919
4920    /**
4921     * Returns true if this view has focus
4922     *
4923     * @return True if this view has focus, false otherwise.
4924     */
4925    @ViewDebug.ExportedProperty(category = "focus")
4926    public boolean isFocused() {
4927        return (mPrivateFlags & FOCUSED) != 0;
4928    }
4929
4930    /**
4931     * Find the view in the hierarchy rooted at this view that currently has
4932     * focus.
4933     *
4934     * @return The view that currently has focus, or null if no focused view can
4935     *         be found.
4936     */
4937    public View findFocus() {
4938        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4939    }
4940
4941    /**
4942     * Indicates whether this view is one of the set of scrollable containers in
4943     * its window.
4944     *
4945     * @return whether this view is one of the set of scrollable containers in
4946     * its window
4947     *
4948     * @attr ref android.R.styleable#View_isScrollContainer
4949     */
4950    public boolean isScrollContainer() {
4951        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4952    }
4953
4954    /**
4955     * Change whether this view is one of the set of scrollable containers in
4956     * its window.  This will be used to determine whether the window can
4957     * resize or must pan when a soft input area is open -- scrollable
4958     * containers allow the window to use resize mode since the container
4959     * will appropriately shrink.
4960     *
4961     * @attr ref android.R.styleable#View_isScrollContainer
4962     */
4963    public void setScrollContainer(boolean isScrollContainer) {
4964        if (isScrollContainer) {
4965            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4966                mAttachInfo.mScrollContainers.add(this);
4967                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4968            }
4969            mPrivateFlags |= SCROLL_CONTAINER;
4970        } else {
4971            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4972                mAttachInfo.mScrollContainers.remove(this);
4973            }
4974            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4975        }
4976    }
4977
4978    /**
4979     * Returns the quality of the drawing cache.
4980     *
4981     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4982     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4983     *
4984     * @see #setDrawingCacheQuality(int)
4985     * @see #setDrawingCacheEnabled(boolean)
4986     * @see #isDrawingCacheEnabled()
4987     *
4988     * @attr ref android.R.styleable#View_drawingCacheQuality
4989     */
4990    public int getDrawingCacheQuality() {
4991        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4992    }
4993
4994    /**
4995     * Set the drawing cache quality of this view. This value is used only when the
4996     * drawing cache is enabled
4997     *
4998     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4999     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5000     *
5001     * @see #getDrawingCacheQuality()
5002     * @see #setDrawingCacheEnabled(boolean)
5003     * @see #isDrawingCacheEnabled()
5004     *
5005     * @attr ref android.R.styleable#View_drawingCacheQuality
5006     */
5007    public void setDrawingCacheQuality(int quality) {
5008        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5009    }
5010
5011    /**
5012     * Returns whether the screen should remain on, corresponding to the current
5013     * value of {@link #KEEP_SCREEN_ON}.
5014     *
5015     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5016     *
5017     * @see #setKeepScreenOn(boolean)
5018     *
5019     * @attr ref android.R.styleable#View_keepScreenOn
5020     */
5021    public boolean getKeepScreenOn() {
5022        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5023    }
5024
5025    /**
5026     * Controls whether the screen should remain on, modifying the
5027     * value of {@link #KEEP_SCREEN_ON}.
5028     *
5029     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5030     *
5031     * @see #getKeepScreenOn()
5032     *
5033     * @attr ref android.R.styleable#View_keepScreenOn
5034     */
5035    public void setKeepScreenOn(boolean keepScreenOn) {
5036        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5037    }
5038
5039    /**
5040     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5041     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5042     *
5043     * @attr ref android.R.styleable#View_nextFocusLeft
5044     */
5045    public int getNextFocusLeftId() {
5046        return mNextFocusLeftId;
5047    }
5048
5049    /**
5050     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5051     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5052     * decide automatically.
5053     *
5054     * @attr ref android.R.styleable#View_nextFocusLeft
5055     */
5056    public void setNextFocusLeftId(int nextFocusLeftId) {
5057        mNextFocusLeftId = nextFocusLeftId;
5058    }
5059
5060    /**
5061     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5062     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5063     *
5064     * @attr ref android.R.styleable#View_nextFocusRight
5065     */
5066    public int getNextFocusRightId() {
5067        return mNextFocusRightId;
5068    }
5069
5070    /**
5071     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5072     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5073     * decide automatically.
5074     *
5075     * @attr ref android.R.styleable#View_nextFocusRight
5076     */
5077    public void setNextFocusRightId(int nextFocusRightId) {
5078        mNextFocusRightId = nextFocusRightId;
5079    }
5080
5081    /**
5082     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5083     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5084     *
5085     * @attr ref android.R.styleable#View_nextFocusUp
5086     */
5087    public int getNextFocusUpId() {
5088        return mNextFocusUpId;
5089    }
5090
5091    /**
5092     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5093     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5094     * decide automatically.
5095     *
5096     * @attr ref android.R.styleable#View_nextFocusUp
5097     */
5098    public void setNextFocusUpId(int nextFocusUpId) {
5099        mNextFocusUpId = nextFocusUpId;
5100    }
5101
5102    /**
5103     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5104     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5105     *
5106     * @attr ref android.R.styleable#View_nextFocusDown
5107     */
5108    public int getNextFocusDownId() {
5109        return mNextFocusDownId;
5110    }
5111
5112    /**
5113     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5114     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5115     * decide automatically.
5116     *
5117     * @attr ref android.R.styleable#View_nextFocusDown
5118     */
5119    public void setNextFocusDownId(int nextFocusDownId) {
5120        mNextFocusDownId = nextFocusDownId;
5121    }
5122
5123    /**
5124     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5125     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5126     *
5127     * @attr ref android.R.styleable#View_nextFocusForward
5128     */
5129    public int getNextFocusForwardId() {
5130        return mNextFocusForwardId;
5131    }
5132
5133    /**
5134     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5135     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5136     * decide automatically.
5137     *
5138     * @attr ref android.R.styleable#View_nextFocusForward
5139     */
5140    public void setNextFocusForwardId(int nextFocusForwardId) {
5141        mNextFocusForwardId = nextFocusForwardId;
5142    }
5143
5144    /**
5145     * Returns the visibility of this view and all of its ancestors
5146     *
5147     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5148     */
5149    public boolean isShown() {
5150        View current = this;
5151        //noinspection ConstantConditions
5152        do {
5153            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5154                return false;
5155            }
5156            ViewParent parent = current.mParent;
5157            if (parent == null) {
5158                return false; // We are not attached to the view root
5159            }
5160            if (!(parent instanceof View)) {
5161                return true;
5162            }
5163            current = (View) parent;
5164        } while (current != null);
5165
5166        return false;
5167    }
5168
5169    /**
5170     * Called by the view hierarchy when the content insets for a window have
5171     * changed, to allow it to adjust its content to fit within those windows.
5172     * The content insets tell you the space that the status bar, input method,
5173     * and other system windows infringe on the application's window.
5174     *
5175     * <p>You do not normally need to deal with this function, since the default
5176     * window decoration given to applications takes care of applying it to the
5177     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5178     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5179     * and your content can be placed under those system elements.  You can then
5180     * use this method within your view hierarchy if you have parts of your UI
5181     * which you would like to ensure are not being covered.
5182     *
5183     * <p>The default implementation of this method simply applies the content
5184     * inset's to the view's padding.  This can be enabled through
5185     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5186     * the method and handle the insets however you would like.  Note that the
5187     * insets provided by the framework are always relative to the far edges
5188     * of the window, not accounting for the location of the called view within
5189     * that window.  (In fact when this method is called you do not yet know
5190     * where the layout will place the view, as it is done before layout happens.)
5191     *
5192     * <p>Note: unlike many View methods, there is no dispatch phase to this
5193     * call.  If you are overriding it in a ViewGroup and want to allow the
5194     * call to continue to your children, you must be sure to call the super
5195     * implementation.
5196     *
5197     * @param insets Current content insets of the window.  Prior to
5198     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5199     * the insets or else you and Android will be unhappy.
5200     *
5201     * @return Return true if this view applied the insets and it should not
5202     * continue propagating further down the hierarchy, false otherwise.
5203     */
5204    protected boolean fitSystemWindows(Rect insets) {
5205        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5206            mUserPaddingStart = -1;
5207            mUserPaddingEnd = -1;
5208            mUserPaddingRelative = false;
5209            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5210                    || mAttachInfo == null
5211                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5212                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5213                return true;
5214            } else {
5215                internalSetPadding(0, 0, 0, 0);
5216                return false;
5217            }
5218        }
5219        return false;
5220    }
5221
5222    /**
5223     * Set whether or not this view should account for system screen decorations
5224     * such as the status bar and inset its content. This allows this view to be
5225     * positioned in absolute screen coordinates and remain visible to the user.
5226     *
5227     * <p>This should only be used by top-level window decor views.
5228     *
5229     * @param fitSystemWindows true to inset content for system screen decorations, false for
5230     *                         default behavior.
5231     *
5232     * @attr ref android.R.styleable#View_fitsSystemWindows
5233     */
5234    public void setFitsSystemWindows(boolean fitSystemWindows) {
5235        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5236    }
5237
5238    /**
5239     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5240     * will account for system screen decorations such as the status bar and inset its
5241     * content. This allows the view to be positioned in absolute screen coordinates
5242     * and remain visible to the user.
5243     *
5244     * @return true if this view will adjust its content bounds for system screen decorations.
5245     *
5246     * @attr ref android.R.styleable#View_fitsSystemWindows
5247     */
5248    public boolean fitsSystemWindows() {
5249        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5250    }
5251
5252    /**
5253     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5254     */
5255    public void requestFitSystemWindows() {
5256        if (mParent != null) {
5257            mParent.requestFitSystemWindows();
5258        }
5259    }
5260
5261    /**
5262     * For use by PhoneWindow to make its own system window fitting optional.
5263     * @hide
5264     */
5265    public void makeOptionalFitsSystemWindows() {
5266        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5267    }
5268
5269    /**
5270     * Returns the visibility status for this view.
5271     *
5272     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5273     * @attr ref android.R.styleable#View_visibility
5274     */
5275    @ViewDebug.ExportedProperty(mapping = {
5276        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5277        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5278        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5279    })
5280    public int getVisibility() {
5281        return mViewFlags & VISIBILITY_MASK;
5282    }
5283
5284    /**
5285     * Set the enabled state of this view.
5286     *
5287     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5288     * @attr ref android.R.styleable#View_visibility
5289     */
5290    @RemotableViewMethod
5291    public void setVisibility(int visibility) {
5292        setFlags(visibility, VISIBILITY_MASK);
5293        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5294    }
5295
5296    /**
5297     * Returns the enabled status for this view. The interpretation of the
5298     * enabled state varies by subclass.
5299     *
5300     * @return True if this view is enabled, false otherwise.
5301     */
5302    @ViewDebug.ExportedProperty
5303    public boolean isEnabled() {
5304        return (mViewFlags & ENABLED_MASK) == ENABLED;
5305    }
5306
5307    /**
5308     * Set the enabled state of this view. The interpretation of the enabled
5309     * state varies by subclass.
5310     *
5311     * @param enabled True if this view is enabled, false otherwise.
5312     */
5313    @RemotableViewMethod
5314    public void setEnabled(boolean enabled) {
5315        if (enabled == isEnabled()) return;
5316
5317        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5318
5319        /*
5320         * The View most likely has to change its appearance, so refresh
5321         * the drawable state.
5322         */
5323        refreshDrawableState();
5324
5325        // Invalidate too, since the default behavior for views is to be
5326        // be drawn at 50% alpha rather than to change the drawable.
5327        invalidate(true);
5328    }
5329
5330    /**
5331     * Set whether this view can receive the focus.
5332     *
5333     * Setting this to false will also ensure that this view is not focusable
5334     * in touch mode.
5335     *
5336     * @param focusable If true, this view can receive the focus.
5337     *
5338     * @see #setFocusableInTouchMode(boolean)
5339     * @attr ref android.R.styleable#View_focusable
5340     */
5341    public void setFocusable(boolean focusable) {
5342        if (!focusable) {
5343            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5344        }
5345        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5346    }
5347
5348    /**
5349     * Set whether this view can receive focus while in touch mode.
5350     *
5351     * Setting this to true will also ensure that this view is focusable.
5352     *
5353     * @param focusableInTouchMode If true, this view can receive the focus while
5354     *   in touch mode.
5355     *
5356     * @see #setFocusable(boolean)
5357     * @attr ref android.R.styleable#View_focusableInTouchMode
5358     */
5359    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5360        // Focusable in touch mode should always be set before the focusable flag
5361        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5362        // which, in touch mode, will not successfully request focus on this view
5363        // because the focusable in touch mode flag is not set
5364        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5365        if (focusableInTouchMode) {
5366            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5367        }
5368    }
5369
5370    /**
5371     * Set whether this view should have sound effects enabled for events such as
5372     * clicking and touching.
5373     *
5374     * <p>You may wish to disable sound effects for a view if you already play sounds,
5375     * for instance, a dial key that plays dtmf tones.
5376     *
5377     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5378     * @see #isSoundEffectsEnabled()
5379     * @see #playSoundEffect(int)
5380     * @attr ref android.R.styleable#View_soundEffectsEnabled
5381     */
5382    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5383        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5384    }
5385
5386    /**
5387     * @return whether this view should have sound effects enabled for events such as
5388     *     clicking and touching.
5389     *
5390     * @see #setSoundEffectsEnabled(boolean)
5391     * @see #playSoundEffect(int)
5392     * @attr ref android.R.styleable#View_soundEffectsEnabled
5393     */
5394    @ViewDebug.ExportedProperty
5395    public boolean isSoundEffectsEnabled() {
5396        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5397    }
5398
5399    /**
5400     * Set whether this view should have haptic feedback for events such as
5401     * long presses.
5402     *
5403     * <p>You may wish to disable haptic feedback if your view already controls
5404     * its own haptic feedback.
5405     *
5406     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5407     * @see #isHapticFeedbackEnabled()
5408     * @see #performHapticFeedback(int)
5409     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5410     */
5411    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5412        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5413    }
5414
5415    /**
5416     * @return whether this view should have haptic feedback enabled for events
5417     * long presses.
5418     *
5419     * @see #setHapticFeedbackEnabled(boolean)
5420     * @see #performHapticFeedback(int)
5421     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5422     */
5423    @ViewDebug.ExportedProperty
5424    public boolean isHapticFeedbackEnabled() {
5425        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5426    }
5427
5428    /**
5429     * Returns the layout direction for this view.
5430     *
5431     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5432     *   {@link #LAYOUT_DIRECTION_RTL},
5433     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5434     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5435     * @attr ref android.R.styleable#View_layoutDirection
5436     */
5437    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5438        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5439        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5440        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5441        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5442    })
5443    public int getLayoutDirection() {
5444        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5445    }
5446
5447    /**
5448     * Set the layout direction for this view. This will propagate a reset of layout direction
5449     * resolution to the view's children and resolve layout direction for this view.
5450     *
5451     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5452     *   {@link #LAYOUT_DIRECTION_RTL},
5453     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5454     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5455     *
5456     * @attr ref android.R.styleable#View_layoutDirection
5457     */
5458    @RemotableViewMethod
5459    public void setLayoutDirection(int layoutDirection) {
5460        if (getLayoutDirection() != layoutDirection) {
5461            // Reset the current layout direction and the resolved one
5462            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5463            resetResolvedLayoutDirection();
5464            // Set the new layout direction (filtered) and ask for a layout pass
5465            mPrivateFlags2 |=
5466                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5467            requestLayout();
5468        }
5469    }
5470
5471    /**
5472     * Returns the resolved layout direction for this view.
5473     *
5474     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5475     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5476     */
5477    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5478        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5479        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5480    })
5481    public int getResolvedLayoutDirection() {
5482        // The layout diretion will be resolved only if needed
5483        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5484            resolveLayoutDirection();
5485        }
5486        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5487                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5488    }
5489
5490    /**
5491     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5492     * layout attribute and/or the inherited value from the parent
5493     *
5494     * @return true if the layout is right-to-left.
5495     */
5496    @ViewDebug.ExportedProperty(category = "layout")
5497    public boolean isLayoutRtl() {
5498        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5499    }
5500
5501    /**
5502     * Indicates whether the view is currently tracking transient state that the
5503     * app should not need to concern itself with saving and restoring, but that
5504     * the framework should take special note to preserve when possible.
5505     *
5506     * <p>A view with transient state cannot be trivially rebound from an external
5507     * data source, such as an adapter binding item views in a list. This may be
5508     * because the view is performing an animation, tracking user selection
5509     * of content, or similar.</p>
5510     *
5511     * @return true if the view has transient state
5512     */
5513    @ViewDebug.ExportedProperty(category = "layout")
5514    public boolean hasTransientState() {
5515        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5516    }
5517
5518    /**
5519     * Set whether this view is currently tracking transient state that the
5520     * framework should attempt to preserve when possible. This flag is reference counted,
5521     * so every call to setHasTransientState(true) should be paired with a later call
5522     * to setHasTransientState(false).
5523     *
5524     * <p>A view with transient state cannot be trivially rebound from an external
5525     * data source, such as an adapter binding item views in a list. This may be
5526     * because the view is performing an animation, tracking user selection
5527     * of content, or similar.</p>
5528     *
5529     * @param hasTransientState true if this view has transient state
5530     */
5531    public void setHasTransientState(boolean hasTransientState) {
5532        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5533                mTransientStateCount - 1;
5534        if (mTransientStateCount < 0) {
5535            mTransientStateCount = 0;
5536            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5537                    "unmatched pair of setHasTransientState calls");
5538        }
5539        if ((hasTransientState && mTransientStateCount == 1) ||
5540                (hasTransientState && mTransientStateCount == 0)) {
5541            // update flag if we've just incremented up from 0 or decremented down to 0
5542            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5543                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5544            if (mParent != null) {
5545                try {
5546                    mParent.childHasTransientStateChanged(this, hasTransientState);
5547                } catch (AbstractMethodError e) {
5548                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5549                            " does not fully implement ViewParent", e);
5550                }
5551            }
5552        }
5553    }
5554
5555    /**
5556     * If this view doesn't do any drawing on its own, set this flag to
5557     * allow further optimizations. By default, this flag is not set on
5558     * View, but could be set on some View subclasses such as ViewGroup.
5559     *
5560     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5561     * you should clear this flag.
5562     *
5563     * @param willNotDraw whether or not this View draw on its own
5564     */
5565    public void setWillNotDraw(boolean willNotDraw) {
5566        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5567    }
5568
5569    /**
5570     * Returns whether or not this View draws on its own.
5571     *
5572     * @return true if this view has nothing to draw, false otherwise
5573     */
5574    @ViewDebug.ExportedProperty(category = "drawing")
5575    public boolean willNotDraw() {
5576        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5577    }
5578
5579    /**
5580     * When a View's drawing cache is enabled, drawing is redirected to an
5581     * offscreen bitmap. Some views, like an ImageView, must be able to
5582     * bypass this mechanism if they already draw a single bitmap, to avoid
5583     * unnecessary usage of the memory.
5584     *
5585     * @param willNotCacheDrawing true if this view does not cache its
5586     *        drawing, false otherwise
5587     */
5588    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5589        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5590    }
5591
5592    /**
5593     * Returns whether or not this View can cache its drawing or not.
5594     *
5595     * @return true if this view does not cache its drawing, false otherwise
5596     */
5597    @ViewDebug.ExportedProperty(category = "drawing")
5598    public boolean willNotCacheDrawing() {
5599        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5600    }
5601
5602    /**
5603     * Indicates whether this view reacts to click events or not.
5604     *
5605     * @return true if the view is clickable, false otherwise
5606     *
5607     * @see #setClickable(boolean)
5608     * @attr ref android.R.styleable#View_clickable
5609     */
5610    @ViewDebug.ExportedProperty
5611    public boolean isClickable() {
5612        return (mViewFlags & CLICKABLE) == CLICKABLE;
5613    }
5614
5615    /**
5616     * Enables or disables click events for this view. When a view
5617     * is clickable it will change its state to "pressed" on every click.
5618     * Subclasses should set the view clickable to visually react to
5619     * user's clicks.
5620     *
5621     * @param clickable true to make the view clickable, false otherwise
5622     *
5623     * @see #isClickable()
5624     * @attr ref android.R.styleable#View_clickable
5625     */
5626    public void setClickable(boolean clickable) {
5627        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5628    }
5629
5630    /**
5631     * Indicates whether this view reacts to long click events or not.
5632     *
5633     * @return true if the view is long clickable, false otherwise
5634     *
5635     * @see #setLongClickable(boolean)
5636     * @attr ref android.R.styleable#View_longClickable
5637     */
5638    public boolean isLongClickable() {
5639        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5640    }
5641
5642    /**
5643     * Enables or disables long click events for this view. When a view is long
5644     * clickable it reacts to the user holding down the button for a longer
5645     * duration than a tap. This event can either launch the listener or a
5646     * context menu.
5647     *
5648     * @param longClickable true to make the view long clickable, false otherwise
5649     * @see #isLongClickable()
5650     * @attr ref android.R.styleable#View_longClickable
5651     */
5652    public void setLongClickable(boolean longClickable) {
5653        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5654    }
5655
5656    /**
5657     * Sets the pressed state for this view.
5658     *
5659     * @see #isClickable()
5660     * @see #setClickable(boolean)
5661     *
5662     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5663     *        the View's internal state from a previously set "pressed" state.
5664     */
5665    public void setPressed(boolean pressed) {
5666        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5667
5668        if (pressed) {
5669            mPrivateFlags |= PRESSED;
5670        } else {
5671            mPrivateFlags &= ~PRESSED;
5672        }
5673
5674        if (needsRefresh) {
5675            refreshDrawableState();
5676        }
5677        dispatchSetPressed(pressed);
5678    }
5679
5680    /**
5681     * Dispatch setPressed to all of this View's children.
5682     *
5683     * @see #setPressed(boolean)
5684     *
5685     * @param pressed The new pressed state
5686     */
5687    protected void dispatchSetPressed(boolean pressed) {
5688    }
5689
5690    /**
5691     * Indicates whether the view is currently in pressed state. Unless
5692     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5693     * the pressed state.
5694     *
5695     * @see #setPressed(boolean)
5696     * @see #isClickable()
5697     * @see #setClickable(boolean)
5698     *
5699     * @return true if the view is currently pressed, false otherwise
5700     */
5701    public boolean isPressed() {
5702        return (mPrivateFlags & PRESSED) == PRESSED;
5703    }
5704
5705    /**
5706     * Indicates whether this view will save its state (that is,
5707     * whether its {@link #onSaveInstanceState} method will be called).
5708     *
5709     * @return Returns true if the view state saving is enabled, else false.
5710     *
5711     * @see #setSaveEnabled(boolean)
5712     * @attr ref android.R.styleable#View_saveEnabled
5713     */
5714    public boolean isSaveEnabled() {
5715        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5716    }
5717
5718    /**
5719     * Controls whether the saving of this view's state is
5720     * enabled (that is, whether its {@link #onSaveInstanceState} method
5721     * will be called).  Note that even if freezing is enabled, the
5722     * view still must have an id assigned to it (via {@link #setId(int)})
5723     * for its state to be saved.  This flag can only disable the
5724     * saving of this view; any child views may still have their state saved.
5725     *
5726     * @param enabled Set to false to <em>disable</em> state saving, or true
5727     * (the default) to allow it.
5728     *
5729     * @see #isSaveEnabled()
5730     * @see #setId(int)
5731     * @see #onSaveInstanceState()
5732     * @attr ref android.R.styleable#View_saveEnabled
5733     */
5734    public void setSaveEnabled(boolean enabled) {
5735        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5736    }
5737
5738    /**
5739     * Gets whether the framework should discard touches when the view's
5740     * window is obscured by another visible window.
5741     * Refer to the {@link View} security documentation for more details.
5742     *
5743     * @return True if touch filtering is enabled.
5744     *
5745     * @see #setFilterTouchesWhenObscured(boolean)
5746     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5747     */
5748    @ViewDebug.ExportedProperty
5749    public boolean getFilterTouchesWhenObscured() {
5750        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5751    }
5752
5753    /**
5754     * Sets whether the framework should discard touches when the view's
5755     * window is obscured by another visible window.
5756     * Refer to the {@link View} security documentation for more details.
5757     *
5758     * @param enabled True if touch filtering should be enabled.
5759     *
5760     * @see #getFilterTouchesWhenObscured
5761     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5762     */
5763    public void setFilterTouchesWhenObscured(boolean enabled) {
5764        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5765                FILTER_TOUCHES_WHEN_OBSCURED);
5766    }
5767
5768    /**
5769     * Indicates whether the entire hierarchy under this view will save its
5770     * state when a state saving traversal occurs from its parent.  The default
5771     * is true; if false, these views will not be saved unless
5772     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5773     *
5774     * @return Returns true if the view state saving from parent is enabled, else false.
5775     *
5776     * @see #setSaveFromParentEnabled(boolean)
5777     */
5778    public boolean isSaveFromParentEnabled() {
5779        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5780    }
5781
5782    /**
5783     * Controls whether the entire hierarchy under this view will save its
5784     * state when a state saving traversal occurs from its parent.  The default
5785     * is true; if false, these views will not be saved unless
5786     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5787     *
5788     * @param enabled Set to false to <em>disable</em> state saving, or true
5789     * (the default) to allow it.
5790     *
5791     * @see #isSaveFromParentEnabled()
5792     * @see #setId(int)
5793     * @see #onSaveInstanceState()
5794     */
5795    public void setSaveFromParentEnabled(boolean enabled) {
5796        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5797    }
5798
5799
5800    /**
5801     * Returns whether this View is able to take focus.
5802     *
5803     * @return True if this view can take focus, or false otherwise.
5804     * @attr ref android.R.styleable#View_focusable
5805     */
5806    @ViewDebug.ExportedProperty(category = "focus")
5807    public final boolean isFocusable() {
5808        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5809    }
5810
5811    /**
5812     * When a view is focusable, it may not want to take focus when in touch mode.
5813     * For example, a button would like focus when the user is navigating via a D-pad
5814     * so that the user can click on it, but once the user starts touching the screen,
5815     * the button shouldn't take focus
5816     * @return Whether the view is focusable in touch mode.
5817     * @attr ref android.R.styleable#View_focusableInTouchMode
5818     */
5819    @ViewDebug.ExportedProperty
5820    public final boolean isFocusableInTouchMode() {
5821        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5822    }
5823
5824    /**
5825     * Find the nearest view in the specified direction that can take focus.
5826     * This does not actually give focus to that view.
5827     *
5828     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5829     *
5830     * @return The nearest focusable in the specified direction, or null if none
5831     *         can be found.
5832     */
5833    public View focusSearch(int direction) {
5834        if (mParent != null) {
5835            return mParent.focusSearch(this, direction);
5836        } else {
5837            return null;
5838        }
5839    }
5840
5841    /**
5842     * This method is the last chance for the focused view and its ancestors to
5843     * respond to an arrow key. This is called when the focused view did not
5844     * consume the key internally, nor could the view system find a new view in
5845     * the requested direction to give focus to.
5846     *
5847     * @param focused The currently focused view.
5848     * @param direction The direction focus wants to move. One of FOCUS_UP,
5849     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5850     * @return True if the this view consumed this unhandled move.
5851     */
5852    public boolean dispatchUnhandledMove(View focused, int direction) {
5853        return false;
5854    }
5855
5856    /**
5857     * If a user manually specified the next view id for a particular direction,
5858     * use the root to look up the view.
5859     * @param root The root view of the hierarchy containing this view.
5860     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5861     * or FOCUS_BACKWARD.
5862     * @return The user specified next view, or null if there is none.
5863     */
5864    View findUserSetNextFocus(View root, int direction) {
5865        switch (direction) {
5866            case FOCUS_LEFT:
5867                if (mNextFocusLeftId == View.NO_ID) return null;
5868                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5869            case FOCUS_RIGHT:
5870                if (mNextFocusRightId == View.NO_ID) return null;
5871                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5872            case FOCUS_UP:
5873                if (mNextFocusUpId == View.NO_ID) return null;
5874                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5875            case FOCUS_DOWN:
5876                if (mNextFocusDownId == View.NO_ID) return null;
5877                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5878            case FOCUS_FORWARD:
5879                if (mNextFocusForwardId == View.NO_ID) return null;
5880                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5881            case FOCUS_BACKWARD: {
5882                if (mID == View.NO_ID) return null;
5883                final int id = mID;
5884                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5885                    @Override
5886                    public boolean apply(View t) {
5887                        return t.mNextFocusForwardId == id;
5888                    }
5889                });
5890            }
5891        }
5892        return null;
5893    }
5894
5895    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5896        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5897            @Override
5898            public boolean apply(View t) {
5899                return t.mID == childViewId;
5900            }
5901        });
5902
5903        if (result == null) {
5904            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5905                    + "by user for id " + childViewId);
5906        }
5907        return result;
5908    }
5909
5910    /**
5911     * Find and return all focusable views that are descendants of this view,
5912     * possibly including this view if it is focusable itself.
5913     *
5914     * @param direction The direction of the focus
5915     * @return A list of focusable views
5916     */
5917    public ArrayList<View> getFocusables(int direction) {
5918        ArrayList<View> result = new ArrayList<View>(24);
5919        addFocusables(result, direction);
5920        return result;
5921    }
5922
5923    /**
5924     * Add any focusable views that are descendants of this view (possibly
5925     * including this view if it is focusable itself) to views.  If we are in touch mode,
5926     * only add views that are also focusable in touch mode.
5927     *
5928     * @param views Focusable views found so far
5929     * @param direction The direction of the focus
5930     */
5931    public void addFocusables(ArrayList<View> views, int direction) {
5932        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5933    }
5934
5935    /**
5936     * Adds any focusable views that are descendants of this view (possibly
5937     * including this view if it is focusable itself) to views. This method
5938     * adds all focusable views regardless if we are in touch mode or
5939     * only views focusable in touch mode if we are in touch mode or
5940     * only views that can take accessibility focus if accessibility is enabeld
5941     * depending on the focusable mode paramater.
5942     *
5943     * @param views Focusable views found so far or null if all we are interested is
5944     *        the number of focusables.
5945     * @param direction The direction of the focus.
5946     * @param focusableMode The type of focusables to be added.
5947     *
5948     * @see #FOCUSABLES_ALL
5949     * @see #FOCUSABLES_TOUCH_MODE
5950     */
5951    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5952        if (views == null) {
5953            return;
5954        }
5955        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5956            if (AccessibilityManager.getInstance(mContext).isEnabled()
5957                    && includeForAccessibility()) {
5958                views.add(this);
5959                return;
5960            }
5961        }
5962        if (!isFocusable()) {
5963            return;
5964        }
5965        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5966                && isInTouchMode() && !isFocusableInTouchMode()) {
5967            return;
5968        }
5969        views.add(this);
5970    }
5971
5972    /**
5973     * Finds the Views that contain given text. The containment is case insensitive.
5974     * The search is performed by either the text that the View renders or the content
5975     * description that describes the view for accessibility purposes and the view does
5976     * not render or both. Clients can specify how the search is to be performed via
5977     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5978     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5979     *
5980     * @param outViews The output list of matching Views.
5981     * @param searched The text to match against.
5982     *
5983     * @see #FIND_VIEWS_WITH_TEXT
5984     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5985     * @see #setContentDescription(CharSequence)
5986     */
5987    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5988        if (getAccessibilityNodeProvider() != null) {
5989            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5990                outViews.add(this);
5991            }
5992        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5993                && (searched != null && searched.length() > 0)
5994                && (mContentDescription != null && mContentDescription.length() > 0)) {
5995            String searchedLowerCase = searched.toString().toLowerCase();
5996            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5997            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5998                outViews.add(this);
5999            }
6000        }
6001    }
6002
6003    /**
6004     * Find and return all touchable views that are descendants of this view,
6005     * possibly including this view if it is touchable itself.
6006     *
6007     * @return A list of touchable views
6008     */
6009    public ArrayList<View> getTouchables() {
6010        ArrayList<View> result = new ArrayList<View>();
6011        addTouchables(result);
6012        return result;
6013    }
6014
6015    /**
6016     * Add any touchable views that are descendants of this view (possibly
6017     * including this view if it is touchable itself) to views.
6018     *
6019     * @param views Touchable views found so far
6020     */
6021    public void addTouchables(ArrayList<View> views) {
6022        final int viewFlags = mViewFlags;
6023
6024        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6025                && (viewFlags & ENABLED_MASK) == ENABLED) {
6026            views.add(this);
6027        }
6028    }
6029
6030    /**
6031     * Returns whether this View is accessibility focused.
6032     *
6033     * @return True if this View is accessibility focused.
6034     */
6035    boolean isAccessibilityFocused() {
6036        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6037    }
6038
6039    /**
6040     * Call this to try to give accessibility focus to this view.
6041     *
6042     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6043     * returns false or the view is no visible or the view already has accessibility
6044     * focus.
6045     *
6046     * See also {@link #focusSearch(int)}, which is what you call to say that you
6047     * have focus, and you want your parent to look for the next one.
6048     *
6049     * @return Whether this view actually took accessibility focus.
6050     *
6051     * @hide
6052     */
6053    public boolean requestAccessibilityFocus() {
6054        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6055        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6056            return false;
6057        }
6058        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6059            return false;
6060        }
6061        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6062            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6063            ViewRootImpl viewRootImpl = getViewRootImpl();
6064            if (viewRootImpl != null) {
6065                viewRootImpl.setAccessibilityFocusedHost(this);
6066            }
6067            invalidate();
6068            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6069            notifyAccessibilityStateChanged();
6070            // Try to give input focus to this view - not a descendant.
6071            requestFocusNoSearch(View.FOCUS_DOWN, null);
6072            return true;
6073        }
6074        return false;
6075    }
6076
6077    /**
6078     * Call this to try to clear accessibility focus of this view.
6079     *
6080     * See also {@link #focusSearch(int)}, which is what you call to say that you
6081     * have focus, and you want your parent to look for the next one.
6082     *
6083     * @hide
6084     */
6085    public void clearAccessibilityFocus() {
6086        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6087            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6088            ViewRootImpl viewRootImpl = getViewRootImpl();
6089            if (viewRootImpl != null) {
6090                viewRootImpl.setAccessibilityFocusedHost(null);
6091            }
6092            invalidate();
6093            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6094            notifyAccessibilityStateChanged();
6095
6096            // Clear the text navigation state.
6097            setAccessibilityCursorPosition(-1);
6098
6099            // Try to move accessibility focus to the input focus.
6100            View rootView = getRootView();
6101            if (rootView != null) {
6102                View inputFocus = rootView.findFocus();
6103                if (inputFocus != null) {
6104                    inputFocus.requestAccessibilityFocus();
6105                }
6106            }
6107        }
6108    }
6109
6110    /**
6111     * Find the best view to take accessibility focus from a hover.
6112     * This function finds the deepest actionable view and if that
6113     * fails ask the parent to take accessibility focus from hover.
6114     *
6115     * @param x The X hovered location in this view coorditantes.
6116     * @param y The Y hovered location in this view coorditantes.
6117     * @return Whether the request was handled.
6118     *
6119     * @hide
6120     */
6121    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6122        if (onRequestAccessibilityFocusFromHover(x, y)) {
6123            return true;
6124        }
6125        ViewParent parent = mParent;
6126        if (parent instanceof View) {
6127            View parentView = (View) parent;
6128
6129            float[] position = mAttachInfo.mTmpTransformLocation;
6130            position[0] = x;
6131            position[1] = y;
6132
6133            // Compensate for the transformation of the current matrix.
6134            if (!hasIdentityMatrix()) {
6135                getMatrix().mapPoints(position);
6136            }
6137
6138            // Compensate for the parent scroll and the offset
6139            // of this view stop from the parent top.
6140            position[0] += mLeft - parentView.mScrollX;
6141            position[1] += mTop - parentView.mScrollY;
6142
6143            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6144        }
6145        return false;
6146    }
6147
6148    /**
6149     * Requests to give this View focus from hover.
6150     *
6151     * @param x The X hovered location in this view coorditantes.
6152     * @param y The Y hovered location in this view coorditantes.
6153     * @return Whether the request was handled.
6154     *
6155     * @hide
6156     */
6157    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6158        if (includeForAccessibility()
6159                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6160            return requestAccessibilityFocus();
6161        }
6162        return false;
6163    }
6164
6165    /**
6166     * Clears accessibility focus without calling any callback methods
6167     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6168     * is used for clearing accessibility focus when giving this focus to
6169     * another view.
6170     */
6171    void clearAccessibilityFocusNoCallbacks() {
6172        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6173            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6174            invalidate();
6175        }
6176    }
6177
6178    /**
6179     * Call this to try to give focus to a specific view or to one of its
6180     * descendants.
6181     *
6182     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6183     * false), or if it is focusable and it is not focusable in touch mode
6184     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6185     *
6186     * See also {@link #focusSearch(int)}, which is what you call to say that you
6187     * have focus, and you want your parent to look for the next one.
6188     *
6189     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6190     * {@link #FOCUS_DOWN} and <code>null</code>.
6191     *
6192     * @return Whether this view or one of its descendants actually took focus.
6193     */
6194    public final boolean requestFocus() {
6195        return requestFocus(View.FOCUS_DOWN);
6196    }
6197
6198    /**
6199     * Call this to try to give focus to a specific view or to one of its
6200     * descendants and give it a hint about what direction focus is heading.
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
6210     * <code>null</code> set for the previously focused rectangle.
6211     *
6212     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6213     * @return Whether this view or one of its descendants actually took focus.
6214     */
6215    public final boolean requestFocus(int direction) {
6216        return requestFocus(direction, null);
6217    }
6218
6219    /**
6220     * Call this to try to give focus to a specific view or to one of its descendants
6221     * and give it hints about the direction and a specific rectangle that the focus
6222     * is coming from.  The rectangle can help give larger views a finer grained hint
6223     * about where focus is coming from, and therefore, where to show selection, or
6224     * forward focus change internally.
6225     *
6226     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6227     * false), or if it is focusable and it is not focusable in touch mode
6228     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6229     *
6230     * A View will not take focus if it is not visible.
6231     *
6232     * A View will not take focus if one of its parents has
6233     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6234     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6235     *
6236     * See also {@link #focusSearch(int)}, which is what you call to say that you
6237     * have focus, and you want your parent to look for the next one.
6238     *
6239     * You may wish to override this method if your custom {@link View} has an internal
6240     * {@link View} that it wishes to forward the request to.
6241     *
6242     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6243     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6244     *        to give a finer grained hint about where focus is coming from.  May be null
6245     *        if there is no hint.
6246     * @return Whether this view or one of its descendants actually took focus.
6247     */
6248    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6249        return requestFocusNoSearch(direction, previouslyFocusedRect);
6250    }
6251
6252    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6253        // need to be focusable
6254        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6255                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6256            return false;
6257        }
6258
6259        // need to be focusable in touch mode if in touch mode
6260        if (isInTouchMode() &&
6261            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6262               return false;
6263        }
6264
6265        // need to not have any parents blocking us
6266        if (hasAncestorThatBlocksDescendantFocus()) {
6267            return false;
6268        }
6269
6270        handleFocusGainInternal(direction, previouslyFocusedRect);
6271        return true;
6272    }
6273
6274    /**
6275     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6276     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6277     * touch mode to request focus when they are touched.
6278     *
6279     * @return Whether this view or one of its descendants actually took focus.
6280     *
6281     * @see #isInTouchMode()
6282     *
6283     */
6284    public final boolean requestFocusFromTouch() {
6285        // Leave touch mode if we need to
6286        if (isInTouchMode()) {
6287            ViewRootImpl viewRoot = getViewRootImpl();
6288            if (viewRoot != null) {
6289                viewRoot.ensureTouchMode(false);
6290            }
6291        }
6292        return requestFocus(View.FOCUS_DOWN);
6293    }
6294
6295    /**
6296     * @return Whether any ancestor of this view blocks descendant focus.
6297     */
6298    private boolean hasAncestorThatBlocksDescendantFocus() {
6299        ViewParent ancestor = mParent;
6300        while (ancestor instanceof ViewGroup) {
6301            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6302            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6303                return true;
6304            } else {
6305                ancestor = vgAncestor.getParent();
6306            }
6307        }
6308        return false;
6309    }
6310
6311    /**
6312     * Gets the mode for determining whether this View is important for accessibility
6313     * which is if it fires accessibility events and if it is reported to
6314     * accessibility services that query the screen.
6315     *
6316     * @return The mode for determining whether a View is important for accessibility.
6317     *
6318     * @attr ref android.R.styleable#View_importantForAccessibility
6319     *
6320     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6321     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6322     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6323     */
6324    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6325            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6326                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6327            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6328                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6329            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6330                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6331        })
6332    public int getImportantForAccessibility() {
6333        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6334                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6335    }
6336
6337    /**
6338     * Sets how to determine whether this view is important for accessibility
6339     * which is if it fires accessibility events and if it is reported to
6340     * accessibility services that query the screen.
6341     *
6342     * @param mode How to determine whether this view is important for accessibility.
6343     *
6344     * @attr ref android.R.styleable#View_importantForAccessibility
6345     *
6346     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6347     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6348     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6349     */
6350    public void setImportantForAccessibility(int mode) {
6351        if (mode != getImportantForAccessibility()) {
6352            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6353            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6354                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6355            notifyAccessibilityStateChanged();
6356        }
6357    }
6358
6359    /**
6360     * Gets whether this view should be exposed for accessibility.
6361     *
6362     * @return Whether the view is exposed for accessibility.
6363     *
6364     * @hide
6365     */
6366    public boolean isImportantForAccessibility() {
6367        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6368                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6369        switch (mode) {
6370            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6371                return true;
6372            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6373                return false;
6374            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6375                return isActionableForAccessibility() || hasListenersForAccessibility();
6376            default:
6377                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6378                        + mode);
6379        }
6380    }
6381
6382    /**
6383     * Gets the parent for accessibility purposes. Note that the parent for
6384     * accessibility is not necessary the immediate parent. It is the first
6385     * predecessor that is important for accessibility.
6386     *
6387     * @return The parent for accessibility purposes.
6388     */
6389    public ViewParent getParentForAccessibility() {
6390        if (mParent instanceof View) {
6391            View parentView = (View) mParent;
6392            if (parentView.includeForAccessibility()) {
6393                return mParent;
6394            } else {
6395                return mParent.getParentForAccessibility();
6396            }
6397        }
6398        return null;
6399    }
6400
6401    /**
6402     * Adds the children of a given View for accessibility. Since some Views are
6403     * not important for accessibility the children for accessibility are not
6404     * necessarily direct children of the riew, rather they are the first level of
6405     * descendants important for accessibility.
6406     *
6407     * @param children The list of children for accessibility.
6408     */
6409    public void addChildrenForAccessibility(ArrayList<View> children) {
6410        if (includeForAccessibility()) {
6411            children.add(this);
6412        }
6413    }
6414
6415    /**
6416     * Whether to regard this view for accessibility. A view is regarded for
6417     * accessibility if it is important for accessibility or the querying
6418     * accessibility service has explicitly requested that view not
6419     * important for accessibility are regarded.
6420     *
6421     * @return Whether to regard the view for accessibility.
6422     */
6423    boolean includeForAccessibility() {
6424        if (mAttachInfo != null) {
6425            if (!mAttachInfo.mIncludeNotImportantViews) {
6426                return isImportantForAccessibility();
6427            } else {
6428                return true;
6429            }
6430        }
6431        return false;
6432    }
6433
6434    /**
6435     * Returns whether the View is considered actionable from
6436     * accessibility perspective. Such view are important for
6437     * accessiiblity.
6438     *
6439     * @return True if the view is actionable for accessibility.
6440     */
6441    private boolean isActionableForAccessibility() {
6442        return (isClickable() || isLongClickable() || isFocusable());
6443    }
6444
6445    /**
6446     * Returns whether the View has registered callbacks wich makes it
6447     * important for accessiiblity.
6448     *
6449     * @return True if the view is actionable for accessibility.
6450     */
6451    private boolean hasListenersForAccessibility() {
6452        ListenerInfo info = getListenerInfo();
6453        return mTouchDelegate != null || info.mOnKeyListener != null
6454                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6455                || info.mOnHoverListener != null || info.mOnDragListener != null;
6456    }
6457
6458    /**
6459     * Notifies accessibility services that some view's important for
6460     * accessibility state has changed. Note that such notifications
6461     * are made at most once every
6462     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6463     * to avoid unnecessary load to the system. Also once a view has
6464     * made a notifucation this method is a NOP until the notification has
6465     * been sent to clients.
6466     *
6467     * @hide
6468     *
6469     * TODO: Makse sure this method is called for any view state change
6470     *       that is interesting for accessilility purposes.
6471     */
6472    public void notifyAccessibilityStateChanged() {
6473        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6474            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6475            if (mParent != null) {
6476                mParent.childAccessibilityStateChanged(this);
6477            }
6478        }
6479    }
6480
6481    /**
6482     * Reset the state indicating the this view has requested clients
6483     * interested in its accessiblity state to be notified.
6484     *
6485     * @hide
6486     */
6487    public void resetAccessibilityStateChanged() {
6488        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6489    }
6490
6491    /**
6492     * Performs the specified accessibility action on the view. For
6493     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6494    * <p>
6495    * If an {@link AccessibilityDelegate} has been specified via calling
6496    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6497    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6498    * is responsible for handling this call.
6499    * </p>
6500     *
6501     * @param action The action to perform.
6502     * @param arguments Optional action arguments.
6503     * @return Whether the action was performed.
6504     */
6505    public boolean performAccessibilityAction(int action, Bundle arguments) {
6506      if (mAccessibilityDelegate != null) {
6507          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6508      } else {
6509          return performAccessibilityActionInternal(action, arguments);
6510      }
6511    }
6512
6513   /**
6514    * @see #performAccessibilityAction(int, Bundle)
6515    *
6516    * Note: Called from the default {@link AccessibilityDelegate}.
6517    */
6518    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6519        switch (action) {
6520            case AccessibilityNodeInfo.ACTION_CLICK: {
6521                if (isClickable()) {
6522                    return performClick();
6523                }
6524            } break;
6525            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6526                if (isLongClickable()) {
6527                    return performLongClick();
6528                }
6529            } break;
6530            case AccessibilityNodeInfo.ACTION_FOCUS: {
6531                if (!hasFocus()) {
6532                    // Get out of touch mode since accessibility
6533                    // wants to move focus around.
6534                    getViewRootImpl().ensureTouchMode(false);
6535                    return requestFocus();
6536                }
6537            } break;
6538            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6539                if (hasFocus()) {
6540                    clearFocus();
6541                    return !isFocused();
6542                }
6543            } break;
6544            case AccessibilityNodeInfo.ACTION_SELECT: {
6545                if (!isSelected()) {
6546                    setSelected(true);
6547                    return isSelected();
6548                }
6549            } break;
6550            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6551                if (isSelected()) {
6552                    setSelected(false);
6553                    return !isSelected();
6554                }
6555            } break;
6556            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6557                if (!isAccessibilityFocused()) {
6558                    return requestAccessibilityFocus();
6559                }
6560            } break;
6561            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6562                if (isAccessibilityFocused()) {
6563                    clearAccessibilityFocus();
6564                    return true;
6565                }
6566            } break;
6567            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6568                if (arguments != null) {
6569                    final int granularity = arguments.getInt(
6570                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6571                    return nextAtGranularity(granularity);
6572                }
6573            } break;
6574            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6575                if (arguments != null) {
6576                    final int granularity = arguments.getInt(
6577                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6578                    return previousAtGranularity(granularity);
6579                }
6580            } break;
6581        }
6582        return false;
6583    }
6584
6585    private boolean nextAtGranularity(int granularity) {
6586        CharSequence text = getIterableTextForAccessibility();
6587        if (text != null && text.length() > 0) {
6588            return false;
6589        }
6590        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6591        if (iterator == null) {
6592            return false;
6593        }
6594        final int current = getAccessibilityCursorPosition();
6595        final int[] range = iterator.following(current);
6596        if (range == null) {
6597            setAccessibilityCursorPosition(-1);
6598            return false;
6599        }
6600        final int start = range[0];
6601        final int end = range[1];
6602        setAccessibilityCursorPosition(start);
6603        sendViewTextTraversedAtGranularityEvent(
6604                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6605                granularity, start, end);
6606        return true;
6607    }
6608
6609    private boolean previousAtGranularity(int granularity) {
6610        CharSequence text = getIterableTextForAccessibility();
6611        if (text != null && text.length() > 0) {
6612            return false;
6613        }
6614        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6615        if (iterator == null) {
6616            return false;
6617        }
6618        final int selectionStart = getAccessibilityCursorPosition();
6619        final int current = selectionStart >= 0 ? selectionStart : text.length() + 1;
6620        final int[] range = iterator.preceding(current);
6621        if (range == null) {
6622            setAccessibilityCursorPosition(-1);
6623            return false;
6624        }
6625        final int start = range[0];
6626        final int end = range[1];
6627        setAccessibilityCursorPosition(end);
6628        sendViewTextTraversedAtGranularityEvent(
6629                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6630                granularity, start, end);
6631        return true;
6632    }
6633
6634    /**
6635     * Gets the text reported for accessibility purposes.
6636     *
6637     * @return The accessibility text.
6638     *
6639     * @hide
6640     */
6641    public CharSequence getIterableTextForAccessibility() {
6642        return mContentDescription;
6643    }
6644
6645    /**
6646     * @hide
6647     */
6648    public int getAccessibilityCursorPosition() {
6649        return mAccessibilityCursorPosition;
6650    }
6651
6652    /**
6653     * @hide
6654     */
6655    public void setAccessibilityCursorPosition(int position) {
6656        mAccessibilityCursorPosition = position;
6657    }
6658
6659    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6660            int fromIndex, int toIndex) {
6661        if (mParent == null) {
6662            return;
6663        }
6664        AccessibilityEvent event = AccessibilityEvent.obtain(
6665                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6666        onInitializeAccessibilityEvent(event);
6667        onPopulateAccessibilityEvent(event);
6668        event.setFromIndex(fromIndex);
6669        event.setToIndex(toIndex);
6670        event.setAction(action);
6671        event.setMovementGranularity(granularity);
6672        mParent.requestSendAccessibilityEvent(this, event);
6673    }
6674
6675    /**
6676     * @hide
6677     */
6678    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6679        switch (granularity) {
6680            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6681                CharSequence text = getIterableTextForAccessibility();
6682                if (text != null && text.length() > 0) {
6683                    CharacterTextSegmentIterator iterator =
6684                        CharacterTextSegmentIterator.getInstance(mContext);
6685                    iterator.initialize(text.toString());
6686                    return iterator;
6687                }
6688            } break;
6689            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6690                CharSequence text = getIterableTextForAccessibility();
6691                if (text != null && text.length() > 0) {
6692                    WordTextSegmentIterator iterator =
6693                        WordTextSegmentIterator.getInstance(mContext);
6694                    iterator.initialize(text.toString());
6695                    return iterator;
6696                }
6697            } break;
6698            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6699                CharSequence text = getIterableTextForAccessibility();
6700                if (text != null && text.length() > 0) {
6701                    ParagraphTextSegmentIterator iterator =
6702                        ParagraphTextSegmentIterator.getInstance();
6703                    iterator.initialize(text.toString());
6704                    return iterator;
6705                }
6706            } break;
6707        }
6708        return null;
6709    }
6710
6711    /**
6712     * @hide
6713     */
6714    public void dispatchStartTemporaryDetach() {
6715        clearAccessibilityFocus();
6716        onStartTemporaryDetach();
6717    }
6718
6719    /**
6720     * This is called when a container is going to temporarily detach a child, with
6721     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6722     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6723     * {@link #onDetachedFromWindow()} when the container is done.
6724     */
6725    public void onStartTemporaryDetach() {
6726        removeUnsetPressCallback();
6727        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6728    }
6729
6730    /**
6731     * @hide
6732     */
6733    public void dispatchFinishTemporaryDetach() {
6734        onFinishTemporaryDetach();
6735    }
6736
6737    /**
6738     * Called after {@link #onStartTemporaryDetach} when the container is done
6739     * changing the view.
6740     */
6741    public void onFinishTemporaryDetach() {
6742    }
6743
6744    /**
6745     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6746     * for this view's window.  Returns null if the view is not currently attached
6747     * to the window.  Normally you will not need to use this directly, but
6748     * just use the standard high-level event callbacks like
6749     * {@link #onKeyDown(int, KeyEvent)}.
6750     */
6751    public KeyEvent.DispatcherState getKeyDispatcherState() {
6752        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6753    }
6754
6755    /**
6756     * Dispatch a key event before it is processed by any input method
6757     * associated with the view hierarchy.  This can be used to intercept
6758     * key events in special situations before the IME consumes them; a
6759     * typical example would be handling the BACK key to update the application's
6760     * UI instead of allowing the IME to see it and close itself.
6761     *
6762     * @param event The key event to be dispatched.
6763     * @return True if the event was handled, false otherwise.
6764     */
6765    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6766        return onKeyPreIme(event.getKeyCode(), event);
6767    }
6768
6769    /**
6770     * Dispatch a key event to the next view on the focus path. This path runs
6771     * from the top of the view tree down to the currently focused view. If this
6772     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6773     * the next node down the focus path. This method also fires any key
6774     * listeners.
6775     *
6776     * @param event The key event to be dispatched.
6777     * @return True if the event was handled, false otherwise.
6778     */
6779    public boolean dispatchKeyEvent(KeyEvent event) {
6780        if (mInputEventConsistencyVerifier != null) {
6781            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6782        }
6783
6784        // Give any attached key listener a first crack at the event.
6785        //noinspection SimplifiableIfStatement
6786        ListenerInfo li = mListenerInfo;
6787        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6788                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6789            return true;
6790        }
6791
6792        if (event.dispatch(this, mAttachInfo != null
6793                ? mAttachInfo.mKeyDispatchState : null, this)) {
6794            return true;
6795        }
6796
6797        if (mInputEventConsistencyVerifier != null) {
6798            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6799        }
6800        return false;
6801    }
6802
6803    /**
6804     * Dispatches a key shortcut event.
6805     *
6806     * @param event The key event to be dispatched.
6807     * @return True if the event was handled by the view, false otherwise.
6808     */
6809    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6810        return onKeyShortcut(event.getKeyCode(), event);
6811    }
6812
6813    /**
6814     * Pass the touch screen motion event down to the target view, or this
6815     * view if it is the target.
6816     *
6817     * @param event The motion event to be dispatched.
6818     * @return True if the event was handled by the view, false otherwise.
6819     */
6820    public boolean dispatchTouchEvent(MotionEvent event) {
6821        if (mInputEventConsistencyVerifier != null) {
6822            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6823        }
6824
6825        if (onFilterTouchEventForSecurity(event)) {
6826            //noinspection SimplifiableIfStatement
6827            ListenerInfo li = mListenerInfo;
6828            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6829                    && li.mOnTouchListener.onTouch(this, event)) {
6830                return true;
6831            }
6832
6833            if (onTouchEvent(event)) {
6834                return true;
6835            }
6836        }
6837
6838        if (mInputEventConsistencyVerifier != null) {
6839            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6840        }
6841        return false;
6842    }
6843
6844    /**
6845     * Filter the touch event to apply security policies.
6846     *
6847     * @param event The motion event to be filtered.
6848     * @return True if the event should be dispatched, false if the event should be dropped.
6849     *
6850     * @see #getFilterTouchesWhenObscured
6851     */
6852    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6853        //noinspection RedundantIfStatement
6854        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6855                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6856            // Window is obscured, drop this touch.
6857            return false;
6858        }
6859        return true;
6860    }
6861
6862    /**
6863     * Pass a trackball motion event down to the focused view.
6864     *
6865     * @param event The motion event to be dispatched.
6866     * @return True if the event was handled by the view, false otherwise.
6867     */
6868    public boolean dispatchTrackballEvent(MotionEvent event) {
6869        if (mInputEventConsistencyVerifier != null) {
6870            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6871        }
6872
6873        return onTrackballEvent(event);
6874    }
6875
6876    /**
6877     * Dispatch a generic motion event.
6878     * <p>
6879     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6880     * are delivered to the view under the pointer.  All other generic motion events are
6881     * delivered to the focused view.  Hover events are handled specially and are delivered
6882     * to {@link #onHoverEvent(MotionEvent)}.
6883     * </p>
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 dispatchGenericMotionEvent(MotionEvent event) {
6889        if (mInputEventConsistencyVerifier != null) {
6890            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6891        }
6892
6893        final int source = event.getSource();
6894        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6895            final int action = event.getAction();
6896            if (action == MotionEvent.ACTION_HOVER_ENTER
6897                    || action == MotionEvent.ACTION_HOVER_MOVE
6898                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6899                if (dispatchHoverEvent(event)) {
6900                    return true;
6901                }
6902            } else if (dispatchGenericPointerEvent(event)) {
6903                return true;
6904            }
6905        } else if (dispatchGenericFocusedEvent(event)) {
6906            return true;
6907        }
6908
6909        if (dispatchGenericMotionEventInternal(event)) {
6910            return true;
6911        }
6912
6913        if (mInputEventConsistencyVerifier != null) {
6914            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6915        }
6916        return false;
6917    }
6918
6919    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6920        //noinspection SimplifiableIfStatement
6921        ListenerInfo li = mListenerInfo;
6922        if (li != null && li.mOnGenericMotionListener != null
6923                && (mViewFlags & ENABLED_MASK) == ENABLED
6924                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6925            return true;
6926        }
6927
6928        if (onGenericMotionEvent(event)) {
6929            return true;
6930        }
6931
6932        if (mInputEventConsistencyVerifier != null) {
6933            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6934        }
6935        return false;
6936    }
6937
6938    /**
6939     * Dispatch a hover event.
6940     * <p>
6941     * Do not call this method directly.
6942     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6943     * </p>
6944     *
6945     * @param event The motion event to be dispatched.
6946     * @return True if the event was handled by the view, false otherwise.
6947     */
6948    protected boolean dispatchHoverEvent(MotionEvent event) {
6949        //noinspection SimplifiableIfStatement
6950        ListenerInfo li = mListenerInfo;
6951        if (li != null && li.mOnHoverListener != null
6952                && (mViewFlags & ENABLED_MASK) == ENABLED
6953                && li.mOnHoverListener.onHover(this, event)) {
6954            return true;
6955        }
6956
6957        return onHoverEvent(event);
6958    }
6959
6960    /**
6961     * Returns true if the view has a child to which it has recently sent
6962     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6963     * it does not have a hovered child, then it must be the innermost hovered view.
6964     * @hide
6965     */
6966    protected boolean hasHoveredChild() {
6967        return false;
6968    }
6969
6970    /**
6971     * Dispatch a generic motion event to the view under the first pointer.
6972     * <p>
6973     * Do not call this method directly.
6974     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6975     * </p>
6976     *
6977     * @param event The motion event to be dispatched.
6978     * @return True if the event was handled by the view, false otherwise.
6979     */
6980    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6981        return false;
6982    }
6983
6984    /**
6985     * Dispatch a generic motion event to the currently focused view.
6986     * <p>
6987     * Do not call this method directly.
6988     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6989     * </p>
6990     *
6991     * @param event The motion event to be dispatched.
6992     * @return True if the event was handled by the view, false otherwise.
6993     */
6994    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6995        return false;
6996    }
6997
6998    /**
6999     * Dispatch a pointer event.
7000     * <p>
7001     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7002     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7003     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7004     * and should not be expected to handle other pointing device features.
7005     * </p>
7006     *
7007     * @param event The motion event to be dispatched.
7008     * @return True if the event was handled by the view, false otherwise.
7009     * @hide
7010     */
7011    public final boolean dispatchPointerEvent(MotionEvent event) {
7012        if (event.isTouchEvent()) {
7013            return dispatchTouchEvent(event);
7014        } else {
7015            return dispatchGenericMotionEvent(event);
7016        }
7017    }
7018
7019    /**
7020     * Called when the window containing this view gains or loses window focus.
7021     * ViewGroups should override to route to their children.
7022     *
7023     * @param hasFocus True if the window containing this view now has focus,
7024     *        false otherwise.
7025     */
7026    public void dispatchWindowFocusChanged(boolean hasFocus) {
7027        onWindowFocusChanged(hasFocus);
7028    }
7029
7030    /**
7031     * Called when the window containing this view gains or loses focus.  Note
7032     * that this is separate from view focus: to receive key events, both
7033     * your view and its window must have focus.  If a window is displayed
7034     * on top of yours that takes input focus, then your own window will lose
7035     * focus but the view focus will remain unchanged.
7036     *
7037     * @param hasWindowFocus True if the window containing this view now has
7038     *        focus, false otherwise.
7039     */
7040    public void onWindowFocusChanged(boolean hasWindowFocus) {
7041        InputMethodManager imm = InputMethodManager.peekInstance();
7042        if (!hasWindowFocus) {
7043            if (isPressed()) {
7044                setPressed(false);
7045            }
7046            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7047                imm.focusOut(this);
7048            }
7049            removeLongPressCallback();
7050            removeTapCallback();
7051            onFocusLost();
7052        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7053            imm.focusIn(this);
7054        }
7055        refreshDrawableState();
7056    }
7057
7058    /**
7059     * Returns true if this view is in a window that currently has window focus.
7060     * Note that this is not the same as the view itself having focus.
7061     *
7062     * @return True if this view is in a window that currently has window focus.
7063     */
7064    public boolean hasWindowFocus() {
7065        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7066    }
7067
7068    /**
7069     * Dispatch a view visibility change down the view hierarchy.
7070     * ViewGroups should override to route to their children.
7071     * @param changedView The view whose visibility changed. Could be 'this' or
7072     * an ancestor view.
7073     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7074     * {@link #INVISIBLE} or {@link #GONE}.
7075     */
7076    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7077        onVisibilityChanged(changedView, visibility);
7078    }
7079
7080    /**
7081     * Called when the visibility of the view or an ancestor of the view is changed.
7082     * @param changedView The view whose visibility changed. Could be 'this' or
7083     * an ancestor view.
7084     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7085     * {@link #INVISIBLE} or {@link #GONE}.
7086     */
7087    protected void onVisibilityChanged(View changedView, int visibility) {
7088        if (visibility == VISIBLE) {
7089            if (mAttachInfo != null) {
7090                initialAwakenScrollBars();
7091            } else {
7092                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7093            }
7094        }
7095    }
7096
7097    /**
7098     * Dispatch a hint about whether this view is displayed. For instance, when
7099     * a View moves out of the screen, it might receives a display hint indicating
7100     * the view is not displayed. Applications should not <em>rely</em> on this hint
7101     * as there is no guarantee that they will receive one.
7102     *
7103     * @param hint A hint about whether or not this view is displayed:
7104     * {@link #VISIBLE} or {@link #INVISIBLE}.
7105     */
7106    public void dispatchDisplayHint(int hint) {
7107        onDisplayHint(hint);
7108    }
7109
7110    /**
7111     * Gives this view a hint about whether is displayed or not. For instance, when
7112     * a View moves out of the screen, it might receives a display hint indicating
7113     * the view is not displayed. Applications should not <em>rely</em> on this hint
7114     * as there is no guarantee that they will receive one.
7115     *
7116     * @param hint A hint about whether or not this view is displayed:
7117     * {@link #VISIBLE} or {@link #INVISIBLE}.
7118     */
7119    protected void onDisplayHint(int hint) {
7120    }
7121
7122    /**
7123     * Dispatch a window visibility change down the view hierarchy.
7124     * ViewGroups should override to route to their children.
7125     *
7126     * @param visibility The new visibility of the window.
7127     *
7128     * @see #onWindowVisibilityChanged(int)
7129     */
7130    public void dispatchWindowVisibilityChanged(int visibility) {
7131        onWindowVisibilityChanged(visibility);
7132    }
7133
7134    /**
7135     * Called when the window containing has change its visibility
7136     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7137     * that this tells you whether or not your window is being made visible
7138     * to the window manager; this does <em>not</em> tell you whether or not
7139     * your window is obscured by other windows on the screen, even if it
7140     * is itself visible.
7141     *
7142     * @param visibility The new visibility of the window.
7143     */
7144    protected void onWindowVisibilityChanged(int visibility) {
7145        if (visibility == VISIBLE) {
7146            initialAwakenScrollBars();
7147        }
7148    }
7149
7150    /**
7151     * Returns the current visibility of the window this view is attached to
7152     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7153     *
7154     * @return Returns the current visibility of the view's window.
7155     */
7156    public int getWindowVisibility() {
7157        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7158    }
7159
7160    /**
7161     * Retrieve the overall visible display size in which the window this view is
7162     * attached to has been positioned in.  This takes into account screen
7163     * decorations above the window, for both cases where the window itself
7164     * is being position inside of them or the window is being placed under
7165     * then and covered insets are used for the window to position its content
7166     * inside.  In effect, this tells you the available area where content can
7167     * be placed and remain visible to users.
7168     *
7169     * <p>This function requires an IPC back to the window manager to retrieve
7170     * the requested information, so should not be used in performance critical
7171     * code like drawing.
7172     *
7173     * @param outRect Filled in with the visible display frame.  If the view
7174     * is not attached to a window, this is simply the raw display size.
7175     */
7176    public void getWindowVisibleDisplayFrame(Rect outRect) {
7177        if (mAttachInfo != null) {
7178            try {
7179                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7180            } catch (RemoteException e) {
7181                return;
7182            }
7183            // XXX This is really broken, and probably all needs to be done
7184            // in the window manager, and we need to know more about whether
7185            // we want the area behind or in front of the IME.
7186            final Rect insets = mAttachInfo.mVisibleInsets;
7187            outRect.left += insets.left;
7188            outRect.top += insets.top;
7189            outRect.right -= insets.right;
7190            outRect.bottom -= insets.bottom;
7191            return;
7192        }
7193        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7194        d.getRectSize(outRect);
7195    }
7196
7197    /**
7198     * Dispatch a notification about a resource configuration change down
7199     * the view hierarchy.
7200     * ViewGroups should override to route to their children.
7201     *
7202     * @param newConfig The new resource configuration.
7203     *
7204     * @see #onConfigurationChanged(android.content.res.Configuration)
7205     */
7206    public void dispatchConfigurationChanged(Configuration newConfig) {
7207        onConfigurationChanged(newConfig);
7208    }
7209
7210    /**
7211     * Called when the current configuration of the resources being used
7212     * by the application have changed.  You can use this to decide when
7213     * to reload resources that can changed based on orientation and other
7214     * configuration characterstics.  You only need to use this if you are
7215     * not relying on the normal {@link android.app.Activity} mechanism of
7216     * recreating the activity instance upon a configuration change.
7217     *
7218     * @param newConfig The new resource configuration.
7219     */
7220    protected void onConfigurationChanged(Configuration newConfig) {
7221    }
7222
7223    /**
7224     * Private function to aggregate all per-view attributes in to the view
7225     * root.
7226     */
7227    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7228        performCollectViewAttributes(attachInfo, visibility);
7229    }
7230
7231    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7232        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7233            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7234                attachInfo.mKeepScreenOn = true;
7235            }
7236            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7237            ListenerInfo li = mListenerInfo;
7238            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7239                attachInfo.mHasSystemUiListeners = true;
7240            }
7241        }
7242    }
7243
7244    void needGlobalAttributesUpdate(boolean force) {
7245        final AttachInfo ai = mAttachInfo;
7246        if (ai != null) {
7247            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7248                    || ai.mHasSystemUiListeners) {
7249                ai.mRecomputeGlobalAttributes = true;
7250            }
7251        }
7252    }
7253
7254    /**
7255     * Returns whether the device is currently in touch mode.  Touch mode is entered
7256     * once the user begins interacting with the device by touch, and affects various
7257     * things like whether focus is always visible to the user.
7258     *
7259     * @return Whether the device is in touch mode.
7260     */
7261    @ViewDebug.ExportedProperty
7262    public boolean isInTouchMode() {
7263        if (mAttachInfo != null) {
7264            return mAttachInfo.mInTouchMode;
7265        } else {
7266            return ViewRootImpl.isInTouchMode();
7267        }
7268    }
7269
7270    /**
7271     * Returns the context the view is running in, through which it can
7272     * access the current theme, resources, etc.
7273     *
7274     * @return The view's Context.
7275     */
7276    @ViewDebug.CapturedViewProperty
7277    public final Context getContext() {
7278        return mContext;
7279    }
7280
7281    /**
7282     * Handle a key event before it is processed by any input method
7283     * associated with the view hierarchy.  This can be used to intercept
7284     * key events in special situations before the IME consumes them; a
7285     * typical example would be handling the BACK key to update the application's
7286     * UI instead of allowing the IME to see it and close itself.
7287     *
7288     * @param keyCode The value in event.getKeyCode().
7289     * @param event Description of the key event.
7290     * @return If you handled the event, return true. If you want to allow the
7291     *         event to be handled by the next receiver, return false.
7292     */
7293    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7294        return false;
7295    }
7296
7297    /**
7298     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7299     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7300     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7301     * is released, if the view is enabled and clickable.
7302     *
7303     * @param keyCode A key code that represents the button pressed, from
7304     *                {@link android.view.KeyEvent}.
7305     * @param event   The KeyEvent object that defines the button action.
7306     */
7307    public boolean onKeyDown(int keyCode, KeyEvent event) {
7308        boolean result = false;
7309
7310        switch (keyCode) {
7311            case KeyEvent.KEYCODE_DPAD_CENTER:
7312            case KeyEvent.KEYCODE_ENTER: {
7313                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7314                    return true;
7315                }
7316                // Long clickable items don't necessarily have to be clickable
7317                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7318                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7319                        (event.getRepeatCount() == 0)) {
7320                    setPressed(true);
7321                    checkForLongClick(0);
7322                    return true;
7323                }
7324                break;
7325            }
7326        }
7327        return result;
7328    }
7329
7330    /**
7331     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7332     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7333     * the event).
7334     */
7335    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7336        return false;
7337    }
7338
7339    /**
7340     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7341     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7342     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7343     * {@link KeyEvent#KEYCODE_ENTER} is released.
7344     *
7345     * @param keyCode A key code that represents the button pressed, from
7346     *                {@link android.view.KeyEvent}.
7347     * @param event   The KeyEvent object that defines the button action.
7348     */
7349    public boolean onKeyUp(int keyCode, KeyEvent event) {
7350        boolean result = false;
7351
7352        switch (keyCode) {
7353            case KeyEvent.KEYCODE_DPAD_CENTER:
7354            case KeyEvent.KEYCODE_ENTER: {
7355                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7356                    return true;
7357                }
7358                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7359                    setPressed(false);
7360
7361                    if (!mHasPerformedLongPress) {
7362                        // This is a tap, so remove the longpress check
7363                        removeLongPressCallback();
7364
7365                        result = performClick();
7366                    }
7367                }
7368                break;
7369            }
7370        }
7371        return result;
7372    }
7373
7374    /**
7375     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7376     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7377     * the event).
7378     *
7379     * @param keyCode     A key code that represents the button pressed, from
7380     *                    {@link android.view.KeyEvent}.
7381     * @param repeatCount The number of times the action was made.
7382     * @param event       The KeyEvent object that defines the button action.
7383     */
7384    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7385        return false;
7386    }
7387
7388    /**
7389     * Called on the focused view when a key shortcut event is not handled.
7390     * Override this method to implement local key shortcuts for the View.
7391     * Key shortcuts can also be implemented by setting the
7392     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7393     *
7394     * @param keyCode The value in event.getKeyCode().
7395     * @param event Description of the key event.
7396     * @return If you handled the event, return true. If you want to allow the
7397     *         event to be handled by the next receiver, return false.
7398     */
7399    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7400        return false;
7401    }
7402
7403    /**
7404     * Check whether the called view is a text editor, in which case it
7405     * would make sense to automatically display a soft input window for
7406     * it.  Subclasses should override this if they implement
7407     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7408     * a call on that method would return a non-null InputConnection, and
7409     * they are really a first-class editor that the user would normally
7410     * start typing on when the go into a window containing your view.
7411     *
7412     * <p>The default implementation always returns false.  This does
7413     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7414     * will not be called or the user can not otherwise perform edits on your
7415     * view; it is just a hint to the system that this is not the primary
7416     * purpose of this view.
7417     *
7418     * @return Returns true if this view is a text editor, else false.
7419     */
7420    public boolean onCheckIsTextEditor() {
7421        return false;
7422    }
7423
7424    /**
7425     * Create a new InputConnection for an InputMethod to interact
7426     * with the view.  The default implementation returns null, since it doesn't
7427     * support input methods.  You can override this to implement such support.
7428     * This is only needed for views that take focus and text input.
7429     *
7430     * <p>When implementing this, you probably also want to implement
7431     * {@link #onCheckIsTextEditor()} to indicate you will return a
7432     * non-null InputConnection.
7433     *
7434     * @param outAttrs Fill in with attribute information about the connection.
7435     */
7436    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7437        return null;
7438    }
7439
7440    /**
7441     * Called by the {@link android.view.inputmethod.InputMethodManager}
7442     * when a view who is not the current
7443     * input connection target is trying to make a call on the manager.  The
7444     * default implementation returns false; you can override this to return
7445     * true for certain views if you are performing InputConnection proxying
7446     * to them.
7447     * @param view The View that is making the InputMethodManager call.
7448     * @return Return true to allow the call, false to reject.
7449     */
7450    public boolean checkInputConnectionProxy(View view) {
7451        return false;
7452    }
7453
7454    /**
7455     * Show the context menu for this view. It is not safe to hold on to the
7456     * menu after returning from this method.
7457     *
7458     * You should normally not overload this method. Overload
7459     * {@link #onCreateContextMenu(ContextMenu)} or define an
7460     * {@link OnCreateContextMenuListener} to add items to the context menu.
7461     *
7462     * @param menu The context menu to populate
7463     */
7464    public void createContextMenu(ContextMenu menu) {
7465        ContextMenuInfo menuInfo = getContextMenuInfo();
7466
7467        // Sets the current menu info so all items added to menu will have
7468        // my extra info set.
7469        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7470
7471        onCreateContextMenu(menu);
7472        ListenerInfo li = mListenerInfo;
7473        if (li != null && li.mOnCreateContextMenuListener != null) {
7474            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7475        }
7476
7477        // Clear the extra information so subsequent items that aren't mine don't
7478        // have my extra info.
7479        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7480
7481        if (mParent != null) {
7482            mParent.createContextMenu(menu);
7483        }
7484    }
7485
7486    /**
7487     * Views should implement this if they have extra information to associate
7488     * with the context menu. The return result is supplied as a parameter to
7489     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7490     * callback.
7491     *
7492     * @return Extra information about the item for which the context menu
7493     *         should be shown. This information will vary across different
7494     *         subclasses of View.
7495     */
7496    protected ContextMenuInfo getContextMenuInfo() {
7497        return null;
7498    }
7499
7500    /**
7501     * Views should implement this if the view itself is going to add items to
7502     * the context menu.
7503     *
7504     * @param menu the context menu to populate
7505     */
7506    protected void onCreateContextMenu(ContextMenu menu) {
7507    }
7508
7509    /**
7510     * Implement this method to handle trackball motion events.  The
7511     * <em>relative</em> movement of the trackball since the last event
7512     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7513     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7514     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7515     * they will often be fractional values, representing the more fine-grained
7516     * movement information available from a trackball).
7517     *
7518     * @param event The motion event.
7519     * @return True if the event was handled, false otherwise.
7520     */
7521    public boolean onTrackballEvent(MotionEvent event) {
7522        return false;
7523    }
7524
7525    /**
7526     * Implement this method to handle generic motion events.
7527     * <p>
7528     * Generic motion events describe joystick movements, mouse hovers, track pad
7529     * touches, scroll wheel movements and other input events.  The
7530     * {@link MotionEvent#getSource() source} of the motion event specifies
7531     * the class of input that was received.  Implementations of this method
7532     * must examine the bits in the source before processing the event.
7533     * The following code example shows how this is done.
7534     * </p><p>
7535     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7536     * are delivered to the view under the pointer.  All other generic motion events are
7537     * delivered to the focused view.
7538     * </p>
7539     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7540     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7541     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7542     *             // process the joystick movement...
7543     *             return true;
7544     *         }
7545     *     }
7546     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7547     *         switch (event.getAction()) {
7548     *             case MotionEvent.ACTION_HOVER_MOVE:
7549     *                 // process the mouse hover movement...
7550     *                 return true;
7551     *             case MotionEvent.ACTION_SCROLL:
7552     *                 // process the scroll wheel movement...
7553     *                 return true;
7554     *         }
7555     *     }
7556     *     return super.onGenericMotionEvent(event);
7557     * }</pre>
7558     *
7559     * @param event The generic motion event being processed.
7560     * @return True if the event was handled, false otherwise.
7561     */
7562    public boolean onGenericMotionEvent(MotionEvent event) {
7563        return false;
7564    }
7565
7566    /**
7567     * Implement this method to handle hover events.
7568     * <p>
7569     * This method is called whenever a pointer is hovering into, over, or out of the
7570     * bounds of a view and the view is not currently being touched.
7571     * Hover events are represented as pointer events with action
7572     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7573     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7574     * </p>
7575     * <ul>
7576     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7577     * when the pointer enters the bounds of the view.</li>
7578     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7579     * when the pointer has already entered the bounds of the view and has moved.</li>
7580     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7581     * when the pointer has exited the bounds of the view or when the pointer is
7582     * about to go down due to a button click, tap, or similar user action that
7583     * causes the view to be touched.</li>
7584     * </ul>
7585     * <p>
7586     * The view should implement this method to return true to indicate that it is
7587     * handling the hover event, such as by changing its drawable state.
7588     * </p><p>
7589     * The default implementation calls {@link #setHovered} to update the hovered state
7590     * of the view when a hover enter or hover exit event is received, if the view
7591     * is enabled and is clickable.  The default implementation also sends hover
7592     * accessibility events.
7593     * </p>
7594     *
7595     * @param event The motion event that describes the hover.
7596     * @return True if the view handled the hover event.
7597     *
7598     * @see #isHovered
7599     * @see #setHovered
7600     * @see #onHoverChanged
7601     */
7602    public boolean onHoverEvent(MotionEvent event) {
7603        // The root view may receive hover (or touch) events that are outside the bounds of
7604        // the window.  This code ensures that we only send accessibility events for
7605        // hovers that are actually within the bounds of the root view.
7606        final int action = event.getActionMasked();
7607        if (!mSendingHoverAccessibilityEvents) {
7608            if ((action == MotionEvent.ACTION_HOVER_ENTER
7609                    || action == MotionEvent.ACTION_HOVER_MOVE)
7610                    && !hasHoveredChild()
7611                    && pointInView(event.getX(), event.getY())) {
7612                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7613                mSendingHoverAccessibilityEvents = true;
7614                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7615            }
7616        } else {
7617            if (action == MotionEvent.ACTION_HOVER_EXIT
7618                    || (action == MotionEvent.ACTION_MOVE
7619                            && !pointInView(event.getX(), event.getY()))) {
7620                mSendingHoverAccessibilityEvents = false;
7621                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7622                // If the window does not have input focus we take away accessibility
7623                // focus as soon as the user stop hovering over the view.
7624                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7625                    getViewRootImpl().setAccessibilityFocusedHost(null);
7626                }
7627            }
7628        }
7629
7630        if (isHoverable()) {
7631            switch (action) {
7632                case MotionEvent.ACTION_HOVER_ENTER:
7633                    setHovered(true);
7634                    break;
7635                case MotionEvent.ACTION_HOVER_EXIT:
7636                    setHovered(false);
7637                    break;
7638            }
7639
7640            // Dispatch the event to onGenericMotionEvent before returning true.
7641            // This is to provide compatibility with existing applications that
7642            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7643            // break because of the new default handling for hoverable views
7644            // in onHoverEvent.
7645            // Note that onGenericMotionEvent will be called by default when
7646            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7647            dispatchGenericMotionEventInternal(event);
7648            return true;
7649        }
7650
7651        return false;
7652    }
7653
7654    /**
7655     * Returns true if the view should handle {@link #onHoverEvent}
7656     * by calling {@link #setHovered} to change its hovered state.
7657     *
7658     * @return True if the view is hoverable.
7659     */
7660    private boolean isHoverable() {
7661        final int viewFlags = mViewFlags;
7662        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7663            return false;
7664        }
7665
7666        return (viewFlags & CLICKABLE) == CLICKABLE
7667                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7668    }
7669
7670    /**
7671     * Returns true if the view is currently hovered.
7672     *
7673     * @return True if the view is currently hovered.
7674     *
7675     * @see #setHovered
7676     * @see #onHoverChanged
7677     */
7678    @ViewDebug.ExportedProperty
7679    public boolean isHovered() {
7680        return (mPrivateFlags & HOVERED) != 0;
7681    }
7682
7683    /**
7684     * Sets whether the view is currently hovered.
7685     * <p>
7686     * Calling this method also changes the drawable state of the view.  This
7687     * enables the view to react to hover by using different drawable resources
7688     * to change its appearance.
7689     * </p><p>
7690     * The {@link #onHoverChanged} method is called when the hovered state changes.
7691     * </p>
7692     *
7693     * @param hovered True if the view is hovered.
7694     *
7695     * @see #isHovered
7696     * @see #onHoverChanged
7697     */
7698    public void setHovered(boolean hovered) {
7699        if (hovered) {
7700            if ((mPrivateFlags & HOVERED) == 0) {
7701                mPrivateFlags |= HOVERED;
7702                refreshDrawableState();
7703                onHoverChanged(true);
7704            }
7705        } else {
7706            if ((mPrivateFlags & HOVERED) != 0) {
7707                mPrivateFlags &= ~HOVERED;
7708                refreshDrawableState();
7709                onHoverChanged(false);
7710            }
7711        }
7712    }
7713
7714    /**
7715     * Implement this method to handle hover state changes.
7716     * <p>
7717     * This method is called whenever the hover state changes as a result of a
7718     * call to {@link #setHovered}.
7719     * </p>
7720     *
7721     * @param hovered The current hover state, as returned by {@link #isHovered}.
7722     *
7723     * @see #isHovered
7724     * @see #setHovered
7725     */
7726    public void onHoverChanged(boolean hovered) {
7727    }
7728
7729    /**
7730     * Implement this method to handle touch screen motion events.
7731     *
7732     * @param event The motion event.
7733     * @return True if the event was handled, false otherwise.
7734     */
7735    public boolean onTouchEvent(MotionEvent event) {
7736        final int viewFlags = mViewFlags;
7737
7738        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7739            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7740                setPressed(false);
7741            }
7742            // A disabled view that is clickable still consumes the touch
7743            // events, it just doesn't respond to them.
7744            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7745                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7746        }
7747
7748        if (mTouchDelegate != null) {
7749            if (mTouchDelegate.onTouchEvent(event)) {
7750                return true;
7751            }
7752        }
7753
7754        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7755                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7756            switch (event.getAction()) {
7757                case MotionEvent.ACTION_UP:
7758                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7759                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7760                        // take focus if we don't have it already and we should in
7761                        // touch mode.
7762                        boolean focusTaken = false;
7763                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7764                            focusTaken = requestFocus();
7765                        }
7766
7767                        if (prepressed) {
7768                            // The button is being released before we actually
7769                            // showed it as pressed.  Make it show the pressed
7770                            // state now (before scheduling the click) to ensure
7771                            // the user sees it.
7772                            setPressed(true);
7773                       }
7774
7775                        if (!mHasPerformedLongPress) {
7776                            // This is a tap, so remove the longpress check
7777                            removeLongPressCallback();
7778
7779                            // Only perform take click actions if we were in the pressed state
7780                            if (!focusTaken) {
7781                                // Use a Runnable and post this rather than calling
7782                                // performClick directly. This lets other visual state
7783                                // of the view update before click actions start.
7784                                if (mPerformClick == null) {
7785                                    mPerformClick = new PerformClick();
7786                                }
7787                                if (!post(mPerformClick)) {
7788                                    performClick();
7789                                }
7790                            }
7791                        }
7792
7793                        if (mUnsetPressedState == null) {
7794                            mUnsetPressedState = new UnsetPressedState();
7795                        }
7796
7797                        if (prepressed) {
7798                            postDelayed(mUnsetPressedState,
7799                                    ViewConfiguration.getPressedStateDuration());
7800                        } else if (!post(mUnsetPressedState)) {
7801                            // If the post failed, unpress right now
7802                            mUnsetPressedState.run();
7803                        }
7804                        removeTapCallback();
7805                    }
7806                    break;
7807
7808                case MotionEvent.ACTION_DOWN:
7809                    mHasPerformedLongPress = false;
7810
7811                    if (performButtonActionOnTouchDown(event)) {
7812                        break;
7813                    }
7814
7815                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7816                    boolean isInScrollingContainer = isInScrollingContainer();
7817
7818                    // For views inside a scrolling container, delay the pressed feedback for
7819                    // a short period in case this is a scroll.
7820                    if (isInScrollingContainer) {
7821                        mPrivateFlags |= PREPRESSED;
7822                        if (mPendingCheckForTap == null) {
7823                            mPendingCheckForTap = new CheckForTap();
7824                        }
7825                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7826                    } else {
7827                        // Not inside a scrolling container, so show the feedback right away
7828                        setPressed(true);
7829                        checkForLongClick(0);
7830                    }
7831                    break;
7832
7833                case MotionEvent.ACTION_CANCEL:
7834                    setPressed(false);
7835                    removeTapCallback();
7836                    break;
7837
7838                case MotionEvent.ACTION_MOVE:
7839                    final int x = (int) event.getX();
7840                    final int y = (int) event.getY();
7841
7842                    // Be lenient about moving outside of buttons
7843                    if (!pointInView(x, y, mTouchSlop)) {
7844                        // Outside button
7845                        removeTapCallback();
7846                        if ((mPrivateFlags & PRESSED) != 0) {
7847                            // Remove any future long press/tap checks
7848                            removeLongPressCallback();
7849
7850                            setPressed(false);
7851                        }
7852                    }
7853                    break;
7854            }
7855            return true;
7856        }
7857
7858        return false;
7859    }
7860
7861    /**
7862     * @hide
7863     */
7864    public boolean isInScrollingContainer() {
7865        ViewParent p = getParent();
7866        while (p != null && p instanceof ViewGroup) {
7867            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7868                return true;
7869            }
7870            p = p.getParent();
7871        }
7872        return false;
7873    }
7874
7875    /**
7876     * Remove the longpress detection timer.
7877     */
7878    private void removeLongPressCallback() {
7879        if (mPendingCheckForLongPress != null) {
7880          removeCallbacks(mPendingCheckForLongPress);
7881        }
7882    }
7883
7884    /**
7885     * Remove the pending click action
7886     */
7887    private void removePerformClickCallback() {
7888        if (mPerformClick != null) {
7889            removeCallbacks(mPerformClick);
7890        }
7891    }
7892
7893    /**
7894     * Remove the prepress detection timer.
7895     */
7896    private void removeUnsetPressCallback() {
7897        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7898            setPressed(false);
7899            removeCallbacks(mUnsetPressedState);
7900        }
7901    }
7902
7903    /**
7904     * Remove the tap detection timer.
7905     */
7906    private void removeTapCallback() {
7907        if (mPendingCheckForTap != null) {
7908            mPrivateFlags &= ~PREPRESSED;
7909            removeCallbacks(mPendingCheckForTap);
7910        }
7911    }
7912
7913    /**
7914     * Cancels a pending long press.  Your subclass can use this if you
7915     * want the context menu to come up if the user presses and holds
7916     * at the same place, but you don't want it to come up if they press
7917     * and then move around enough to cause scrolling.
7918     */
7919    public void cancelLongPress() {
7920        removeLongPressCallback();
7921
7922        /*
7923         * The prepressed state handled by the tap callback is a display
7924         * construct, but the tap callback will post a long press callback
7925         * less its own timeout. Remove it here.
7926         */
7927        removeTapCallback();
7928    }
7929
7930    /**
7931     * Remove the pending callback for sending a
7932     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7933     */
7934    private void removeSendViewScrolledAccessibilityEventCallback() {
7935        if (mSendViewScrolledAccessibilityEvent != null) {
7936            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7937        }
7938    }
7939
7940    /**
7941     * Sets the TouchDelegate for this View.
7942     */
7943    public void setTouchDelegate(TouchDelegate delegate) {
7944        mTouchDelegate = delegate;
7945    }
7946
7947    /**
7948     * Gets the TouchDelegate for this View.
7949     */
7950    public TouchDelegate getTouchDelegate() {
7951        return mTouchDelegate;
7952    }
7953
7954    /**
7955     * Set flags controlling behavior of this view.
7956     *
7957     * @param flags Constant indicating the value which should be set
7958     * @param mask Constant indicating the bit range that should be changed
7959     */
7960    void setFlags(int flags, int mask) {
7961        int old = mViewFlags;
7962        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7963
7964        int changed = mViewFlags ^ old;
7965        if (changed == 0) {
7966            return;
7967        }
7968        int privateFlags = mPrivateFlags;
7969
7970        /* Check if the FOCUSABLE bit has changed */
7971        if (((changed & FOCUSABLE_MASK) != 0) &&
7972                ((privateFlags & HAS_BOUNDS) !=0)) {
7973            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7974                    && ((privateFlags & FOCUSED) != 0)) {
7975                /* Give up focus if we are no longer focusable */
7976                clearFocus();
7977            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7978                    && ((privateFlags & FOCUSED) == 0)) {
7979                /*
7980                 * Tell the view system that we are now available to take focus
7981                 * if no one else already has it.
7982                 */
7983                if (mParent != null) mParent.focusableViewAvailable(this);
7984            }
7985            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7986                notifyAccessibilityStateChanged();
7987            }
7988        }
7989
7990        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7991            if ((changed & VISIBILITY_MASK) != 0) {
7992                /*
7993                 * If this view is becoming visible, invalidate it in case it changed while
7994                 * it was not visible. Marking it drawn ensures that the invalidation will
7995                 * go through.
7996                 */
7997                mPrivateFlags |= DRAWN;
7998                invalidate(true);
7999
8000                needGlobalAttributesUpdate(true);
8001
8002                // a view becoming visible is worth notifying the parent
8003                // about in case nothing has focus.  even if this specific view
8004                // isn't focusable, it may contain something that is, so let
8005                // the root view try to give this focus if nothing else does.
8006                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8007                    mParent.focusableViewAvailable(this);
8008                }
8009            }
8010        }
8011
8012        /* Check if the GONE bit has changed */
8013        if ((changed & GONE) != 0) {
8014            needGlobalAttributesUpdate(false);
8015            requestLayout();
8016
8017            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8018                if (hasFocus()) clearFocus();
8019                clearAccessibilityFocus();
8020                destroyDrawingCache();
8021                if (mParent instanceof View) {
8022                    // GONE views noop invalidation, so invalidate the parent
8023                    ((View) mParent).invalidate(true);
8024                }
8025                // Mark the view drawn to ensure that it gets invalidated properly the next
8026                // time it is visible and gets invalidated
8027                mPrivateFlags |= DRAWN;
8028            }
8029            if (mAttachInfo != null) {
8030                mAttachInfo.mViewVisibilityChanged = true;
8031            }
8032        }
8033
8034        /* Check if the VISIBLE bit has changed */
8035        if ((changed & INVISIBLE) != 0) {
8036            needGlobalAttributesUpdate(false);
8037            /*
8038             * If this view is becoming invisible, set the DRAWN flag so that
8039             * the next invalidate() will not be skipped.
8040             */
8041            mPrivateFlags |= DRAWN;
8042
8043            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8044                // root view becoming invisible shouldn't clear focus and accessibility focus
8045                if (getRootView() != this) {
8046                    clearFocus();
8047                    clearAccessibilityFocus();
8048                }
8049            }
8050            if (mAttachInfo != null) {
8051                mAttachInfo.mViewVisibilityChanged = true;
8052            }
8053        }
8054
8055        if ((changed & VISIBILITY_MASK) != 0) {
8056            if (mParent instanceof ViewGroup) {
8057                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8058                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8059                ((View) mParent).invalidate(true);
8060            } else if (mParent != null) {
8061                mParent.invalidateChild(this, null);
8062            }
8063            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8064        }
8065
8066        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8067            destroyDrawingCache();
8068        }
8069
8070        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8071            destroyDrawingCache();
8072            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8073            invalidateParentCaches();
8074        }
8075
8076        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8077            destroyDrawingCache();
8078            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8079        }
8080
8081        if ((changed & DRAW_MASK) != 0) {
8082            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8083                if (mBackground != null) {
8084                    mPrivateFlags &= ~SKIP_DRAW;
8085                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8086                } else {
8087                    mPrivateFlags |= SKIP_DRAW;
8088                }
8089            } else {
8090                mPrivateFlags &= ~SKIP_DRAW;
8091            }
8092            requestLayout();
8093            invalidate(true);
8094        }
8095
8096        if ((changed & KEEP_SCREEN_ON) != 0) {
8097            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8098                mParent.recomputeViewAttributes(this);
8099            }
8100        }
8101
8102        if (AccessibilityManager.getInstance(mContext).isEnabled()
8103                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8104                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8105            notifyAccessibilityStateChanged();
8106        }
8107    }
8108
8109    /**
8110     * Change the view's z order in the tree, so it's on top of other sibling
8111     * views
8112     */
8113    public void bringToFront() {
8114        if (mParent != null) {
8115            mParent.bringChildToFront(this);
8116        }
8117    }
8118
8119    /**
8120     * This is called in response to an internal scroll in this view (i.e., the
8121     * view scrolled its own contents). This is typically as a result of
8122     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8123     * called.
8124     *
8125     * @param l Current horizontal scroll origin.
8126     * @param t Current vertical scroll origin.
8127     * @param oldl Previous horizontal scroll origin.
8128     * @param oldt Previous vertical scroll origin.
8129     */
8130    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8131        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8132            postSendViewScrolledAccessibilityEventCallback();
8133        }
8134
8135        mBackgroundSizeChanged = true;
8136
8137        final AttachInfo ai = mAttachInfo;
8138        if (ai != null) {
8139            ai.mViewScrollChanged = true;
8140        }
8141    }
8142
8143    /**
8144     * Interface definition for a callback to be invoked when the layout bounds of a view
8145     * changes due to layout processing.
8146     */
8147    public interface OnLayoutChangeListener {
8148        /**
8149         * Called when the focus state of a view has changed.
8150         *
8151         * @param v The view whose state has changed.
8152         * @param left The new value of the view's left property.
8153         * @param top The new value of the view's top property.
8154         * @param right The new value of the view's right property.
8155         * @param bottom The new value of the view's bottom property.
8156         * @param oldLeft The previous value of the view's left property.
8157         * @param oldTop The previous value of the view's top property.
8158         * @param oldRight The previous value of the view's right property.
8159         * @param oldBottom The previous value of the view's bottom property.
8160         */
8161        void onLayoutChange(View v, int left, int top, int right, int bottom,
8162            int oldLeft, int oldTop, int oldRight, int oldBottom);
8163    }
8164
8165    /**
8166     * This is called during layout when the size of this view has changed. If
8167     * you were just added to the view hierarchy, you're called with the old
8168     * values of 0.
8169     *
8170     * @param w Current width of this view.
8171     * @param h Current height of this view.
8172     * @param oldw Old width of this view.
8173     * @param oldh Old height of this view.
8174     */
8175    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8176    }
8177
8178    /**
8179     * Called by draw to draw the child views. This may be overridden
8180     * by derived classes to gain control just before its children are drawn
8181     * (but after its own view has been drawn).
8182     * @param canvas the canvas on which to draw the view
8183     */
8184    protected void dispatchDraw(Canvas canvas) {
8185
8186    }
8187
8188    /**
8189     * Gets the parent of this view. Note that the parent is a
8190     * ViewParent and not necessarily a View.
8191     *
8192     * @return Parent of this view.
8193     */
8194    public final ViewParent getParent() {
8195        return mParent;
8196    }
8197
8198    /**
8199     * Set the horizontal scrolled position of your view. This will cause a call to
8200     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8201     * invalidated.
8202     * @param value the x position to scroll to
8203     */
8204    public void setScrollX(int value) {
8205        scrollTo(value, mScrollY);
8206    }
8207
8208    /**
8209     * Set the vertical scrolled position of your view. This will cause a call to
8210     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8211     * invalidated.
8212     * @param value the y position to scroll to
8213     */
8214    public void setScrollY(int value) {
8215        scrollTo(mScrollX, value);
8216    }
8217
8218    /**
8219     * Return the scrolled left position of this view. This is the left edge of
8220     * the displayed part of your view. You do not need to draw any pixels
8221     * farther left, since those are outside of the frame of your view on
8222     * screen.
8223     *
8224     * @return The left edge of the displayed part of your view, in pixels.
8225     */
8226    public final int getScrollX() {
8227        return mScrollX;
8228    }
8229
8230    /**
8231     * Return the scrolled top position of this view. This is the top edge of
8232     * the displayed part of your view. You do not need to draw any pixels above
8233     * it, since those are outside of the frame of your view on screen.
8234     *
8235     * @return The top edge of the displayed part of your view, in pixels.
8236     */
8237    public final int getScrollY() {
8238        return mScrollY;
8239    }
8240
8241    /**
8242     * Return the width of the your view.
8243     *
8244     * @return The width of your view, in pixels.
8245     */
8246    @ViewDebug.ExportedProperty(category = "layout")
8247    public final int getWidth() {
8248        return mRight - mLeft;
8249    }
8250
8251    /**
8252     * Return the height of your view.
8253     *
8254     * @return The height of your view, in pixels.
8255     */
8256    @ViewDebug.ExportedProperty(category = "layout")
8257    public final int getHeight() {
8258        return mBottom - mTop;
8259    }
8260
8261    /**
8262     * Return the visible drawing bounds of your view. Fills in the output
8263     * rectangle with the values from getScrollX(), getScrollY(),
8264     * getWidth(), and getHeight().
8265     *
8266     * @param outRect The (scrolled) drawing bounds of the view.
8267     */
8268    public void getDrawingRect(Rect outRect) {
8269        outRect.left = mScrollX;
8270        outRect.top = mScrollY;
8271        outRect.right = mScrollX + (mRight - mLeft);
8272        outRect.bottom = mScrollY + (mBottom - mTop);
8273    }
8274
8275    /**
8276     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8277     * raw width component (that is the result is masked by
8278     * {@link #MEASURED_SIZE_MASK}).
8279     *
8280     * @return The raw measured width of this view.
8281     */
8282    public final int getMeasuredWidth() {
8283        return mMeasuredWidth & MEASURED_SIZE_MASK;
8284    }
8285
8286    /**
8287     * Return the full width measurement information for this view as computed
8288     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8289     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8290     * This should be used during measurement and layout calculations only. Use
8291     * {@link #getWidth()} to see how wide a view is after layout.
8292     *
8293     * @return The measured width of this view as a bit mask.
8294     */
8295    public final int getMeasuredWidthAndState() {
8296        return mMeasuredWidth;
8297    }
8298
8299    /**
8300     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8301     * raw width component (that is the result is masked by
8302     * {@link #MEASURED_SIZE_MASK}).
8303     *
8304     * @return The raw measured height of this view.
8305     */
8306    public final int getMeasuredHeight() {
8307        return mMeasuredHeight & MEASURED_SIZE_MASK;
8308    }
8309
8310    /**
8311     * Return the full height measurement information for this view as computed
8312     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8313     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8314     * This should be used during measurement and layout calculations only. Use
8315     * {@link #getHeight()} to see how wide a view is after layout.
8316     *
8317     * @return The measured width of this view as a bit mask.
8318     */
8319    public final int getMeasuredHeightAndState() {
8320        return mMeasuredHeight;
8321    }
8322
8323    /**
8324     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8325     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8326     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8327     * and the height component is at the shifted bits
8328     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8329     */
8330    public final int getMeasuredState() {
8331        return (mMeasuredWidth&MEASURED_STATE_MASK)
8332                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8333                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8334    }
8335
8336    /**
8337     * The transform matrix of this view, which is calculated based on the current
8338     * roation, scale, and pivot properties.
8339     *
8340     * @see #getRotation()
8341     * @see #getScaleX()
8342     * @see #getScaleY()
8343     * @see #getPivotX()
8344     * @see #getPivotY()
8345     * @return The current transform matrix for the view
8346     */
8347    public Matrix getMatrix() {
8348        if (mTransformationInfo != null) {
8349            updateMatrix();
8350            return mTransformationInfo.mMatrix;
8351        }
8352        return Matrix.IDENTITY_MATRIX;
8353    }
8354
8355    /**
8356     * Utility function to determine if the value is far enough away from zero to be
8357     * considered non-zero.
8358     * @param value A floating point value to check for zero-ness
8359     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8360     */
8361    private static boolean nonzero(float value) {
8362        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8363    }
8364
8365    /**
8366     * Returns true if the transform matrix is the identity matrix.
8367     * Recomputes the matrix if necessary.
8368     *
8369     * @return True if the transform matrix is the identity matrix, false otherwise.
8370     */
8371    final boolean hasIdentityMatrix() {
8372        if (mTransformationInfo != null) {
8373            updateMatrix();
8374            return mTransformationInfo.mMatrixIsIdentity;
8375        }
8376        return true;
8377    }
8378
8379    void ensureTransformationInfo() {
8380        if (mTransformationInfo == null) {
8381            mTransformationInfo = new TransformationInfo();
8382        }
8383    }
8384
8385    /**
8386     * Recomputes the transform matrix if necessary.
8387     */
8388    private void updateMatrix() {
8389        final TransformationInfo info = mTransformationInfo;
8390        if (info == null) {
8391            return;
8392        }
8393        if (info.mMatrixDirty) {
8394            // transform-related properties have changed since the last time someone
8395            // asked for the matrix; recalculate it with the current values
8396
8397            // Figure out if we need to update the pivot point
8398            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8399                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8400                    info.mPrevWidth = mRight - mLeft;
8401                    info.mPrevHeight = mBottom - mTop;
8402                    info.mPivotX = info.mPrevWidth / 2f;
8403                    info.mPivotY = info.mPrevHeight / 2f;
8404                }
8405            }
8406            info.mMatrix.reset();
8407            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8408                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8409                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8410                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8411            } else {
8412                if (info.mCamera == null) {
8413                    info.mCamera = new Camera();
8414                    info.matrix3D = new Matrix();
8415                }
8416                info.mCamera.save();
8417                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8418                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8419                info.mCamera.getMatrix(info.matrix3D);
8420                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8421                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8422                        info.mPivotY + info.mTranslationY);
8423                info.mMatrix.postConcat(info.matrix3D);
8424                info.mCamera.restore();
8425            }
8426            info.mMatrixDirty = false;
8427            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8428            info.mInverseMatrixDirty = true;
8429        }
8430    }
8431
8432    /**
8433     * Utility method to retrieve the inverse of the current mMatrix property.
8434     * We cache the matrix to avoid recalculating it when transform properties
8435     * have not changed.
8436     *
8437     * @return The inverse of the current matrix of this view.
8438     */
8439    final Matrix getInverseMatrix() {
8440        final TransformationInfo info = mTransformationInfo;
8441        if (info != null) {
8442            updateMatrix();
8443            if (info.mInverseMatrixDirty) {
8444                if (info.mInverseMatrix == null) {
8445                    info.mInverseMatrix = new Matrix();
8446                }
8447                info.mMatrix.invert(info.mInverseMatrix);
8448                info.mInverseMatrixDirty = false;
8449            }
8450            return info.mInverseMatrix;
8451        }
8452        return Matrix.IDENTITY_MATRIX;
8453    }
8454
8455    /**
8456     * Gets the distance along the Z axis from the camera to this view.
8457     *
8458     * @see #setCameraDistance(float)
8459     *
8460     * @return The distance along the Z axis.
8461     */
8462    public float getCameraDistance() {
8463        ensureTransformationInfo();
8464        final float dpi = mResources.getDisplayMetrics().densityDpi;
8465        final TransformationInfo info = mTransformationInfo;
8466        if (info.mCamera == null) {
8467            info.mCamera = new Camera();
8468            info.matrix3D = new Matrix();
8469        }
8470        return -(info.mCamera.getLocationZ() * dpi);
8471    }
8472
8473    /**
8474     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8475     * views are drawn) from the camera to this view. The camera's distance
8476     * affects 3D transformations, for instance rotations around the X and Y
8477     * axis. If the rotationX or rotationY properties are changed and this view is
8478     * large (more than half the size of the screen), it is recommended to always
8479     * use a camera distance that's greater than the height (X axis rotation) or
8480     * the width (Y axis rotation) of this view.</p>
8481     *
8482     * <p>The distance of the camera from the view plane can have an affect on the
8483     * perspective distortion of the view when it is rotated around the x or y axis.
8484     * For example, a large distance will result in a large viewing angle, and there
8485     * will not be much perspective distortion of the view as it rotates. A short
8486     * distance may cause much more perspective distortion upon rotation, and can
8487     * also result in some drawing artifacts if the rotated view ends up partially
8488     * behind the camera (which is why the recommendation is to use a distance at
8489     * least as far as the size of the view, if the view is to be rotated.)</p>
8490     *
8491     * <p>The distance is expressed in "depth pixels." The default distance depends
8492     * on the screen density. For instance, on a medium density display, the
8493     * default distance is 1280. On a high density display, the default distance
8494     * is 1920.</p>
8495     *
8496     * <p>If you want to specify a distance that leads to visually consistent
8497     * results across various densities, use the following formula:</p>
8498     * <pre>
8499     * float scale = context.getResources().getDisplayMetrics().density;
8500     * view.setCameraDistance(distance * scale);
8501     * </pre>
8502     *
8503     * <p>The density scale factor of a high density display is 1.5,
8504     * and 1920 = 1280 * 1.5.</p>
8505     *
8506     * @param distance The distance in "depth pixels", if negative the opposite
8507     *        value is used
8508     *
8509     * @see #setRotationX(float)
8510     * @see #setRotationY(float)
8511     */
8512    public void setCameraDistance(float distance) {
8513        invalidateViewProperty(true, false);
8514
8515        ensureTransformationInfo();
8516        final float dpi = mResources.getDisplayMetrics().densityDpi;
8517        final TransformationInfo info = mTransformationInfo;
8518        if (info.mCamera == null) {
8519            info.mCamera = new Camera();
8520            info.matrix3D = new Matrix();
8521        }
8522
8523        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8524        info.mMatrixDirty = true;
8525
8526        invalidateViewProperty(false, false);
8527        if (mDisplayList != null) {
8528            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8529        }
8530    }
8531
8532    /**
8533     * The degrees that the view is rotated around the pivot point.
8534     *
8535     * @see #setRotation(float)
8536     * @see #getPivotX()
8537     * @see #getPivotY()
8538     *
8539     * @return The degrees of rotation.
8540     */
8541    @ViewDebug.ExportedProperty(category = "drawing")
8542    public float getRotation() {
8543        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8544    }
8545
8546    /**
8547     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8548     * result in clockwise rotation.
8549     *
8550     * @param rotation The degrees of rotation.
8551     *
8552     * @see #getRotation()
8553     * @see #getPivotX()
8554     * @see #getPivotY()
8555     * @see #setRotationX(float)
8556     * @see #setRotationY(float)
8557     *
8558     * @attr ref android.R.styleable#View_rotation
8559     */
8560    public void setRotation(float rotation) {
8561        ensureTransformationInfo();
8562        final TransformationInfo info = mTransformationInfo;
8563        if (info.mRotation != rotation) {
8564            // Double-invalidation is necessary to capture view's old and new areas
8565            invalidateViewProperty(true, false);
8566            info.mRotation = rotation;
8567            info.mMatrixDirty = true;
8568            invalidateViewProperty(false, true);
8569            if (mDisplayList != null) {
8570                mDisplayList.setRotation(rotation);
8571            }
8572        }
8573    }
8574
8575    /**
8576     * The degrees that the view is rotated around the vertical axis through the pivot point.
8577     *
8578     * @see #getPivotX()
8579     * @see #getPivotY()
8580     * @see #setRotationY(float)
8581     *
8582     * @return The degrees of Y rotation.
8583     */
8584    @ViewDebug.ExportedProperty(category = "drawing")
8585    public float getRotationY() {
8586        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8587    }
8588
8589    /**
8590     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8591     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8592     * down the y axis.
8593     *
8594     * When rotating large views, it is recommended to adjust the camera distance
8595     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8596     *
8597     * @param rotationY The degrees of Y rotation.
8598     *
8599     * @see #getRotationY()
8600     * @see #getPivotX()
8601     * @see #getPivotY()
8602     * @see #setRotation(float)
8603     * @see #setRotationX(float)
8604     * @see #setCameraDistance(float)
8605     *
8606     * @attr ref android.R.styleable#View_rotationY
8607     */
8608    public void setRotationY(float rotationY) {
8609        ensureTransformationInfo();
8610        final TransformationInfo info = mTransformationInfo;
8611        if (info.mRotationY != rotationY) {
8612            invalidateViewProperty(true, false);
8613            info.mRotationY = rotationY;
8614            info.mMatrixDirty = true;
8615            invalidateViewProperty(false, true);
8616            if (mDisplayList != null) {
8617                mDisplayList.setRotationY(rotationY);
8618            }
8619        }
8620    }
8621
8622    /**
8623     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8624     *
8625     * @see #getPivotX()
8626     * @see #getPivotY()
8627     * @see #setRotationX(float)
8628     *
8629     * @return The degrees of X rotation.
8630     */
8631    @ViewDebug.ExportedProperty(category = "drawing")
8632    public float getRotationX() {
8633        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8634    }
8635
8636    /**
8637     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8638     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8639     * x axis.
8640     *
8641     * When rotating large views, it is recommended to adjust the camera distance
8642     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8643     *
8644     * @param rotationX The degrees of X rotation.
8645     *
8646     * @see #getRotationX()
8647     * @see #getPivotX()
8648     * @see #getPivotY()
8649     * @see #setRotation(float)
8650     * @see #setRotationY(float)
8651     * @see #setCameraDistance(float)
8652     *
8653     * @attr ref android.R.styleable#View_rotationX
8654     */
8655    public void setRotationX(float rotationX) {
8656        ensureTransformationInfo();
8657        final TransformationInfo info = mTransformationInfo;
8658        if (info.mRotationX != rotationX) {
8659            invalidateViewProperty(true, false);
8660            info.mRotationX = rotationX;
8661            info.mMatrixDirty = true;
8662            invalidateViewProperty(false, true);
8663            if (mDisplayList != null) {
8664                mDisplayList.setRotationX(rotationX);
8665            }
8666        }
8667    }
8668
8669    /**
8670     * The amount that the view is scaled in x around the pivot point, as a proportion of
8671     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8672     *
8673     * <p>By default, this is 1.0f.
8674     *
8675     * @see #getPivotX()
8676     * @see #getPivotY()
8677     * @return The scaling factor.
8678     */
8679    @ViewDebug.ExportedProperty(category = "drawing")
8680    public float getScaleX() {
8681        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8682    }
8683
8684    /**
8685     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8686     * the view's unscaled width. A value of 1 means that no scaling is applied.
8687     *
8688     * @param scaleX The scaling factor.
8689     * @see #getPivotX()
8690     * @see #getPivotY()
8691     *
8692     * @attr ref android.R.styleable#View_scaleX
8693     */
8694    public void setScaleX(float scaleX) {
8695        ensureTransformationInfo();
8696        final TransformationInfo info = mTransformationInfo;
8697        if (info.mScaleX != scaleX) {
8698            invalidateViewProperty(true, false);
8699            info.mScaleX = scaleX;
8700            info.mMatrixDirty = true;
8701            invalidateViewProperty(false, true);
8702            if (mDisplayList != null) {
8703                mDisplayList.setScaleX(scaleX);
8704            }
8705        }
8706    }
8707
8708    /**
8709     * The amount that the view is scaled in y around the pivot point, as a proportion of
8710     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8711     *
8712     * <p>By default, this is 1.0f.
8713     *
8714     * @see #getPivotX()
8715     * @see #getPivotY()
8716     * @return The scaling factor.
8717     */
8718    @ViewDebug.ExportedProperty(category = "drawing")
8719    public float getScaleY() {
8720        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8721    }
8722
8723    /**
8724     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8725     * the view's unscaled width. A value of 1 means that no scaling is applied.
8726     *
8727     * @param scaleY The scaling factor.
8728     * @see #getPivotX()
8729     * @see #getPivotY()
8730     *
8731     * @attr ref android.R.styleable#View_scaleY
8732     */
8733    public void setScaleY(float scaleY) {
8734        ensureTransformationInfo();
8735        final TransformationInfo info = mTransformationInfo;
8736        if (info.mScaleY != scaleY) {
8737            invalidateViewProperty(true, false);
8738            info.mScaleY = scaleY;
8739            info.mMatrixDirty = true;
8740            invalidateViewProperty(false, true);
8741            if (mDisplayList != null) {
8742                mDisplayList.setScaleY(scaleY);
8743            }
8744        }
8745    }
8746
8747    /**
8748     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8749     * and {@link #setScaleX(float) scaled}.
8750     *
8751     * @see #getRotation()
8752     * @see #getScaleX()
8753     * @see #getScaleY()
8754     * @see #getPivotY()
8755     * @return The x location of the pivot point.
8756     *
8757     * @attr ref android.R.styleable#View_transformPivotX
8758     */
8759    @ViewDebug.ExportedProperty(category = "drawing")
8760    public float getPivotX() {
8761        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8762    }
8763
8764    /**
8765     * Sets the x location of the point around which the view is
8766     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8767     * By default, the pivot point is centered on the object.
8768     * Setting this property disables this behavior and causes the view to use only the
8769     * explicitly set pivotX and pivotY values.
8770     *
8771     * @param pivotX The x location of the pivot point.
8772     * @see #getRotation()
8773     * @see #getScaleX()
8774     * @see #getScaleY()
8775     * @see #getPivotY()
8776     *
8777     * @attr ref android.R.styleable#View_transformPivotX
8778     */
8779    public void setPivotX(float pivotX) {
8780        ensureTransformationInfo();
8781        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8782        final TransformationInfo info = mTransformationInfo;
8783        if (info.mPivotX != pivotX) {
8784            invalidateViewProperty(true, false);
8785            info.mPivotX = pivotX;
8786            info.mMatrixDirty = true;
8787            invalidateViewProperty(false, true);
8788            if (mDisplayList != null) {
8789                mDisplayList.setPivotX(pivotX);
8790            }
8791        }
8792    }
8793
8794    /**
8795     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8796     * and {@link #setScaleY(float) scaled}.
8797     *
8798     * @see #getRotation()
8799     * @see #getScaleX()
8800     * @see #getScaleY()
8801     * @see #getPivotY()
8802     * @return The y location of the pivot point.
8803     *
8804     * @attr ref android.R.styleable#View_transformPivotY
8805     */
8806    @ViewDebug.ExportedProperty(category = "drawing")
8807    public float getPivotY() {
8808        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8809    }
8810
8811    /**
8812     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8813     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8814     * Setting this property disables this behavior and causes the view to use only the
8815     * explicitly set pivotX and pivotY values.
8816     *
8817     * @param pivotY The y location of the pivot point.
8818     * @see #getRotation()
8819     * @see #getScaleX()
8820     * @see #getScaleY()
8821     * @see #getPivotY()
8822     *
8823     * @attr ref android.R.styleable#View_transformPivotY
8824     */
8825    public void setPivotY(float pivotY) {
8826        ensureTransformationInfo();
8827        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8828        final TransformationInfo info = mTransformationInfo;
8829        if (info.mPivotY != pivotY) {
8830            invalidateViewProperty(true, false);
8831            info.mPivotY = pivotY;
8832            info.mMatrixDirty = true;
8833            invalidateViewProperty(false, true);
8834            if (mDisplayList != null) {
8835                mDisplayList.setPivotY(pivotY);
8836            }
8837        }
8838    }
8839
8840    /**
8841     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8842     * completely transparent and 1 means the view is completely opaque.
8843     *
8844     * <p>By default this is 1.0f.
8845     * @return The opacity of the view.
8846     */
8847    @ViewDebug.ExportedProperty(category = "drawing")
8848    public float getAlpha() {
8849        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8850    }
8851
8852    /**
8853     * Returns whether this View has content which overlaps. This function, intended to be
8854     * overridden by specific View types, is an optimization when alpha is set on a view. If
8855     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8856     * and then composited it into place, which can be expensive. If the view has no overlapping
8857     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8858     * An example of overlapping rendering is a TextView with a background image, such as a
8859     * Button. An example of non-overlapping rendering is a TextView with no background, or
8860     * an ImageView with only the foreground image. The default implementation returns true;
8861     * subclasses should override if they have cases which can be optimized.
8862     *
8863     * @return true if the content in this view might overlap, false otherwise.
8864     */
8865    public boolean hasOverlappingRendering() {
8866        return true;
8867    }
8868
8869    /**
8870     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8871     * completely transparent and 1 means the view is completely opaque.</p>
8872     *
8873     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8874     * responsible for applying the opacity itself. Otherwise, calling this method is
8875     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8876     * setting a hardware layer.</p>
8877     *
8878     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8879     * performance implications. It is generally best to use the alpha property sparingly and
8880     * transiently, as in the case of fading animations.</p>
8881     *
8882     * @param alpha The opacity of the view.
8883     *
8884     * @see #setLayerType(int, android.graphics.Paint)
8885     *
8886     * @attr ref android.R.styleable#View_alpha
8887     */
8888    public void setAlpha(float alpha) {
8889        ensureTransformationInfo();
8890        if (mTransformationInfo.mAlpha != alpha) {
8891            mTransformationInfo.mAlpha = alpha;
8892            if (onSetAlpha((int) (alpha * 255))) {
8893                mPrivateFlags |= ALPHA_SET;
8894                // subclass is handling alpha - don't optimize rendering cache invalidation
8895                invalidateParentCaches();
8896                invalidate(true);
8897            } else {
8898                mPrivateFlags &= ~ALPHA_SET;
8899                invalidateViewProperty(true, false);
8900                if (mDisplayList != null) {
8901                    mDisplayList.setAlpha(alpha);
8902                }
8903            }
8904        }
8905    }
8906
8907    /**
8908     * Faster version of setAlpha() which performs the same steps except there are
8909     * no calls to invalidate(). The caller of this function should perform proper invalidation
8910     * on the parent and this object. The return value indicates whether the subclass handles
8911     * alpha (the return value for onSetAlpha()).
8912     *
8913     * @param alpha The new value for the alpha property
8914     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8915     *         the new value for the alpha property is different from the old value
8916     */
8917    boolean setAlphaNoInvalidation(float alpha) {
8918        ensureTransformationInfo();
8919        if (mTransformationInfo.mAlpha != alpha) {
8920            mTransformationInfo.mAlpha = alpha;
8921            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8922            if (subclassHandlesAlpha) {
8923                mPrivateFlags |= ALPHA_SET;
8924                return true;
8925            } else {
8926                mPrivateFlags &= ~ALPHA_SET;
8927                if (mDisplayList != null) {
8928                    mDisplayList.setAlpha(alpha);
8929                }
8930            }
8931        }
8932        return false;
8933    }
8934
8935    /**
8936     * Top position of this view relative to its parent.
8937     *
8938     * @return The top of this view, in pixels.
8939     */
8940    @ViewDebug.CapturedViewProperty
8941    public final int getTop() {
8942        return mTop;
8943    }
8944
8945    /**
8946     * Sets the top position of this view relative to its parent. This method is meant to be called
8947     * by the layout system and should not generally be called otherwise, because the property
8948     * may be changed at any time by the layout.
8949     *
8950     * @param top The top of this view, in pixels.
8951     */
8952    public final void setTop(int top) {
8953        if (top != mTop) {
8954            updateMatrix();
8955            final boolean matrixIsIdentity = mTransformationInfo == null
8956                    || mTransformationInfo.mMatrixIsIdentity;
8957            if (matrixIsIdentity) {
8958                if (mAttachInfo != null) {
8959                    int minTop;
8960                    int yLoc;
8961                    if (top < mTop) {
8962                        minTop = top;
8963                        yLoc = top - mTop;
8964                    } else {
8965                        minTop = mTop;
8966                        yLoc = 0;
8967                    }
8968                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8969                }
8970            } else {
8971                // Double-invalidation is necessary to capture view's old and new areas
8972                invalidate(true);
8973            }
8974
8975            int width = mRight - mLeft;
8976            int oldHeight = mBottom - mTop;
8977
8978            mTop = top;
8979            if (mDisplayList != null) {
8980                mDisplayList.setTop(mTop);
8981            }
8982
8983            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8984
8985            if (!matrixIsIdentity) {
8986                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8987                    // A change in dimension means an auto-centered pivot point changes, too
8988                    mTransformationInfo.mMatrixDirty = true;
8989                }
8990                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8991                invalidate(true);
8992            }
8993            mBackgroundSizeChanged = true;
8994            invalidateParentIfNeeded();
8995        }
8996    }
8997
8998    /**
8999     * Bottom position of this view relative to its parent.
9000     *
9001     * @return The bottom of this view, in pixels.
9002     */
9003    @ViewDebug.CapturedViewProperty
9004    public final int getBottom() {
9005        return mBottom;
9006    }
9007
9008    /**
9009     * True if this view has changed since the last time being drawn.
9010     *
9011     * @return The dirty state of this view.
9012     */
9013    public boolean isDirty() {
9014        return (mPrivateFlags & DIRTY_MASK) != 0;
9015    }
9016
9017    /**
9018     * Sets the bottom position of this view relative to its parent. This method is meant to be
9019     * called by the layout system and should not generally be called otherwise, because the
9020     * property may be changed at any time by the layout.
9021     *
9022     * @param bottom The bottom of this view, in pixels.
9023     */
9024    public final void setBottom(int bottom) {
9025        if (bottom != mBottom) {
9026            updateMatrix();
9027            final boolean matrixIsIdentity = mTransformationInfo == null
9028                    || mTransformationInfo.mMatrixIsIdentity;
9029            if (matrixIsIdentity) {
9030                if (mAttachInfo != null) {
9031                    int maxBottom;
9032                    if (bottom < mBottom) {
9033                        maxBottom = mBottom;
9034                    } else {
9035                        maxBottom = bottom;
9036                    }
9037                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9038                }
9039            } else {
9040                // Double-invalidation is necessary to capture view's old and new areas
9041                invalidate(true);
9042            }
9043
9044            int width = mRight - mLeft;
9045            int oldHeight = mBottom - mTop;
9046
9047            mBottom = bottom;
9048            if (mDisplayList != null) {
9049                mDisplayList.setBottom(mBottom);
9050            }
9051
9052            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9053
9054            if (!matrixIsIdentity) {
9055                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9056                    // A change in dimension means an auto-centered pivot point changes, too
9057                    mTransformationInfo.mMatrixDirty = true;
9058                }
9059                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9060                invalidate(true);
9061            }
9062            mBackgroundSizeChanged = true;
9063            invalidateParentIfNeeded();
9064        }
9065    }
9066
9067    /**
9068     * Left position of this view relative to its parent.
9069     *
9070     * @return The left edge of this view, in pixels.
9071     */
9072    @ViewDebug.CapturedViewProperty
9073    public final int getLeft() {
9074        return mLeft;
9075    }
9076
9077    /**
9078     * Sets the left position of this view relative to its parent. This method is meant to be called
9079     * by the layout system and should not generally be called otherwise, because the property
9080     * may be changed at any time by the layout.
9081     *
9082     * @param left The bottom of this view, in pixels.
9083     */
9084    public final void setLeft(int left) {
9085        if (left != mLeft) {
9086            updateMatrix();
9087            final boolean matrixIsIdentity = mTransformationInfo == null
9088                    || mTransformationInfo.mMatrixIsIdentity;
9089            if (matrixIsIdentity) {
9090                if (mAttachInfo != null) {
9091                    int minLeft;
9092                    int xLoc;
9093                    if (left < mLeft) {
9094                        minLeft = left;
9095                        xLoc = left - mLeft;
9096                    } else {
9097                        minLeft = mLeft;
9098                        xLoc = 0;
9099                    }
9100                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9101                }
9102            } else {
9103                // Double-invalidation is necessary to capture view's old and new areas
9104                invalidate(true);
9105            }
9106
9107            int oldWidth = mRight - mLeft;
9108            int height = mBottom - mTop;
9109
9110            mLeft = left;
9111            if (mDisplayList != null) {
9112                mDisplayList.setLeft(left);
9113            }
9114
9115            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9116
9117            if (!matrixIsIdentity) {
9118                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9119                    // A change in dimension means an auto-centered pivot point changes, too
9120                    mTransformationInfo.mMatrixDirty = true;
9121                }
9122                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9123                invalidate(true);
9124            }
9125            mBackgroundSizeChanged = true;
9126            invalidateParentIfNeeded();
9127        }
9128    }
9129
9130    /**
9131     * Right position of this view relative to its parent.
9132     *
9133     * @return The right edge of this view, in pixels.
9134     */
9135    @ViewDebug.CapturedViewProperty
9136    public final int getRight() {
9137        return mRight;
9138    }
9139
9140    /**
9141     * Sets the right position of this view relative to its parent. This method is meant to be called
9142     * by the layout system and should not generally be called otherwise, because the property
9143     * may be changed at any time by the layout.
9144     *
9145     * @param right The bottom of this view, in pixels.
9146     */
9147    public final void setRight(int right) {
9148        if (right != mRight) {
9149            updateMatrix();
9150            final boolean matrixIsIdentity = mTransformationInfo == null
9151                    || mTransformationInfo.mMatrixIsIdentity;
9152            if (matrixIsIdentity) {
9153                if (mAttachInfo != null) {
9154                    int maxRight;
9155                    if (right < mRight) {
9156                        maxRight = mRight;
9157                    } else {
9158                        maxRight = right;
9159                    }
9160                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9161                }
9162            } else {
9163                // Double-invalidation is necessary to capture view's old and new areas
9164                invalidate(true);
9165            }
9166
9167            int oldWidth = mRight - mLeft;
9168            int height = mBottom - mTop;
9169
9170            mRight = right;
9171            if (mDisplayList != null) {
9172                mDisplayList.setRight(mRight);
9173            }
9174
9175            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9176
9177            if (!matrixIsIdentity) {
9178                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9179                    // A change in dimension means an auto-centered pivot point changes, too
9180                    mTransformationInfo.mMatrixDirty = true;
9181                }
9182                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9183                invalidate(true);
9184            }
9185            mBackgroundSizeChanged = true;
9186            invalidateParentIfNeeded();
9187        }
9188    }
9189
9190    /**
9191     * The visual x position of this view, in pixels. This is equivalent to the
9192     * {@link #setTranslationX(float) translationX} property plus the current
9193     * {@link #getLeft() left} property.
9194     *
9195     * @return The visual x position of this view, in pixels.
9196     */
9197    @ViewDebug.ExportedProperty(category = "drawing")
9198    public float getX() {
9199        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9200    }
9201
9202    /**
9203     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9204     * {@link #setTranslationX(float) translationX} property to be the difference between
9205     * the x value passed in and the current {@link #getLeft() left} property.
9206     *
9207     * @param x The visual x position of this view, in pixels.
9208     */
9209    public void setX(float x) {
9210        setTranslationX(x - mLeft);
9211    }
9212
9213    /**
9214     * The visual y position of this view, in pixels. This is equivalent to the
9215     * {@link #setTranslationY(float) translationY} property plus the current
9216     * {@link #getTop() top} property.
9217     *
9218     * @return The visual y position of this view, in pixels.
9219     */
9220    @ViewDebug.ExportedProperty(category = "drawing")
9221    public float getY() {
9222        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9223    }
9224
9225    /**
9226     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9227     * {@link #setTranslationY(float) translationY} property to be the difference between
9228     * the y value passed in and the current {@link #getTop() top} property.
9229     *
9230     * @param y The visual y position of this view, in pixels.
9231     */
9232    public void setY(float y) {
9233        setTranslationY(y - mTop);
9234    }
9235
9236
9237    /**
9238     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9239     * This position is post-layout, in addition to wherever the object's
9240     * layout placed it.
9241     *
9242     * @return The horizontal position of this view relative to its left position, in pixels.
9243     */
9244    @ViewDebug.ExportedProperty(category = "drawing")
9245    public float getTranslationX() {
9246        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9247    }
9248
9249    /**
9250     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9251     * This effectively positions the object post-layout, in addition to wherever the object's
9252     * layout placed it.
9253     *
9254     * @param translationX The horizontal position of this view relative to its left position,
9255     * in pixels.
9256     *
9257     * @attr ref android.R.styleable#View_translationX
9258     */
9259    public void setTranslationX(float translationX) {
9260        ensureTransformationInfo();
9261        final TransformationInfo info = mTransformationInfo;
9262        if (info.mTranslationX != translationX) {
9263            // Double-invalidation is necessary to capture view's old and new areas
9264            invalidateViewProperty(true, false);
9265            info.mTranslationX = translationX;
9266            info.mMatrixDirty = true;
9267            invalidateViewProperty(false, true);
9268            if (mDisplayList != null) {
9269                mDisplayList.setTranslationX(translationX);
9270            }
9271        }
9272    }
9273
9274    /**
9275     * The horizontal location of this view relative to its {@link #getTop() top} position.
9276     * This position is post-layout, in addition to wherever the object's
9277     * layout placed it.
9278     *
9279     * @return The vertical position of this view relative to its top position,
9280     * in pixels.
9281     */
9282    @ViewDebug.ExportedProperty(category = "drawing")
9283    public float getTranslationY() {
9284        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9285    }
9286
9287    /**
9288     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9289     * This effectively positions the object post-layout, in addition to wherever the object's
9290     * layout placed it.
9291     *
9292     * @param translationY The vertical position of this view relative to its top position,
9293     * in pixels.
9294     *
9295     * @attr ref android.R.styleable#View_translationY
9296     */
9297    public void setTranslationY(float translationY) {
9298        ensureTransformationInfo();
9299        final TransformationInfo info = mTransformationInfo;
9300        if (info.mTranslationY != translationY) {
9301            invalidateViewProperty(true, false);
9302            info.mTranslationY = translationY;
9303            info.mMatrixDirty = true;
9304            invalidateViewProperty(false, true);
9305            if (mDisplayList != null) {
9306                mDisplayList.setTranslationY(translationY);
9307            }
9308        }
9309    }
9310
9311    /**
9312     * Hit rectangle in parent's coordinates
9313     *
9314     * @param outRect The hit rectangle of the view.
9315     */
9316    public void getHitRect(Rect outRect) {
9317        updateMatrix();
9318        final TransformationInfo info = mTransformationInfo;
9319        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9320            outRect.set(mLeft, mTop, mRight, mBottom);
9321        } else {
9322            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9323            tmpRect.set(-info.mPivotX, -info.mPivotY,
9324                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9325            info.mMatrix.mapRect(tmpRect);
9326            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9327                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9328        }
9329    }
9330
9331    /**
9332     * Determines whether the given point, in local coordinates is inside the view.
9333     */
9334    /*package*/ final boolean pointInView(float localX, float localY) {
9335        return localX >= 0 && localX < (mRight - mLeft)
9336                && localY >= 0 && localY < (mBottom - mTop);
9337    }
9338
9339    /**
9340     * Utility method to determine whether the given point, in local coordinates,
9341     * is inside the view, where the area of the view is expanded by the slop factor.
9342     * This method is called while processing touch-move events to determine if the event
9343     * is still within the view.
9344     */
9345    private boolean pointInView(float localX, float localY, float slop) {
9346        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9347                localY < ((mBottom - mTop) + slop);
9348    }
9349
9350    /**
9351     * When a view has focus and the user navigates away from it, the next view is searched for
9352     * starting from the rectangle filled in by this method.
9353     *
9354     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9355     * of the view.  However, if your view maintains some idea of internal selection,
9356     * such as a cursor, or a selected row or column, you should override this method and
9357     * fill in a more specific rectangle.
9358     *
9359     * @param r The rectangle to fill in, in this view's coordinates.
9360     */
9361    public void getFocusedRect(Rect r) {
9362        getDrawingRect(r);
9363    }
9364
9365    /**
9366     * If some part of this view is not clipped by any of its parents, then
9367     * return that area in r in global (root) coordinates. To convert r to local
9368     * coordinates (without taking possible View rotations into account), offset
9369     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9370     * If the view is completely clipped or translated out, return false.
9371     *
9372     * @param r If true is returned, r holds the global coordinates of the
9373     *        visible portion of this view.
9374     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9375     *        between this view and its root. globalOffet may be null.
9376     * @return true if r is non-empty (i.e. part of the view is visible at the
9377     *         root level.
9378     */
9379    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9380        int width = mRight - mLeft;
9381        int height = mBottom - mTop;
9382        if (width > 0 && height > 0) {
9383            r.set(0, 0, width, height);
9384            if (globalOffset != null) {
9385                globalOffset.set(-mScrollX, -mScrollY);
9386            }
9387            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9388        }
9389        return false;
9390    }
9391
9392    public final boolean getGlobalVisibleRect(Rect r) {
9393        return getGlobalVisibleRect(r, null);
9394    }
9395
9396    public final boolean getLocalVisibleRect(Rect r) {
9397        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9398        if (getGlobalVisibleRect(r, offset)) {
9399            r.offset(-offset.x, -offset.y); // make r local
9400            return true;
9401        }
9402        return false;
9403    }
9404
9405    /**
9406     * Offset this view's vertical location by the specified number of pixels.
9407     *
9408     * @param offset the number of pixels to offset the view by
9409     */
9410    public void offsetTopAndBottom(int offset) {
9411        if (offset != 0) {
9412            updateMatrix();
9413            final boolean matrixIsIdentity = mTransformationInfo == null
9414                    || mTransformationInfo.mMatrixIsIdentity;
9415            if (matrixIsIdentity) {
9416                if (mDisplayList != null) {
9417                    invalidateViewProperty(false, false);
9418                } else {
9419                    final ViewParent p = mParent;
9420                    if (p != null && mAttachInfo != null) {
9421                        final Rect r = mAttachInfo.mTmpInvalRect;
9422                        int minTop;
9423                        int maxBottom;
9424                        int yLoc;
9425                        if (offset < 0) {
9426                            minTop = mTop + offset;
9427                            maxBottom = mBottom;
9428                            yLoc = offset;
9429                        } else {
9430                            minTop = mTop;
9431                            maxBottom = mBottom + offset;
9432                            yLoc = 0;
9433                        }
9434                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9435                        p.invalidateChild(this, r);
9436                    }
9437                }
9438            } else {
9439                invalidateViewProperty(false, false);
9440            }
9441
9442            mTop += offset;
9443            mBottom += offset;
9444            if (mDisplayList != null) {
9445                mDisplayList.offsetTopBottom(offset);
9446                invalidateViewProperty(false, false);
9447            } else {
9448                if (!matrixIsIdentity) {
9449                    invalidateViewProperty(false, true);
9450                }
9451                invalidateParentIfNeeded();
9452            }
9453        }
9454    }
9455
9456    /**
9457     * Offset this view's horizontal location by the specified amount of pixels.
9458     *
9459     * @param offset the numer of pixels to offset the view by
9460     */
9461    public void offsetLeftAndRight(int offset) {
9462        if (offset != 0) {
9463            updateMatrix();
9464            final boolean matrixIsIdentity = mTransformationInfo == null
9465                    || mTransformationInfo.mMatrixIsIdentity;
9466            if (matrixIsIdentity) {
9467                if (mDisplayList != null) {
9468                    invalidateViewProperty(false, false);
9469                } else {
9470                    final ViewParent p = mParent;
9471                    if (p != null && mAttachInfo != null) {
9472                        final Rect r = mAttachInfo.mTmpInvalRect;
9473                        int minLeft;
9474                        int maxRight;
9475                        if (offset < 0) {
9476                            minLeft = mLeft + offset;
9477                            maxRight = mRight;
9478                        } else {
9479                            minLeft = mLeft;
9480                            maxRight = mRight + offset;
9481                        }
9482                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9483                        p.invalidateChild(this, r);
9484                    }
9485                }
9486            } else {
9487                invalidateViewProperty(false, false);
9488            }
9489
9490            mLeft += offset;
9491            mRight += offset;
9492            if (mDisplayList != null) {
9493                mDisplayList.offsetLeftRight(offset);
9494                invalidateViewProperty(false, false);
9495            } else {
9496                if (!matrixIsIdentity) {
9497                    invalidateViewProperty(false, true);
9498                }
9499                invalidateParentIfNeeded();
9500            }
9501        }
9502    }
9503
9504    /**
9505     * Get the LayoutParams associated with this view. All views should have
9506     * layout parameters. These supply parameters to the <i>parent</i> of this
9507     * view specifying how it should be arranged. There are many subclasses of
9508     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9509     * of ViewGroup that are responsible for arranging their children.
9510     *
9511     * This method may return null if this View is not attached to a parent
9512     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9513     * was not invoked successfully. When a View is attached to a parent
9514     * ViewGroup, this method must not return null.
9515     *
9516     * @return The LayoutParams associated with this view, or null if no
9517     *         parameters have been set yet
9518     */
9519    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9520    public ViewGroup.LayoutParams getLayoutParams() {
9521        return mLayoutParams;
9522    }
9523
9524    /**
9525     * Set the layout parameters associated with this view. These supply
9526     * parameters to the <i>parent</i> of this view specifying how it should be
9527     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9528     * correspond to the different subclasses of ViewGroup that are responsible
9529     * for arranging their children.
9530     *
9531     * @param params The layout parameters for this view, cannot be null
9532     */
9533    public void setLayoutParams(ViewGroup.LayoutParams params) {
9534        if (params == null) {
9535            throw new NullPointerException("Layout parameters cannot be null");
9536        }
9537        mLayoutParams = params;
9538        if (mParent instanceof ViewGroup) {
9539            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9540        }
9541        requestLayout();
9542    }
9543
9544    /**
9545     * Set the scrolled position of your view. This will cause a call to
9546     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9547     * invalidated.
9548     * @param x the x position to scroll to
9549     * @param y the y position to scroll to
9550     */
9551    public void scrollTo(int x, int y) {
9552        if (mScrollX != x || mScrollY != y) {
9553            int oldX = mScrollX;
9554            int oldY = mScrollY;
9555            mScrollX = x;
9556            mScrollY = y;
9557            invalidateParentCaches();
9558            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9559            if (!awakenScrollBars()) {
9560                postInvalidateOnAnimation();
9561            }
9562        }
9563    }
9564
9565    /**
9566     * Move the scrolled position of your view. This will cause a call to
9567     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9568     * invalidated.
9569     * @param x the amount of pixels to scroll by horizontally
9570     * @param y the amount of pixels to scroll by vertically
9571     */
9572    public void scrollBy(int x, int y) {
9573        scrollTo(mScrollX + x, mScrollY + y);
9574    }
9575
9576    /**
9577     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9578     * animation to fade the scrollbars out after a default delay. If a subclass
9579     * provides animated scrolling, the start delay should equal the duration
9580     * of the scrolling animation.</p>
9581     *
9582     * <p>The animation starts only if at least one of the scrollbars is
9583     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9584     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9585     * this method returns true, and false otherwise. If the animation is
9586     * started, this method calls {@link #invalidate()}; in that case the
9587     * caller should not call {@link #invalidate()}.</p>
9588     *
9589     * <p>This method should be invoked every time a subclass directly updates
9590     * the scroll parameters.</p>
9591     *
9592     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9593     * and {@link #scrollTo(int, int)}.</p>
9594     *
9595     * @return true if the animation is played, false otherwise
9596     *
9597     * @see #awakenScrollBars(int)
9598     * @see #scrollBy(int, int)
9599     * @see #scrollTo(int, int)
9600     * @see #isHorizontalScrollBarEnabled()
9601     * @see #isVerticalScrollBarEnabled()
9602     * @see #setHorizontalScrollBarEnabled(boolean)
9603     * @see #setVerticalScrollBarEnabled(boolean)
9604     */
9605    protected boolean awakenScrollBars() {
9606        return mScrollCache != null &&
9607                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9608    }
9609
9610    /**
9611     * Trigger the scrollbars to draw.
9612     * This method differs from awakenScrollBars() only in its default duration.
9613     * initialAwakenScrollBars() will show the scroll bars for longer than
9614     * usual to give the user more of a chance to notice them.
9615     *
9616     * @return true if the animation is played, false otherwise.
9617     */
9618    private boolean initialAwakenScrollBars() {
9619        return mScrollCache != null &&
9620                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9621    }
9622
9623    /**
9624     * <p>
9625     * Trigger the scrollbars to draw. When invoked this method starts an
9626     * animation to fade the scrollbars out after a fixed delay. If a subclass
9627     * provides animated scrolling, the start delay should equal the duration of
9628     * the scrolling animation.
9629     * </p>
9630     *
9631     * <p>
9632     * The animation starts only if at least one of the scrollbars is enabled,
9633     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9634     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9635     * this method returns true, and false otherwise. If the animation is
9636     * started, this method calls {@link #invalidate()}; in that case the caller
9637     * should not call {@link #invalidate()}.
9638     * </p>
9639     *
9640     * <p>
9641     * This method should be invoked everytime a subclass directly updates the
9642     * scroll parameters.
9643     * </p>
9644     *
9645     * @param startDelay the delay, in milliseconds, after which the animation
9646     *        should start; when the delay is 0, the animation starts
9647     *        immediately
9648     * @return true if the animation is played, false otherwise
9649     *
9650     * @see #scrollBy(int, int)
9651     * @see #scrollTo(int, int)
9652     * @see #isHorizontalScrollBarEnabled()
9653     * @see #isVerticalScrollBarEnabled()
9654     * @see #setHorizontalScrollBarEnabled(boolean)
9655     * @see #setVerticalScrollBarEnabled(boolean)
9656     */
9657    protected boolean awakenScrollBars(int startDelay) {
9658        return awakenScrollBars(startDelay, true);
9659    }
9660
9661    /**
9662     * <p>
9663     * Trigger the scrollbars to draw. When invoked this method starts an
9664     * animation to fade the scrollbars out after a fixed delay. If a subclass
9665     * provides animated scrolling, the start delay should equal the duration of
9666     * the scrolling animation.
9667     * </p>
9668     *
9669     * <p>
9670     * The animation starts only if at least one of the scrollbars is enabled,
9671     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9672     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9673     * this method returns true, and false otherwise. If the animation is
9674     * started, this method calls {@link #invalidate()} if the invalidate parameter
9675     * is set to true; in that case the caller
9676     * should not call {@link #invalidate()}.
9677     * </p>
9678     *
9679     * <p>
9680     * This method should be invoked everytime a subclass directly updates the
9681     * scroll parameters.
9682     * </p>
9683     *
9684     * @param startDelay the delay, in milliseconds, after which the animation
9685     *        should start; when the delay is 0, the animation starts
9686     *        immediately
9687     *
9688     * @param invalidate Wheter this method should call invalidate
9689     *
9690     * @return true if the animation is played, false otherwise
9691     *
9692     * @see #scrollBy(int, int)
9693     * @see #scrollTo(int, int)
9694     * @see #isHorizontalScrollBarEnabled()
9695     * @see #isVerticalScrollBarEnabled()
9696     * @see #setHorizontalScrollBarEnabled(boolean)
9697     * @see #setVerticalScrollBarEnabled(boolean)
9698     */
9699    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9700        final ScrollabilityCache scrollCache = mScrollCache;
9701
9702        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9703            return false;
9704        }
9705
9706        if (scrollCache.scrollBar == null) {
9707            scrollCache.scrollBar = new ScrollBarDrawable();
9708        }
9709
9710        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9711
9712            if (invalidate) {
9713                // Invalidate to show the scrollbars
9714                postInvalidateOnAnimation();
9715            }
9716
9717            if (scrollCache.state == ScrollabilityCache.OFF) {
9718                // FIXME: this is copied from WindowManagerService.
9719                // We should get this value from the system when it
9720                // is possible to do so.
9721                final int KEY_REPEAT_FIRST_DELAY = 750;
9722                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9723            }
9724
9725            // Tell mScrollCache when we should start fading. This may
9726            // extend the fade start time if one was already scheduled
9727            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9728            scrollCache.fadeStartTime = fadeStartTime;
9729            scrollCache.state = ScrollabilityCache.ON;
9730
9731            // Schedule our fader to run, unscheduling any old ones first
9732            if (mAttachInfo != null) {
9733                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9734                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9735            }
9736
9737            return true;
9738        }
9739
9740        return false;
9741    }
9742
9743    /**
9744     * Do not invalidate views which are not visible and which are not running an animation. They
9745     * will not get drawn and they should not set dirty flags as if they will be drawn
9746     */
9747    private boolean skipInvalidate() {
9748        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9749                (!(mParent instanceof ViewGroup) ||
9750                        !((ViewGroup) mParent).isViewTransitioning(this));
9751    }
9752    /**
9753     * Mark the area defined by dirty as needing to be drawn. If the view is
9754     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9755     * in the future. This must be called from a UI thread. To call from a non-UI
9756     * thread, call {@link #postInvalidate()}.
9757     *
9758     * WARNING: This method is destructive to dirty.
9759     * @param dirty the rectangle representing the bounds of the dirty region
9760     */
9761    public void invalidate(Rect dirty) {
9762        if (ViewDebug.TRACE_HIERARCHY) {
9763            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9764        }
9765
9766        if (skipInvalidate()) {
9767            return;
9768        }
9769        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9770                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9771                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9772            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9773            mPrivateFlags |= INVALIDATED;
9774            mPrivateFlags |= DIRTY;
9775            final ViewParent p = mParent;
9776            final AttachInfo ai = mAttachInfo;
9777            //noinspection PointlessBooleanExpression,ConstantConditions
9778            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9779                if (p != null && ai != null && ai.mHardwareAccelerated) {
9780                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9781                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9782                    p.invalidateChild(this, null);
9783                    return;
9784                }
9785            }
9786            if (p != null && ai != null) {
9787                final int scrollX = mScrollX;
9788                final int scrollY = mScrollY;
9789                final Rect r = ai.mTmpInvalRect;
9790                r.set(dirty.left - scrollX, dirty.top - scrollY,
9791                        dirty.right - scrollX, dirty.bottom - scrollY);
9792                mParent.invalidateChild(this, r);
9793            }
9794        }
9795    }
9796
9797    /**
9798     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9799     * The coordinates of the dirty rect are relative to the view.
9800     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9801     * will be called at some point in the future. This must be called from
9802     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9803     * @param l the left position of the dirty region
9804     * @param t the top position of the dirty region
9805     * @param r the right position of the dirty region
9806     * @param b the bottom position of the dirty region
9807     */
9808    public void invalidate(int l, int t, int r, int b) {
9809        if (ViewDebug.TRACE_HIERARCHY) {
9810            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9811        }
9812
9813        if (skipInvalidate()) {
9814            return;
9815        }
9816        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9817                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9818                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9819            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9820            mPrivateFlags |= INVALIDATED;
9821            mPrivateFlags |= DIRTY;
9822            final ViewParent p = mParent;
9823            final AttachInfo ai = mAttachInfo;
9824            //noinspection PointlessBooleanExpression,ConstantConditions
9825            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9826                if (p != null && ai != null && ai.mHardwareAccelerated) {
9827                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9828                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9829                    p.invalidateChild(this, null);
9830                    return;
9831                }
9832            }
9833            if (p != null && ai != null && l < r && t < b) {
9834                final int scrollX = mScrollX;
9835                final int scrollY = mScrollY;
9836                final Rect tmpr = ai.mTmpInvalRect;
9837                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9838                p.invalidateChild(this, tmpr);
9839            }
9840        }
9841    }
9842
9843    /**
9844     * Invalidate the whole view. If the view is visible,
9845     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9846     * the future. This must be called from a UI thread. To call from a non-UI thread,
9847     * call {@link #postInvalidate()}.
9848     */
9849    public void invalidate() {
9850        invalidate(true);
9851    }
9852
9853    /**
9854     * This is where the invalidate() work actually happens. A full invalidate()
9855     * causes the drawing cache to be invalidated, but this function can be called with
9856     * invalidateCache set to false to skip that invalidation step for cases that do not
9857     * need it (for example, a component that remains at the same dimensions with the same
9858     * content).
9859     *
9860     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9861     * well. This is usually true for a full invalidate, but may be set to false if the
9862     * View's contents or dimensions have not changed.
9863     */
9864    void invalidate(boolean invalidateCache) {
9865        if (ViewDebug.TRACE_HIERARCHY) {
9866            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9867        }
9868
9869        if (skipInvalidate()) {
9870            return;
9871        }
9872        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9873                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9874                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9875            mLastIsOpaque = isOpaque();
9876            mPrivateFlags &= ~DRAWN;
9877            mPrivateFlags |= DIRTY;
9878            if (invalidateCache) {
9879                mPrivateFlags |= INVALIDATED;
9880                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9881            }
9882            final AttachInfo ai = mAttachInfo;
9883            final ViewParent p = mParent;
9884            //noinspection PointlessBooleanExpression,ConstantConditions
9885            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9886                if (p != null && ai != null && ai.mHardwareAccelerated) {
9887                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9888                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9889                    p.invalidateChild(this, null);
9890                    return;
9891                }
9892            }
9893
9894            if (p != null && ai != null) {
9895                final Rect r = ai.mTmpInvalRect;
9896                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9897                // Don't call invalidate -- we don't want to internally scroll
9898                // our own bounds
9899                p.invalidateChild(this, r);
9900            }
9901        }
9902    }
9903
9904    /**
9905     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9906     * set any flags or handle all of the cases handled by the default invalidation methods.
9907     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9908     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9909     * walk up the hierarchy, transforming the dirty rect as necessary.
9910     *
9911     * The method also handles normal invalidation logic if display list properties are not
9912     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9913     * backup approach, to handle these cases used in the various property-setting methods.
9914     *
9915     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9916     * are not being used in this view
9917     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9918     * list properties are not being used in this view
9919     */
9920    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9921        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9922            if (invalidateParent) {
9923                invalidateParentCaches();
9924            }
9925            if (forceRedraw) {
9926                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9927            }
9928            invalidate(false);
9929        } else {
9930            final AttachInfo ai = mAttachInfo;
9931            final ViewParent p = mParent;
9932            if (p != null && ai != null) {
9933                final Rect r = ai.mTmpInvalRect;
9934                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9935                if (mParent instanceof ViewGroup) {
9936                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9937                } else {
9938                    mParent.invalidateChild(this, r);
9939                }
9940            }
9941        }
9942    }
9943
9944    /**
9945     * Utility method to transform a given Rect by the current matrix of this view.
9946     */
9947    void transformRect(final Rect rect) {
9948        if (!getMatrix().isIdentity()) {
9949            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9950            boundingRect.set(rect);
9951            getMatrix().mapRect(boundingRect);
9952            rect.set((int) (boundingRect.left - 0.5f),
9953                    (int) (boundingRect.top - 0.5f),
9954                    (int) (boundingRect.right + 0.5f),
9955                    (int) (boundingRect.bottom + 0.5f));
9956        }
9957    }
9958
9959    /**
9960     * Used to indicate that the parent of this view should clear its caches. This functionality
9961     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9962     * which is necessary when various parent-managed properties of the view change, such as
9963     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9964     * clears the parent caches and does not causes an invalidate event.
9965     *
9966     * @hide
9967     */
9968    protected void invalidateParentCaches() {
9969        if (mParent instanceof View) {
9970            ((View) mParent).mPrivateFlags |= INVALIDATED;
9971        }
9972    }
9973
9974    /**
9975     * Used to indicate that the parent of this view should be invalidated. This functionality
9976     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9977     * which is necessary when various parent-managed properties of the view change, such as
9978     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9979     * an invalidation event to the parent.
9980     *
9981     * @hide
9982     */
9983    protected void invalidateParentIfNeeded() {
9984        if (isHardwareAccelerated() && mParent instanceof View) {
9985            ((View) mParent).invalidate(true);
9986        }
9987    }
9988
9989    /**
9990     * Indicates whether this View is opaque. An opaque View guarantees that it will
9991     * draw all the pixels overlapping its bounds using a fully opaque color.
9992     *
9993     * Subclasses of View should override this method whenever possible to indicate
9994     * whether an instance is opaque. Opaque Views are treated in a special way by
9995     * the View hierarchy, possibly allowing it to perform optimizations during
9996     * invalidate/draw passes.
9997     *
9998     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9999     */
10000    @ViewDebug.ExportedProperty(category = "drawing")
10001    public boolean isOpaque() {
10002        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10003                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10004                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10005    }
10006
10007    /**
10008     * @hide
10009     */
10010    protected void computeOpaqueFlags() {
10011        // Opaque if:
10012        //   - Has a background
10013        //   - Background is opaque
10014        //   - Doesn't have scrollbars or scrollbars are inside overlay
10015
10016        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10017            mPrivateFlags |= OPAQUE_BACKGROUND;
10018        } else {
10019            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10020        }
10021
10022        final int flags = mViewFlags;
10023        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10024                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10025            mPrivateFlags |= OPAQUE_SCROLLBARS;
10026        } else {
10027            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10028        }
10029    }
10030
10031    /**
10032     * @hide
10033     */
10034    protected boolean hasOpaqueScrollbars() {
10035        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10036    }
10037
10038    /**
10039     * @return A handler associated with the thread running the View. This
10040     * handler can be used to pump events in the UI events queue.
10041     */
10042    public Handler getHandler() {
10043        if (mAttachInfo != null) {
10044            return mAttachInfo.mHandler;
10045        }
10046        return null;
10047    }
10048
10049    /**
10050     * Gets the view root associated with the View.
10051     * @return The view root, or null if none.
10052     * @hide
10053     */
10054    public ViewRootImpl getViewRootImpl() {
10055        if (mAttachInfo != null) {
10056            return mAttachInfo.mViewRootImpl;
10057        }
10058        return null;
10059    }
10060
10061    /**
10062     * <p>Causes the Runnable to be added to the message queue.
10063     * The runnable will be run on the user interface thread.</p>
10064     *
10065     * <p>This method can be invoked from outside of the UI thread
10066     * only when this View is attached to a window.</p>
10067     *
10068     * @param action The Runnable that will be executed.
10069     *
10070     * @return Returns true if the Runnable was successfully placed in to the
10071     *         message queue.  Returns false on failure, usually because the
10072     *         looper processing the message queue is exiting.
10073     *
10074     * @see #postDelayed
10075     * @see #removeCallbacks
10076     */
10077    public boolean post(Runnable action) {
10078        final AttachInfo attachInfo = mAttachInfo;
10079        if (attachInfo != null) {
10080            return attachInfo.mHandler.post(action);
10081        }
10082        // Assume that post will succeed later
10083        ViewRootImpl.getRunQueue().post(action);
10084        return true;
10085    }
10086
10087    /**
10088     * <p>Causes the Runnable to be added to the message queue, to be run
10089     * after the specified amount of time elapses.
10090     * The runnable will be run on the user interface thread.</p>
10091     *
10092     * <p>This method can be invoked from outside of the UI thread
10093     * only when this View is attached to a window.</p>
10094     *
10095     * @param action The Runnable that will be executed.
10096     * @param delayMillis The delay (in milliseconds) until the Runnable
10097     *        will be executed.
10098     *
10099     * @return true if the Runnable was successfully placed in to the
10100     *         message queue.  Returns false on failure, usually because the
10101     *         looper processing the message queue is exiting.  Note that a
10102     *         result of true does not mean the Runnable will be processed --
10103     *         if the looper is quit before the delivery time of the message
10104     *         occurs then the message will be dropped.
10105     *
10106     * @see #post
10107     * @see #removeCallbacks
10108     */
10109    public boolean postDelayed(Runnable action, long delayMillis) {
10110        final AttachInfo attachInfo = mAttachInfo;
10111        if (attachInfo != null) {
10112            return attachInfo.mHandler.postDelayed(action, delayMillis);
10113        }
10114        // Assume that post will succeed later
10115        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10116        return true;
10117    }
10118
10119    /**
10120     * <p>Causes the Runnable to execute on the next animation time step.
10121     * The runnable will be run on the user interface thread.</p>
10122     *
10123     * <p>This method can be invoked from outside of the UI thread
10124     * only when this View is attached to a window.</p>
10125     *
10126     * @param action The Runnable that will be executed.
10127     *
10128     * @see #postOnAnimationDelayed
10129     * @see #removeCallbacks
10130     */
10131    public void postOnAnimation(Runnable action) {
10132        final AttachInfo attachInfo = mAttachInfo;
10133        if (attachInfo != null) {
10134            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10135                    Choreographer.CALLBACK_ANIMATION, action, null);
10136        } else {
10137            // Assume that post will succeed later
10138            ViewRootImpl.getRunQueue().post(action);
10139        }
10140    }
10141
10142    /**
10143     * <p>Causes the Runnable to execute on the next animation time step,
10144     * after the specified amount of time elapses.
10145     * The runnable will be run on the user interface thread.</p>
10146     *
10147     * <p>This method can be invoked from outside of the UI thread
10148     * only when this View is attached to a window.</p>
10149     *
10150     * @param action The Runnable that will be executed.
10151     * @param delayMillis The delay (in milliseconds) until the Runnable
10152     *        will be executed.
10153     *
10154     * @see #postOnAnimation
10155     * @see #removeCallbacks
10156     */
10157    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10158        final AttachInfo attachInfo = mAttachInfo;
10159        if (attachInfo != null) {
10160            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10161                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10162        } else {
10163            // Assume that post will succeed later
10164            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10165        }
10166    }
10167
10168    /**
10169     * <p>Removes the specified Runnable from the message queue.</p>
10170     *
10171     * <p>This method can be invoked from outside of the UI thread
10172     * only when this View is attached to a window.</p>
10173     *
10174     * @param action The Runnable to remove from the message handling queue
10175     *
10176     * @return true if this view could ask the Handler to remove the Runnable,
10177     *         false otherwise. When the returned value is true, the Runnable
10178     *         may or may not have been actually removed from the message queue
10179     *         (for instance, if the Runnable was not in the queue already.)
10180     *
10181     * @see #post
10182     * @see #postDelayed
10183     * @see #postOnAnimation
10184     * @see #postOnAnimationDelayed
10185     */
10186    public boolean removeCallbacks(Runnable action) {
10187        if (action != null) {
10188            final AttachInfo attachInfo = mAttachInfo;
10189            if (attachInfo != null) {
10190                attachInfo.mHandler.removeCallbacks(action);
10191                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10192                        Choreographer.CALLBACK_ANIMATION, action, null);
10193            } else {
10194                // Assume that post will succeed later
10195                ViewRootImpl.getRunQueue().removeCallbacks(action);
10196            }
10197        }
10198        return true;
10199    }
10200
10201    /**
10202     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10203     * Use this to invalidate the View from a non-UI thread.</p>
10204     *
10205     * <p>This method can be invoked from outside of the UI thread
10206     * only when this View is attached to a window.</p>
10207     *
10208     * @see #invalidate()
10209     * @see #postInvalidateDelayed(long)
10210     */
10211    public void postInvalidate() {
10212        postInvalidateDelayed(0);
10213    }
10214
10215    /**
10216     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10217     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10218     *
10219     * <p>This method can be invoked from outside of the UI thread
10220     * only when this View is attached to a window.</p>
10221     *
10222     * @param left The left coordinate of the rectangle to invalidate.
10223     * @param top The top coordinate of the rectangle to invalidate.
10224     * @param right The right coordinate of the rectangle to invalidate.
10225     * @param bottom The bottom coordinate of the rectangle to invalidate.
10226     *
10227     * @see #invalidate(int, int, int, int)
10228     * @see #invalidate(Rect)
10229     * @see #postInvalidateDelayed(long, int, int, int, int)
10230     */
10231    public void postInvalidate(int left, int top, int right, int bottom) {
10232        postInvalidateDelayed(0, left, top, right, bottom);
10233    }
10234
10235    /**
10236     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10237     * loop. Waits for the specified amount of time.</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 delayMilliseconds the duration in milliseconds to delay the
10243     *         invalidation by
10244     *
10245     * @see #invalidate()
10246     * @see #postInvalidate()
10247     */
10248    public void postInvalidateDelayed(long delayMilliseconds) {
10249        // We try only with the AttachInfo because there's no point in invalidating
10250        // if we are not attached to our window
10251        final AttachInfo attachInfo = mAttachInfo;
10252        if (attachInfo != null) {
10253            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10254        }
10255    }
10256
10257    /**
10258     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10259     * through the event loop. Waits for the specified amount of time.</p>
10260     *
10261     * <p>This method can be invoked from outside of the UI thread
10262     * only when this View is attached to a window.</p>
10263     *
10264     * @param delayMilliseconds the duration in milliseconds to delay the
10265     *         invalidation by
10266     * @param left The left coordinate of the rectangle to invalidate.
10267     * @param top The top coordinate of the rectangle to invalidate.
10268     * @param right The right coordinate of the rectangle to invalidate.
10269     * @param bottom The bottom coordinate of the rectangle to invalidate.
10270     *
10271     * @see #invalidate(int, int, int, int)
10272     * @see #invalidate(Rect)
10273     * @see #postInvalidate(int, int, int, int)
10274     */
10275    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10276            int right, int bottom) {
10277
10278        // We try only with the AttachInfo because there's no point in invalidating
10279        // if we are not attached to our window
10280        final AttachInfo attachInfo = mAttachInfo;
10281        if (attachInfo != null) {
10282            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10283            info.target = this;
10284            info.left = left;
10285            info.top = top;
10286            info.right = right;
10287            info.bottom = bottom;
10288
10289            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10290        }
10291    }
10292
10293    /**
10294     * <p>Cause an invalidate to happen on the next animation time step, typically the
10295     * next display frame.</p>
10296     *
10297     * <p>This method can be invoked from outside of the UI thread
10298     * only when this View is attached to a window.</p>
10299     *
10300     * @see #invalidate()
10301     */
10302    public void postInvalidateOnAnimation() {
10303        // We try only with the AttachInfo because there's no point in invalidating
10304        // if we are not attached to our window
10305        final AttachInfo attachInfo = mAttachInfo;
10306        if (attachInfo != null) {
10307            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10308        }
10309    }
10310
10311    /**
10312     * <p>Cause an invalidate of the specified area to happen on the next animation
10313     * time step, typically the next display frame.</p>
10314     *
10315     * <p>This method can be invoked from outside of the UI thread
10316     * only when this View is attached to a window.</p>
10317     *
10318     * @param left The left coordinate of the rectangle to invalidate.
10319     * @param top The top coordinate of the rectangle to invalidate.
10320     * @param right The right coordinate of the rectangle to invalidate.
10321     * @param bottom The bottom coordinate of the rectangle to invalidate.
10322     *
10323     * @see #invalidate(int, int, int, int)
10324     * @see #invalidate(Rect)
10325     */
10326    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10327        // We try only with the AttachInfo because there's no point in invalidating
10328        // if we are not attached to our window
10329        final AttachInfo attachInfo = mAttachInfo;
10330        if (attachInfo != null) {
10331            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10332            info.target = this;
10333            info.left = left;
10334            info.top = top;
10335            info.right = right;
10336            info.bottom = bottom;
10337
10338            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10339        }
10340    }
10341
10342    /**
10343     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10344     * This event is sent at most once every
10345     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10346     */
10347    private void postSendViewScrolledAccessibilityEventCallback() {
10348        if (mSendViewScrolledAccessibilityEvent == null) {
10349            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10350        }
10351        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10352            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10353            postDelayed(mSendViewScrolledAccessibilityEvent,
10354                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10355        }
10356    }
10357
10358    /**
10359     * Called by a parent to request that a child update its values for mScrollX
10360     * and mScrollY if necessary. This will typically be done if the child is
10361     * animating a scroll using a {@link android.widget.Scroller Scroller}
10362     * object.
10363     */
10364    public void computeScroll() {
10365    }
10366
10367    /**
10368     * <p>Indicate whether the horizontal edges are faded when the view is
10369     * scrolled horizontally.</p>
10370     *
10371     * @return true if the horizontal edges should are faded on scroll, false
10372     *         otherwise
10373     *
10374     * @see #setHorizontalFadingEdgeEnabled(boolean)
10375     *
10376     * @attr ref android.R.styleable#View_requiresFadingEdge
10377     */
10378    public boolean isHorizontalFadingEdgeEnabled() {
10379        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10380    }
10381
10382    /**
10383     * <p>Define whether the horizontal edges should be faded when this view
10384     * is scrolled horizontally.</p>
10385     *
10386     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10387     *                                    be faded when the view is scrolled
10388     *                                    horizontally
10389     *
10390     * @see #isHorizontalFadingEdgeEnabled()
10391     *
10392     * @attr ref android.R.styleable#View_requiresFadingEdge
10393     */
10394    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10395        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10396            if (horizontalFadingEdgeEnabled) {
10397                initScrollCache();
10398            }
10399
10400            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10401        }
10402    }
10403
10404    /**
10405     * <p>Indicate whether the vertical edges are faded when the view is
10406     * scrolled horizontally.</p>
10407     *
10408     * @return true if the vertical edges should are faded on scroll, false
10409     *         otherwise
10410     *
10411     * @see #setVerticalFadingEdgeEnabled(boolean)
10412     *
10413     * @attr ref android.R.styleable#View_requiresFadingEdge
10414     */
10415    public boolean isVerticalFadingEdgeEnabled() {
10416        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10417    }
10418
10419    /**
10420     * <p>Define whether the vertical edges should be faded when this view
10421     * is scrolled vertically.</p>
10422     *
10423     * @param verticalFadingEdgeEnabled true if the vertical edges should
10424     *                                  be faded when the view is scrolled
10425     *                                  vertically
10426     *
10427     * @see #isVerticalFadingEdgeEnabled()
10428     *
10429     * @attr ref android.R.styleable#View_requiresFadingEdge
10430     */
10431    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10432        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10433            if (verticalFadingEdgeEnabled) {
10434                initScrollCache();
10435            }
10436
10437            mViewFlags ^= FADING_EDGE_VERTICAL;
10438        }
10439    }
10440
10441    /**
10442     * Returns the strength, or intensity, of the top faded edge. The strength is
10443     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10444     * returns 0.0 or 1.0 but no value in between.
10445     *
10446     * Subclasses should override this method to provide a smoother fade transition
10447     * when scrolling occurs.
10448     *
10449     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10450     */
10451    protected float getTopFadingEdgeStrength() {
10452        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10453    }
10454
10455    /**
10456     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10457     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10458     * returns 0.0 or 1.0 but no value in between.
10459     *
10460     * Subclasses should override this method to provide a smoother fade transition
10461     * when scrolling occurs.
10462     *
10463     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10464     */
10465    protected float getBottomFadingEdgeStrength() {
10466        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10467                computeVerticalScrollRange() ? 1.0f : 0.0f;
10468    }
10469
10470    /**
10471     * Returns the strength, or intensity, of the left faded edge. The strength is
10472     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10473     * returns 0.0 or 1.0 but no value in between.
10474     *
10475     * Subclasses should override this method to provide a smoother fade transition
10476     * when scrolling occurs.
10477     *
10478     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10479     */
10480    protected float getLeftFadingEdgeStrength() {
10481        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10482    }
10483
10484    /**
10485     * Returns the strength, or intensity, of the right faded edge. The strength is
10486     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10487     * returns 0.0 or 1.0 but no value in between.
10488     *
10489     * Subclasses should override this method to provide a smoother fade transition
10490     * when scrolling occurs.
10491     *
10492     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10493     */
10494    protected float getRightFadingEdgeStrength() {
10495        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10496                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10497    }
10498
10499    /**
10500     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10501     * scrollbar is not drawn by default.</p>
10502     *
10503     * @return true if the horizontal scrollbar should be painted, false
10504     *         otherwise
10505     *
10506     * @see #setHorizontalScrollBarEnabled(boolean)
10507     */
10508    public boolean isHorizontalScrollBarEnabled() {
10509        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10510    }
10511
10512    /**
10513     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10514     * scrollbar is not drawn by default.</p>
10515     *
10516     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10517     *                                   be painted
10518     *
10519     * @see #isHorizontalScrollBarEnabled()
10520     */
10521    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10522        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10523            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10524            computeOpaqueFlags();
10525            resolvePadding();
10526        }
10527    }
10528
10529    /**
10530     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10531     * scrollbar is not drawn by default.</p>
10532     *
10533     * @return true if the vertical scrollbar should be painted, false
10534     *         otherwise
10535     *
10536     * @see #setVerticalScrollBarEnabled(boolean)
10537     */
10538    public boolean isVerticalScrollBarEnabled() {
10539        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10540    }
10541
10542    /**
10543     * <p>Define whether the vertical scrollbar should be drawn or not. The
10544     * scrollbar is not drawn by default.</p>
10545     *
10546     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10547     *                                 be painted
10548     *
10549     * @see #isVerticalScrollBarEnabled()
10550     */
10551    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10552        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10553            mViewFlags ^= SCROLLBARS_VERTICAL;
10554            computeOpaqueFlags();
10555            resolvePadding();
10556        }
10557    }
10558
10559    /**
10560     * @hide
10561     */
10562    protected void recomputePadding() {
10563        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10564    }
10565
10566    /**
10567     * Define whether scrollbars will fade when the view is not scrolling.
10568     *
10569     * @param fadeScrollbars wheter to enable fading
10570     *
10571     * @attr ref android.R.styleable#View_fadeScrollbars
10572     */
10573    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10574        initScrollCache();
10575        final ScrollabilityCache scrollabilityCache = mScrollCache;
10576        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10577        if (fadeScrollbars) {
10578            scrollabilityCache.state = ScrollabilityCache.OFF;
10579        } else {
10580            scrollabilityCache.state = ScrollabilityCache.ON;
10581        }
10582    }
10583
10584    /**
10585     *
10586     * Returns true if scrollbars will fade when this view is not scrolling
10587     *
10588     * @return true if scrollbar fading is enabled
10589     *
10590     * @attr ref android.R.styleable#View_fadeScrollbars
10591     */
10592    public boolean isScrollbarFadingEnabled() {
10593        return mScrollCache != null && mScrollCache.fadeScrollBars;
10594    }
10595
10596    /**
10597     *
10598     * Returns the delay before scrollbars fade.
10599     *
10600     * @return the delay before scrollbars fade
10601     *
10602     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10603     */
10604    public int getScrollBarDefaultDelayBeforeFade() {
10605        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10606                mScrollCache.scrollBarDefaultDelayBeforeFade;
10607    }
10608
10609    /**
10610     * Define the delay before scrollbars fade.
10611     *
10612     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10613     *
10614     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10615     */
10616    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10617        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10618    }
10619
10620    /**
10621     *
10622     * Returns the scrollbar fade duration.
10623     *
10624     * @return the scrollbar fade duration
10625     *
10626     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10627     */
10628    public int getScrollBarFadeDuration() {
10629        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10630                mScrollCache.scrollBarFadeDuration;
10631    }
10632
10633    /**
10634     * Define the scrollbar fade duration.
10635     *
10636     * @param scrollBarFadeDuration - the scrollbar fade duration
10637     *
10638     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10639     */
10640    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10641        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10642    }
10643
10644    /**
10645     *
10646     * Returns the scrollbar size.
10647     *
10648     * @return the scrollbar size
10649     *
10650     * @attr ref android.R.styleable#View_scrollbarSize
10651     */
10652    public int getScrollBarSize() {
10653        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10654                mScrollCache.scrollBarSize;
10655    }
10656
10657    /**
10658     * Define the scrollbar size.
10659     *
10660     * @param scrollBarSize - the scrollbar size
10661     *
10662     * @attr ref android.R.styleable#View_scrollbarSize
10663     */
10664    public void setScrollBarSize(int scrollBarSize) {
10665        getScrollCache().scrollBarSize = scrollBarSize;
10666    }
10667
10668    /**
10669     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10670     * inset. When inset, they add to the padding of the view. And the scrollbars
10671     * can be drawn inside the padding area or on the edge of the view. For example,
10672     * if a view has a background drawable and you want to draw the scrollbars
10673     * inside the padding specified by the drawable, you can use
10674     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10675     * appear at the edge of the view, ignoring the padding, then you can use
10676     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10677     * @param style the style of the scrollbars. Should be one of
10678     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10679     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10680     * @see #SCROLLBARS_INSIDE_OVERLAY
10681     * @see #SCROLLBARS_INSIDE_INSET
10682     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10683     * @see #SCROLLBARS_OUTSIDE_INSET
10684     *
10685     * @attr ref android.R.styleable#View_scrollbarStyle
10686     */
10687    public void setScrollBarStyle(int style) {
10688        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10689            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10690            computeOpaqueFlags();
10691            resolvePadding();
10692        }
10693    }
10694
10695    /**
10696     * <p>Returns the current scrollbar style.</p>
10697     * @return the current scrollbar style
10698     * @see #SCROLLBARS_INSIDE_OVERLAY
10699     * @see #SCROLLBARS_INSIDE_INSET
10700     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10701     * @see #SCROLLBARS_OUTSIDE_INSET
10702     *
10703     * @attr ref android.R.styleable#View_scrollbarStyle
10704     */
10705    @ViewDebug.ExportedProperty(mapping = {
10706            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10707            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10708            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10709            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10710    })
10711    public int getScrollBarStyle() {
10712        return mViewFlags & SCROLLBARS_STYLE_MASK;
10713    }
10714
10715    /**
10716     * <p>Compute the horizontal range that the horizontal scrollbar
10717     * represents.</p>
10718     *
10719     * <p>The range is expressed in arbitrary units that must be the same as the
10720     * units used by {@link #computeHorizontalScrollExtent()} and
10721     * {@link #computeHorizontalScrollOffset()}.</p>
10722     *
10723     * <p>The default range is the drawing width of this view.</p>
10724     *
10725     * @return the total horizontal range represented by the horizontal
10726     *         scrollbar
10727     *
10728     * @see #computeHorizontalScrollExtent()
10729     * @see #computeHorizontalScrollOffset()
10730     * @see android.widget.ScrollBarDrawable
10731     */
10732    protected int computeHorizontalScrollRange() {
10733        return getWidth();
10734    }
10735
10736    /**
10737     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10738     * within the horizontal range. This value is used to compute the position
10739     * of the thumb within the scrollbar's track.</p>
10740     *
10741     * <p>The range is expressed in arbitrary units that must be the same as the
10742     * units used by {@link #computeHorizontalScrollRange()} and
10743     * {@link #computeHorizontalScrollExtent()}.</p>
10744     *
10745     * <p>The default offset is the scroll offset of this view.</p>
10746     *
10747     * @return the horizontal offset of the scrollbar's thumb
10748     *
10749     * @see #computeHorizontalScrollRange()
10750     * @see #computeHorizontalScrollExtent()
10751     * @see android.widget.ScrollBarDrawable
10752     */
10753    protected int computeHorizontalScrollOffset() {
10754        return mScrollX;
10755    }
10756
10757    /**
10758     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10759     * within the horizontal range. This value is used to compute the length
10760     * of the thumb within the scrollbar's track.</p>
10761     *
10762     * <p>The range is expressed in arbitrary units that must be the same as the
10763     * units used by {@link #computeHorizontalScrollRange()} and
10764     * {@link #computeHorizontalScrollOffset()}.</p>
10765     *
10766     * <p>The default extent is the drawing width of this view.</p>
10767     *
10768     * @return the horizontal extent of the scrollbar's thumb
10769     *
10770     * @see #computeHorizontalScrollRange()
10771     * @see #computeHorizontalScrollOffset()
10772     * @see android.widget.ScrollBarDrawable
10773     */
10774    protected int computeHorizontalScrollExtent() {
10775        return getWidth();
10776    }
10777
10778    /**
10779     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10780     *
10781     * <p>The range is expressed in arbitrary units that must be the same as the
10782     * units used by {@link #computeVerticalScrollExtent()} and
10783     * {@link #computeVerticalScrollOffset()}.</p>
10784     *
10785     * @return the total vertical range represented by the vertical scrollbar
10786     *
10787     * <p>The default range is the drawing height of this view.</p>
10788     *
10789     * @see #computeVerticalScrollExtent()
10790     * @see #computeVerticalScrollOffset()
10791     * @see android.widget.ScrollBarDrawable
10792     */
10793    protected int computeVerticalScrollRange() {
10794        return getHeight();
10795    }
10796
10797    /**
10798     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10799     * within the horizontal range. This value is used to compute the position
10800     * of the thumb within the scrollbar's track.</p>
10801     *
10802     * <p>The range is expressed in arbitrary units that must be the same as the
10803     * units used by {@link #computeVerticalScrollRange()} and
10804     * {@link #computeVerticalScrollExtent()}.</p>
10805     *
10806     * <p>The default offset is the scroll offset of this view.</p>
10807     *
10808     * @return the vertical offset of the scrollbar's thumb
10809     *
10810     * @see #computeVerticalScrollRange()
10811     * @see #computeVerticalScrollExtent()
10812     * @see android.widget.ScrollBarDrawable
10813     */
10814    protected int computeVerticalScrollOffset() {
10815        return mScrollY;
10816    }
10817
10818    /**
10819     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10820     * within the vertical range. This value is used to compute the length
10821     * of the thumb within the scrollbar's track.</p>
10822     *
10823     * <p>The range is expressed in arbitrary units that must be the same as the
10824     * units used by {@link #computeVerticalScrollRange()} and
10825     * {@link #computeVerticalScrollOffset()}.</p>
10826     *
10827     * <p>The default extent is the drawing height of this view.</p>
10828     *
10829     * @return the vertical extent of the scrollbar's thumb
10830     *
10831     * @see #computeVerticalScrollRange()
10832     * @see #computeVerticalScrollOffset()
10833     * @see android.widget.ScrollBarDrawable
10834     */
10835    protected int computeVerticalScrollExtent() {
10836        return getHeight();
10837    }
10838
10839    /**
10840     * Check if this view can be scrolled horizontally in a certain direction.
10841     *
10842     * @param direction Negative to check scrolling left, positive to check scrolling right.
10843     * @return true if this view can be scrolled in the specified direction, false otherwise.
10844     */
10845    public boolean canScrollHorizontally(int direction) {
10846        final int offset = computeHorizontalScrollOffset();
10847        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10848        if (range == 0) return false;
10849        if (direction < 0) {
10850            return offset > 0;
10851        } else {
10852            return offset < range - 1;
10853        }
10854    }
10855
10856    /**
10857     * Check if this view can be scrolled vertically in a certain direction.
10858     *
10859     * @param direction Negative to check scrolling up, positive to check scrolling down.
10860     * @return true if this view can be scrolled in the specified direction, false otherwise.
10861     */
10862    public boolean canScrollVertically(int direction) {
10863        final int offset = computeVerticalScrollOffset();
10864        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10865        if (range == 0) return false;
10866        if (direction < 0) {
10867            return offset > 0;
10868        } else {
10869            return offset < range - 1;
10870        }
10871    }
10872
10873    /**
10874     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10875     * scrollbars are painted only if they have been awakened first.</p>
10876     *
10877     * @param canvas the canvas on which to draw the scrollbars
10878     *
10879     * @see #awakenScrollBars(int)
10880     */
10881    protected final void onDrawScrollBars(Canvas canvas) {
10882        // scrollbars are drawn only when the animation is running
10883        final ScrollabilityCache cache = mScrollCache;
10884        if (cache != null) {
10885
10886            int state = cache.state;
10887
10888            if (state == ScrollabilityCache.OFF) {
10889                return;
10890            }
10891
10892            boolean invalidate = false;
10893
10894            if (state == ScrollabilityCache.FADING) {
10895                // We're fading -- get our fade interpolation
10896                if (cache.interpolatorValues == null) {
10897                    cache.interpolatorValues = new float[1];
10898                }
10899
10900                float[] values = cache.interpolatorValues;
10901
10902                // Stops the animation if we're done
10903                if (cache.scrollBarInterpolator.timeToValues(values) ==
10904                        Interpolator.Result.FREEZE_END) {
10905                    cache.state = ScrollabilityCache.OFF;
10906                } else {
10907                    cache.scrollBar.setAlpha(Math.round(values[0]));
10908                }
10909
10910                // This will make the scroll bars inval themselves after
10911                // drawing. We only want this when we're fading so that
10912                // we prevent excessive redraws
10913                invalidate = true;
10914            } else {
10915                // We're just on -- but we may have been fading before so
10916                // reset alpha
10917                cache.scrollBar.setAlpha(255);
10918            }
10919
10920
10921            final int viewFlags = mViewFlags;
10922
10923            final boolean drawHorizontalScrollBar =
10924                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10925            final boolean drawVerticalScrollBar =
10926                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10927                && !isVerticalScrollBarHidden();
10928
10929            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10930                final int width = mRight - mLeft;
10931                final int height = mBottom - mTop;
10932
10933                final ScrollBarDrawable scrollBar = cache.scrollBar;
10934
10935                final int scrollX = mScrollX;
10936                final int scrollY = mScrollY;
10937                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10938
10939                int left, top, right, bottom;
10940
10941                if (drawHorizontalScrollBar) {
10942                    int size = scrollBar.getSize(false);
10943                    if (size <= 0) {
10944                        size = cache.scrollBarSize;
10945                    }
10946
10947                    scrollBar.setParameters(computeHorizontalScrollRange(),
10948                                            computeHorizontalScrollOffset(),
10949                                            computeHorizontalScrollExtent(), false);
10950                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10951                            getVerticalScrollbarWidth() : 0;
10952                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10953                    left = scrollX + (mPaddingLeft & inside);
10954                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10955                    bottom = top + size;
10956                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10957                    if (invalidate) {
10958                        invalidate(left, top, right, bottom);
10959                    }
10960                }
10961
10962                if (drawVerticalScrollBar) {
10963                    int size = scrollBar.getSize(true);
10964                    if (size <= 0) {
10965                        size = cache.scrollBarSize;
10966                    }
10967
10968                    scrollBar.setParameters(computeVerticalScrollRange(),
10969                                            computeVerticalScrollOffset(),
10970                                            computeVerticalScrollExtent(), true);
10971                    switch (mVerticalScrollbarPosition) {
10972                        default:
10973                        case SCROLLBAR_POSITION_DEFAULT:
10974                        case SCROLLBAR_POSITION_RIGHT:
10975                            left = scrollX + width - size - (mUserPaddingRight & inside);
10976                            break;
10977                        case SCROLLBAR_POSITION_LEFT:
10978                            left = scrollX + (mUserPaddingLeft & inside);
10979                            break;
10980                    }
10981                    top = scrollY + (mPaddingTop & inside);
10982                    right = left + size;
10983                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10984                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10985                    if (invalidate) {
10986                        invalidate(left, top, right, bottom);
10987                    }
10988                }
10989            }
10990        }
10991    }
10992
10993    /**
10994     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10995     * FastScroller is visible.
10996     * @return whether to temporarily hide the vertical scrollbar
10997     * @hide
10998     */
10999    protected boolean isVerticalScrollBarHidden() {
11000        return false;
11001    }
11002
11003    /**
11004     * <p>Draw the horizontal scrollbar if
11005     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11006     *
11007     * @param canvas the canvas on which to draw the scrollbar
11008     * @param scrollBar the scrollbar's drawable
11009     *
11010     * @see #isHorizontalScrollBarEnabled()
11011     * @see #computeHorizontalScrollRange()
11012     * @see #computeHorizontalScrollExtent()
11013     * @see #computeHorizontalScrollOffset()
11014     * @see android.widget.ScrollBarDrawable
11015     * @hide
11016     */
11017    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11018            int l, int t, int r, int b) {
11019        scrollBar.setBounds(l, t, r, b);
11020        scrollBar.draw(canvas);
11021    }
11022
11023    /**
11024     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11025     * 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 #isVerticalScrollBarEnabled()
11031     * @see #computeVerticalScrollRange()
11032     * @see #computeVerticalScrollExtent()
11033     * @see #computeVerticalScrollOffset()
11034     * @see android.widget.ScrollBarDrawable
11035     * @hide
11036     */
11037    protected void onDrawVerticalScrollBar(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     * Implement this to do your drawing.
11045     *
11046     * @param canvas the canvas on which the background will be drawn
11047     */
11048    protected void onDraw(Canvas canvas) {
11049    }
11050
11051    /*
11052     * Caller is responsible for calling requestLayout if necessary.
11053     * (This allows addViewInLayout to not request a new layout.)
11054     */
11055    void assignParent(ViewParent parent) {
11056        if (mParent == null) {
11057            mParent = parent;
11058        } else if (parent == null) {
11059            mParent = null;
11060        } else {
11061            throw new RuntimeException("view " + this + " being added, but"
11062                    + " it already has a parent");
11063        }
11064    }
11065
11066    /**
11067     * This is called when the view is attached to a window.  At this point it
11068     * has a Surface and will start drawing.  Note that this function is
11069     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11070     * however it may be called any time before the first onDraw -- including
11071     * before or after {@link #onMeasure(int, int)}.
11072     *
11073     * @see #onDetachedFromWindow()
11074     */
11075    protected void onAttachedToWindow() {
11076        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11077            mParent.requestTransparentRegion(this);
11078        }
11079
11080        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11081            initialAwakenScrollBars();
11082            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11083        }
11084
11085        jumpDrawablesToCurrentState();
11086
11087        // Order is important here: LayoutDirection MUST be resolved before Padding
11088        // and TextDirection
11089        resolveLayoutDirection();
11090        resolvePadding();
11091        resolveTextDirection();
11092        resolveTextAlignment();
11093
11094        clearAccessibilityFocus();
11095        if (isFocused()) {
11096            InputMethodManager imm = InputMethodManager.peekInstance();
11097            imm.focusIn(this);
11098        }
11099
11100        if (mAttachInfo != null && mDisplayList != null) {
11101            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11102        }
11103    }
11104
11105    /**
11106     * @see #onScreenStateChanged(int)
11107     */
11108    void dispatchScreenStateChanged(int screenState) {
11109        onScreenStateChanged(screenState);
11110    }
11111
11112    /**
11113     * This method is called whenever the state of the screen this view is
11114     * attached to changes. A state change will usually occurs when the screen
11115     * turns on or off (whether it happens automatically or the user does it
11116     * manually.)
11117     *
11118     * @param screenState The new state of the screen. Can be either
11119     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11120     */
11121    public void onScreenStateChanged(int screenState) {
11122    }
11123
11124    /**
11125     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11126     */
11127    private boolean hasRtlSupport() {
11128        return mContext.getApplicationInfo().hasRtlSupport();
11129    }
11130
11131    /**
11132     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11133     * that the parent directionality can and will be resolved before its children.
11134     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11135     */
11136    public void resolveLayoutDirection() {
11137        // Clear any previous layout direction resolution
11138        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11139
11140        if (hasRtlSupport()) {
11141            // Set resolved depending on layout direction
11142            switch (getLayoutDirection()) {
11143                case LAYOUT_DIRECTION_INHERIT:
11144                    // If this is root view, no need to look at parent's layout dir.
11145                    if (canResolveLayoutDirection()) {
11146                        ViewGroup viewGroup = ((ViewGroup) mParent);
11147
11148                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11149                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11150                        }
11151                    } else {
11152                        // Nothing to do, LTR by default
11153                    }
11154                    break;
11155                case LAYOUT_DIRECTION_RTL:
11156                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11157                    break;
11158                case LAYOUT_DIRECTION_LOCALE:
11159                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11160                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11161                    }
11162                    break;
11163                default:
11164                    // Nothing to do, LTR by default
11165            }
11166        }
11167
11168        // Set to resolved
11169        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11170        onResolvedLayoutDirectionChanged();
11171        // Resolve padding
11172        resolvePadding();
11173    }
11174
11175    /**
11176     * Called when layout direction has been resolved.
11177     *
11178     * The default implementation does nothing.
11179     */
11180    public void onResolvedLayoutDirectionChanged() {
11181    }
11182
11183    /**
11184     * Resolve padding depending on layout direction.
11185     */
11186    public void resolvePadding() {
11187        // If the user specified the absolute padding (either with android:padding or
11188        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11189        // use the default padding or the padding from the background drawable
11190        // (stored at this point in mPadding*)
11191        int resolvedLayoutDirection = getResolvedLayoutDirection();
11192        switch (resolvedLayoutDirection) {
11193            case LAYOUT_DIRECTION_RTL:
11194                // Start user padding override Right user padding. Otherwise, if Right user
11195                // padding is not defined, use the default Right padding. If Right user padding
11196                // is defined, just use it.
11197                if (mUserPaddingStart >= 0) {
11198                    mUserPaddingRight = mUserPaddingStart;
11199                } else if (mUserPaddingRight < 0) {
11200                    mUserPaddingRight = mPaddingRight;
11201                }
11202                if (mUserPaddingEnd >= 0) {
11203                    mUserPaddingLeft = mUserPaddingEnd;
11204                } else if (mUserPaddingLeft < 0) {
11205                    mUserPaddingLeft = mPaddingLeft;
11206                }
11207                break;
11208            case LAYOUT_DIRECTION_LTR:
11209            default:
11210                // Start user padding override Left user padding. Otherwise, if Left user
11211                // padding is not defined, use the default left padding. If Left user padding
11212                // is defined, just use it.
11213                if (mUserPaddingStart >= 0) {
11214                    mUserPaddingLeft = mUserPaddingStart;
11215                } else if (mUserPaddingLeft < 0) {
11216                    mUserPaddingLeft = mPaddingLeft;
11217                }
11218                if (mUserPaddingEnd >= 0) {
11219                    mUserPaddingRight = mUserPaddingEnd;
11220                } else if (mUserPaddingRight < 0) {
11221                    mUserPaddingRight = mPaddingRight;
11222                }
11223        }
11224
11225        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11226
11227        if(isPaddingRelative()) {
11228            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11229        } else {
11230            recomputePadding();
11231        }
11232        onPaddingChanged(resolvedLayoutDirection);
11233    }
11234
11235    /**
11236     * Resolve padding depending on the layout direction. Subclasses that care about
11237     * padding resolution should override this method. The default implementation does
11238     * nothing.
11239     *
11240     * @param layoutDirection the direction of the layout
11241     *
11242     * @see {@link #LAYOUT_DIRECTION_LTR}
11243     * @see {@link #LAYOUT_DIRECTION_RTL}
11244     */
11245    public void onPaddingChanged(int layoutDirection) {
11246    }
11247
11248    /**
11249     * Check if layout direction resolution can be done.
11250     *
11251     * @return true if layout direction resolution can be done otherwise return false.
11252     */
11253    public boolean canResolveLayoutDirection() {
11254        switch (getLayoutDirection()) {
11255            case LAYOUT_DIRECTION_INHERIT:
11256                return (mParent != null) && (mParent instanceof ViewGroup);
11257            default:
11258                return true;
11259        }
11260    }
11261
11262    /**
11263     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11264     * when reset is done.
11265     */
11266    public void resetResolvedLayoutDirection() {
11267        // Reset the current resolved bits
11268        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11269        onResolvedLayoutDirectionReset();
11270        // Reset also the text direction
11271        resetResolvedTextDirection();
11272    }
11273
11274    /**
11275     * Called during reset of resolved layout direction.
11276     *
11277     * Subclasses need to override this method to clear cached information that depends on the
11278     * resolved layout direction, or to inform child views that inherit their layout direction.
11279     *
11280     * The default implementation does nothing.
11281     */
11282    public void onResolvedLayoutDirectionReset() {
11283    }
11284
11285    /**
11286     * Check if a Locale uses an RTL script.
11287     *
11288     * @param locale Locale to check
11289     * @return true if the Locale uses an RTL script.
11290     */
11291    protected static boolean isLayoutDirectionRtl(Locale locale) {
11292        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11293    }
11294
11295    /**
11296     * This is called when the view is detached from a window.  At this point it
11297     * no longer has a surface for drawing.
11298     *
11299     * @see #onAttachedToWindow()
11300     */
11301    protected void onDetachedFromWindow() {
11302        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11303
11304        removeUnsetPressCallback();
11305        removeLongPressCallback();
11306        removePerformClickCallback();
11307        removeSendViewScrolledAccessibilityEventCallback();
11308
11309        destroyDrawingCache();
11310
11311        destroyLayer(false);
11312
11313        if (mAttachInfo != null) {
11314            if (mDisplayList != null) {
11315                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11316            }
11317            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11318        } else {
11319            if (mDisplayList != null) {
11320                // Should never happen
11321                mDisplayList.invalidate();
11322            }
11323        }
11324
11325        mCurrentAnimation = null;
11326
11327        resetResolvedLayoutDirection();
11328        resetResolvedTextAlignment();
11329        resetAccessibilityStateChanged();
11330    }
11331
11332    /**
11333     * @return The number of times this view has been attached to a window
11334     */
11335    protected int getWindowAttachCount() {
11336        return mWindowAttachCount;
11337    }
11338
11339    /**
11340     * Retrieve a unique token identifying the window this view is attached to.
11341     * @return Return the window's token for use in
11342     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11343     */
11344    public IBinder getWindowToken() {
11345        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11346    }
11347
11348    /**
11349     * Retrieve a unique token identifying the top-level "real" window of
11350     * the window that this view is attached to.  That is, this is like
11351     * {@link #getWindowToken}, except if the window this view in is a panel
11352     * window (attached to another containing window), then the token of
11353     * the containing window is returned instead.
11354     *
11355     * @return Returns the associated window token, either
11356     * {@link #getWindowToken()} or the containing window's token.
11357     */
11358    public IBinder getApplicationWindowToken() {
11359        AttachInfo ai = mAttachInfo;
11360        if (ai != null) {
11361            IBinder appWindowToken = ai.mPanelParentWindowToken;
11362            if (appWindowToken == null) {
11363                appWindowToken = ai.mWindowToken;
11364            }
11365            return appWindowToken;
11366        }
11367        return null;
11368    }
11369
11370    /**
11371     * Retrieve private session object this view hierarchy is using to
11372     * communicate with the window manager.
11373     * @return the session object to communicate with the window manager
11374     */
11375    /*package*/ IWindowSession getWindowSession() {
11376        return mAttachInfo != null ? mAttachInfo.mSession : null;
11377    }
11378
11379    /**
11380     * @param info the {@link android.view.View.AttachInfo} to associated with
11381     *        this view
11382     */
11383    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11384        //System.out.println("Attached! " + this);
11385        mAttachInfo = info;
11386        mWindowAttachCount++;
11387        // We will need to evaluate the drawable state at least once.
11388        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11389        if (mFloatingTreeObserver != null) {
11390            info.mTreeObserver.merge(mFloatingTreeObserver);
11391            mFloatingTreeObserver = null;
11392        }
11393        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11394            mAttachInfo.mScrollContainers.add(this);
11395            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11396        }
11397        performCollectViewAttributes(mAttachInfo, visibility);
11398        onAttachedToWindow();
11399
11400        ListenerInfo li = mListenerInfo;
11401        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11402                li != null ? li.mOnAttachStateChangeListeners : null;
11403        if (listeners != null && listeners.size() > 0) {
11404            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11405            // perform the dispatching. The iterator is a safe guard against listeners that
11406            // could mutate the list by calling the various add/remove methods. This prevents
11407            // the array from being modified while we iterate it.
11408            for (OnAttachStateChangeListener listener : listeners) {
11409                listener.onViewAttachedToWindow(this);
11410            }
11411        }
11412
11413        int vis = info.mWindowVisibility;
11414        if (vis != GONE) {
11415            onWindowVisibilityChanged(vis);
11416        }
11417        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11418            // If nobody has evaluated the drawable state yet, then do it now.
11419            refreshDrawableState();
11420        }
11421    }
11422
11423    void dispatchDetachedFromWindow() {
11424        AttachInfo info = mAttachInfo;
11425        if (info != null) {
11426            int vis = info.mWindowVisibility;
11427            if (vis != GONE) {
11428                onWindowVisibilityChanged(GONE);
11429            }
11430        }
11431
11432        onDetachedFromWindow();
11433
11434        ListenerInfo li = mListenerInfo;
11435        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11436                li != null ? li.mOnAttachStateChangeListeners : null;
11437        if (listeners != null && listeners.size() > 0) {
11438            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11439            // perform the dispatching. The iterator is a safe guard against listeners that
11440            // could mutate the list by calling the various add/remove methods. This prevents
11441            // the array from being modified while we iterate it.
11442            for (OnAttachStateChangeListener listener : listeners) {
11443                listener.onViewDetachedFromWindow(this);
11444            }
11445        }
11446
11447        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11448            mAttachInfo.mScrollContainers.remove(this);
11449            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11450        }
11451
11452        mAttachInfo = null;
11453    }
11454
11455    /**
11456     * Store this view hierarchy's frozen state into the given container.
11457     *
11458     * @param container The SparseArray in which to save the view's state.
11459     *
11460     * @see #restoreHierarchyState(android.util.SparseArray)
11461     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11462     * @see #onSaveInstanceState()
11463     */
11464    public void saveHierarchyState(SparseArray<Parcelable> container) {
11465        dispatchSaveInstanceState(container);
11466    }
11467
11468    /**
11469     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11470     * this view and its children. May be overridden to modify how freezing happens to a
11471     * view's children; for example, some views may want to not store state for their children.
11472     *
11473     * @param container The SparseArray in which to save the view's state.
11474     *
11475     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11476     * @see #saveHierarchyState(android.util.SparseArray)
11477     * @see #onSaveInstanceState()
11478     */
11479    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11480        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11481            mPrivateFlags &= ~SAVE_STATE_CALLED;
11482            Parcelable state = onSaveInstanceState();
11483            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11484                throw new IllegalStateException(
11485                        "Derived class did not call super.onSaveInstanceState()");
11486            }
11487            if (state != null) {
11488                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11489                // + ": " + state);
11490                container.put(mID, state);
11491            }
11492        }
11493    }
11494
11495    /**
11496     * Hook allowing a view to generate a representation of its internal state
11497     * that can later be used to create a new instance with that same state.
11498     * This state should only contain information that is not persistent or can
11499     * not be reconstructed later. For example, you will never store your
11500     * current position on screen because that will be computed again when a
11501     * new instance of the view is placed in its view hierarchy.
11502     * <p>
11503     * Some examples of things you may store here: the current cursor position
11504     * in a text view (but usually not the text itself since that is stored in a
11505     * content provider or other persistent storage), the currently selected
11506     * item in a list view.
11507     *
11508     * @return Returns a Parcelable object containing the view's current dynamic
11509     *         state, or null if there is nothing interesting to save. The
11510     *         default implementation returns null.
11511     * @see #onRestoreInstanceState(android.os.Parcelable)
11512     * @see #saveHierarchyState(android.util.SparseArray)
11513     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11514     * @see #setSaveEnabled(boolean)
11515     */
11516    protected Parcelable onSaveInstanceState() {
11517        mPrivateFlags |= SAVE_STATE_CALLED;
11518        return BaseSavedState.EMPTY_STATE;
11519    }
11520
11521    /**
11522     * Restore this view hierarchy's frozen state from the given container.
11523     *
11524     * @param container The SparseArray which holds previously frozen states.
11525     *
11526     * @see #saveHierarchyState(android.util.SparseArray)
11527     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11528     * @see #onRestoreInstanceState(android.os.Parcelable)
11529     */
11530    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11531        dispatchRestoreInstanceState(container);
11532    }
11533
11534    /**
11535     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11536     * state for this view and its children. May be overridden to modify how restoring
11537     * happens to a view's children; for example, some views may want to not store state
11538     * for their children.
11539     *
11540     * @param container The SparseArray which holds previously saved state.
11541     *
11542     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11543     * @see #restoreHierarchyState(android.util.SparseArray)
11544     * @see #onRestoreInstanceState(android.os.Parcelable)
11545     */
11546    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11547        if (mID != NO_ID) {
11548            Parcelable state = container.get(mID);
11549            if (state != null) {
11550                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11551                // + ": " + state);
11552                mPrivateFlags &= ~SAVE_STATE_CALLED;
11553                onRestoreInstanceState(state);
11554                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11555                    throw new IllegalStateException(
11556                            "Derived class did not call super.onRestoreInstanceState()");
11557                }
11558            }
11559        }
11560    }
11561
11562    /**
11563     * Hook allowing a view to re-apply a representation of its internal state that had previously
11564     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11565     * null state.
11566     *
11567     * @param state The frozen state that had previously been returned by
11568     *        {@link #onSaveInstanceState}.
11569     *
11570     * @see #onSaveInstanceState()
11571     * @see #restoreHierarchyState(android.util.SparseArray)
11572     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11573     */
11574    protected void onRestoreInstanceState(Parcelable state) {
11575        mPrivateFlags |= SAVE_STATE_CALLED;
11576        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11577            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11578                    + "received " + state.getClass().toString() + " instead. This usually happens "
11579                    + "when two views of different type have the same id in the same hierarchy. "
11580                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11581                    + "other views do not use the same id.");
11582        }
11583    }
11584
11585    /**
11586     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11587     *
11588     * @return the drawing start time in milliseconds
11589     */
11590    public long getDrawingTime() {
11591        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11592    }
11593
11594    /**
11595     * <p>Enables or disables the duplication of the parent's state into this view. When
11596     * duplication is enabled, this view gets its drawable state from its parent rather
11597     * than from its own internal properties.</p>
11598     *
11599     * <p>Note: in the current implementation, setting this property to true after the
11600     * view was added to a ViewGroup might have no effect at all. This property should
11601     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11602     *
11603     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11604     * property is enabled, an exception will be thrown.</p>
11605     *
11606     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11607     * parent, these states should not be affected by this method.</p>
11608     *
11609     * @param enabled True to enable duplication of the parent's drawable state, false
11610     *                to disable it.
11611     *
11612     * @see #getDrawableState()
11613     * @see #isDuplicateParentStateEnabled()
11614     */
11615    public void setDuplicateParentStateEnabled(boolean enabled) {
11616        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11617    }
11618
11619    /**
11620     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11621     *
11622     * @return True if this view's drawable state is duplicated from the parent,
11623     *         false otherwise
11624     *
11625     * @see #getDrawableState()
11626     * @see #setDuplicateParentStateEnabled(boolean)
11627     */
11628    public boolean isDuplicateParentStateEnabled() {
11629        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11630    }
11631
11632    /**
11633     * <p>Specifies the type of layer backing this view. The layer can be
11634     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11635     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11636     *
11637     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11638     * instance that controls how the layer is composed on screen. The following
11639     * properties of the paint are taken into account when composing the layer:</p>
11640     * <ul>
11641     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11642     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11643     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11644     * </ul>
11645     *
11646     * <p>If this view has an alpha value set to < 1.0 by calling
11647     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11648     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11649     * equivalent to setting a hardware layer on this view and providing a paint with
11650     * the desired alpha value.<p>
11651     *
11652     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11653     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11654     * for more information on when and how to use layers.</p>
11655     *
11656     * @param layerType The ype of layer to use with this view, must be one of
11657     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11658     *        {@link #LAYER_TYPE_HARDWARE}
11659     * @param paint The paint used to compose the layer. This argument is optional
11660     *        and can be null. It is ignored when the layer type is
11661     *        {@link #LAYER_TYPE_NONE}
11662     *
11663     * @see #getLayerType()
11664     * @see #LAYER_TYPE_NONE
11665     * @see #LAYER_TYPE_SOFTWARE
11666     * @see #LAYER_TYPE_HARDWARE
11667     * @see #setAlpha(float)
11668     *
11669     * @attr ref android.R.styleable#View_layerType
11670     */
11671    public void setLayerType(int layerType, Paint paint) {
11672        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11673            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11674                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11675        }
11676
11677        if (layerType == mLayerType) {
11678            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11679                mLayerPaint = paint == null ? new Paint() : paint;
11680                invalidateParentCaches();
11681                invalidate(true);
11682            }
11683            return;
11684        }
11685
11686        // Destroy any previous software drawing cache if needed
11687        switch (mLayerType) {
11688            case LAYER_TYPE_HARDWARE:
11689                destroyLayer(false);
11690                // fall through - non-accelerated views may use software layer mechanism instead
11691            case LAYER_TYPE_SOFTWARE:
11692                destroyDrawingCache();
11693                break;
11694            default:
11695                break;
11696        }
11697
11698        mLayerType = layerType;
11699        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11700        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11701        mLocalDirtyRect = layerDisabled ? null : new Rect();
11702
11703        invalidateParentCaches();
11704        invalidate(true);
11705    }
11706
11707    /**
11708     * Indicates whether this view has a static layer. A view with layer type
11709     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11710     * dynamic.
11711     */
11712    boolean hasStaticLayer() {
11713        return true;
11714    }
11715
11716    /**
11717     * Indicates what type of layer is currently associated with this view. By default
11718     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11719     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11720     * for more information on the different types of layers.
11721     *
11722     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11723     *         {@link #LAYER_TYPE_HARDWARE}
11724     *
11725     * @see #setLayerType(int, android.graphics.Paint)
11726     * @see #buildLayer()
11727     * @see #LAYER_TYPE_NONE
11728     * @see #LAYER_TYPE_SOFTWARE
11729     * @see #LAYER_TYPE_HARDWARE
11730     */
11731    public int getLayerType() {
11732        return mLayerType;
11733    }
11734
11735    /**
11736     * Forces this view's layer to be created and this view to be rendered
11737     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11738     * invoking this method will have no effect.
11739     *
11740     * This method can for instance be used to render a view into its layer before
11741     * starting an animation. If this view is complex, rendering into the layer
11742     * before starting the animation will avoid skipping frames.
11743     *
11744     * @throws IllegalStateException If this view is not attached to a window
11745     *
11746     * @see #setLayerType(int, android.graphics.Paint)
11747     */
11748    public void buildLayer() {
11749        if (mLayerType == LAYER_TYPE_NONE) return;
11750
11751        if (mAttachInfo == null) {
11752            throw new IllegalStateException("This view must be attached to a window first");
11753        }
11754
11755        switch (mLayerType) {
11756            case LAYER_TYPE_HARDWARE:
11757                if (mAttachInfo.mHardwareRenderer != null &&
11758                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11759                        mAttachInfo.mHardwareRenderer.validate()) {
11760                    getHardwareLayer();
11761                }
11762                break;
11763            case LAYER_TYPE_SOFTWARE:
11764                buildDrawingCache(true);
11765                break;
11766        }
11767    }
11768
11769    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11770    void flushLayer() {
11771        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11772            mHardwareLayer.flush();
11773        }
11774    }
11775
11776    /**
11777     * <p>Returns a hardware layer that can be used to draw this view again
11778     * without executing its draw method.</p>
11779     *
11780     * @return A HardwareLayer ready to render, or null if an error occurred.
11781     */
11782    HardwareLayer getHardwareLayer() {
11783        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11784                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11785            return null;
11786        }
11787
11788        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11789
11790        final int width = mRight - mLeft;
11791        final int height = mBottom - mTop;
11792
11793        if (width == 0 || height == 0) {
11794            return null;
11795        }
11796
11797        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11798            if (mHardwareLayer == null) {
11799                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11800                        width, height, isOpaque());
11801                mLocalDirtyRect.set(0, 0, width, height);
11802            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11803                mHardwareLayer.resize(width, height);
11804                mLocalDirtyRect.set(0, 0, width, height);
11805            }
11806
11807            // The layer is not valid if the underlying GPU resources cannot be allocated
11808            if (!mHardwareLayer.isValid()) {
11809                return null;
11810            }
11811
11812            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11813            mLocalDirtyRect.setEmpty();
11814        }
11815
11816        return mHardwareLayer;
11817    }
11818
11819    /**
11820     * Destroys this View's hardware layer if possible.
11821     *
11822     * @return True if the layer was destroyed, false otherwise.
11823     *
11824     * @see #setLayerType(int, android.graphics.Paint)
11825     * @see #LAYER_TYPE_HARDWARE
11826     */
11827    boolean destroyLayer(boolean valid) {
11828        if (mHardwareLayer != null) {
11829            AttachInfo info = mAttachInfo;
11830            if (info != null && info.mHardwareRenderer != null &&
11831                    info.mHardwareRenderer.isEnabled() &&
11832                    (valid || info.mHardwareRenderer.validate())) {
11833                mHardwareLayer.destroy();
11834                mHardwareLayer = null;
11835
11836                invalidate(true);
11837                invalidateParentCaches();
11838            }
11839            return true;
11840        }
11841        return false;
11842    }
11843
11844    /**
11845     * Destroys all hardware rendering resources. This method is invoked
11846     * when the system needs to reclaim resources. Upon execution of this
11847     * method, you should free any OpenGL resources created by the view.
11848     *
11849     * Note: you <strong>must</strong> call
11850     * <code>super.destroyHardwareResources()</code> when overriding
11851     * this method.
11852     *
11853     * @hide
11854     */
11855    protected void destroyHardwareResources() {
11856        destroyLayer(true);
11857    }
11858
11859    /**
11860     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11861     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11862     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11863     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11864     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11865     * null.</p>
11866     *
11867     * <p>Enabling the drawing cache is similar to
11868     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11869     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11870     * drawing cache has no effect on rendering because the system uses a different mechanism
11871     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11872     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11873     * for information on how to enable software and hardware layers.</p>
11874     *
11875     * <p>This API can be used to manually generate
11876     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11877     * {@link #getDrawingCache()}.</p>
11878     *
11879     * @param enabled true to enable the drawing cache, false otherwise
11880     *
11881     * @see #isDrawingCacheEnabled()
11882     * @see #getDrawingCache()
11883     * @see #buildDrawingCache()
11884     * @see #setLayerType(int, android.graphics.Paint)
11885     */
11886    public void setDrawingCacheEnabled(boolean enabled) {
11887        mCachingFailed = false;
11888        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11889    }
11890
11891    /**
11892     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11893     *
11894     * @return true if the drawing cache is enabled
11895     *
11896     * @see #setDrawingCacheEnabled(boolean)
11897     * @see #getDrawingCache()
11898     */
11899    @ViewDebug.ExportedProperty(category = "drawing")
11900    public boolean isDrawingCacheEnabled() {
11901        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11902    }
11903
11904    /**
11905     * Debugging utility which recursively outputs the dirty state of a view and its
11906     * descendants.
11907     *
11908     * @hide
11909     */
11910    @SuppressWarnings({"UnusedDeclaration"})
11911    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11912        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11913                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11914                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11915                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11916        if (clear) {
11917            mPrivateFlags &= clearMask;
11918        }
11919        if (this instanceof ViewGroup) {
11920            ViewGroup parent = (ViewGroup) this;
11921            final int count = parent.getChildCount();
11922            for (int i = 0; i < count; i++) {
11923                final View child = parent.getChildAt(i);
11924                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11925            }
11926        }
11927    }
11928
11929    /**
11930     * This method is used by ViewGroup to cause its children to restore or recreate their
11931     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11932     * to recreate its own display list, which would happen if it went through the normal
11933     * draw/dispatchDraw mechanisms.
11934     *
11935     * @hide
11936     */
11937    protected void dispatchGetDisplayList() {}
11938
11939    /**
11940     * A view that is not attached or hardware accelerated cannot create a display list.
11941     * This method checks these conditions and returns the appropriate result.
11942     *
11943     * @return true if view has the ability to create a display list, false otherwise.
11944     *
11945     * @hide
11946     */
11947    public boolean canHaveDisplayList() {
11948        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11949    }
11950
11951    /**
11952     * @return The HardwareRenderer associated with that view or null if hardware rendering
11953     * is not supported or this this has not been attached to a window.
11954     *
11955     * @hide
11956     */
11957    public HardwareRenderer getHardwareRenderer() {
11958        if (mAttachInfo != null) {
11959            return mAttachInfo.mHardwareRenderer;
11960        }
11961        return null;
11962    }
11963
11964    /**
11965     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11966     * Otherwise, the same display list will be returned (after having been rendered into
11967     * along the way, depending on the invalidation state of the view).
11968     *
11969     * @param displayList The previous version of this displayList, could be null.
11970     * @param isLayer Whether the requester of the display list is a layer. If so,
11971     * the view will avoid creating a layer inside the resulting display list.
11972     * @return A new or reused DisplayList object.
11973     */
11974    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11975        if (!canHaveDisplayList()) {
11976            return null;
11977        }
11978
11979        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11980                displayList == null || !displayList.isValid() ||
11981                (!isLayer && mRecreateDisplayList))) {
11982            // Don't need to recreate the display list, just need to tell our
11983            // children to restore/recreate theirs
11984            if (displayList != null && displayList.isValid() &&
11985                    !isLayer && !mRecreateDisplayList) {
11986                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11987                mPrivateFlags &= ~DIRTY_MASK;
11988                dispatchGetDisplayList();
11989
11990                return displayList;
11991            }
11992
11993            if (!isLayer) {
11994                // If we got here, we're recreating it. Mark it as such to ensure that
11995                // we copy in child display lists into ours in drawChild()
11996                mRecreateDisplayList = true;
11997            }
11998            if (displayList == null) {
11999                final String name = getClass().getSimpleName();
12000                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12001                // If we're creating a new display list, make sure our parent gets invalidated
12002                // since they will need to recreate their display list to account for this
12003                // new child display list.
12004                invalidateParentCaches();
12005            }
12006
12007            boolean caching = false;
12008            final HardwareCanvas canvas = displayList.start();
12009            int width = mRight - mLeft;
12010            int height = mBottom - mTop;
12011
12012            try {
12013                canvas.setViewport(width, height);
12014                // The dirty rect should always be null for a display list
12015                canvas.onPreDraw(null);
12016                int layerType = (
12017                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12018                        getLayerType() : LAYER_TYPE_NONE;
12019                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12020                    if (layerType == LAYER_TYPE_HARDWARE) {
12021                        final HardwareLayer layer = getHardwareLayer();
12022                        if (layer != null && layer.isValid()) {
12023                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12024                        } else {
12025                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12026                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12027                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12028                        }
12029                        caching = true;
12030                    } else {
12031                        buildDrawingCache(true);
12032                        Bitmap cache = getDrawingCache(true);
12033                        if (cache != null) {
12034                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12035                            caching = true;
12036                        }
12037                    }
12038                } else {
12039
12040                    computeScroll();
12041
12042                    canvas.translate(-mScrollX, -mScrollY);
12043                    if (!isLayer) {
12044                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12045                        mPrivateFlags &= ~DIRTY_MASK;
12046                    }
12047
12048                    // Fast path for layouts with no backgrounds
12049                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12050                        dispatchDraw(canvas);
12051                    } else {
12052                        draw(canvas);
12053                    }
12054                }
12055            } finally {
12056                canvas.onPostDraw();
12057
12058                displayList.end();
12059                displayList.setCaching(caching);
12060                if (isLayer) {
12061                    displayList.setLeftTopRightBottom(0, 0, width, height);
12062                } else {
12063                    setDisplayListProperties(displayList);
12064                }
12065            }
12066        } else if (!isLayer) {
12067            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12068            mPrivateFlags &= ~DIRTY_MASK;
12069        }
12070
12071        return displayList;
12072    }
12073
12074    /**
12075     * Get the DisplayList for the HardwareLayer
12076     *
12077     * @param layer The HardwareLayer whose DisplayList we want
12078     * @return A DisplayList fopr the specified HardwareLayer
12079     */
12080    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12081        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12082        layer.setDisplayList(displayList);
12083        return displayList;
12084    }
12085
12086
12087    /**
12088     * <p>Returns a display list that can be used to draw this view again
12089     * without executing its draw method.</p>
12090     *
12091     * @return A DisplayList ready to replay, or null if caching is not enabled.
12092     *
12093     * @hide
12094     */
12095    public DisplayList getDisplayList() {
12096        mDisplayList = getDisplayList(mDisplayList, false);
12097        return mDisplayList;
12098    }
12099
12100    /**
12101     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12102     *
12103     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12104     *
12105     * @see #getDrawingCache(boolean)
12106     */
12107    public Bitmap getDrawingCache() {
12108        return getDrawingCache(false);
12109    }
12110
12111    /**
12112     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12113     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12114     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12115     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12116     * request the drawing cache by calling this method and draw it on screen if the
12117     * returned bitmap is not null.</p>
12118     *
12119     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12120     * this method will create a bitmap of the same size as this view. Because this bitmap
12121     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12122     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12123     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12124     * size than the view. This implies that your application must be able to handle this
12125     * size.</p>
12126     *
12127     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12128     *        the current density of the screen when the application is in compatibility
12129     *        mode.
12130     *
12131     * @return A bitmap representing this view or null if cache is disabled.
12132     *
12133     * @see #setDrawingCacheEnabled(boolean)
12134     * @see #isDrawingCacheEnabled()
12135     * @see #buildDrawingCache(boolean)
12136     * @see #destroyDrawingCache()
12137     */
12138    public Bitmap getDrawingCache(boolean autoScale) {
12139        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12140            return null;
12141        }
12142        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12143            buildDrawingCache(autoScale);
12144        }
12145        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12146    }
12147
12148    /**
12149     * <p>Frees the resources used by the drawing cache. If you call
12150     * {@link #buildDrawingCache()} manually without calling
12151     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12152     * should cleanup the cache with this method afterwards.</p>
12153     *
12154     * @see #setDrawingCacheEnabled(boolean)
12155     * @see #buildDrawingCache()
12156     * @see #getDrawingCache()
12157     */
12158    public void destroyDrawingCache() {
12159        if (mDrawingCache != null) {
12160            mDrawingCache.recycle();
12161            mDrawingCache = null;
12162        }
12163        if (mUnscaledDrawingCache != null) {
12164            mUnscaledDrawingCache.recycle();
12165            mUnscaledDrawingCache = null;
12166        }
12167    }
12168
12169    /**
12170     * Setting a solid background color for the drawing cache's bitmaps will improve
12171     * performance and memory usage. Note, though that this should only be used if this
12172     * view will always be drawn on top of a solid color.
12173     *
12174     * @param color The background color to use for the drawing cache's bitmap
12175     *
12176     * @see #setDrawingCacheEnabled(boolean)
12177     * @see #buildDrawingCache()
12178     * @see #getDrawingCache()
12179     */
12180    public void setDrawingCacheBackgroundColor(int color) {
12181        if (color != mDrawingCacheBackgroundColor) {
12182            mDrawingCacheBackgroundColor = color;
12183            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12184        }
12185    }
12186
12187    /**
12188     * @see #setDrawingCacheBackgroundColor(int)
12189     *
12190     * @return The background color to used for the drawing cache's bitmap
12191     */
12192    public int getDrawingCacheBackgroundColor() {
12193        return mDrawingCacheBackgroundColor;
12194    }
12195
12196    /**
12197     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12198     *
12199     * @see #buildDrawingCache(boolean)
12200     */
12201    public void buildDrawingCache() {
12202        buildDrawingCache(false);
12203    }
12204
12205    /**
12206     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12207     *
12208     * <p>If you call {@link #buildDrawingCache()} manually without calling
12209     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12210     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12211     *
12212     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12213     * this method will create a bitmap of the same size as this view. Because this bitmap
12214     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12215     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12216     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12217     * size than the view. This implies that your application must be able to handle this
12218     * size.</p>
12219     *
12220     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12221     * you do not need the drawing cache bitmap, calling this method will increase memory
12222     * usage and cause the view to be rendered in software once, thus negatively impacting
12223     * performance.</p>
12224     *
12225     * @see #getDrawingCache()
12226     * @see #destroyDrawingCache()
12227     */
12228    public void buildDrawingCache(boolean autoScale) {
12229        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12230                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12231            mCachingFailed = false;
12232
12233            if (ViewDebug.TRACE_HIERARCHY) {
12234                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
12235            }
12236
12237            int width = mRight - mLeft;
12238            int height = mBottom - mTop;
12239
12240            final AttachInfo attachInfo = mAttachInfo;
12241            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12242
12243            if (autoScale && scalingRequired) {
12244                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12245                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12246            }
12247
12248            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12249            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12250            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12251
12252            if (width <= 0 || height <= 0 ||
12253                     // Projected bitmap size in bytes
12254                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12255                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12256                destroyDrawingCache();
12257                mCachingFailed = true;
12258                return;
12259            }
12260
12261            boolean clear = true;
12262            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12263
12264            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12265                Bitmap.Config quality;
12266                if (!opaque) {
12267                    // Never pick ARGB_4444 because it looks awful
12268                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12269                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12270                        case DRAWING_CACHE_QUALITY_AUTO:
12271                            quality = Bitmap.Config.ARGB_8888;
12272                            break;
12273                        case DRAWING_CACHE_QUALITY_LOW:
12274                            quality = Bitmap.Config.ARGB_8888;
12275                            break;
12276                        case DRAWING_CACHE_QUALITY_HIGH:
12277                            quality = Bitmap.Config.ARGB_8888;
12278                            break;
12279                        default:
12280                            quality = Bitmap.Config.ARGB_8888;
12281                            break;
12282                    }
12283                } else {
12284                    // Optimization for translucent windows
12285                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12286                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12287                }
12288
12289                // Try to cleanup memory
12290                if (bitmap != null) bitmap.recycle();
12291
12292                try {
12293                    bitmap = Bitmap.createBitmap(width, height, quality);
12294                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12295                    if (autoScale) {
12296                        mDrawingCache = bitmap;
12297                    } else {
12298                        mUnscaledDrawingCache = bitmap;
12299                    }
12300                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12301                } catch (OutOfMemoryError e) {
12302                    // If there is not enough memory to create the bitmap cache, just
12303                    // ignore the issue as bitmap caches are not required to draw the
12304                    // view hierarchy
12305                    if (autoScale) {
12306                        mDrawingCache = null;
12307                    } else {
12308                        mUnscaledDrawingCache = null;
12309                    }
12310                    mCachingFailed = true;
12311                    return;
12312                }
12313
12314                clear = drawingCacheBackgroundColor != 0;
12315            }
12316
12317            Canvas canvas;
12318            if (attachInfo != null) {
12319                canvas = attachInfo.mCanvas;
12320                if (canvas == null) {
12321                    canvas = new Canvas();
12322                }
12323                canvas.setBitmap(bitmap);
12324                // Temporarily clobber the cached Canvas in case one of our children
12325                // is also using a drawing cache. Without this, the children would
12326                // steal the canvas by attaching their own bitmap to it and bad, bad
12327                // thing would happen (invisible views, corrupted drawings, etc.)
12328                attachInfo.mCanvas = null;
12329            } else {
12330                // This case should hopefully never or seldom happen
12331                canvas = new Canvas(bitmap);
12332            }
12333
12334            if (clear) {
12335                bitmap.eraseColor(drawingCacheBackgroundColor);
12336            }
12337
12338            computeScroll();
12339            final int restoreCount = canvas.save();
12340
12341            if (autoScale && scalingRequired) {
12342                final float scale = attachInfo.mApplicationScale;
12343                canvas.scale(scale, scale);
12344            }
12345
12346            canvas.translate(-mScrollX, -mScrollY);
12347
12348            mPrivateFlags |= DRAWN;
12349            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12350                    mLayerType != LAYER_TYPE_NONE) {
12351                mPrivateFlags |= DRAWING_CACHE_VALID;
12352            }
12353
12354            // Fast path for layouts with no backgrounds
12355            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12356                if (ViewDebug.TRACE_HIERARCHY) {
12357                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12358                }
12359                mPrivateFlags &= ~DIRTY_MASK;
12360                dispatchDraw(canvas);
12361            } else {
12362                draw(canvas);
12363            }
12364
12365            canvas.restoreToCount(restoreCount);
12366            canvas.setBitmap(null);
12367
12368            if (attachInfo != null) {
12369                // Restore the cached Canvas for our siblings
12370                attachInfo.mCanvas = canvas;
12371            }
12372        }
12373    }
12374
12375    /**
12376     * Create a snapshot of the view into a bitmap.  We should probably make
12377     * some form of this public, but should think about the API.
12378     */
12379    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12380        int width = mRight - mLeft;
12381        int height = mBottom - mTop;
12382
12383        final AttachInfo attachInfo = mAttachInfo;
12384        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12385        width = (int) ((width * scale) + 0.5f);
12386        height = (int) ((height * scale) + 0.5f);
12387
12388        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12389        if (bitmap == null) {
12390            throw new OutOfMemoryError();
12391        }
12392
12393        Resources resources = getResources();
12394        if (resources != null) {
12395            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12396        }
12397
12398        Canvas canvas;
12399        if (attachInfo != null) {
12400            canvas = attachInfo.mCanvas;
12401            if (canvas == null) {
12402                canvas = new Canvas();
12403            }
12404            canvas.setBitmap(bitmap);
12405            // Temporarily clobber the cached Canvas in case one of our children
12406            // is also using a drawing cache. Without this, the children would
12407            // steal the canvas by attaching their own bitmap to it and bad, bad
12408            // things would happen (invisible views, corrupted drawings, etc.)
12409            attachInfo.mCanvas = null;
12410        } else {
12411            // This case should hopefully never or seldom happen
12412            canvas = new Canvas(bitmap);
12413        }
12414
12415        if ((backgroundColor & 0xff000000) != 0) {
12416            bitmap.eraseColor(backgroundColor);
12417        }
12418
12419        computeScroll();
12420        final int restoreCount = canvas.save();
12421        canvas.scale(scale, scale);
12422        canvas.translate(-mScrollX, -mScrollY);
12423
12424        // Temporarily remove the dirty mask
12425        int flags = mPrivateFlags;
12426        mPrivateFlags &= ~DIRTY_MASK;
12427
12428        // Fast path for layouts with no backgrounds
12429        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12430            dispatchDraw(canvas);
12431        } else {
12432            draw(canvas);
12433        }
12434
12435        mPrivateFlags = flags;
12436
12437        canvas.restoreToCount(restoreCount);
12438        canvas.setBitmap(null);
12439
12440        if (attachInfo != null) {
12441            // Restore the cached Canvas for our siblings
12442            attachInfo.mCanvas = canvas;
12443        }
12444
12445        return bitmap;
12446    }
12447
12448    /**
12449     * Indicates whether this View is currently in edit mode. A View is usually
12450     * in edit mode when displayed within a developer tool. For instance, if
12451     * this View is being drawn by a visual user interface builder, this method
12452     * should return true.
12453     *
12454     * Subclasses should check the return value of this method to provide
12455     * different behaviors if their normal behavior might interfere with the
12456     * host environment. For instance: the class spawns a thread in its
12457     * constructor, the drawing code relies on device-specific features, etc.
12458     *
12459     * This method is usually checked in the drawing code of custom widgets.
12460     *
12461     * @return True if this View is in edit mode, false otherwise.
12462     */
12463    public boolean isInEditMode() {
12464        return false;
12465    }
12466
12467    /**
12468     * If the View draws content inside its padding and enables fading edges,
12469     * it needs to support padding offsets. Padding offsets are added to the
12470     * fading edges to extend the length of the fade so that it covers pixels
12471     * drawn inside the padding.
12472     *
12473     * Subclasses of this class should override this method if they need
12474     * to draw content inside the padding.
12475     *
12476     * @return True if padding offset must be applied, false otherwise.
12477     *
12478     * @see #getLeftPaddingOffset()
12479     * @see #getRightPaddingOffset()
12480     * @see #getTopPaddingOffset()
12481     * @see #getBottomPaddingOffset()
12482     *
12483     * @since CURRENT
12484     */
12485    protected boolean isPaddingOffsetRequired() {
12486        return false;
12487    }
12488
12489    /**
12490     * Amount by which to extend the left fading region. Called only when
12491     * {@link #isPaddingOffsetRequired()} returns true.
12492     *
12493     * @return The left padding offset in pixels.
12494     *
12495     * @see #isPaddingOffsetRequired()
12496     *
12497     * @since CURRENT
12498     */
12499    protected int getLeftPaddingOffset() {
12500        return 0;
12501    }
12502
12503    /**
12504     * Amount by which to extend the right fading region. Called only when
12505     * {@link #isPaddingOffsetRequired()} returns true.
12506     *
12507     * @return The right padding offset in pixels.
12508     *
12509     * @see #isPaddingOffsetRequired()
12510     *
12511     * @since CURRENT
12512     */
12513    protected int getRightPaddingOffset() {
12514        return 0;
12515    }
12516
12517    /**
12518     * Amount by which to extend the top fading region. Called only when
12519     * {@link #isPaddingOffsetRequired()} returns true.
12520     *
12521     * @return The top padding offset in pixels.
12522     *
12523     * @see #isPaddingOffsetRequired()
12524     *
12525     * @since CURRENT
12526     */
12527    protected int getTopPaddingOffset() {
12528        return 0;
12529    }
12530
12531    /**
12532     * Amount by which to extend the bottom fading region. Called only when
12533     * {@link #isPaddingOffsetRequired()} returns true.
12534     *
12535     * @return The bottom padding offset in pixels.
12536     *
12537     * @see #isPaddingOffsetRequired()
12538     *
12539     * @since CURRENT
12540     */
12541    protected int getBottomPaddingOffset() {
12542        return 0;
12543    }
12544
12545    /**
12546     * @hide
12547     * @param offsetRequired
12548     */
12549    protected int getFadeTop(boolean offsetRequired) {
12550        int top = mPaddingTop;
12551        if (offsetRequired) top += getTopPaddingOffset();
12552        return top;
12553    }
12554
12555    /**
12556     * @hide
12557     * @param offsetRequired
12558     */
12559    protected int getFadeHeight(boolean offsetRequired) {
12560        int padding = mPaddingTop;
12561        if (offsetRequired) padding += getTopPaddingOffset();
12562        return mBottom - mTop - mPaddingBottom - padding;
12563    }
12564
12565    /**
12566     * <p>Indicates whether this view is attached to a hardware accelerated
12567     * window or not.</p>
12568     *
12569     * <p>Even if this method returns true, it does not mean that every call
12570     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12571     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12572     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12573     * window is hardware accelerated,
12574     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12575     * return false, and this method will return true.</p>
12576     *
12577     * @return True if the view is attached to a window and the window is
12578     *         hardware accelerated; false in any other case.
12579     */
12580    public boolean isHardwareAccelerated() {
12581        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12582    }
12583
12584    /**
12585     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12586     * case of an active Animation being run on the view.
12587     */
12588    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12589            Animation a, boolean scalingRequired) {
12590        Transformation invalidationTransform;
12591        final int flags = parent.mGroupFlags;
12592        final boolean initialized = a.isInitialized();
12593        if (!initialized) {
12594            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12595            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12596            onAnimationStart();
12597        }
12598
12599        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12600        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12601            if (parent.mInvalidationTransformation == null) {
12602                parent.mInvalidationTransformation = new Transformation();
12603            }
12604            invalidationTransform = parent.mInvalidationTransformation;
12605            a.getTransformation(drawingTime, invalidationTransform, 1f);
12606        } else {
12607            invalidationTransform = parent.mChildTransformation;
12608        }
12609        if (more) {
12610            if (!a.willChangeBounds()) {
12611                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12612                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12613                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12614                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12615                    // The child need to draw an animation, potentially offscreen, so
12616                    // make sure we do not cancel invalidate requests
12617                    parent.mPrivateFlags |= DRAW_ANIMATION;
12618                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12619                }
12620            } else {
12621                if (parent.mInvalidateRegion == null) {
12622                    parent.mInvalidateRegion = new RectF();
12623                }
12624                final RectF region = parent.mInvalidateRegion;
12625                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12626                        invalidationTransform);
12627
12628                // The child need to draw an animation, potentially offscreen, so
12629                // make sure we do not cancel invalidate requests
12630                parent.mPrivateFlags |= DRAW_ANIMATION;
12631
12632                final int left = mLeft + (int) region.left;
12633                final int top = mTop + (int) region.top;
12634                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12635                        top + (int) (region.height() + .5f));
12636            }
12637        }
12638        return more;
12639    }
12640
12641    /**
12642     * This method is called by getDisplayList() when a display list is created or re-rendered.
12643     * It sets or resets the current value of all properties on that display list (resetting is
12644     * necessary when a display list is being re-created, because we need to make sure that
12645     * previously-set transform values
12646     */
12647    void setDisplayListProperties(DisplayList displayList) {
12648        if (displayList != null) {
12649            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12650            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12651            if (mParent instanceof ViewGroup) {
12652                displayList.setClipChildren(
12653                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12654            }
12655            float alpha = 1;
12656            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12657                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12658                ViewGroup parentVG = (ViewGroup) mParent;
12659                final boolean hasTransform =
12660                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12661                if (hasTransform) {
12662                    Transformation transform = parentVG.mChildTransformation;
12663                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12664                    if (transformType != Transformation.TYPE_IDENTITY) {
12665                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12666                            alpha = transform.getAlpha();
12667                        }
12668                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12669                            displayList.setStaticMatrix(transform.getMatrix());
12670                        }
12671                    }
12672                }
12673            }
12674            if (mTransformationInfo != null) {
12675                alpha *= mTransformationInfo.mAlpha;
12676                if (alpha < 1) {
12677                    final int multipliedAlpha = (int) (255 * alpha);
12678                    if (onSetAlpha(multipliedAlpha)) {
12679                        alpha = 1;
12680                    }
12681                }
12682                displayList.setTransformationInfo(alpha,
12683                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12684                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12685                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12686                        mTransformationInfo.mScaleY);
12687                if (mTransformationInfo.mCamera == null) {
12688                    mTransformationInfo.mCamera = new Camera();
12689                    mTransformationInfo.matrix3D = new Matrix();
12690                }
12691                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12692                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12693                    displayList.setPivotX(getPivotX());
12694                    displayList.setPivotY(getPivotY());
12695                }
12696            } else if (alpha < 1) {
12697                displayList.setAlpha(alpha);
12698            }
12699        }
12700    }
12701
12702    /**
12703     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12704     * This draw() method is an implementation detail and is not intended to be overridden or
12705     * to be called from anywhere else other than ViewGroup.drawChild().
12706     */
12707    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12708        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12709        boolean more = false;
12710        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12711        final int flags = parent.mGroupFlags;
12712
12713        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12714            parent.mChildTransformation.clear();
12715            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12716        }
12717
12718        Transformation transformToApply = null;
12719        boolean concatMatrix = false;
12720
12721        boolean scalingRequired = false;
12722        boolean caching;
12723        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12724
12725        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12726        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12727                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12728            caching = true;
12729            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12730            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12731        } else {
12732            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12733        }
12734
12735        final Animation a = getAnimation();
12736        if (a != null) {
12737            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12738            concatMatrix = a.willChangeTransformationMatrix();
12739            transformToApply = parent.mChildTransformation;
12740        } else if (!useDisplayListProperties &&
12741                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12742            final boolean hasTransform =
12743                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12744            if (hasTransform) {
12745                final int transformType = parent.mChildTransformation.getTransformationType();
12746                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12747                        parent.mChildTransformation : null;
12748                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12749            }
12750        }
12751
12752        concatMatrix |= !childHasIdentityMatrix;
12753
12754        // Sets the flag as early as possible to allow draw() implementations
12755        // to call invalidate() successfully when doing animations
12756        mPrivateFlags |= DRAWN;
12757
12758        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12759                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12760            return more;
12761        }
12762
12763        if (hardwareAccelerated) {
12764            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12765            // retain the flag's value temporarily in the mRecreateDisplayList flag
12766            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12767            mPrivateFlags &= ~INVALIDATED;
12768        }
12769
12770        computeScroll();
12771
12772        final int sx = mScrollX;
12773        final int sy = mScrollY;
12774
12775        DisplayList displayList = null;
12776        Bitmap cache = null;
12777        boolean hasDisplayList = false;
12778        if (caching) {
12779            if (!hardwareAccelerated) {
12780                if (layerType != LAYER_TYPE_NONE) {
12781                    layerType = LAYER_TYPE_SOFTWARE;
12782                    buildDrawingCache(true);
12783                }
12784                cache = getDrawingCache(true);
12785            } else {
12786                switch (layerType) {
12787                    case LAYER_TYPE_SOFTWARE:
12788                        if (useDisplayListProperties) {
12789                            hasDisplayList = canHaveDisplayList();
12790                        } else {
12791                            buildDrawingCache(true);
12792                            cache = getDrawingCache(true);
12793                        }
12794                        break;
12795                    case LAYER_TYPE_HARDWARE:
12796                        if (useDisplayListProperties) {
12797                            hasDisplayList = canHaveDisplayList();
12798                        }
12799                        break;
12800                    case LAYER_TYPE_NONE:
12801                        // Delay getting the display list until animation-driven alpha values are
12802                        // set up and possibly passed on to the view
12803                        hasDisplayList = canHaveDisplayList();
12804                        break;
12805                }
12806            }
12807        }
12808        useDisplayListProperties &= hasDisplayList;
12809        if (useDisplayListProperties) {
12810            displayList = getDisplayList();
12811            if (!displayList.isValid()) {
12812                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12813                // to getDisplayList(), the display list will be marked invalid and we should not
12814                // try to use it again.
12815                displayList = null;
12816                hasDisplayList = false;
12817                useDisplayListProperties = false;
12818            }
12819        }
12820
12821        final boolean hasNoCache = cache == null || hasDisplayList;
12822        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12823                layerType != LAYER_TYPE_HARDWARE;
12824
12825        int restoreTo = -1;
12826        if (!useDisplayListProperties || transformToApply != null) {
12827            restoreTo = canvas.save();
12828        }
12829        if (offsetForScroll) {
12830            canvas.translate(mLeft - sx, mTop - sy);
12831        } else {
12832            if (!useDisplayListProperties) {
12833                canvas.translate(mLeft, mTop);
12834            }
12835            if (scalingRequired) {
12836                if (useDisplayListProperties) {
12837                    // TODO: Might not need this if we put everything inside the DL
12838                    restoreTo = canvas.save();
12839                }
12840                // mAttachInfo cannot be null, otherwise scalingRequired == false
12841                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12842                canvas.scale(scale, scale);
12843            }
12844        }
12845
12846        float alpha = useDisplayListProperties ? 1 : getAlpha();
12847        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12848            if (transformToApply != null || !childHasIdentityMatrix) {
12849                int transX = 0;
12850                int transY = 0;
12851
12852                if (offsetForScroll) {
12853                    transX = -sx;
12854                    transY = -sy;
12855                }
12856
12857                if (transformToApply != null) {
12858                    if (concatMatrix) {
12859                        if (useDisplayListProperties) {
12860                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12861                        } else {
12862                            // Undo the scroll translation, apply the transformation matrix,
12863                            // then redo the scroll translate to get the correct result.
12864                            canvas.translate(-transX, -transY);
12865                            canvas.concat(transformToApply.getMatrix());
12866                            canvas.translate(transX, transY);
12867                        }
12868                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12869                    }
12870
12871                    float transformAlpha = transformToApply.getAlpha();
12872                    if (transformAlpha < 1) {
12873                        alpha *= transformToApply.getAlpha();
12874                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12875                    }
12876                }
12877
12878                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12879                    canvas.translate(-transX, -transY);
12880                    canvas.concat(getMatrix());
12881                    canvas.translate(transX, transY);
12882                }
12883            }
12884
12885            if (alpha < 1) {
12886                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12887                if (hasNoCache) {
12888                    final int multipliedAlpha = (int) (255 * alpha);
12889                    if (!onSetAlpha(multipliedAlpha)) {
12890                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12891                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12892                                layerType != LAYER_TYPE_NONE) {
12893                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12894                        }
12895                        if (useDisplayListProperties) {
12896                            displayList.setAlpha(alpha * getAlpha());
12897                        } else  if (layerType == LAYER_TYPE_NONE) {
12898                            final int scrollX = hasDisplayList ? 0 : sx;
12899                            final int scrollY = hasDisplayList ? 0 : sy;
12900                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12901                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12902                        }
12903                    } else {
12904                        // Alpha is handled by the child directly, clobber the layer's alpha
12905                        mPrivateFlags |= ALPHA_SET;
12906                    }
12907                }
12908            }
12909        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12910            onSetAlpha(255);
12911            mPrivateFlags &= ~ALPHA_SET;
12912        }
12913
12914        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12915                !useDisplayListProperties) {
12916            if (offsetForScroll) {
12917                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12918            } else {
12919                if (!scalingRequired || cache == null) {
12920                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12921                } else {
12922                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12923                }
12924            }
12925        }
12926
12927        if (!useDisplayListProperties && hasDisplayList) {
12928            displayList = getDisplayList();
12929            if (!displayList.isValid()) {
12930                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12931                // to getDisplayList(), the display list will be marked invalid and we should not
12932                // try to use it again.
12933                displayList = null;
12934                hasDisplayList = false;
12935            }
12936        }
12937
12938        if (hasNoCache) {
12939            boolean layerRendered = false;
12940            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12941                final HardwareLayer layer = getHardwareLayer();
12942                if (layer != null && layer.isValid()) {
12943                    mLayerPaint.setAlpha((int) (alpha * 255));
12944                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12945                    layerRendered = true;
12946                } else {
12947                    final int scrollX = hasDisplayList ? 0 : sx;
12948                    final int scrollY = hasDisplayList ? 0 : sy;
12949                    canvas.saveLayer(scrollX, scrollY,
12950                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12951                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12952                }
12953            }
12954
12955            if (!layerRendered) {
12956                if (!hasDisplayList) {
12957                    // Fast path for layouts with no backgrounds
12958                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12959                        if (ViewDebug.TRACE_HIERARCHY) {
12960                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12961                        }
12962                        mPrivateFlags &= ~DIRTY_MASK;
12963                        dispatchDraw(canvas);
12964                    } else {
12965                        draw(canvas);
12966                    }
12967                } else {
12968                    mPrivateFlags &= ~DIRTY_MASK;
12969                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
12970                }
12971            }
12972        } else if (cache != null) {
12973            mPrivateFlags &= ~DIRTY_MASK;
12974            Paint cachePaint;
12975
12976            if (layerType == LAYER_TYPE_NONE) {
12977                cachePaint = parent.mCachePaint;
12978                if (cachePaint == null) {
12979                    cachePaint = new Paint();
12980                    cachePaint.setDither(false);
12981                    parent.mCachePaint = cachePaint;
12982                }
12983                if (alpha < 1) {
12984                    cachePaint.setAlpha((int) (alpha * 255));
12985                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12986                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12987                    cachePaint.setAlpha(255);
12988                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12989                }
12990            } else {
12991                cachePaint = mLayerPaint;
12992                cachePaint.setAlpha((int) (alpha * 255));
12993            }
12994            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
12995        }
12996
12997        if (restoreTo >= 0) {
12998            canvas.restoreToCount(restoreTo);
12999        }
13000
13001        if (a != null && !more) {
13002            if (!hardwareAccelerated && !a.getFillAfter()) {
13003                onSetAlpha(255);
13004            }
13005            parent.finishAnimatingView(this, a);
13006        }
13007
13008        if (more && hardwareAccelerated) {
13009            // invalidation is the trigger to recreate display lists, so if we're using
13010            // display lists to render, force an invalidate to allow the animation to
13011            // continue drawing another frame
13012            parent.invalidate(true);
13013            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13014                // alpha animations should cause the child to recreate its display list
13015                invalidate(true);
13016            }
13017        }
13018
13019        mRecreateDisplayList = false;
13020
13021        return more;
13022    }
13023
13024    /**
13025     * Manually render this view (and all of its children) to the given Canvas.
13026     * The view must have already done a full layout before this function is
13027     * called.  When implementing a view, implement
13028     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13029     * If you do need to override this method, call the superclass version.
13030     *
13031     * @param canvas The Canvas to which the View is rendered.
13032     */
13033    public void draw(Canvas canvas) {
13034        if (ViewDebug.TRACE_HIERARCHY) {
13035            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
13036        }
13037
13038        final int privateFlags = mPrivateFlags;
13039        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13040                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13041        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13042
13043        /*
13044         * Draw traversal performs several drawing steps which must be executed
13045         * in the appropriate order:
13046         *
13047         *      1. Draw the background
13048         *      2. If necessary, save the canvas' layers to prepare for fading
13049         *      3. Draw view's content
13050         *      4. Draw children
13051         *      5. If necessary, draw the fading edges and restore layers
13052         *      6. Draw decorations (scrollbars for instance)
13053         */
13054
13055        // Step 1, draw the background, if needed
13056        int saveCount;
13057
13058        if (!dirtyOpaque) {
13059            final Drawable background = mBackground;
13060            if (background != null) {
13061                final int scrollX = mScrollX;
13062                final int scrollY = mScrollY;
13063
13064                if (mBackgroundSizeChanged) {
13065                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13066                    mBackgroundSizeChanged = false;
13067                }
13068
13069                if ((scrollX | scrollY) == 0) {
13070                    background.draw(canvas);
13071                } else {
13072                    canvas.translate(scrollX, scrollY);
13073                    background.draw(canvas);
13074                    canvas.translate(-scrollX, -scrollY);
13075                }
13076            }
13077        }
13078
13079        // skip step 2 & 5 if possible (common case)
13080        final int viewFlags = mViewFlags;
13081        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13082        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13083        if (!verticalEdges && !horizontalEdges) {
13084            // Step 3, draw the content
13085            if (!dirtyOpaque) onDraw(canvas);
13086
13087            // Step 4, draw the children
13088            dispatchDraw(canvas);
13089
13090            // Step 6, draw decorations (scrollbars)
13091            onDrawScrollBars(canvas);
13092
13093            // we're done...
13094            return;
13095        }
13096
13097        /*
13098         * Here we do the full fledged routine...
13099         * (this is an uncommon case where speed matters less,
13100         * this is why we repeat some of the tests that have been
13101         * done above)
13102         */
13103
13104        boolean drawTop = false;
13105        boolean drawBottom = false;
13106        boolean drawLeft = false;
13107        boolean drawRight = false;
13108
13109        float topFadeStrength = 0.0f;
13110        float bottomFadeStrength = 0.0f;
13111        float leftFadeStrength = 0.0f;
13112        float rightFadeStrength = 0.0f;
13113
13114        // Step 2, save the canvas' layers
13115        int paddingLeft = mPaddingLeft;
13116
13117        final boolean offsetRequired = isPaddingOffsetRequired();
13118        if (offsetRequired) {
13119            paddingLeft += getLeftPaddingOffset();
13120        }
13121
13122        int left = mScrollX + paddingLeft;
13123        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13124        int top = mScrollY + getFadeTop(offsetRequired);
13125        int bottom = top + getFadeHeight(offsetRequired);
13126
13127        if (offsetRequired) {
13128            right += getRightPaddingOffset();
13129            bottom += getBottomPaddingOffset();
13130        }
13131
13132        final ScrollabilityCache scrollabilityCache = mScrollCache;
13133        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13134        int length = (int) fadeHeight;
13135
13136        // clip the fade length if top and bottom fades overlap
13137        // overlapping fades produce odd-looking artifacts
13138        if (verticalEdges && (top + length > bottom - length)) {
13139            length = (bottom - top) / 2;
13140        }
13141
13142        // also clip horizontal fades if necessary
13143        if (horizontalEdges && (left + length > right - length)) {
13144            length = (right - left) / 2;
13145        }
13146
13147        if (verticalEdges) {
13148            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13149            drawTop = topFadeStrength * fadeHeight > 1.0f;
13150            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13151            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13152        }
13153
13154        if (horizontalEdges) {
13155            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13156            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13157            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13158            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13159        }
13160
13161        saveCount = canvas.getSaveCount();
13162
13163        int solidColor = getSolidColor();
13164        if (solidColor == 0) {
13165            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13166
13167            if (drawTop) {
13168                canvas.saveLayer(left, top, right, top + length, null, flags);
13169            }
13170
13171            if (drawBottom) {
13172                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13173            }
13174
13175            if (drawLeft) {
13176                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13177            }
13178
13179            if (drawRight) {
13180                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13181            }
13182        } else {
13183            scrollabilityCache.setFadeColor(solidColor);
13184        }
13185
13186        // Step 3, draw the content
13187        if (!dirtyOpaque) onDraw(canvas);
13188
13189        // Step 4, draw the children
13190        dispatchDraw(canvas);
13191
13192        // Step 5, draw the fade effect and restore layers
13193        final Paint p = scrollabilityCache.paint;
13194        final Matrix matrix = scrollabilityCache.matrix;
13195        final Shader fade = scrollabilityCache.shader;
13196
13197        if (drawTop) {
13198            matrix.setScale(1, fadeHeight * topFadeStrength);
13199            matrix.postTranslate(left, top);
13200            fade.setLocalMatrix(matrix);
13201            canvas.drawRect(left, top, right, top + length, p);
13202        }
13203
13204        if (drawBottom) {
13205            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13206            matrix.postRotate(180);
13207            matrix.postTranslate(left, bottom);
13208            fade.setLocalMatrix(matrix);
13209            canvas.drawRect(left, bottom - length, right, bottom, p);
13210        }
13211
13212        if (drawLeft) {
13213            matrix.setScale(1, fadeHeight * leftFadeStrength);
13214            matrix.postRotate(-90);
13215            matrix.postTranslate(left, top);
13216            fade.setLocalMatrix(matrix);
13217            canvas.drawRect(left, top, left + length, bottom, p);
13218        }
13219
13220        if (drawRight) {
13221            matrix.setScale(1, fadeHeight * rightFadeStrength);
13222            matrix.postRotate(90);
13223            matrix.postTranslate(right, top);
13224            fade.setLocalMatrix(matrix);
13225            canvas.drawRect(right - length, top, right, bottom, p);
13226        }
13227
13228        canvas.restoreToCount(saveCount);
13229
13230        // Step 6, draw decorations (scrollbars)
13231        onDrawScrollBars(canvas);
13232    }
13233
13234    /**
13235     * Override this if your view is known to always be drawn on top of a solid color background,
13236     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13237     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13238     * should be set to 0xFF.
13239     *
13240     * @see #setVerticalFadingEdgeEnabled(boolean)
13241     * @see #setHorizontalFadingEdgeEnabled(boolean)
13242     *
13243     * @return The known solid color background for this view, or 0 if the color may vary
13244     */
13245    @ViewDebug.ExportedProperty(category = "drawing")
13246    public int getSolidColor() {
13247        return 0;
13248    }
13249
13250    /**
13251     * Build a human readable string representation of the specified view flags.
13252     *
13253     * @param flags the view flags to convert to a string
13254     * @return a String representing the supplied flags
13255     */
13256    private static String printFlags(int flags) {
13257        String output = "";
13258        int numFlags = 0;
13259        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13260            output += "TAKES_FOCUS";
13261            numFlags++;
13262        }
13263
13264        switch (flags & VISIBILITY_MASK) {
13265        case INVISIBLE:
13266            if (numFlags > 0) {
13267                output += " ";
13268            }
13269            output += "INVISIBLE";
13270            // USELESS HERE numFlags++;
13271            break;
13272        case GONE:
13273            if (numFlags > 0) {
13274                output += " ";
13275            }
13276            output += "GONE";
13277            // USELESS HERE numFlags++;
13278            break;
13279        default:
13280            break;
13281        }
13282        return output;
13283    }
13284
13285    /**
13286     * Build a human readable string representation of the specified private
13287     * view flags.
13288     *
13289     * @param privateFlags the private view flags to convert to a string
13290     * @return a String representing the supplied flags
13291     */
13292    private static String printPrivateFlags(int privateFlags) {
13293        String output = "";
13294        int numFlags = 0;
13295
13296        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13297            output += "WANTS_FOCUS";
13298            numFlags++;
13299        }
13300
13301        if ((privateFlags & FOCUSED) == FOCUSED) {
13302            if (numFlags > 0) {
13303                output += " ";
13304            }
13305            output += "FOCUSED";
13306            numFlags++;
13307        }
13308
13309        if ((privateFlags & SELECTED) == SELECTED) {
13310            if (numFlags > 0) {
13311                output += " ";
13312            }
13313            output += "SELECTED";
13314            numFlags++;
13315        }
13316
13317        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13318            if (numFlags > 0) {
13319                output += " ";
13320            }
13321            output += "IS_ROOT_NAMESPACE";
13322            numFlags++;
13323        }
13324
13325        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13326            if (numFlags > 0) {
13327                output += " ";
13328            }
13329            output += "HAS_BOUNDS";
13330            numFlags++;
13331        }
13332
13333        if ((privateFlags & DRAWN) == DRAWN) {
13334            if (numFlags > 0) {
13335                output += " ";
13336            }
13337            output += "DRAWN";
13338            // USELESS HERE numFlags++;
13339        }
13340        return output;
13341    }
13342
13343    /**
13344     * <p>Indicates whether or not this view's layout will be requested during
13345     * the next hierarchy layout pass.</p>
13346     *
13347     * @return true if the layout will be forced during next layout pass
13348     */
13349    public boolean isLayoutRequested() {
13350        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13351    }
13352
13353    /**
13354     * Assign a size and position to a view and all of its
13355     * descendants
13356     *
13357     * <p>This is the second phase of the layout mechanism.
13358     * (The first is measuring). In this phase, each parent calls
13359     * layout on all of its children to position them.
13360     * This is typically done using the child measurements
13361     * that were stored in the measure pass().</p>
13362     *
13363     * <p>Derived classes should not override this method.
13364     * Derived classes with children should override
13365     * onLayout. In that method, they should
13366     * call layout on each of their children.</p>
13367     *
13368     * @param l Left position, relative to parent
13369     * @param t Top position, relative to parent
13370     * @param r Right position, relative to parent
13371     * @param b Bottom position, relative to parent
13372     */
13373    @SuppressWarnings({"unchecked"})
13374    public void layout(int l, int t, int r, int b) {
13375        int oldL = mLeft;
13376        int oldT = mTop;
13377        int oldB = mBottom;
13378        int oldR = mRight;
13379        boolean changed = setFrame(l, t, r, b);
13380        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13381            if (ViewDebug.TRACE_HIERARCHY) {
13382                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13383            }
13384
13385            onLayout(changed, l, t, r, b);
13386            mPrivateFlags &= ~LAYOUT_REQUIRED;
13387
13388            ListenerInfo li = mListenerInfo;
13389            if (li != null && li.mOnLayoutChangeListeners != null) {
13390                ArrayList<OnLayoutChangeListener> listenersCopy =
13391                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13392                int numListeners = listenersCopy.size();
13393                for (int i = 0; i < numListeners; ++i) {
13394                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13395                }
13396            }
13397        }
13398        mPrivateFlags &= ~FORCE_LAYOUT;
13399    }
13400
13401    /**
13402     * Called from layout when this view should
13403     * assign a size and position to each of its children.
13404     *
13405     * Derived classes with children should override
13406     * this method and call layout on each of
13407     * their children.
13408     * @param changed This is a new size or position for this view
13409     * @param left Left position, relative to parent
13410     * @param top Top position, relative to parent
13411     * @param right Right position, relative to parent
13412     * @param bottom Bottom position, relative to parent
13413     */
13414    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13415    }
13416
13417    /**
13418     * Assign a size and position to this view.
13419     *
13420     * This is called from layout.
13421     *
13422     * @param left Left position, relative to parent
13423     * @param top Top position, relative to parent
13424     * @param right Right position, relative to parent
13425     * @param bottom Bottom position, relative to parent
13426     * @return true if the new size and position are different than the
13427     *         previous ones
13428     * {@hide}
13429     */
13430    protected boolean setFrame(int left, int top, int right, int bottom) {
13431        boolean changed = false;
13432
13433        if (DBG) {
13434            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13435                    + right + "," + bottom + ")");
13436        }
13437
13438        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13439            changed = true;
13440
13441            // Remember our drawn bit
13442            int drawn = mPrivateFlags & DRAWN;
13443
13444            int oldWidth = mRight - mLeft;
13445            int oldHeight = mBottom - mTop;
13446            int newWidth = right - left;
13447            int newHeight = bottom - top;
13448            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13449
13450            // Invalidate our old position
13451            invalidate(sizeChanged);
13452
13453            mLeft = left;
13454            mTop = top;
13455            mRight = right;
13456            mBottom = bottom;
13457            if (mDisplayList != null) {
13458                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13459            }
13460
13461            mPrivateFlags |= HAS_BOUNDS;
13462
13463
13464            if (sizeChanged) {
13465                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13466                    // A change in dimension means an auto-centered pivot point changes, too
13467                    if (mTransformationInfo != null) {
13468                        mTransformationInfo.mMatrixDirty = true;
13469                    }
13470                }
13471                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13472            }
13473
13474            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13475                // If we are visible, force the DRAWN bit to on so that
13476                // this invalidate will go through (at least to our parent).
13477                // This is because someone may have invalidated this view
13478                // before this call to setFrame came in, thereby clearing
13479                // the DRAWN bit.
13480                mPrivateFlags |= DRAWN;
13481                invalidate(sizeChanged);
13482                // parent display list may need to be recreated based on a change in the bounds
13483                // of any child
13484                invalidateParentCaches();
13485            }
13486
13487            // Reset drawn bit to original value (invalidate turns it off)
13488            mPrivateFlags |= drawn;
13489
13490            mBackgroundSizeChanged = true;
13491        }
13492        return changed;
13493    }
13494
13495    /**
13496     * Finalize inflating a view from XML.  This is called as the last phase
13497     * of inflation, after all child views have been added.
13498     *
13499     * <p>Even if the subclass overrides onFinishInflate, they should always be
13500     * sure to call the super method, so that we get called.
13501     */
13502    protected void onFinishInflate() {
13503    }
13504
13505    /**
13506     * Returns the resources associated with this view.
13507     *
13508     * @return Resources object.
13509     */
13510    public Resources getResources() {
13511        return mResources;
13512    }
13513
13514    /**
13515     * Invalidates the specified Drawable.
13516     *
13517     * @param drawable the drawable to invalidate
13518     */
13519    public void invalidateDrawable(Drawable drawable) {
13520        if (verifyDrawable(drawable)) {
13521            final Rect dirty = drawable.getBounds();
13522            final int scrollX = mScrollX;
13523            final int scrollY = mScrollY;
13524
13525            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13526                    dirty.right + scrollX, dirty.bottom + scrollY);
13527        }
13528    }
13529
13530    /**
13531     * Schedules an action on a drawable to occur at a specified time.
13532     *
13533     * @param who the recipient of the action
13534     * @param what the action to run on the drawable
13535     * @param when the time at which the action must occur. Uses the
13536     *        {@link SystemClock#uptimeMillis} timebase.
13537     */
13538    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13539        if (verifyDrawable(who) && what != null) {
13540            final long delay = when - SystemClock.uptimeMillis();
13541            if (mAttachInfo != null) {
13542                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13543                        Choreographer.CALLBACK_ANIMATION, what, who,
13544                        Choreographer.subtractFrameDelay(delay));
13545            } else {
13546                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13547            }
13548        }
13549    }
13550
13551    /**
13552     * Cancels a scheduled action on a drawable.
13553     *
13554     * @param who the recipient of the action
13555     * @param what the action to cancel
13556     */
13557    public void unscheduleDrawable(Drawable who, Runnable what) {
13558        if (verifyDrawable(who) && what != null) {
13559            if (mAttachInfo != null) {
13560                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13561                        Choreographer.CALLBACK_ANIMATION, what, who);
13562            } else {
13563                ViewRootImpl.getRunQueue().removeCallbacks(what);
13564            }
13565        }
13566    }
13567
13568    /**
13569     * Unschedule any events associated with the given Drawable.  This can be
13570     * used when selecting a new Drawable into a view, so that the previous
13571     * one is completely unscheduled.
13572     *
13573     * @param who The Drawable to unschedule.
13574     *
13575     * @see #drawableStateChanged
13576     */
13577    public void unscheduleDrawable(Drawable who) {
13578        if (mAttachInfo != null && who != null) {
13579            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13580                    Choreographer.CALLBACK_ANIMATION, null, who);
13581        }
13582    }
13583
13584    /**
13585    * Return the layout direction of a given Drawable.
13586    *
13587    * @param who the Drawable to query
13588    */
13589    public int getResolvedLayoutDirection(Drawable who) {
13590        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13591    }
13592
13593    /**
13594     * If your view subclass is displaying its own Drawable objects, it should
13595     * override this function and return true for any Drawable it is
13596     * displaying.  This allows animations for those drawables to be
13597     * scheduled.
13598     *
13599     * <p>Be sure to call through to the super class when overriding this
13600     * function.
13601     *
13602     * @param who The Drawable to verify.  Return true if it is one you are
13603     *            displaying, else return the result of calling through to the
13604     *            super class.
13605     *
13606     * @return boolean If true than the Drawable is being displayed in the
13607     *         view; else false and it is not allowed to animate.
13608     *
13609     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13610     * @see #drawableStateChanged()
13611     */
13612    protected boolean verifyDrawable(Drawable who) {
13613        return who == mBackground;
13614    }
13615
13616    /**
13617     * This function is called whenever the state of the view changes in such
13618     * a way that it impacts the state of drawables being shown.
13619     *
13620     * <p>Be sure to call through to the superclass when overriding this
13621     * function.
13622     *
13623     * @see Drawable#setState(int[])
13624     */
13625    protected void drawableStateChanged() {
13626        Drawable d = mBackground;
13627        if (d != null && d.isStateful()) {
13628            d.setState(getDrawableState());
13629        }
13630    }
13631
13632    /**
13633     * Call this to force a view to update its drawable state. This will cause
13634     * drawableStateChanged to be called on this view. Views that are interested
13635     * in the new state should call getDrawableState.
13636     *
13637     * @see #drawableStateChanged
13638     * @see #getDrawableState
13639     */
13640    public void refreshDrawableState() {
13641        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13642        drawableStateChanged();
13643
13644        ViewParent parent = mParent;
13645        if (parent != null) {
13646            parent.childDrawableStateChanged(this);
13647        }
13648    }
13649
13650    /**
13651     * Return an array of resource IDs of the drawable states representing the
13652     * current state of the view.
13653     *
13654     * @return The current drawable state
13655     *
13656     * @see Drawable#setState(int[])
13657     * @see #drawableStateChanged()
13658     * @see #onCreateDrawableState(int)
13659     */
13660    public final int[] getDrawableState() {
13661        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13662            return mDrawableState;
13663        } else {
13664            mDrawableState = onCreateDrawableState(0);
13665            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13666            return mDrawableState;
13667        }
13668    }
13669
13670    /**
13671     * Generate the new {@link android.graphics.drawable.Drawable} state for
13672     * this view. This is called by the view
13673     * system when the cached Drawable state is determined to be invalid.  To
13674     * retrieve the current state, you should use {@link #getDrawableState}.
13675     *
13676     * @param extraSpace if non-zero, this is the number of extra entries you
13677     * would like in the returned array in which you can place your own
13678     * states.
13679     *
13680     * @return Returns an array holding the current {@link Drawable} state of
13681     * the view.
13682     *
13683     * @see #mergeDrawableStates(int[], int[])
13684     */
13685    protected int[] onCreateDrawableState(int extraSpace) {
13686        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13687                mParent instanceof View) {
13688            return ((View) mParent).onCreateDrawableState(extraSpace);
13689        }
13690
13691        int[] drawableState;
13692
13693        int privateFlags = mPrivateFlags;
13694
13695        int viewStateIndex = 0;
13696        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13697        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13698        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13699        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13700        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13701        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13702        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13703                HardwareRenderer.isAvailable()) {
13704            // This is set if HW acceleration is requested, even if the current
13705            // process doesn't allow it.  This is just to allow app preview
13706            // windows to better match their app.
13707            viewStateIndex |= VIEW_STATE_ACCELERATED;
13708        }
13709        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13710
13711        final int privateFlags2 = mPrivateFlags2;
13712        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13713        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13714
13715        drawableState = VIEW_STATE_SETS[viewStateIndex];
13716
13717        //noinspection ConstantIfStatement
13718        if (false) {
13719            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13720            Log.i("View", toString()
13721                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13722                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13723                    + " fo=" + hasFocus()
13724                    + " sl=" + ((privateFlags & SELECTED) != 0)
13725                    + " wf=" + hasWindowFocus()
13726                    + ": " + Arrays.toString(drawableState));
13727        }
13728
13729        if (extraSpace == 0) {
13730            return drawableState;
13731        }
13732
13733        final int[] fullState;
13734        if (drawableState != null) {
13735            fullState = new int[drawableState.length + extraSpace];
13736            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13737        } else {
13738            fullState = new int[extraSpace];
13739        }
13740
13741        return fullState;
13742    }
13743
13744    /**
13745     * Merge your own state values in <var>additionalState</var> into the base
13746     * state values <var>baseState</var> that were returned by
13747     * {@link #onCreateDrawableState(int)}.
13748     *
13749     * @param baseState The base state values returned by
13750     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13751     * own additional state values.
13752     *
13753     * @param additionalState The additional state values you would like
13754     * added to <var>baseState</var>; this array is not modified.
13755     *
13756     * @return As a convenience, the <var>baseState</var> array you originally
13757     * passed into the function is returned.
13758     *
13759     * @see #onCreateDrawableState(int)
13760     */
13761    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13762        final int N = baseState.length;
13763        int i = N - 1;
13764        while (i >= 0 && baseState[i] == 0) {
13765            i--;
13766        }
13767        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13768        return baseState;
13769    }
13770
13771    /**
13772     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13773     * on all Drawable objects associated with this view.
13774     */
13775    public void jumpDrawablesToCurrentState() {
13776        if (mBackground != null) {
13777            mBackground.jumpToCurrentState();
13778        }
13779    }
13780
13781    /**
13782     * Sets the background color for this view.
13783     * @param color the color of the background
13784     */
13785    @RemotableViewMethod
13786    public void setBackgroundColor(int color) {
13787        if (mBackground instanceof ColorDrawable) {
13788            ((ColorDrawable) mBackground).setColor(color);
13789        } else {
13790            setBackground(new ColorDrawable(color));
13791        }
13792    }
13793
13794    /**
13795     * Set the background to a given resource. The resource should refer to
13796     * a Drawable object or 0 to remove the background.
13797     * @param resid The identifier of the resource.
13798     *
13799     * @attr ref android.R.styleable#View_background
13800     */
13801    @RemotableViewMethod
13802    public void setBackgroundResource(int resid) {
13803        if (resid != 0 && resid == mBackgroundResource) {
13804            return;
13805        }
13806
13807        Drawable d= null;
13808        if (resid != 0) {
13809            d = mResources.getDrawable(resid);
13810        }
13811        setBackground(d);
13812
13813        mBackgroundResource = resid;
13814    }
13815
13816    /**
13817     * Set the background to a given Drawable, or remove the background. If the
13818     * background has padding, this View's padding is set to the background's
13819     * padding. However, when a background is removed, this View's padding isn't
13820     * touched. If setting the padding is desired, please use
13821     * {@link #setPadding(int, int, int, int)}.
13822     *
13823     * @param background The Drawable to use as the background, or null to remove the
13824     *        background
13825     */
13826    public void setBackground(Drawable background) {
13827        //noinspection deprecation
13828        setBackgroundDrawable(background);
13829    }
13830
13831    /**
13832     * @deprecated use {@link #setBackground(Drawable)} instead
13833     */
13834    @Deprecated
13835    public void setBackgroundDrawable(Drawable background) {
13836        if (background == mBackground) {
13837            return;
13838        }
13839
13840        boolean requestLayout = false;
13841
13842        mBackgroundResource = 0;
13843
13844        /*
13845         * Regardless of whether we're setting a new background or not, we want
13846         * to clear the previous drawable.
13847         */
13848        if (mBackground != null) {
13849            mBackground.setCallback(null);
13850            unscheduleDrawable(mBackground);
13851        }
13852
13853        if (background != null) {
13854            Rect padding = sThreadLocal.get();
13855            if (padding == null) {
13856                padding = new Rect();
13857                sThreadLocal.set(padding);
13858            }
13859            if (background.getPadding(padding)) {
13860                switch (background.getResolvedLayoutDirectionSelf()) {
13861                    case LAYOUT_DIRECTION_RTL:
13862                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13863                        break;
13864                    case LAYOUT_DIRECTION_LTR:
13865                    default:
13866                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13867                }
13868            }
13869
13870            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13871            // if it has a different minimum size, we should layout again
13872            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13873                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13874                requestLayout = true;
13875            }
13876
13877            background.setCallback(this);
13878            if (background.isStateful()) {
13879                background.setState(getDrawableState());
13880            }
13881            background.setVisible(getVisibility() == VISIBLE, false);
13882            mBackground = background;
13883
13884            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13885                mPrivateFlags &= ~SKIP_DRAW;
13886                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13887                requestLayout = true;
13888            }
13889        } else {
13890            /* Remove the background */
13891            mBackground = null;
13892
13893            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13894                /*
13895                 * This view ONLY drew the background before and we're removing
13896                 * the background, so now it won't draw anything
13897                 * (hence we SKIP_DRAW)
13898                 */
13899                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13900                mPrivateFlags |= SKIP_DRAW;
13901            }
13902
13903            /*
13904             * When the background is set, we try to apply its padding to this
13905             * View. When the background is removed, we don't touch this View's
13906             * padding. This is noted in the Javadocs. Hence, we don't need to
13907             * requestLayout(), the invalidate() below is sufficient.
13908             */
13909
13910            // The old background's minimum size could have affected this
13911            // View's layout, so let's requestLayout
13912            requestLayout = true;
13913        }
13914
13915        computeOpaqueFlags();
13916
13917        if (requestLayout) {
13918            requestLayout();
13919        }
13920
13921        mBackgroundSizeChanged = true;
13922        invalidate(true);
13923    }
13924
13925    /**
13926     * Gets the background drawable
13927     *
13928     * @return The drawable used as the background for this view, if any.
13929     *
13930     * @see #setBackground(Drawable)
13931     *
13932     * @attr ref android.R.styleable#View_background
13933     */
13934    public Drawable getBackground() {
13935        return mBackground;
13936    }
13937
13938    /**
13939     * Sets the padding. The view may add on the space required to display
13940     * the scrollbars, depending on the style and visibility of the scrollbars.
13941     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13942     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13943     * from the values set in this call.
13944     *
13945     * @attr ref android.R.styleable#View_padding
13946     * @attr ref android.R.styleable#View_paddingBottom
13947     * @attr ref android.R.styleable#View_paddingLeft
13948     * @attr ref android.R.styleable#View_paddingRight
13949     * @attr ref android.R.styleable#View_paddingTop
13950     * @param left the left padding in pixels
13951     * @param top the top padding in pixels
13952     * @param right the right padding in pixels
13953     * @param bottom the bottom padding in pixels
13954     */
13955    public void setPadding(int left, int top, int right, int bottom) {
13956        mUserPaddingStart = -1;
13957        mUserPaddingEnd = -1;
13958        mUserPaddingRelative = false;
13959
13960        internalSetPadding(left, top, right, bottom);
13961    }
13962
13963    private void internalSetPadding(int left, int top, int right, int bottom) {
13964        mUserPaddingLeft = left;
13965        mUserPaddingRight = right;
13966        mUserPaddingBottom = bottom;
13967
13968        final int viewFlags = mViewFlags;
13969        boolean changed = false;
13970
13971        // Common case is there are no scroll bars.
13972        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13973            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13974                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13975                        ? 0 : getVerticalScrollbarWidth();
13976                switch (mVerticalScrollbarPosition) {
13977                    case SCROLLBAR_POSITION_DEFAULT:
13978                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13979                            left += offset;
13980                        } else {
13981                            right += offset;
13982                        }
13983                        break;
13984                    case SCROLLBAR_POSITION_RIGHT:
13985                        right += offset;
13986                        break;
13987                    case SCROLLBAR_POSITION_LEFT:
13988                        left += offset;
13989                        break;
13990                }
13991            }
13992            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
13993                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
13994                        ? 0 : getHorizontalScrollbarHeight();
13995            }
13996        }
13997
13998        if (mPaddingLeft != left) {
13999            changed = true;
14000            mPaddingLeft = left;
14001        }
14002        if (mPaddingTop != top) {
14003            changed = true;
14004            mPaddingTop = top;
14005        }
14006        if (mPaddingRight != right) {
14007            changed = true;
14008            mPaddingRight = right;
14009        }
14010        if (mPaddingBottom != bottom) {
14011            changed = true;
14012            mPaddingBottom = bottom;
14013        }
14014
14015        if (changed) {
14016            requestLayout();
14017        }
14018    }
14019
14020    /**
14021     * Sets the relative padding. The view may add on the space required to display
14022     * the scrollbars, depending on the style and visibility of the scrollbars.
14023     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14024     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14025     * from the values set in this call.
14026     *
14027     * @attr ref android.R.styleable#View_padding
14028     * @attr ref android.R.styleable#View_paddingBottom
14029     * @attr ref android.R.styleable#View_paddingStart
14030     * @attr ref android.R.styleable#View_paddingEnd
14031     * @attr ref android.R.styleable#View_paddingTop
14032     * @param start the start padding in pixels
14033     * @param top the top padding in pixels
14034     * @param end the end padding in pixels
14035     * @param bottom the bottom padding in pixels
14036     */
14037    public void setPaddingRelative(int start, int top, int end, int bottom) {
14038        mUserPaddingStart = start;
14039        mUserPaddingEnd = end;
14040        mUserPaddingRelative = true;
14041
14042        switch(getResolvedLayoutDirection()) {
14043            case LAYOUT_DIRECTION_RTL:
14044                internalSetPadding(end, top, start, bottom);
14045                break;
14046            case LAYOUT_DIRECTION_LTR:
14047            default:
14048                internalSetPadding(start, top, end, bottom);
14049        }
14050    }
14051
14052    /**
14053     * Returns the top padding of this view.
14054     *
14055     * @return the top padding in pixels
14056     */
14057    public int getPaddingTop() {
14058        return mPaddingTop;
14059    }
14060
14061    /**
14062     * Returns the bottom padding of this view. If there are inset and enabled
14063     * scrollbars, this value may include the space required to display the
14064     * scrollbars as well.
14065     *
14066     * @return the bottom padding in pixels
14067     */
14068    public int getPaddingBottom() {
14069        return mPaddingBottom;
14070    }
14071
14072    /**
14073     * Returns the left padding of this view. If there are inset and enabled
14074     * scrollbars, this value may include the space required to display the
14075     * scrollbars as well.
14076     *
14077     * @return the left padding in pixels
14078     */
14079    public int getPaddingLeft() {
14080        return mPaddingLeft;
14081    }
14082
14083    /**
14084     * Returns the start padding of this view depending on its resolved layout direction.
14085     * If there are inset and enabled scrollbars, this value may include the space
14086     * required to display the scrollbars as well.
14087     *
14088     * @return the start padding in pixels
14089     */
14090    public int getPaddingStart() {
14091        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14092                mPaddingRight : mPaddingLeft;
14093    }
14094
14095    /**
14096     * Returns the right 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 right padding in pixels
14101     */
14102    public int getPaddingRight() {
14103        return mPaddingRight;
14104    }
14105
14106    /**
14107     * Returns the end 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 end padding in pixels
14112     */
14113    public int getPaddingEnd() {
14114        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14115                mPaddingLeft : mPaddingRight;
14116    }
14117
14118    /**
14119     * Return if the padding as been set thru relative values
14120     * {@link #setPaddingRelative(int, int, int, int)} or thru
14121     * @attr ref android.R.styleable#View_paddingStart or
14122     * @attr ref android.R.styleable#View_paddingEnd
14123     *
14124     * @return true if the padding is relative or false if it is not.
14125     */
14126    public boolean isPaddingRelative() {
14127        return mUserPaddingRelative;
14128    }
14129
14130    /**
14131     * @hide
14132     */
14133    public Insets getOpticalInsets() {
14134        if (mLayoutInsets == null) {
14135            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14136        }
14137        return mLayoutInsets;
14138    }
14139
14140    /**
14141     * @hide
14142     */
14143    public void setLayoutInsets(Insets layoutInsets) {
14144        mLayoutInsets = layoutInsets;
14145    }
14146
14147    /**
14148     * Changes the selection state of this view. A view can be selected or not.
14149     * Note that selection is not the same as focus. Views are typically
14150     * selected in the context of an AdapterView like ListView or GridView;
14151     * the selected view is the view that is highlighted.
14152     *
14153     * @param selected true if the view must be selected, false otherwise
14154     */
14155    public void setSelected(boolean selected) {
14156        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14157            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14158            if (!selected) resetPressedState();
14159            invalidate(true);
14160            refreshDrawableState();
14161            dispatchSetSelected(selected);
14162            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14163                notifyAccessibilityStateChanged();
14164            }
14165        }
14166    }
14167
14168    /**
14169     * Dispatch setSelected to all of this View's children.
14170     *
14171     * @see #setSelected(boolean)
14172     *
14173     * @param selected The new selected state
14174     */
14175    protected void dispatchSetSelected(boolean selected) {
14176    }
14177
14178    /**
14179     * Indicates the selection state of this view.
14180     *
14181     * @return true if the view is selected, false otherwise
14182     */
14183    @ViewDebug.ExportedProperty
14184    public boolean isSelected() {
14185        return (mPrivateFlags & SELECTED) != 0;
14186    }
14187
14188    /**
14189     * Changes the activated state of this view. A view can be activated or not.
14190     * Note that activation is not the same as selection.  Selection is
14191     * a transient property, representing the view (hierarchy) the user is
14192     * currently interacting with.  Activation is a longer-term state that the
14193     * user can move views in and out of.  For example, in a list view with
14194     * single or multiple selection enabled, the views in the current selection
14195     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14196     * here.)  The activated state is propagated down to children of the view it
14197     * is set on.
14198     *
14199     * @param activated true if the view must be activated, false otherwise
14200     */
14201    public void setActivated(boolean activated) {
14202        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14203            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14204            invalidate(true);
14205            refreshDrawableState();
14206            dispatchSetActivated(activated);
14207        }
14208    }
14209
14210    /**
14211     * Dispatch setActivated to all of this View's children.
14212     *
14213     * @see #setActivated(boolean)
14214     *
14215     * @param activated The new activated state
14216     */
14217    protected void dispatchSetActivated(boolean activated) {
14218    }
14219
14220    /**
14221     * Indicates the activation state of this view.
14222     *
14223     * @return true if the view is activated, false otherwise
14224     */
14225    @ViewDebug.ExportedProperty
14226    public boolean isActivated() {
14227        return (mPrivateFlags & ACTIVATED) != 0;
14228    }
14229
14230    /**
14231     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14232     * observer can be used to get notifications when global events, like
14233     * layout, happen.
14234     *
14235     * The returned ViewTreeObserver observer is not guaranteed to remain
14236     * valid for the lifetime of this View. If the caller of this method keeps
14237     * a long-lived reference to ViewTreeObserver, it should always check for
14238     * the return value of {@link ViewTreeObserver#isAlive()}.
14239     *
14240     * @return The ViewTreeObserver for this view's hierarchy.
14241     */
14242    public ViewTreeObserver getViewTreeObserver() {
14243        if (mAttachInfo != null) {
14244            return mAttachInfo.mTreeObserver;
14245        }
14246        if (mFloatingTreeObserver == null) {
14247            mFloatingTreeObserver = new ViewTreeObserver();
14248        }
14249        return mFloatingTreeObserver;
14250    }
14251
14252    /**
14253     * <p>Finds the topmost view in the current view hierarchy.</p>
14254     *
14255     * @return the topmost view containing this view
14256     */
14257    public View getRootView() {
14258        if (mAttachInfo != null) {
14259            final View v = mAttachInfo.mRootView;
14260            if (v != null) {
14261                return v;
14262            }
14263        }
14264
14265        View parent = this;
14266
14267        while (parent.mParent != null && parent.mParent instanceof View) {
14268            parent = (View) parent.mParent;
14269        }
14270
14271        return parent;
14272    }
14273
14274    /**
14275     * <p>Computes the coordinates of this view on the screen. The argument
14276     * must be an array of two integers. After the method returns, the array
14277     * contains the x and y location in that order.</p>
14278     *
14279     * @param location an array of two integers in which to hold the coordinates
14280     */
14281    public void getLocationOnScreen(int[] location) {
14282        getLocationInWindow(location);
14283
14284        final AttachInfo info = mAttachInfo;
14285        if (info != null) {
14286            location[0] += info.mWindowLeft;
14287            location[1] += info.mWindowTop;
14288        }
14289    }
14290
14291    /**
14292     * <p>Computes the coordinates of this view in its window. The argument
14293     * must be an array of two integers. After the method returns, the array
14294     * contains the x and y location in that order.</p>
14295     *
14296     * @param location an array of two integers in which to hold the coordinates
14297     */
14298    public void getLocationInWindow(int[] location) {
14299        if (location == null || location.length < 2) {
14300            throw new IllegalArgumentException("location must be an array of two integers");
14301        }
14302
14303        if (mAttachInfo == null) {
14304            // When the view is not attached to a window, this method does not make sense
14305            location[0] = location[1] = 0;
14306            return;
14307        }
14308
14309        float[] position = mAttachInfo.mTmpTransformLocation;
14310        position[0] = position[1] = 0.0f;
14311
14312        if (!hasIdentityMatrix()) {
14313            getMatrix().mapPoints(position);
14314        }
14315
14316        position[0] += mLeft;
14317        position[1] += mTop;
14318
14319        ViewParent viewParent = mParent;
14320        while (viewParent instanceof View) {
14321            final View view = (View) viewParent;
14322
14323            position[0] -= view.mScrollX;
14324            position[1] -= view.mScrollY;
14325
14326            if (!view.hasIdentityMatrix()) {
14327                view.getMatrix().mapPoints(position);
14328            }
14329
14330            position[0] += view.mLeft;
14331            position[1] += view.mTop;
14332
14333            viewParent = view.mParent;
14334         }
14335
14336        if (viewParent instanceof ViewRootImpl) {
14337            // *cough*
14338            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14339            position[1] -= vr.mCurScrollY;
14340        }
14341
14342        location[0] = (int) (position[0] + 0.5f);
14343        location[1] = (int) (position[1] + 0.5f);
14344    }
14345
14346    /**
14347     * {@hide}
14348     * @param id the id of the view to be found
14349     * @return the view of the specified id, null if cannot be found
14350     */
14351    protected View findViewTraversal(int id) {
14352        if (id == mID) {
14353            return this;
14354        }
14355        return null;
14356    }
14357
14358    /**
14359     * {@hide}
14360     * @param tag the tag of the view to be found
14361     * @return the view of specified tag, null if cannot be found
14362     */
14363    protected View findViewWithTagTraversal(Object tag) {
14364        if (tag != null && tag.equals(mTag)) {
14365            return this;
14366        }
14367        return null;
14368    }
14369
14370    /**
14371     * {@hide}
14372     * @param predicate The predicate to evaluate.
14373     * @param childToSkip If not null, ignores this child during the recursive traversal.
14374     * @return The first view that matches the predicate or null.
14375     */
14376    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14377        if (predicate.apply(this)) {
14378            return this;
14379        }
14380        return null;
14381    }
14382
14383    /**
14384     * Look for a child view with the given id.  If this view has the given
14385     * id, return this view.
14386     *
14387     * @param id The id to search for.
14388     * @return The view that has the given id in the hierarchy or null
14389     */
14390    public final View findViewById(int id) {
14391        if (id < 0) {
14392            return null;
14393        }
14394        return findViewTraversal(id);
14395    }
14396
14397    /**
14398     * Finds a view by its unuque and stable accessibility id.
14399     *
14400     * @param accessibilityId The searched accessibility id.
14401     * @return The found view.
14402     */
14403    final View findViewByAccessibilityId(int accessibilityId) {
14404        if (accessibilityId < 0) {
14405            return null;
14406        }
14407        return findViewByAccessibilityIdTraversal(accessibilityId);
14408    }
14409
14410    /**
14411     * Performs the traversal to find a view by its unuque and stable accessibility id.
14412     *
14413     * <strong>Note:</strong>This method does not stop at the root namespace
14414     * boundary since the user can touch the screen at an arbitrary location
14415     * potentially crossing the root namespace bounday which will send an
14416     * accessibility event to accessibility services and they should be able
14417     * to obtain the event source. Also accessibility ids are guaranteed to be
14418     * unique in the window.
14419     *
14420     * @param accessibilityId The accessibility id.
14421     * @return The found view.
14422     */
14423    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14424        if (getAccessibilityViewId() == accessibilityId) {
14425            return this;
14426        }
14427        return null;
14428    }
14429
14430    /**
14431     * Look for a child view with the given tag.  If this view has the given
14432     * tag, return this view.
14433     *
14434     * @param tag The tag to search for, using "tag.equals(getTag())".
14435     * @return The View that has the given tag in the hierarchy or null
14436     */
14437    public final View findViewWithTag(Object tag) {
14438        if (tag == null) {
14439            return null;
14440        }
14441        return findViewWithTagTraversal(tag);
14442    }
14443
14444    /**
14445     * {@hide}
14446     * Look for a child view that matches the specified predicate.
14447     * If this view matches the predicate, return this view.
14448     *
14449     * @param predicate The predicate to evaluate.
14450     * @return The first view that matches the predicate or null.
14451     */
14452    public final View findViewByPredicate(Predicate<View> predicate) {
14453        return findViewByPredicateTraversal(predicate, null);
14454    }
14455
14456    /**
14457     * {@hide}
14458     * Look for a child view that matches the specified predicate,
14459     * starting with the specified view and its descendents and then
14460     * recusively searching the ancestors and siblings of that view
14461     * until this view is reached.
14462     *
14463     * This method is useful in cases where the predicate does not match
14464     * a single unique view (perhaps multiple views use the same id)
14465     * and we are trying to find the view that is "closest" in scope to the
14466     * starting view.
14467     *
14468     * @param start The view to start from.
14469     * @param predicate The predicate to evaluate.
14470     * @return The first view that matches the predicate or null.
14471     */
14472    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14473        View childToSkip = null;
14474        for (;;) {
14475            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14476            if (view != null || start == this) {
14477                return view;
14478            }
14479
14480            ViewParent parent = start.getParent();
14481            if (parent == null || !(parent instanceof View)) {
14482                return null;
14483            }
14484
14485            childToSkip = start;
14486            start = (View) parent;
14487        }
14488    }
14489
14490    /**
14491     * Sets the identifier for this view. The identifier does not have to be
14492     * unique in this view's hierarchy. The identifier should be a positive
14493     * number.
14494     *
14495     * @see #NO_ID
14496     * @see #getId()
14497     * @see #findViewById(int)
14498     *
14499     * @param id a number used to identify the view
14500     *
14501     * @attr ref android.R.styleable#View_id
14502     */
14503    public void setId(int id) {
14504        mID = id;
14505    }
14506
14507    /**
14508     * {@hide}
14509     *
14510     * @param isRoot true if the view belongs to the root namespace, false
14511     *        otherwise
14512     */
14513    public void setIsRootNamespace(boolean isRoot) {
14514        if (isRoot) {
14515            mPrivateFlags |= IS_ROOT_NAMESPACE;
14516        } else {
14517            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14518        }
14519    }
14520
14521    /**
14522     * {@hide}
14523     *
14524     * @return true if the view belongs to the root namespace, false otherwise
14525     */
14526    public boolean isRootNamespace() {
14527        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14528    }
14529
14530    /**
14531     * Returns this view's identifier.
14532     *
14533     * @return a positive integer used to identify the view or {@link #NO_ID}
14534     *         if the view has no ID
14535     *
14536     * @see #setId(int)
14537     * @see #findViewById(int)
14538     * @attr ref android.R.styleable#View_id
14539     */
14540    @ViewDebug.CapturedViewProperty
14541    public int getId() {
14542        return mID;
14543    }
14544
14545    /**
14546     * Returns this view's tag.
14547     *
14548     * @return the Object stored in this view as a tag
14549     *
14550     * @see #setTag(Object)
14551     * @see #getTag(int)
14552     */
14553    @ViewDebug.ExportedProperty
14554    public Object getTag() {
14555        return mTag;
14556    }
14557
14558    /**
14559     * Sets the tag associated with this view. A tag can be used to mark
14560     * a view in its hierarchy and does not have to be unique within the
14561     * hierarchy. Tags can also be used to store data within a view without
14562     * resorting to another data structure.
14563     *
14564     * @param tag an Object to tag the view with
14565     *
14566     * @see #getTag()
14567     * @see #setTag(int, Object)
14568     */
14569    public void setTag(final Object tag) {
14570        mTag = tag;
14571    }
14572
14573    /**
14574     * Returns the tag associated with this view and the specified key.
14575     *
14576     * @param key The key identifying the tag
14577     *
14578     * @return the Object stored in this view as a tag
14579     *
14580     * @see #setTag(int, Object)
14581     * @see #getTag()
14582     */
14583    public Object getTag(int key) {
14584        if (mKeyedTags != null) return mKeyedTags.get(key);
14585        return null;
14586    }
14587
14588    /**
14589     * Sets a tag associated with this view and a key. A tag can be used
14590     * to mark a view in its hierarchy and does not have to be unique within
14591     * the hierarchy. Tags can also be used to store data within a view
14592     * without resorting to another data structure.
14593     *
14594     * The specified key should be an id declared in the resources of the
14595     * application to ensure it is unique (see the <a
14596     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14597     * Keys identified as belonging to
14598     * the Android framework or not associated with any package will cause
14599     * an {@link IllegalArgumentException} to be thrown.
14600     *
14601     * @param key The key identifying the tag
14602     * @param tag An Object to tag the view with
14603     *
14604     * @throws IllegalArgumentException If they specified key is not valid
14605     *
14606     * @see #setTag(Object)
14607     * @see #getTag(int)
14608     */
14609    public void setTag(int key, final Object tag) {
14610        // If the package id is 0x00 or 0x01, it's either an undefined package
14611        // or a framework id
14612        if ((key >>> 24) < 2) {
14613            throw new IllegalArgumentException("The key must be an application-specific "
14614                    + "resource id.");
14615        }
14616
14617        setKeyedTag(key, tag);
14618    }
14619
14620    /**
14621     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14622     * framework id.
14623     *
14624     * @hide
14625     */
14626    public void setTagInternal(int key, Object tag) {
14627        if ((key >>> 24) != 0x1) {
14628            throw new IllegalArgumentException("The key must be a framework-specific "
14629                    + "resource id.");
14630        }
14631
14632        setKeyedTag(key, tag);
14633    }
14634
14635    private void setKeyedTag(int key, Object tag) {
14636        if (mKeyedTags == null) {
14637            mKeyedTags = new SparseArray<Object>();
14638        }
14639
14640        mKeyedTags.put(key, tag);
14641    }
14642
14643    /**
14644     * @param consistency The type of consistency. See ViewDebug for more information.
14645     *
14646     * @hide
14647     */
14648    protected boolean dispatchConsistencyCheck(int consistency) {
14649        return onConsistencyCheck(consistency);
14650    }
14651
14652    /**
14653     * Method that subclasses should implement to check their consistency. The type of
14654     * consistency check is indicated by the bit field passed as a parameter.
14655     *
14656     * @param consistency The type of consistency. See ViewDebug for more information.
14657     *
14658     * @throws IllegalStateException if the view is in an inconsistent state.
14659     *
14660     * @hide
14661     */
14662    protected boolean onConsistencyCheck(int consistency) {
14663        boolean result = true;
14664
14665        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14666        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14667
14668        if (checkLayout) {
14669            if (getParent() == null) {
14670                result = false;
14671                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14672                        "View " + this + " does not have a parent.");
14673            }
14674
14675            if (mAttachInfo == null) {
14676                result = false;
14677                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14678                        "View " + this + " is not attached to a window.");
14679            }
14680        }
14681
14682        if (checkDrawing) {
14683            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14684            // from their draw() method
14685
14686            if ((mPrivateFlags & DRAWN) != DRAWN &&
14687                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14688                result = false;
14689                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14690                        "View " + this + " was invalidated but its drawing cache is valid.");
14691            }
14692        }
14693
14694        return result;
14695    }
14696
14697    /**
14698     * Prints information about this view in the log output, with the tag
14699     * {@link #VIEW_LOG_TAG}.
14700     *
14701     * @hide
14702     */
14703    public void debug() {
14704        debug(0);
14705    }
14706
14707    /**
14708     * Prints information about this view in the log output, with the tag
14709     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14710     * indentation defined by the <code>depth</code>.
14711     *
14712     * @param depth the indentation level
14713     *
14714     * @hide
14715     */
14716    protected void debug(int depth) {
14717        String output = debugIndent(depth - 1);
14718
14719        output += "+ " + this;
14720        int id = getId();
14721        if (id != -1) {
14722            output += " (id=" + id + ")";
14723        }
14724        Object tag = getTag();
14725        if (tag != null) {
14726            output += " (tag=" + tag + ")";
14727        }
14728        Log.d(VIEW_LOG_TAG, output);
14729
14730        if ((mPrivateFlags & FOCUSED) != 0) {
14731            output = debugIndent(depth) + " FOCUSED";
14732            Log.d(VIEW_LOG_TAG, output);
14733        }
14734
14735        output = debugIndent(depth);
14736        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14737                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14738                + "} ";
14739        Log.d(VIEW_LOG_TAG, output);
14740
14741        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14742                || mPaddingBottom != 0) {
14743            output = debugIndent(depth);
14744            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14745                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14746            Log.d(VIEW_LOG_TAG, output);
14747        }
14748
14749        output = debugIndent(depth);
14750        output += "mMeasureWidth=" + mMeasuredWidth +
14751                " mMeasureHeight=" + mMeasuredHeight;
14752        Log.d(VIEW_LOG_TAG, output);
14753
14754        output = debugIndent(depth);
14755        if (mLayoutParams == null) {
14756            output += "BAD! no layout params";
14757        } else {
14758            output = mLayoutParams.debug(output);
14759        }
14760        Log.d(VIEW_LOG_TAG, output);
14761
14762        output = debugIndent(depth);
14763        output += "flags={";
14764        output += View.printFlags(mViewFlags);
14765        output += "}";
14766        Log.d(VIEW_LOG_TAG, output);
14767
14768        output = debugIndent(depth);
14769        output += "privateFlags={";
14770        output += View.printPrivateFlags(mPrivateFlags);
14771        output += "}";
14772        Log.d(VIEW_LOG_TAG, output);
14773    }
14774
14775    /**
14776     * Creates a string of whitespaces used for indentation.
14777     *
14778     * @param depth the indentation level
14779     * @return a String containing (depth * 2 + 3) * 2 white spaces
14780     *
14781     * @hide
14782     */
14783    protected static String debugIndent(int depth) {
14784        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14785        for (int i = 0; i < (depth * 2) + 3; i++) {
14786            spaces.append(' ').append(' ');
14787        }
14788        return spaces.toString();
14789    }
14790
14791    /**
14792     * <p>Return the offset of the widget's text baseline from the widget's top
14793     * boundary. If this widget does not support baseline alignment, this
14794     * method returns -1. </p>
14795     *
14796     * @return the offset of the baseline within the widget's bounds or -1
14797     *         if baseline alignment is not supported
14798     */
14799    @ViewDebug.ExportedProperty(category = "layout")
14800    public int getBaseline() {
14801        return -1;
14802    }
14803
14804    /**
14805     * Call this when something has changed which has invalidated the
14806     * layout of this view. This will schedule a layout pass of the view
14807     * tree.
14808     */
14809    public void requestLayout() {
14810        if (ViewDebug.TRACE_HIERARCHY) {
14811            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14812        }
14813
14814        mPrivateFlags |= FORCE_LAYOUT;
14815        mPrivateFlags |= INVALIDATED;
14816
14817        if (mLayoutParams != null) {
14818            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14819        }
14820
14821        if (mParent != null && !mParent.isLayoutRequested()) {
14822            mParent.requestLayout();
14823        }
14824    }
14825
14826    /**
14827     * Forces this view to be laid out during the next layout pass.
14828     * This method does not call requestLayout() or forceLayout()
14829     * on the parent.
14830     */
14831    public void forceLayout() {
14832        mPrivateFlags |= FORCE_LAYOUT;
14833        mPrivateFlags |= INVALIDATED;
14834    }
14835
14836    /**
14837     * <p>
14838     * This is called to find out how big a view should be. The parent
14839     * supplies constraint information in the width and height parameters.
14840     * </p>
14841     *
14842     * <p>
14843     * The actual measurement work of a view is performed in
14844     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14845     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14846     * </p>
14847     *
14848     *
14849     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14850     *        parent
14851     * @param heightMeasureSpec Vertical space requirements as imposed by the
14852     *        parent
14853     *
14854     * @see #onMeasure(int, int)
14855     */
14856    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14857        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14858                widthMeasureSpec != mOldWidthMeasureSpec ||
14859                heightMeasureSpec != mOldHeightMeasureSpec) {
14860
14861            // first clears the measured dimension flag
14862            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14863
14864            if (ViewDebug.TRACE_HIERARCHY) {
14865                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14866            }
14867
14868            // measure ourselves, this should set the measured dimension flag back
14869            onMeasure(widthMeasureSpec, heightMeasureSpec);
14870
14871            // flag not set, setMeasuredDimension() was not invoked, we raise
14872            // an exception to warn the developer
14873            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14874                throw new IllegalStateException("onMeasure() did not set the"
14875                        + " measured dimension by calling"
14876                        + " setMeasuredDimension()");
14877            }
14878
14879            mPrivateFlags |= LAYOUT_REQUIRED;
14880        }
14881
14882        mOldWidthMeasureSpec = widthMeasureSpec;
14883        mOldHeightMeasureSpec = heightMeasureSpec;
14884    }
14885
14886    /**
14887     * <p>
14888     * Measure the view and its content to determine the measured width and the
14889     * measured height. This method is invoked by {@link #measure(int, int)} and
14890     * should be overriden by subclasses to provide accurate and efficient
14891     * measurement of their contents.
14892     * </p>
14893     *
14894     * <p>
14895     * <strong>CONTRACT:</strong> When overriding this method, you
14896     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14897     * measured width and height of this view. Failure to do so will trigger an
14898     * <code>IllegalStateException</code>, thrown by
14899     * {@link #measure(int, int)}. Calling the superclass'
14900     * {@link #onMeasure(int, int)} is a valid use.
14901     * </p>
14902     *
14903     * <p>
14904     * The base class implementation of measure defaults to the background size,
14905     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14906     * override {@link #onMeasure(int, int)} to provide better measurements of
14907     * their content.
14908     * </p>
14909     *
14910     * <p>
14911     * If this method is overridden, it is the subclass's responsibility to make
14912     * sure the measured height and width are at least the view's minimum height
14913     * and width ({@link #getSuggestedMinimumHeight()} and
14914     * {@link #getSuggestedMinimumWidth()}).
14915     * </p>
14916     *
14917     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14918     *                         The requirements are encoded with
14919     *                         {@link android.view.View.MeasureSpec}.
14920     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14921     *                         The requirements are encoded with
14922     *                         {@link android.view.View.MeasureSpec}.
14923     *
14924     * @see #getMeasuredWidth()
14925     * @see #getMeasuredHeight()
14926     * @see #setMeasuredDimension(int, int)
14927     * @see #getSuggestedMinimumHeight()
14928     * @see #getSuggestedMinimumWidth()
14929     * @see android.view.View.MeasureSpec#getMode(int)
14930     * @see android.view.View.MeasureSpec#getSize(int)
14931     */
14932    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14933        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14934                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14935    }
14936
14937    /**
14938     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14939     * measured width and measured height. Failing to do so will trigger an
14940     * exception at measurement time.</p>
14941     *
14942     * @param measuredWidth The measured width of this view.  May be a complex
14943     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14944     * {@link #MEASURED_STATE_TOO_SMALL}.
14945     * @param measuredHeight The measured height of this view.  May be a complex
14946     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14947     * {@link #MEASURED_STATE_TOO_SMALL}.
14948     */
14949    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14950        mMeasuredWidth = measuredWidth;
14951        mMeasuredHeight = measuredHeight;
14952
14953        mPrivateFlags |= MEASURED_DIMENSION_SET;
14954    }
14955
14956    /**
14957     * Merge two states as returned by {@link #getMeasuredState()}.
14958     * @param curState The current state as returned from a view or the result
14959     * of combining multiple views.
14960     * @param newState The new view state to combine.
14961     * @return Returns a new integer reflecting the combination of the two
14962     * states.
14963     */
14964    public static int combineMeasuredStates(int curState, int newState) {
14965        return curState | newState;
14966    }
14967
14968    /**
14969     * Version of {@link #resolveSizeAndState(int, int, int)}
14970     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14971     */
14972    public static int resolveSize(int size, int measureSpec) {
14973        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14974    }
14975
14976    /**
14977     * Utility to reconcile a desired size and state, with constraints imposed
14978     * by a MeasureSpec.  Will take the desired size, unless a different size
14979     * is imposed by the constraints.  The returned value is a compound integer,
14980     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14981     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14982     * size is smaller than the size the view wants to be.
14983     *
14984     * @param size How big the view wants to be
14985     * @param measureSpec Constraints imposed by the parent
14986     * @return Size information bit mask as defined by
14987     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14988     */
14989    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14990        int result = size;
14991        int specMode = MeasureSpec.getMode(measureSpec);
14992        int specSize =  MeasureSpec.getSize(measureSpec);
14993        switch (specMode) {
14994        case MeasureSpec.UNSPECIFIED:
14995            result = size;
14996            break;
14997        case MeasureSpec.AT_MOST:
14998            if (specSize < size) {
14999                result = specSize | MEASURED_STATE_TOO_SMALL;
15000            } else {
15001                result = size;
15002            }
15003            break;
15004        case MeasureSpec.EXACTLY:
15005            result = specSize;
15006            break;
15007        }
15008        return result | (childMeasuredState&MEASURED_STATE_MASK);
15009    }
15010
15011    /**
15012     * Utility to return a default size. Uses the supplied size if the
15013     * MeasureSpec imposed no constraints. Will get larger if allowed
15014     * by the MeasureSpec.
15015     *
15016     * @param size Default size for this view
15017     * @param measureSpec Constraints imposed by the parent
15018     * @return The size this view should be.
15019     */
15020    public static int getDefaultSize(int size, int measureSpec) {
15021        int result = size;
15022        int specMode = MeasureSpec.getMode(measureSpec);
15023        int specSize = MeasureSpec.getSize(measureSpec);
15024
15025        switch (specMode) {
15026        case MeasureSpec.UNSPECIFIED:
15027            result = size;
15028            break;
15029        case MeasureSpec.AT_MOST:
15030        case MeasureSpec.EXACTLY:
15031            result = specSize;
15032            break;
15033        }
15034        return result;
15035    }
15036
15037    /**
15038     * Returns the suggested minimum height that the view should use. This
15039     * returns the maximum of the view's minimum height
15040     * and the background's minimum height
15041     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15042     * <p>
15043     * When being used in {@link #onMeasure(int, int)}, the caller should still
15044     * ensure the returned height is within the requirements of the parent.
15045     *
15046     * @return The suggested minimum height of the view.
15047     */
15048    protected int getSuggestedMinimumHeight() {
15049        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15050
15051    }
15052
15053    /**
15054     * Returns the suggested minimum width that the view should use. This
15055     * returns the maximum of the view's minimum width)
15056     * and the background's minimum width
15057     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15058     * <p>
15059     * When being used in {@link #onMeasure(int, int)}, the caller should still
15060     * ensure the returned width is within the requirements of the parent.
15061     *
15062     * @return The suggested minimum width of the view.
15063     */
15064    protected int getSuggestedMinimumWidth() {
15065        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15066    }
15067
15068    /**
15069     * Returns the minimum height of the view.
15070     *
15071     * @return the minimum height the view will try to be.
15072     *
15073     * @see #setMinimumHeight(int)
15074     *
15075     * @attr ref android.R.styleable#View_minHeight
15076     */
15077    public int getMinimumHeight() {
15078        return mMinHeight;
15079    }
15080
15081    /**
15082     * Sets the minimum height of the view. It is not guaranteed the view will
15083     * be able to achieve this minimum height (for example, if its parent layout
15084     * constrains it with less available height).
15085     *
15086     * @param minHeight The minimum height the view will try to be.
15087     *
15088     * @see #getMinimumHeight()
15089     *
15090     * @attr ref android.R.styleable#View_minHeight
15091     */
15092    public void setMinimumHeight(int minHeight) {
15093        mMinHeight = minHeight;
15094        requestLayout();
15095    }
15096
15097    /**
15098     * Returns the minimum width of the view.
15099     *
15100     * @return the minimum width the view will try to be.
15101     *
15102     * @see #setMinimumWidth(int)
15103     *
15104     * @attr ref android.R.styleable#View_minWidth
15105     */
15106    public int getMinimumWidth() {
15107        return mMinWidth;
15108    }
15109
15110    /**
15111     * Sets the minimum width of the view. It is not guaranteed the view will
15112     * be able to achieve this minimum width (for example, if its parent layout
15113     * constrains it with less available width).
15114     *
15115     * @param minWidth The minimum width the view will try to be.
15116     *
15117     * @see #getMinimumWidth()
15118     *
15119     * @attr ref android.R.styleable#View_minWidth
15120     */
15121    public void setMinimumWidth(int minWidth) {
15122        mMinWidth = minWidth;
15123        requestLayout();
15124
15125    }
15126
15127    /**
15128     * Get the animation currently associated with this view.
15129     *
15130     * @return The animation that is currently playing or
15131     *         scheduled to play for this view.
15132     */
15133    public Animation getAnimation() {
15134        return mCurrentAnimation;
15135    }
15136
15137    /**
15138     * Start the specified animation now.
15139     *
15140     * @param animation the animation to start now
15141     */
15142    public void startAnimation(Animation animation) {
15143        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15144        setAnimation(animation);
15145        invalidateParentCaches();
15146        invalidate(true);
15147    }
15148
15149    /**
15150     * Cancels any animations for this view.
15151     */
15152    public void clearAnimation() {
15153        if (mCurrentAnimation != null) {
15154            mCurrentAnimation.detach();
15155        }
15156        mCurrentAnimation = null;
15157        invalidateParentIfNeeded();
15158    }
15159
15160    /**
15161     * Sets the next animation to play for this view.
15162     * If you want the animation to play immediately, use
15163     * startAnimation. This method provides allows fine-grained
15164     * control over the start time and invalidation, but you
15165     * must make sure that 1) the animation has a start time set, and
15166     * 2) the view will be invalidated when the animation is supposed to
15167     * start.
15168     *
15169     * @param animation The next animation, or null.
15170     */
15171    public void setAnimation(Animation animation) {
15172        mCurrentAnimation = animation;
15173
15174        if (animation != null) {
15175            // If the screen is off assume the animation start time is now instead of
15176            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15177            // would cause the animation to start when the screen turns back on
15178            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15179                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15180                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15181            }
15182            animation.reset();
15183        }
15184    }
15185
15186    /**
15187     * Invoked by a parent ViewGroup to notify the start of the animation
15188     * currently associated with this view. If you override this method,
15189     * always call super.onAnimationStart();
15190     *
15191     * @see #setAnimation(android.view.animation.Animation)
15192     * @see #getAnimation()
15193     */
15194    protected void onAnimationStart() {
15195        mPrivateFlags |= ANIMATION_STARTED;
15196    }
15197
15198    /**
15199     * Invoked by a parent ViewGroup to notify the end of the animation
15200     * currently associated with this view. If you override this method,
15201     * always call super.onAnimationEnd();
15202     *
15203     * @see #setAnimation(android.view.animation.Animation)
15204     * @see #getAnimation()
15205     */
15206    protected void onAnimationEnd() {
15207        mPrivateFlags &= ~ANIMATION_STARTED;
15208    }
15209
15210    /**
15211     * Invoked if there is a Transform that involves alpha. Subclass that can
15212     * draw themselves with the specified alpha should return true, and then
15213     * respect that alpha when their onDraw() is called. If this returns false
15214     * then the view may be redirected to draw into an offscreen buffer to
15215     * fulfill the request, which will look fine, but may be slower than if the
15216     * subclass handles it internally. The default implementation returns false.
15217     *
15218     * @param alpha The alpha (0..255) to apply to the view's drawing
15219     * @return true if the view can draw with the specified alpha.
15220     */
15221    protected boolean onSetAlpha(int alpha) {
15222        return false;
15223    }
15224
15225    /**
15226     * This is used by the RootView to perform an optimization when
15227     * the view hierarchy contains one or several SurfaceView.
15228     * SurfaceView is always considered transparent, but its children are not,
15229     * therefore all View objects remove themselves from the global transparent
15230     * region (passed as a parameter to this function).
15231     *
15232     * @param region The transparent region for this ViewAncestor (window).
15233     *
15234     * @return Returns true if the effective visibility of the view at this
15235     * point is opaque, regardless of the transparent region; returns false
15236     * if it is possible for underlying windows to be seen behind the view.
15237     *
15238     * {@hide}
15239     */
15240    public boolean gatherTransparentRegion(Region region) {
15241        final AttachInfo attachInfo = mAttachInfo;
15242        if (region != null && attachInfo != null) {
15243            final int pflags = mPrivateFlags;
15244            if ((pflags & SKIP_DRAW) == 0) {
15245                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15246                // remove it from the transparent region.
15247                final int[] location = attachInfo.mTransparentLocation;
15248                getLocationInWindow(location);
15249                region.op(location[0], location[1], location[0] + mRight - mLeft,
15250                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15251            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15252                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15253                // exists, so we remove the background drawable's non-transparent
15254                // parts from this transparent region.
15255                applyDrawableToTransparentRegion(mBackground, region);
15256            }
15257        }
15258        return true;
15259    }
15260
15261    /**
15262     * Play a sound effect for this view.
15263     *
15264     * <p>The framework will play sound effects for some built in actions, such as
15265     * clicking, but you may wish to play these effects in your widget,
15266     * for instance, for internal navigation.
15267     *
15268     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15269     * {@link #isSoundEffectsEnabled()} is true.
15270     *
15271     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15272     */
15273    public void playSoundEffect(int soundConstant) {
15274        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15275            return;
15276        }
15277        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15278    }
15279
15280    /**
15281     * BZZZTT!!1!
15282     *
15283     * <p>Provide haptic feedback to the user for this view.
15284     *
15285     * <p>The framework will provide haptic feedback for some built in actions,
15286     * such as long presses, but you may wish to provide feedback for your
15287     * own widget.
15288     *
15289     * <p>The feedback will only be performed if
15290     * {@link #isHapticFeedbackEnabled()} is true.
15291     *
15292     * @param feedbackConstant One of the constants defined in
15293     * {@link HapticFeedbackConstants}
15294     */
15295    public boolean performHapticFeedback(int feedbackConstant) {
15296        return performHapticFeedback(feedbackConstant, 0);
15297    }
15298
15299    /**
15300     * BZZZTT!!1!
15301     *
15302     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15303     *
15304     * @param feedbackConstant One of the constants defined in
15305     * {@link HapticFeedbackConstants}
15306     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15307     */
15308    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15309        if (mAttachInfo == null) {
15310            return false;
15311        }
15312        //noinspection SimplifiableIfStatement
15313        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15314                && !isHapticFeedbackEnabled()) {
15315            return false;
15316        }
15317        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15318                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15319    }
15320
15321    /**
15322     * Request that the visibility of the status bar or other screen/window
15323     * decorations be changed.
15324     *
15325     * <p>This method is used to put the over device UI into temporary modes
15326     * where the user's attention is focused more on the application content,
15327     * by dimming or hiding surrounding system affordances.  This is typically
15328     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15329     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15330     * to be placed behind the action bar (and with these flags other system
15331     * affordances) so that smooth transitions between hiding and showing them
15332     * can be done.
15333     *
15334     * <p>Two representative examples of the use of system UI visibility is
15335     * implementing a content browsing application (like a magazine reader)
15336     * and a video playing application.
15337     *
15338     * <p>The first code shows a typical implementation of a View in a content
15339     * browsing application.  In this implementation, the application goes
15340     * into a content-oriented mode by hiding the status bar and action bar,
15341     * and putting the navigation elements into lights out mode.  The user can
15342     * then interact with content while in this mode.  Such an application should
15343     * provide an easy way for the user to toggle out of the mode (such as to
15344     * check information in the status bar or access notifications).  In the
15345     * implementation here, this is done simply by tapping on the content.
15346     *
15347     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15348     *      content}
15349     *
15350     * <p>This second code sample shows a typical implementation of a View
15351     * in a video playing application.  In this situation, while the video is
15352     * playing the application would like to go into a complete full-screen mode,
15353     * to use as much of the display as possible for the video.  When in this state
15354     * the user can not interact with the application; the system intercepts
15355     * touching on the screen to pop the UI out of full screen mode.
15356     *
15357     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15358     *      content}
15359     *
15360     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15361     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15362     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15363     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15364     */
15365    public void setSystemUiVisibility(int visibility) {
15366        if (visibility != mSystemUiVisibility) {
15367            mSystemUiVisibility = visibility;
15368            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15369                mParent.recomputeViewAttributes(this);
15370            }
15371        }
15372    }
15373
15374    /**
15375     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15376     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15377     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15378     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15379     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15380     */
15381    public int getSystemUiVisibility() {
15382        return mSystemUiVisibility;
15383    }
15384
15385    /**
15386     * Returns the current system UI visibility that is currently set for
15387     * the entire window.  This is the combination of the
15388     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15389     * views in the window.
15390     */
15391    public int getWindowSystemUiVisibility() {
15392        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15393    }
15394
15395    /**
15396     * Override to find out when the window's requested system UI visibility
15397     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15398     * This is different from the callbacks recieved through
15399     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15400     * in that this is only telling you about the local request of the window,
15401     * not the actual values applied by the system.
15402     */
15403    public void onWindowSystemUiVisibilityChanged(int visible) {
15404    }
15405
15406    /**
15407     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15408     * the view hierarchy.
15409     */
15410    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15411        onWindowSystemUiVisibilityChanged(visible);
15412    }
15413
15414    /**
15415     * Set a listener to receive callbacks when the visibility of the system bar changes.
15416     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15417     */
15418    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15419        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15420        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15421            mParent.recomputeViewAttributes(this);
15422        }
15423    }
15424
15425    /**
15426     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15427     * the view hierarchy.
15428     */
15429    public void dispatchSystemUiVisibilityChanged(int visibility) {
15430        ListenerInfo li = mListenerInfo;
15431        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15432            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15433                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15434        }
15435    }
15436
15437    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15438        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15439        if (val != mSystemUiVisibility) {
15440            setSystemUiVisibility(val);
15441        }
15442    }
15443
15444    /** @hide */
15445    public void setDisabledSystemUiVisibility(int flags) {
15446        if (mAttachInfo != null) {
15447            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15448                mAttachInfo.mDisabledSystemUiVisibility = flags;
15449                if (mParent != null) {
15450                    mParent.recomputeViewAttributes(this);
15451                }
15452            }
15453        }
15454    }
15455
15456    /**
15457     * Creates an image that the system displays during the drag and drop
15458     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15459     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15460     * appearance as the given View. The default also positions the center of the drag shadow
15461     * directly under the touch point. If no View is provided (the constructor with no parameters
15462     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15463     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15464     * default is an invisible drag shadow.
15465     * <p>
15466     * You are not required to use the View you provide to the constructor as the basis of the
15467     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15468     * anything you want as the drag shadow.
15469     * </p>
15470     * <p>
15471     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15472     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15473     *  size and position of the drag shadow. It uses this data to construct a
15474     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15475     *  so that your application can draw the shadow image in the Canvas.
15476     * </p>
15477     *
15478     * <div class="special reference">
15479     * <h3>Developer Guides</h3>
15480     * <p>For a guide to implementing drag and drop features, read the
15481     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15482     * </div>
15483     */
15484    public static class DragShadowBuilder {
15485        private final WeakReference<View> mView;
15486
15487        /**
15488         * Constructs a shadow image builder based on a View. By default, the resulting drag
15489         * shadow will have the same appearance and dimensions as the View, with the touch point
15490         * over the center of the View.
15491         * @param view A View. Any View in scope can be used.
15492         */
15493        public DragShadowBuilder(View view) {
15494            mView = new WeakReference<View>(view);
15495        }
15496
15497        /**
15498         * Construct a shadow builder object with no associated View.  This
15499         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15500         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15501         * to supply the drag shadow's dimensions and appearance without
15502         * reference to any View object. If they are not overridden, then the result is an
15503         * invisible drag shadow.
15504         */
15505        public DragShadowBuilder() {
15506            mView = new WeakReference<View>(null);
15507        }
15508
15509        /**
15510         * Returns the View object that had been passed to the
15511         * {@link #View.DragShadowBuilder(View)}
15512         * constructor.  If that View parameter was {@code null} or if the
15513         * {@link #View.DragShadowBuilder()}
15514         * constructor was used to instantiate the builder object, this method will return
15515         * null.
15516         *
15517         * @return The View object associate with this builder object.
15518         */
15519        @SuppressWarnings({"JavadocReference"})
15520        final public View getView() {
15521            return mView.get();
15522        }
15523
15524        /**
15525         * Provides the metrics for the shadow image. These include the dimensions of
15526         * the shadow image, and the point within that shadow that should
15527         * be centered under the touch location while dragging.
15528         * <p>
15529         * The default implementation sets the dimensions of the shadow to be the
15530         * same as the dimensions of the View itself and centers the shadow under
15531         * the touch point.
15532         * </p>
15533         *
15534         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15535         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15536         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15537         * image.
15538         *
15539         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15540         * shadow image that should be underneath the touch point during the drag and drop
15541         * operation. Your application must set {@link android.graphics.Point#x} to the
15542         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15543         */
15544        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15545            final View view = mView.get();
15546            if (view != null) {
15547                shadowSize.set(view.getWidth(), view.getHeight());
15548                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15549            } else {
15550                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15551            }
15552        }
15553
15554        /**
15555         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15556         * based on the dimensions it received from the
15557         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15558         *
15559         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15560         */
15561        public void onDrawShadow(Canvas canvas) {
15562            final View view = mView.get();
15563            if (view != null) {
15564                view.draw(canvas);
15565            } else {
15566                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15567            }
15568        }
15569    }
15570
15571    /**
15572     * Starts a drag and drop operation. When your application calls this method, it passes a
15573     * {@link android.view.View.DragShadowBuilder} object to the system. The
15574     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15575     * to get metrics for the drag shadow, and then calls the object's
15576     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15577     * <p>
15578     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15579     *  drag events to all the View objects in your application that are currently visible. It does
15580     *  this either by calling the View object's drag listener (an implementation of
15581     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15582     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15583     *  Both are passed a {@link android.view.DragEvent} object that has a
15584     *  {@link android.view.DragEvent#getAction()} value of
15585     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15586     * </p>
15587     * <p>
15588     * Your application can invoke startDrag() on any attached View object. The View object does not
15589     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15590     * be related to the View the user selected for dragging.
15591     * </p>
15592     * @param data A {@link android.content.ClipData} object pointing to the data to be
15593     * transferred by the drag and drop operation.
15594     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15595     * drag shadow.
15596     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15597     * drop operation. This Object is put into every DragEvent object sent by the system during the
15598     * current drag.
15599     * <p>
15600     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15601     * to the target Views. For example, it can contain flags that differentiate between a
15602     * a copy operation and a move operation.
15603     * </p>
15604     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15605     * so the parameter should be set to 0.
15606     * @return {@code true} if the method completes successfully, or
15607     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15608     * do a drag, and so no drag operation is in progress.
15609     */
15610    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15611            Object myLocalState, int flags) {
15612        if (ViewDebug.DEBUG_DRAG) {
15613            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15614        }
15615        boolean okay = false;
15616
15617        Point shadowSize = new Point();
15618        Point shadowTouchPoint = new Point();
15619        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15620
15621        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15622                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15623            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15624        }
15625
15626        if (ViewDebug.DEBUG_DRAG) {
15627            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15628                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15629        }
15630        Surface surface = new Surface();
15631        try {
15632            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15633                    flags, shadowSize.x, shadowSize.y, surface);
15634            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15635                    + " surface=" + surface);
15636            if (token != null) {
15637                Canvas canvas = surface.lockCanvas(null);
15638                try {
15639                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15640                    shadowBuilder.onDrawShadow(canvas);
15641                } finally {
15642                    surface.unlockCanvasAndPost(canvas);
15643                }
15644
15645                final ViewRootImpl root = getViewRootImpl();
15646
15647                // Cache the local state object for delivery with DragEvents
15648                root.setLocalDragState(myLocalState);
15649
15650                // repurpose 'shadowSize' for the last touch point
15651                root.getLastTouchPoint(shadowSize);
15652
15653                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15654                        shadowSize.x, shadowSize.y,
15655                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15656                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15657
15658                // Off and running!  Release our local surface instance; the drag
15659                // shadow surface is now managed by the system process.
15660                surface.release();
15661            }
15662        } catch (Exception e) {
15663            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15664            surface.destroy();
15665        }
15666
15667        return okay;
15668    }
15669
15670    /**
15671     * Handles drag events sent by the system following a call to
15672     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15673     *<p>
15674     * When the system calls this method, it passes a
15675     * {@link android.view.DragEvent} object. A call to
15676     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15677     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15678     * operation.
15679     * @param event The {@link android.view.DragEvent} sent by the system.
15680     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15681     * in DragEvent, indicating the type of drag event represented by this object.
15682     * @return {@code true} if the method was successful, otherwise {@code false}.
15683     * <p>
15684     *  The method should return {@code true} in response to an action type of
15685     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15686     *  operation.
15687     * </p>
15688     * <p>
15689     *  The method should also return {@code true} in response to an action type of
15690     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15691     *  {@code false} if it didn't.
15692     * </p>
15693     */
15694    public boolean onDragEvent(DragEvent event) {
15695        return false;
15696    }
15697
15698    /**
15699     * Detects if this View is enabled and has a drag event listener.
15700     * If both are true, then it calls the drag event listener with the
15701     * {@link android.view.DragEvent} it received. If the drag event listener returns
15702     * {@code true}, then dispatchDragEvent() returns {@code true}.
15703     * <p>
15704     * For all other cases, the method calls the
15705     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15706     * method and returns its result.
15707     * </p>
15708     * <p>
15709     * This ensures that a drag event is always consumed, even if the View does not have a drag
15710     * event listener. However, if the View has a listener and the listener returns true, then
15711     * onDragEvent() is not called.
15712     * </p>
15713     */
15714    public boolean dispatchDragEvent(DragEvent event) {
15715        //noinspection SimplifiableIfStatement
15716        ListenerInfo li = mListenerInfo;
15717        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15718                && li.mOnDragListener.onDrag(this, event)) {
15719            return true;
15720        }
15721        return onDragEvent(event);
15722    }
15723
15724    boolean canAcceptDrag() {
15725        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15726    }
15727
15728    /**
15729     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15730     * it is ever exposed at all.
15731     * @hide
15732     */
15733    public void onCloseSystemDialogs(String reason) {
15734    }
15735
15736    /**
15737     * Given a Drawable whose bounds have been set to draw into this view,
15738     * update a Region being computed for
15739     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15740     * that any non-transparent parts of the Drawable are removed from the
15741     * given transparent region.
15742     *
15743     * @param dr The Drawable whose transparency is to be applied to the region.
15744     * @param region A Region holding the current transparency information,
15745     * where any parts of the region that are set are considered to be
15746     * transparent.  On return, this region will be modified to have the
15747     * transparency information reduced by the corresponding parts of the
15748     * Drawable that are not transparent.
15749     * {@hide}
15750     */
15751    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15752        if (DBG) {
15753            Log.i("View", "Getting transparent region for: " + this);
15754        }
15755        final Region r = dr.getTransparentRegion();
15756        final Rect db = dr.getBounds();
15757        final AttachInfo attachInfo = mAttachInfo;
15758        if (r != null && attachInfo != null) {
15759            final int w = getRight()-getLeft();
15760            final int h = getBottom()-getTop();
15761            if (db.left > 0) {
15762                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15763                r.op(0, 0, db.left, h, Region.Op.UNION);
15764            }
15765            if (db.right < w) {
15766                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15767                r.op(db.right, 0, w, h, Region.Op.UNION);
15768            }
15769            if (db.top > 0) {
15770                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15771                r.op(0, 0, w, db.top, Region.Op.UNION);
15772            }
15773            if (db.bottom < h) {
15774                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15775                r.op(0, db.bottom, w, h, Region.Op.UNION);
15776            }
15777            final int[] location = attachInfo.mTransparentLocation;
15778            getLocationInWindow(location);
15779            r.translate(location[0], location[1]);
15780            region.op(r, Region.Op.INTERSECT);
15781        } else {
15782            region.op(db, Region.Op.DIFFERENCE);
15783        }
15784    }
15785
15786    private void checkForLongClick(int delayOffset) {
15787        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15788            mHasPerformedLongPress = false;
15789
15790            if (mPendingCheckForLongPress == null) {
15791                mPendingCheckForLongPress = new CheckForLongPress();
15792            }
15793            mPendingCheckForLongPress.rememberWindowAttachCount();
15794            postDelayed(mPendingCheckForLongPress,
15795                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15796        }
15797    }
15798
15799    /**
15800     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15801     * LayoutInflater} class, which provides a full range of options for view inflation.
15802     *
15803     * @param context The Context object for your activity or application.
15804     * @param resource The resource ID to inflate
15805     * @param root A view group that will be the parent.  Used to properly inflate the
15806     * layout_* parameters.
15807     * @see LayoutInflater
15808     */
15809    public static View inflate(Context context, int resource, ViewGroup root) {
15810        LayoutInflater factory = LayoutInflater.from(context);
15811        return factory.inflate(resource, root);
15812    }
15813
15814    /**
15815     * Scroll the view with standard behavior for scrolling beyond the normal
15816     * content boundaries. Views that call this method should override
15817     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15818     * results of an over-scroll operation.
15819     *
15820     * Views can use this method to handle any touch or fling-based scrolling.
15821     *
15822     * @param deltaX Change in X in pixels
15823     * @param deltaY Change in Y in pixels
15824     * @param scrollX Current X scroll value in pixels before applying deltaX
15825     * @param scrollY Current Y scroll value in pixels before applying deltaY
15826     * @param scrollRangeX Maximum content scroll range along the X axis
15827     * @param scrollRangeY Maximum content scroll range along the Y axis
15828     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15829     *          along the X axis.
15830     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15831     *          along the Y axis.
15832     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15833     * @return true if scrolling was clamped to an over-scroll boundary along either
15834     *          axis, false otherwise.
15835     */
15836    @SuppressWarnings({"UnusedParameters"})
15837    protected boolean overScrollBy(int deltaX, int deltaY,
15838            int scrollX, int scrollY,
15839            int scrollRangeX, int scrollRangeY,
15840            int maxOverScrollX, int maxOverScrollY,
15841            boolean isTouchEvent) {
15842        final int overScrollMode = mOverScrollMode;
15843        final boolean canScrollHorizontal =
15844                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15845        final boolean canScrollVertical =
15846                computeVerticalScrollRange() > computeVerticalScrollExtent();
15847        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15848                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15849        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15850                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15851
15852        int newScrollX = scrollX + deltaX;
15853        if (!overScrollHorizontal) {
15854            maxOverScrollX = 0;
15855        }
15856
15857        int newScrollY = scrollY + deltaY;
15858        if (!overScrollVertical) {
15859            maxOverScrollY = 0;
15860        }
15861
15862        // Clamp values if at the limits and record
15863        final int left = -maxOverScrollX;
15864        final int right = maxOverScrollX + scrollRangeX;
15865        final int top = -maxOverScrollY;
15866        final int bottom = maxOverScrollY + scrollRangeY;
15867
15868        boolean clampedX = false;
15869        if (newScrollX > right) {
15870            newScrollX = right;
15871            clampedX = true;
15872        } else if (newScrollX < left) {
15873            newScrollX = left;
15874            clampedX = true;
15875        }
15876
15877        boolean clampedY = false;
15878        if (newScrollY > bottom) {
15879            newScrollY = bottom;
15880            clampedY = true;
15881        } else if (newScrollY < top) {
15882            newScrollY = top;
15883            clampedY = true;
15884        }
15885
15886        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15887
15888        return clampedX || clampedY;
15889    }
15890
15891    /**
15892     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15893     * respond to the results of an over-scroll operation.
15894     *
15895     * @param scrollX New X scroll value in pixels
15896     * @param scrollY New Y scroll value in pixels
15897     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15898     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15899     */
15900    protected void onOverScrolled(int scrollX, int scrollY,
15901            boolean clampedX, boolean clampedY) {
15902        // Intentionally empty.
15903    }
15904
15905    /**
15906     * Returns the over-scroll mode for this view. The result will be
15907     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15908     * (allow over-scrolling only if the view content is larger than the container),
15909     * or {@link #OVER_SCROLL_NEVER}.
15910     *
15911     * @return This view's over-scroll mode.
15912     */
15913    public int getOverScrollMode() {
15914        return mOverScrollMode;
15915    }
15916
15917    /**
15918     * Set the over-scroll mode for this view. Valid over-scroll modes are
15919     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15920     * (allow over-scrolling only if the view content is larger than the container),
15921     * or {@link #OVER_SCROLL_NEVER}.
15922     *
15923     * Setting the over-scroll mode of a view will have an effect only if the
15924     * view is capable of scrolling.
15925     *
15926     * @param overScrollMode The new over-scroll mode for this view.
15927     */
15928    public void setOverScrollMode(int overScrollMode) {
15929        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15930                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15931                overScrollMode != OVER_SCROLL_NEVER) {
15932            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15933        }
15934        mOverScrollMode = overScrollMode;
15935    }
15936
15937    /**
15938     * Gets a scale factor that determines the distance the view should scroll
15939     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15940     * @return The vertical scroll scale factor.
15941     * @hide
15942     */
15943    protected float getVerticalScrollFactor() {
15944        if (mVerticalScrollFactor == 0) {
15945            TypedValue outValue = new TypedValue();
15946            if (!mContext.getTheme().resolveAttribute(
15947                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15948                throw new IllegalStateException(
15949                        "Expected theme to define listPreferredItemHeight.");
15950            }
15951            mVerticalScrollFactor = outValue.getDimension(
15952                    mContext.getResources().getDisplayMetrics());
15953        }
15954        return mVerticalScrollFactor;
15955    }
15956
15957    /**
15958     * Gets a scale factor that determines the distance the view should scroll
15959     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15960     * @return The horizontal scroll scale factor.
15961     * @hide
15962     */
15963    protected float getHorizontalScrollFactor() {
15964        // TODO: Should use something else.
15965        return getVerticalScrollFactor();
15966    }
15967
15968    /**
15969     * Return the value specifying the text direction or policy that was set with
15970     * {@link #setTextDirection(int)}.
15971     *
15972     * @return the defined text direction. It can be one of:
15973     *
15974     * {@link #TEXT_DIRECTION_INHERIT},
15975     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15976     * {@link #TEXT_DIRECTION_ANY_RTL},
15977     * {@link #TEXT_DIRECTION_LTR},
15978     * {@link #TEXT_DIRECTION_RTL},
15979     * {@link #TEXT_DIRECTION_LOCALE}
15980     */
15981    @ViewDebug.ExportedProperty(category = "text", mapping = {
15982            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15983            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15984            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15985            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15986            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15987            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15988    })
15989    public int getTextDirection() {
15990        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15991    }
15992
15993    /**
15994     * Set the text direction.
15995     *
15996     * @param textDirection the direction to set. Should 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     */
16005    public void setTextDirection(int textDirection) {
16006        if (getTextDirection() != textDirection) {
16007            // Reset the current text direction and the resolved one
16008            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16009            resetResolvedTextDirection();
16010            // Set the new text direction
16011            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16012            // Refresh
16013            requestLayout();
16014            invalidate(true);
16015        }
16016    }
16017
16018    /**
16019     * Return the resolved text direction.
16020     *
16021     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16022     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16023     * up the parent chain of the view. if there is no parent, then it will return the default
16024     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16025     *
16026     * @return the resolved text direction. Returns one of:
16027     *
16028     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16029     * {@link #TEXT_DIRECTION_ANY_RTL},
16030     * {@link #TEXT_DIRECTION_LTR},
16031     * {@link #TEXT_DIRECTION_RTL},
16032     * {@link #TEXT_DIRECTION_LOCALE}
16033     */
16034    public int getResolvedTextDirection() {
16035        // The text direction will be resolved only if needed
16036        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16037            resolveTextDirection();
16038        }
16039        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16040    }
16041
16042    /**
16043     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16044     * resolution is done.
16045     */
16046    public void resolveTextDirection() {
16047        // Reset any previous text direction resolution
16048        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16049
16050        if (hasRtlSupport()) {
16051            // Set resolved text direction flag depending on text direction flag
16052            final int textDirection = getTextDirection();
16053            switch(textDirection) {
16054                case TEXT_DIRECTION_INHERIT:
16055                    if (canResolveTextDirection()) {
16056                        ViewGroup viewGroup = ((ViewGroup) mParent);
16057
16058                        // Set current resolved direction to the same value as the parent's one
16059                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16060                        switch (parentResolvedDirection) {
16061                            case TEXT_DIRECTION_FIRST_STRONG:
16062                            case TEXT_DIRECTION_ANY_RTL:
16063                            case TEXT_DIRECTION_LTR:
16064                            case TEXT_DIRECTION_RTL:
16065                            case TEXT_DIRECTION_LOCALE:
16066                                mPrivateFlags2 |=
16067                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16068                                break;
16069                            default:
16070                                // Default resolved direction is "first strong" heuristic
16071                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16072                        }
16073                    } else {
16074                        // We cannot do the resolution if there is no parent, so use the default one
16075                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16076                    }
16077                    break;
16078                case TEXT_DIRECTION_FIRST_STRONG:
16079                case TEXT_DIRECTION_ANY_RTL:
16080                case TEXT_DIRECTION_LTR:
16081                case TEXT_DIRECTION_RTL:
16082                case TEXT_DIRECTION_LOCALE:
16083                    // Resolved direction is the same as text direction
16084                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16085                    break;
16086                default:
16087                    // Default resolved direction is "first strong" heuristic
16088                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16089            }
16090        } else {
16091            // Default resolved direction is "first strong" heuristic
16092            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16093        }
16094
16095        // Set to resolved
16096        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16097        onResolvedTextDirectionChanged();
16098    }
16099
16100    /**
16101     * Called when text direction has been resolved. Subclasses that care about text direction
16102     * resolution should override this method.
16103     *
16104     * The default implementation does nothing.
16105     */
16106    public void onResolvedTextDirectionChanged() {
16107    }
16108
16109    /**
16110     * Check if text direction resolution can be done.
16111     *
16112     * @return true if text direction resolution can be done otherwise return false.
16113     */
16114    public boolean canResolveTextDirection() {
16115        switch (getTextDirection()) {
16116            case TEXT_DIRECTION_INHERIT:
16117                return (mParent != null) && (mParent instanceof ViewGroup);
16118            default:
16119                return true;
16120        }
16121    }
16122
16123    /**
16124     * Reset resolved text direction. Text direction can be resolved with a call to
16125     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16126     * reset is done.
16127     */
16128    public void resetResolvedTextDirection() {
16129        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16130        onResolvedTextDirectionReset();
16131    }
16132
16133    /**
16134     * Called when text direction is reset. Subclasses that care about text direction reset should
16135     * override this method and do a reset of the text direction of their children. The default
16136     * implementation does nothing.
16137     */
16138    public void onResolvedTextDirectionReset() {
16139    }
16140
16141    /**
16142     * Return the value specifying the text alignment or policy that was set with
16143     * {@link #setTextAlignment(int)}.
16144     *
16145     * @return the defined text alignment. It can be one of:
16146     *
16147     * {@link #TEXT_ALIGNMENT_INHERIT},
16148     * {@link #TEXT_ALIGNMENT_GRAVITY},
16149     * {@link #TEXT_ALIGNMENT_CENTER},
16150     * {@link #TEXT_ALIGNMENT_TEXT_START},
16151     * {@link #TEXT_ALIGNMENT_TEXT_END},
16152     * {@link #TEXT_ALIGNMENT_VIEW_START},
16153     * {@link #TEXT_ALIGNMENT_VIEW_END}
16154     */
16155    @ViewDebug.ExportedProperty(category = "text", mapping = {
16156            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16157            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16158            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16159            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16160            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16161            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16162            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16163    })
16164    public int getTextAlignment() {
16165        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16166    }
16167
16168    /**
16169     * Set the text alignment.
16170     *
16171     * @param textAlignment The text alignment to set. Should be one of
16172     *
16173     * {@link #TEXT_ALIGNMENT_INHERIT},
16174     * {@link #TEXT_ALIGNMENT_GRAVITY},
16175     * {@link #TEXT_ALIGNMENT_CENTER},
16176     * {@link #TEXT_ALIGNMENT_TEXT_START},
16177     * {@link #TEXT_ALIGNMENT_TEXT_END},
16178     * {@link #TEXT_ALIGNMENT_VIEW_START},
16179     * {@link #TEXT_ALIGNMENT_VIEW_END}
16180     *
16181     * @attr ref android.R.styleable#View_textAlignment
16182     */
16183    public void setTextAlignment(int textAlignment) {
16184        if (textAlignment != getTextAlignment()) {
16185            // Reset the current and resolved text alignment
16186            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16187            resetResolvedTextAlignment();
16188            // Set the new text alignment
16189            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16190            // Refresh
16191            requestLayout();
16192            invalidate(true);
16193        }
16194    }
16195
16196    /**
16197     * Return the resolved text alignment.
16198     *
16199     * The resolved text alignment. This needs resolution if the value is
16200     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16201     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16202     *
16203     * @return the resolved text alignment. Returns one of:
16204     *
16205     * {@link #TEXT_ALIGNMENT_GRAVITY},
16206     * {@link #TEXT_ALIGNMENT_CENTER},
16207     * {@link #TEXT_ALIGNMENT_TEXT_START},
16208     * {@link #TEXT_ALIGNMENT_TEXT_END},
16209     * {@link #TEXT_ALIGNMENT_VIEW_START},
16210     * {@link #TEXT_ALIGNMENT_VIEW_END}
16211     */
16212    @ViewDebug.ExportedProperty(category = "text", mapping = {
16213            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16214            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16215            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16216            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16217            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16218            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16219            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16220    })
16221    public int getResolvedTextAlignment() {
16222        // If text alignment is not resolved, then resolve it
16223        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16224            resolveTextAlignment();
16225        }
16226        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16227    }
16228
16229    /**
16230     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16231     * resolution is done.
16232     */
16233    public void resolveTextAlignment() {
16234        // Reset any previous text alignment resolution
16235        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16236
16237        if (hasRtlSupport()) {
16238            // Set resolved text alignment flag depending on text alignment flag
16239            final int textAlignment = getTextAlignment();
16240            switch (textAlignment) {
16241                case TEXT_ALIGNMENT_INHERIT:
16242                    // Check if we can resolve the text alignment
16243                    if (canResolveLayoutDirection() && mParent instanceof View) {
16244                        View view = (View) mParent;
16245
16246                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16247                        switch (parentResolvedTextAlignment) {
16248                            case TEXT_ALIGNMENT_GRAVITY:
16249                            case TEXT_ALIGNMENT_TEXT_START:
16250                            case TEXT_ALIGNMENT_TEXT_END:
16251                            case TEXT_ALIGNMENT_CENTER:
16252                            case TEXT_ALIGNMENT_VIEW_START:
16253                            case TEXT_ALIGNMENT_VIEW_END:
16254                                // Resolved text alignment is the same as the parent resolved
16255                                // text alignment
16256                                mPrivateFlags2 |=
16257                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16258                                break;
16259                            default:
16260                                // Use default resolved text alignment
16261                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16262                        }
16263                    }
16264                    else {
16265                        // We cannot do the resolution if there is no parent so use the default
16266                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16267                    }
16268                    break;
16269                case TEXT_ALIGNMENT_GRAVITY:
16270                case TEXT_ALIGNMENT_TEXT_START:
16271                case TEXT_ALIGNMENT_TEXT_END:
16272                case TEXT_ALIGNMENT_CENTER:
16273                case TEXT_ALIGNMENT_VIEW_START:
16274                case TEXT_ALIGNMENT_VIEW_END:
16275                    // Resolved text alignment is the same as text alignment
16276                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16277                    break;
16278                default:
16279                    // Use default resolved text alignment
16280                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16281            }
16282        } else {
16283            // Use default resolved text alignment
16284            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16285        }
16286
16287        // Set the resolved
16288        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16289        onResolvedTextAlignmentChanged();
16290    }
16291
16292    /**
16293     * Check if text alignment resolution can be done.
16294     *
16295     * @return true if text alignment resolution can be done otherwise return false.
16296     */
16297    public boolean canResolveTextAlignment() {
16298        switch (getTextAlignment()) {
16299            case TEXT_DIRECTION_INHERIT:
16300                return (mParent != null);
16301            default:
16302                return true;
16303        }
16304    }
16305
16306    /**
16307     * Called when text alignment has been resolved. Subclasses that care about text alignment
16308     * resolution should override this method.
16309     *
16310     * The default implementation does nothing.
16311     */
16312    public void onResolvedTextAlignmentChanged() {
16313    }
16314
16315    /**
16316     * Reset resolved text alignment. Text alignment can be resolved with a call to
16317     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16318     * reset is done.
16319     */
16320    public void resetResolvedTextAlignment() {
16321        // Reset any previous text alignment resolution
16322        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16323        onResolvedTextAlignmentReset();
16324    }
16325
16326    /**
16327     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16328     * override this method and do a reset of the text alignment of their children. The default
16329     * implementation does nothing.
16330     */
16331    public void onResolvedTextAlignmentReset() {
16332    }
16333
16334    //
16335    // Properties
16336    //
16337    /**
16338     * A Property wrapper around the <code>alpha</code> functionality handled by the
16339     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16340     */
16341    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16342        @Override
16343        public void setValue(View object, float value) {
16344            object.setAlpha(value);
16345        }
16346
16347        @Override
16348        public Float get(View object) {
16349            return object.getAlpha();
16350        }
16351    };
16352
16353    /**
16354     * A Property wrapper around the <code>translationX</code> functionality handled by the
16355     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16356     */
16357    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16358        @Override
16359        public void setValue(View object, float value) {
16360            object.setTranslationX(value);
16361        }
16362
16363                @Override
16364        public Float get(View object) {
16365            return object.getTranslationX();
16366        }
16367    };
16368
16369    /**
16370     * A Property wrapper around the <code>translationY</code> functionality handled by the
16371     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16372     */
16373    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16374        @Override
16375        public void setValue(View object, float value) {
16376            object.setTranslationY(value);
16377        }
16378
16379        @Override
16380        public Float get(View object) {
16381            return object.getTranslationY();
16382        }
16383    };
16384
16385    /**
16386     * A Property wrapper around the <code>x</code> functionality handled by the
16387     * {@link View#setX(float)} and {@link View#getX()} methods.
16388     */
16389    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16390        @Override
16391        public void setValue(View object, float value) {
16392            object.setX(value);
16393        }
16394
16395        @Override
16396        public Float get(View object) {
16397            return object.getX();
16398        }
16399    };
16400
16401    /**
16402     * A Property wrapper around the <code>y</code> functionality handled by the
16403     * {@link View#setY(float)} and {@link View#getY()} methods.
16404     */
16405    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16406        @Override
16407        public void setValue(View object, float value) {
16408            object.setY(value);
16409        }
16410
16411        @Override
16412        public Float get(View object) {
16413            return object.getY();
16414        }
16415    };
16416
16417    /**
16418     * A Property wrapper around the <code>rotation</code> functionality handled by the
16419     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16420     */
16421    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16422        @Override
16423        public void setValue(View object, float value) {
16424            object.setRotation(value);
16425        }
16426
16427        @Override
16428        public Float get(View object) {
16429            return object.getRotation();
16430        }
16431    };
16432
16433    /**
16434     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16435     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16436     */
16437    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16438        @Override
16439        public void setValue(View object, float value) {
16440            object.setRotationX(value);
16441        }
16442
16443        @Override
16444        public Float get(View object) {
16445            return object.getRotationX();
16446        }
16447    };
16448
16449    /**
16450     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16451     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16452     */
16453    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16454        @Override
16455        public void setValue(View object, float value) {
16456            object.setRotationY(value);
16457        }
16458
16459        @Override
16460        public Float get(View object) {
16461            return object.getRotationY();
16462        }
16463    };
16464
16465    /**
16466     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16467     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16468     */
16469    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16470        @Override
16471        public void setValue(View object, float value) {
16472            object.setScaleX(value);
16473        }
16474
16475        @Override
16476        public Float get(View object) {
16477            return object.getScaleX();
16478        }
16479    };
16480
16481    /**
16482     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16483     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16484     */
16485    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16486        @Override
16487        public void setValue(View object, float value) {
16488            object.setScaleY(value);
16489        }
16490
16491        @Override
16492        public Float get(View object) {
16493            return object.getScaleY();
16494        }
16495    };
16496
16497    /**
16498     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16499     * Each MeasureSpec represents a requirement for either the width or the height.
16500     * A MeasureSpec is comprised of a size and a mode. There are three possible
16501     * modes:
16502     * <dl>
16503     * <dt>UNSPECIFIED</dt>
16504     * <dd>
16505     * The parent has not imposed any constraint on the child. It can be whatever size
16506     * it wants.
16507     * </dd>
16508     *
16509     * <dt>EXACTLY</dt>
16510     * <dd>
16511     * The parent has determined an exact size for the child. The child is going to be
16512     * given those bounds regardless of how big it wants to be.
16513     * </dd>
16514     *
16515     * <dt>AT_MOST</dt>
16516     * <dd>
16517     * The child can be as large as it wants up to the specified size.
16518     * </dd>
16519     * </dl>
16520     *
16521     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16522     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16523     */
16524    public static class MeasureSpec {
16525        private static final int MODE_SHIFT = 30;
16526        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16527
16528        /**
16529         * Measure specification mode: The parent has not imposed any constraint
16530         * on the child. It can be whatever size it wants.
16531         */
16532        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16533
16534        /**
16535         * Measure specification mode: The parent has determined an exact size
16536         * for the child. The child is going to be given those bounds regardless
16537         * of how big it wants to be.
16538         */
16539        public static final int EXACTLY     = 1 << MODE_SHIFT;
16540
16541        /**
16542         * Measure specification mode: The child can be as large as it wants up
16543         * to the specified size.
16544         */
16545        public static final int AT_MOST     = 2 << MODE_SHIFT;
16546
16547        /**
16548         * Creates a measure specification based on the supplied size and mode.
16549         *
16550         * The mode must always be one of the following:
16551         * <ul>
16552         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16553         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16554         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16555         * </ul>
16556         *
16557         * @param size the size of the measure specification
16558         * @param mode the mode of the measure specification
16559         * @return the measure specification based on size and mode
16560         */
16561        public static int makeMeasureSpec(int size, int mode) {
16562            return size + mode;
16563        }
16564
16565        /**
16566         * Extracts the mode from the supplied measure specification.
16567         *
16568         * @param measureSpec the measure specification to extract the mode from
16569         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16570         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16571         *         {@link android.view.View.MeasureSpec#EXACTLY}
16572         */
16573        public static int getMode(int measureSpec) {
16574            return (measureSpec & MODE_MASK);
16575        }
16576
16577        /**
16578         * Extracts the size from the supplied measure specification.
16579         *
16580         * @param measureSpec the measure specification to extract the size from
16581         * @return the size in pixels defined in the supplied measure specification
16582         */
16583        public static int getSize(int measureSpec) {
16584            return (measureSpec & ~MODE_MASK);
16585        }
16586
16587        /**
16588         * Returns a String representation of the specified measure
16589         * specification.
16590         *
16591         * @param measureSpec the measure specification to convert to a String
16592         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16593         */
16594        public static String toString(int measureSpec) {
16595            int mode = getMode(measureSpec);
16596            int size = getSize(measureSpec);
16597
16598            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16599
16600            if (mode == UNSPECIFIED)
16601                sb.append("UNSPECIFIED ");
16602            else if (mode == EXACTLY)
16603                sb.append("EXACTLY ");
16604            else if (mode == AT_MOST)
16605                sb.append("AT_MOST ");
16606            else
16607                sb.append(mode).append(" ");
16608
16609            sb.append(size);
16610            return sb.toString();
16611        }
16612    }
16613
16614    class CheckForLongPress implements Runnable {
16615
16616        private int mOriginalWindowAttachCount;
16617
16618        public void run() {
16619            if (isPressed() && (mParent != null)
16620                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16621                if (performLongClick()) {
16622                    mHasPerformedLongPress = true;
16623                }
16624            }
16625        }
16626
16627        public void rememberWindowAttachCount() {
16628            mOriginalWindowAttachCount = mWindowAttachCount;
16629        }
16630    }
16631
16632    private final class CheckForTap implements Runnable {
16633        public void run() {
16634            mPrivateFlags &= ~PREPRESSED;
16635            setPressed(true);
16636            checkForLongClick(ViewConfiguration.getTapTimeout());
16637        }
16638    }
16639
16640    private final class PerformClick implements Runnable {
16641        public void run() {
16642            performClick();
16643        }
16644    }
16645
16646    /** @hide */
16647    public void hackTurnOffWindowResizeAnim(boolean off) {
16648        mAttachInfo.mTurnOffWindowResizeAnim = off;
16649    }
16650
16651    /**
16652     * This method returns a ViewPropertyAnimator object, which can be used to animate
16653     * specific properties on this View.
16654     *
16655     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16656     */
16657    public ViewPropertyAnimator animate() {
16658        if (mAnimator == null) {
16659            mAnimator = new ViewPropertyAnimator(this);
16660        }
16661        return mAnimator;
16662    }
16663
16664    /**
16665     * Interface definition for a callback to be invoked when a key event is
16666     * dispatched to this view. The callback will be invoked before the key
16667     * event is given to the view.
16668     */
16669    public interface OnKeyListener {
16670        /**
16671         * Called when a key is dispatched to a view. This allows listeners to
16672         * get a chance to respond before the target view.
16673         *
16674         * @param v The view the key has been dispatched to.
16675         * @param keyCode The code for the physical key that was pressed
16676         * @param event The KeyEvent object containing full information about
16677         *        the event.
16678         * @return True if the listener has consumed the event, false otherwise.
16679         */
16680        boolean onKey(View v, int keyCode, KeyEvent event);
16681    }
16682
16683    /**
16684     * Interface definition for a callback to be invoked when a touch event is
16685     * dispatched to this view. The callback will be invoked before the touch
16686     * event is given to the view.
16687     */
16688    public interface OnTouchListener {
16689        /**
16690         * Called when a touch event is dispatched to a view. This allows listeners to
16691         * get a chance to respond before the target view.
16692         *
16693         * @param v The view the touch event has been dispatched to.
16694         * @param event The MotionEvent object containing full information about
16695         *        the event.
16696         * @return True if the listener has consumed the event, false otherwise.
16697         */
16698        boolean onTouch(View v, MotionEvent event);
16699    }
16700
16701    /**
16702     * Interface definition for a callback to be invoked when a hover event is
16703     * dispatched to this view. The callback will be invoked before the hover
16704     * event is given to the view.
16705     */
16706    public interface OnHoverListener {
16707        /**
16708         * Called when a hover event is dispatched to a view. This allows listeners to
16709         * get a chance to respond before the target view.
16710         *
16711         * @param v The view the hover event has been dispatched to.
16712         * @param event The MotionEvent object containing full information about
16713         *        the event.
16714         * @return True if the listener has consumed the event, false otherwise.
16715         */
16716        boolean onHover(View v, MotionEvent event);
16717    }
16718
16719    /**
16720     * Interface definition for a callback to be invoked when a generic motion event is
16721     * dispatched to this view. The callback will be invoked before the generic motion
16722     * event is given to the view.
16723     */
16724    public interface OnGenericMotionListener {
16725        /**
16726         * Called when a generic motion event is dispatched to a view. This allows listeners to
16727         * get a chance to respond before the target view.
16728         *
16729         * @param v The view the generic motion event has been dispatched to.
16730         * @param event The MotionEvent object containing full information about
16731         *        the event.
16732         * @return True if the listener has consumed the event, false otherwise.
16733         */
16734        boolean onGenericMotion(View v, MotionEvent event);
16735    }
16736
16737    /**
16738     * Interface definition for a callback to be invoked when a view has been clicked and held.
16739     */
16740    public interface OnLongClickListener {
16741        /**
16742         * Called when a view has been clicked and held.
16743         *
16744         * @param v The view that was clicked and held.
16745         *
16746         * @return true if the callback consumed the long click, false otherwise.
16747         */
16748        boolean onLongClick(View v);
16749    }
16750
16751    /**
16752     * Interface definition for a callback to be invoked when a drag is being dispatched
16753     * to this view.  The callback will be invoked before the hosting view's own
16754     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16755     * onDrag(event) behavior, it should return 'false' from this callback.
16756     *
16757     * <div class="special reference">
16758     * <h3>Developer Guides</h3>
16759     * <p>For a guide to implementing drag and drop features, read the
16760     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16761     * </div>
16762     */
16763    public interface OnDragListener {
16764        /**
16765         * Called when a drag event is dispatched to a view. This allows listeners
16766         * to get a chance to override base View behavior.
16767         *
16768         * @param v The View that received the drag event.
16769         * @param event The {@link android.view.DragEvent} object for the drag event.
16770         * @return {@code true} if the drag event was handled successfully, or {@code false}
16771         * if the drag event was not handled. Note that {@code false} will trigger the View
16772         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16773         */
16774        boolean onDrag(View v, DragEvent event);
16775    }
16776
16777    /**
16778     * Interface definition for a callback to be invoked when the focus state of
16779     * a view changed.
16780     */
16781    public interface OnFocusChangeListener {
16782        /**
16783         * Called when the focus state of a view has changed.
16784         *
16785         * @param v The view whose state has changed.
16786         * @param hasFocus The new focus state of v.
16787         */
16788        void onFocusChange(View v, boolean hasFocus);
16789    }
16790
16791    /**
16792     * Interface definition for a callback to be invoked when a view is clicked.
16793     */
16794    public interface OnClickListener {
16795        /**
16796         * Called when a view has been clicked.
16797         *
16798         * @param v The view that was clicked.
16799         */
16800        void onClick(View v);
16801    }
16802
16803    /**
16804     * Interface definition for a callback to be invoked when the context menu
16805     * for this view is being built.
16806     */
16807    public interface OnCreateContextMenuListener {
16808        /**
16809         * Called when the context menu for this view is being built. It is not
16810         * safe to hold onto the menu after this method returns.
16811         *
16812         * @param menu The context menu that is being built
16813         * @param v The view for which the context menu is being built
16814         * @param menuInfo Extra information about the item for which the
16815         *            context menu should be shown. This information will vary
16816         *            depending on the class of v.
16817         */
16818        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16819    }
16820
16821    /**
16822     * Interface definition for a callback to be invoked when the status bar changes
16823     * visibility.  This reports <strong>global</strong> changes to the system UI
16824     * state, not just what the application is requesting.
16825     *
16826     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16827     */
16828    public interface OnSystemUiVisibilityChangeListener {
16829        /**
16830         * Called when the status bar changes visibility because of a call to
16831         * {@link View#setSystemUiVisibility(int)}.
16832         *
16833         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16834         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16835         * <strong>global</strong> state of the UI visibility flags, not what your
16836         * app is currently applying.
16837         */
16838        public void onSystemUiVisibilityChange(int visibility);
16839    }
16840
16841    /**
16842     * Interface definition for a callback to be invoked when this view is attached
16843     * or detached from its window.
16844     */
16845    public interface OnAttachStateChangeListener {
16846        /**
16847         * Called when the view is attached to a window.
16848         * @param v The view that was attached
16849         */
16850        public void onViewAttachedToWindow(View v);
16851        /**
16852         * Called when the view is detached from a window.
16853         * @param v The view that was detached
16854         */
16855        public void onViewDetachedFromWindow(View v);
16856    }
16857
16858    private final class UnsetPressedState implements Runnable {
16859        public void run() {
16860            setPressed(false);
16861        }
16862    }
16863
16864    /**
16865     * Base class for derived classes that want to save and restore their own
16866     * state in {@link android.view.View#onSaveInstanceState()}.
16867     */
16868    public static class BaseSavedState extends AbsSavedState {
16869        /**
16870         * Constructor used when reading from a parcel. Reads the state of the superclass.
16871         *
16872         * @param source
16873         */
16874        public BaseSavedState(Parcel source) {
16875            super(source);
16876        }
16877
16878        /**
16879         * Constructor called by derived classes when creating their SavedState objects
16880         *
16881         * @param superState The state of the superclass of this view
16882         */
16883        public BaseSavedState(Parcelable superState) {
16884            super(superState);
16885        }
16886
16887        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16888                new Parcelable.Creator<BaseSavedState>() {
16889            public BaseSavedState createFromParcel(Parcel in) {
16890                return new BaseSavedState(in);
16891            }
16892
16893            public BaseSavedState[] newArray(int size) {
16894                return new BaseSavedState[size];
16895            }
16896        };
16897    }
16898
16899    /**
16900     * A set of information given to a view when it is attached to its parent
16901     * window.
16902     */
16903    static class AttachInfo {
16904        interface Callbacks {
16905            void playSoundEffect(int effectId);
16906            boolean performHapticFeedback(int effectId, boolean always);
16907        }
16908
16909        /**
16910         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16911         * to a Handler. This class contains the target (View) to invalidate and
16912         * the coordinates of the dirty rectangle.
16913         *
16914         * For performance purposes, this class also implements a pool of up to
16915         * POOL_LIMIT objects that get reused. This reduces memory allocations
16916         * whenever possible.
16917         */
16918        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16919            private static final int POOL_LIMIT = 10;
16920            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16921                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16922                        public InvalidateInfo newInstance() {
16923                            return new InvalidateInfo();
16924                        }
16925
16926                        public void onAcquired(InvalidateInfo element) {
16927                        }
16928
16929                        public void onReleased(InvalidateInfo element) {
16930                            element.target = null;
16931                        }
16932                    }, POOL_LIMIT)
16933            );
16934
16935            private InvalidateInfo mNext;
16936            private boolean mIsPooled;
16937
16938            View target;
16939
16940            int left;
16941            int top;
16942            int right;
16943            int bottom;
16944
16945            public void setNextPoolable(InvalidateInfo element) {
16946                mNext = element;
16947            }
16948
16949            public InvalidateInfo getNextPoolable() {
16950                return mNext;
16951            }
16952
16953            static InvalidateInfo acquire() {
16954                return sPool.acquire();
16955            }
16956
16957            void release() {
16958                sPool.release(this);
16959            }
16960
16961            public boolean isPooled() {
16962                return mIsPooled;
16963            }
16964
16965            public void setPooled(boolean isPooled) {
16966                mIsPooled = isPooled;
16967            }
16968        }
16969
16970        final IWindowSession mSession;
16971
16972        final IWindow mWindow;
16973
16974        final IBinder mWindowToken;
16975
16976        final Callbacks mRootCallbacks;
16977
16978        HardwareCanvas mHardwareCanvas;
16979
16980        /**
16981         * The top view of the hierarchy.
16982         */
16983        View mRootView;
16984
16985        IBinder mPanelParentWindowToken;
16986        Surface mSurface;
16987
16988        boolean mHardwareAccelerated;
16989        boolean mHardwareAccelerationRequested;
16990        HardwareRenderer mHardwareRenderer;
16991
16992        boolean mScreenOn;
16993
16994        /**
16995         * Scale factor used by the compatibility mode
16996         */
16997        float mApplicationScale;
16998
16999        /**
17000         * Indicates whether the application is in compatibility mode
17001         */
17002        boolean mScalingRequired;
17003
17004        /**
17005         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17006         */
17007        boolean mTurnOffWindowResizeAnim;
17008
17009        /**
17010         * Left position of this view's window
17011         */
17012        int mWindowLeft;
17013
17014        /**
17015         * Top position of this view's window
17016         */
17017        int mWindowTop;
17018
17019        /**
17020         * Indicates whether views need to use 32-bit drawing caches
17021         */
17022        boolean mUse32BitDrawingCache;
17023
17024        /**
17025         * Describes the parts of the window that are currently completely
17026         * obscured by system UI elements.
17027         */
17028        final Rect mSystemInsets = new Rect();
17029
17030        /**
17031         * For windows that are full-screen but using insets to layout inside
17032         * of the screen decorations, these are the current insets for the
17033         * content of the window.
17034         */
17035        final Rect mContentInsets = new Rect();
17036
17037        /**
17038         * For windows that are full-screen but using insets to layout inside
17039         * of the screen decorations, these are the current insets for the
17040         * actual visible parts of the window.
17041         */
17042        final Rect mVisibleInsets = new Rect();
17043
17044        /**
17045         * The internal insets given by this window.  This value is
17046         * supplied by the client (through
17047         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17048         * be given to the window manager when changed to be used in laying
17049         * out windows behind it.
17050         */
17051        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17052                = new ViewTreeObserver.InternalInsetsInfo();
17053
17054        /**
17055         * All views in the window's hierarchy that serve as scroll containers,
17056         * used to determine if the window can be resized or must be panned
17057         * to adjust for a soft input area.
17058         */
17059        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17060
17061        final KeyEvent.DispatcherState mKeyDispatchState
17062                = new KeyEvent.DispatcherState();
17063
17064        /**
17065         * Indicates whether the view's window currently has the focus.
17066         */
17067        boolean mHasWindowFocus;
17068
17069        /**
17070         * The current visibility of the window.
17071         */
17072        int mWindowVisibility;
17073
17074        /**
17075         * Indicates the time at which drawing started to occur.
17076         */
17077        long mDrawingTime;
17078
17079        /**
17080         * Indicates whether or not ignoring the DIRTY_MASK flags.
17081         */
17082        boolean mIgnoreDirtyState;
17083
17084        /**
17085         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17086         * to avoid clearing that flag prematurely.
17087         */
17088        boolean mSetIgnoreDirtyState = false;
17089
17090        /**
17091         * Indicates whether the view's window is currently in touch mode.
17092         */
17093        boolean mInTouchMode;
17094
17095        /**
17096         * Indicates that ViewAncestor should trigger a global layout change
17097         * the next time it performs a traversal
17098         */
17099        boolean mRecomputeGlobalAttributes;
17100
17101        /**
17102         * Always report new attributes at next traversal.
17103         */
17104        boolean mForceReportNewAttributes;
17105
17106        /**
17107         * Set during a traveral if any views want to keep the screen on.
17108         */
17109        boolean mKeepScreenOn;
17110
17111        /**
17112         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17113         */
17114        int mSystemUiVisibility;
17115
17116        /**
17117         * Hack to force certain system UI visibility flags to be cleared.
17118         */
17119        int mDisabledSystemUiVisibility;
17120
17121        /**
17122         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17123         * attached.
17124         */
17125        boolean mHasSystemUiListeners;
17126
17127        /**
17128         * Set if the visibility of any views has changed.
17129         */
17130        boolean mViewVisibilityChanged;
17131
17132        /**
17133         * Set to true if a view has been scrolled.
17134         */
17135        boolean mViewScrollChanged;
17136
17137        /**
17138         * Global to the view hierarchy used as a temporary for dealing with
17139         * x/y points in the transparent region computations.
17140         */
17141        final int[] mTransparentLocation = new int[2];
17142
17143        /**
17144         * Global to the view hierarchy used as a temporary for dealing with
17145         * x/y points in the ViewGroup.invalidateChild implementation.
17146         */
17147        final int[] mInvalidateChildLocation = new int[2];
17148
17149
17150        /**
17151         * Global to the view hierarchy used as a temporary for dealing with
17152         * x/y location when view is transformed.
17153         */
17154        final float[] mTmpTransformLocation = new float[2];
17155
17156        /**
17157         * The view tree observer used to dispatch global events like
17158         * layout, pre-draw, touch mode change, etc.
17159         */
17160        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17161
17162        /**
17163         * A Canvas used by the view hierarchy to perform bitmap caching.
17164         */
17165        Canvas mCanvas;
17166
17167        /**
17168         * The view root impl.
17169         */
17170        final ViewRootImpl mViewRootImpl;
17171
17172        /**
17173         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17174         * handler can be used to pump events in the UI events queue.
17175         */
17176        final Handler mHandler;
17177
17178        /**
17179         * Temporary for use in computing invalidate rectangles while
17180         * calling up the hierarchy.
17181         */
17182        final Rect mTmpInvalRect = new Rect();
17183
17184        /**
17185         * Temporary for use in computing hit areas with transformed views
17186         */
17187        final RectF mTmpTransformRect = new RectF();
17188
17189        /**
17190         * Temporary list for use in collecting focusable descendents of a view.
17191         */
17192        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17193
17194        /**
17195         * The id of the window for accessibility purposes.
17196         */
17197        int mAccessibilityWindowId = View.NO_ID;
17198
17199        /**
17200         * Whether to ingore not exposed for accessibility Views when
17201         * reporting the view tree to accessibility services.
17202         */
17203        boolean mIncludeNotImportantViews;
17204
17205        /**
17206         * The drawable for highlighting accessibility focus.
17207         */
17208        Drawable mAccessibilityFocusDrawable;
17209
17210        /**
17211         * Show where the margins, bounds and layout bounds are for each view.
17212         */
17213        final boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17214
17215        /**
17216         * Point used to compute visible regions.
17217         */
17218        final Point mPoint = new Point();
17219
17220        /**
17221         * Creates a new set of attachment information with the specified
17222         * events handler and thread.
17223         *
17224         * @param handler the events handler the view must use
17225         */
17226        AttachInfo(IWindowSession session, IWindow window,
17227                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17228            mSession = session;
17229            mWindow = window;
17230            mWindowToken = window.asBinder();
17231            mViewRootImpl = viewRootImpl;
17232            mHandler = handler;
17233            mRootCallbacks = effectPlayer;
17234        }
17235    }
17236
17237    /**
17238     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17239     * is supported. This avoids keeping too many unused fields in most
17240     * instances of View.</p>
17241     */
17242    private static class ScrollabilityCache implements Runnable {
17243
17244        /**
17245         * Scrollbars are not visible
17246         */
17247        public static final int OFF = 0;
17248
17249        /**
17250         * Scrollbars are visible
17251         */
17252        public static final int ON = 1;
17253
17254        /**
17255         * Scrollbars are fading away
17256         */
17257        public static final int FADING = 2;
17258
17259        public boolean fadeScrollBars;
17260
17261        public int fadingEdgeLength;
17262        public int scrollBarDefaultDelayBeforeFade;
17263        public int scrollBarFadeDuration;
17264
17265        public int scrollBarSize;
17266        public ScrollBarDrawable scrollBar;
17267        public float[] interpolatorValues;
17268        public View host;
17269
17270        public final Paint paint;
17271        public final Matrix matrix;
17272        public Shader shader;
17273
17274        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17275
17276        private static final float[] OPAQUE = { 255 };
17277        private static final float[] TRANSPARENT = { 0.0f };
17278
17279        /**
17280         * When fading should start. This time moves into the future every time
17281         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17282         */
17283        public long fadeStartTime;
17284
17285
17286        /**
17287         * The current state of the scrollbars: ON, OFF, or FADING
17288         */
17289        public int state = OFF;
17290
17291        private int mLastColor;
17292
17293        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17294            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17295            scrollBarSize = configuration.getScaledScrollBarSize();
17296            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17297            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17298
17299            paint = new Paint();
17300            matrix = new Matrix();
17301            // use use a height of 1, and then wack the matrix each time we
17302            // actually use it.
17303            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17304
17305            paint.setShader(shader);
17306            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17307            this.host = host;
17308        }
17309
17310        public void setFadeColor(int color) {
17311            if (color != 0 && color != mLastColor) {
17312                mLastColor = color;
17313                color |= 0xFF000000;
17314
17315                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17316                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17317
17318                paint.setShader(shader);
17319                // Restore the default transfer mode (src_over)
17320                paint.setXfermode(null);
17321            }
17322        }
17323
17324        public void run() {
17325            long now = AnimationUtils.currentAnimationTimeMillis();
17326            if (now >= fadeStartTime) {
17327
17328                // the animation fades the scrollbars out by changing
17329                // the opacity (alpha) from fully opaque to fully
17330                // transparent
17331                int nextFrame = (int) now;
17332                int framesCount = 0;
17333
17334                Interpolator interpolator = scrollBarInterpolator;
17335
17336                // Start opaque
17337                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17338
17339                // End transparent
17340                nextFrame += scrollBarFadeDuration;
17341                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17342
17343                state = FADING;
17344
17345                // Kick off the fade animation
17346                host.invalidate(true);
17347            }
17348        }
17349    }
17350
17351    /**
17352     * Resuable callback for sending
17353     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17354     */
17355    private class SendViewScrolledAccessibilityEvent implements Runnable {
17356        public volatile boolean mIsPending;
17357
17358        public void run() {
17359            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17360            mIsPending = false;
17361        }
17362    }
17363
17364    /**
17365     * <p>
17366     * This class represents a delegate that can be registered in a {@link View}
17367     * to enhance accessibility support via composition rather via inheritance.
17368     * It is specifically targeted to widget developers that extend basic View
17369     * classes i.e. classes in package android.view, that would like their
17370     * applications to be backwards compatible.
17371     * </p>
17372     * <div class="special reference">
17373     * <h3>Developer Guides</h3>
17374     * <p>For more information about making applications accessible, read the
17375     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17376     * developer guide.</p>
17377     * </div>
17378     * <p>
17379     * A scenario in which a developer would like to use an accessibility delegate
17380     * is overriding a method introduced in a later API version then the minimal API
17381     * version supported by the application. For example, the method
17382     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17383     * in API version 4 when the accessibility APIs were first introduced. If a
17384     * developer would like his application to run on API version 4 devices (assuming
17385     * all other APIs used by the application are version 4 or lower) and take advantage
17386     * of this method, instead of overriding the method which would break the application's
17387     * backwards compatibility, he can override the corresponding method in this
17388     * delegate and register the delegate in the target View if the API version of
17389     * the system is high enough i.e. the API version is same or higher to the API
17390     * version that introduced
17391     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17392     * </p>
17393     * <p>
17394     * Here is an example implementation:
17395     * </p>
17396     * <code><pre><p>
17397     * if (Build.VERSION.SDK_INT >= 14) {
17398     *     // If the API version is equal of higher than the version in
17399     *     // which onInitializeAccessibilityNodeInfo was introduced we
17400     *     // register a delegate with a customized implementation.
17401     *     View view = findViewById(R.id.view_id);
17402     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17403     *         public void onInitializeAccessibilityNodeInfo(View host,
17404     *                 AccessibilityNodeInfo info) {
17405     *             // Let the default implementation populate the info.
17406     *             super.onInitializeAccessibilityNodeInfo(host, info);
17407     *             // Set some other information.
17408     *             info.setEnabled(host.isEnabled());
17409     *         }
17410     *     });
17411     * }
17412     * </code></pre></p>
17413     * <p>
17414     * This delegate contains methods that correspond to the accessibility methods
17415     * in View. If a delegate has been specified the implementation in View hands
17416     * off handling to the corresponding method in this delegate. The default
17417     * implementation the delegate methods behaves exactly as the corresponding
17418     * method in View for the case of no accessibility delegate been set. Hence,
17419     * to customize the behavior of a View method, clients can override only the
17420     * corresponding delegate method without altering the behavior of the rest
17421     * accessibility related methods of the host view.
17422     * </p>
17423     */
17424    public static class AccessibilityDelegate {
17425
17426        /**
17427         * Sends an accessibility event of the given type. If accessibility is not
17428         * enabled this method has no effect.
17429         * <p>
17430         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17431         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17432         * been set.
17433         * </p>
17434         *
17435         * @param host The View hosting the delegate.
17436         * @param eventType The type of the event to send.
17437         *
17438         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17439         */
17440        public void sendAccessibilityEvent(View host, int eventType) {
17441            host.sendAccessibilityEventInternal(eventType);
17442        }
17443
17444        /**
17445         * Performs the specified accessibility action on the view. For
17446         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17447         * <p>
17448         * The default implementation behaves as
17449         * {@link View#performAccessibilityAction(int, Bundle)
17450         *  View#performAccessibilityAction(int, Bundle)} for the case of
17451         *  no accessibility delegate been set.
17452         * </p>
17453         *
17454         * @param action The action to perform.
17455         * @return Whether the action was performed.
17456         *
17457         * @see View#performAccessibilityAction(int, Bundle)
17458         *      View#performAccessibilityAction(int, Bundle)
17459         */
17460        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17461            return host.performAccessibilityActionInternal(action, args);
17462        }
17463
17464        /**
17465         * Sends an accessibility event. This method behaves exactly as
17466         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17467         * empty {@link AccessibilityEvent} and does not perform a check whether
17468         * accessibility is enabled.
17469         * <p>
17470         * The default implementation behaves as
17471         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17472         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17473         * the case of no accessibility delegate been set.
17474         * </p>
17475         *
17476         * @param host The View hosting the delegate.
17477         * @param event The event to send.
17478         *
17479         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17480         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17481         */
17482        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17483            host.sendAccessibilityEventUncheckedInternal(event);
17484        }
17485
17486        /**
17487         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17488         * to its children for adding their text content to the event.
17489         * <p>
17490         * The default implementation behaves as
17491         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17492         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17493         * the case of no accessibility delegate been set.
17494         * </p>
17495         *
17496         * @param host The View hosting the delegate.
17497         * @param event The event.
17498         * @return True if the event population was completed.
17499         *
17500         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17501         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17502         */
17503        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17504            return host.dispatchPopulateAccessibilityEventInternal(event);
17505        }
17506
17507        /**
17508         * Gives a chance to the host View to populate the accessibility event with its
17509         * text content.
17510         * <p>
17511         * The default implementation behaves as
17512         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17513         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17514         * the case of no accessibility delegate been set.
17515         * </p>
17516         *
17517         * @param host The View hosting the delegate.
17518         * @param event The accessibility event which to populate.
17519         *
17520         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17521         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17522         */
17523        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17524            host.onPopulateAccessibilityEventInternal(event);
17525        }
17526
17527        /**
17528         * Initializes an {@link AccessibilityEvent} with information about the
17529         * the host View which is the event source.
17530         * <p>
17531         * The default implementation behaves as
17532         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17533         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17534         * the case of no accessibility delegate been set.
17535         * </p>
17536         *
17537         * @param host The View hosting the delegate.
17538         * @param event The event to initialize.
17539         *
17540         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17541         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17542         */
17543        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17544            host.onInitializeAccessibilityEventInternal(event);
17545        }
17546
17547        /**
17548         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17549         * <p>
17550         * The default implementation behaves as
17551         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17552         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17553         * the case of no accessibility delegate been set.
17554         * </p>
17555         *
17556         * @param host The View hosting the delegate.
17557         * @param info The instance to initialize.
17558         *
17559         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17560         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17561         */
17562        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17563            host.onInitializeAccessibilityNodeInfoInternal(info);
17564        }
17565
17566        /**
17567         * Called when a child of the host View has requested sending an
17568         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17569         * to augment the event.
17570         * <p>
17571         * The default implementation behaves as
17572         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17573         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17574         * the case of no accessibility delegate been set.
17575         * </p>
17576         *
17577         * @param host The View hosting the delegate.
17578         * @param child The child which requests sending the event.
17579         * @param event The event to be sent.
17580         * @return True if the event should be sent
17581         *
17582         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17583         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17584         */
17585        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17586                AccessibilityEvent event) {
17587            return host.onRequestSendAccessibilityEventInternal(child, event);
17588        }
17589
17590        /**
17591         * Gets the provider for managing a virtual view hierarchy rooted at this View
17592         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17593         * that explore the window content.
17594         * <p>
17595         * The default implementation behaves as
17596         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17597         * the case of no accessibility delegate been set.
17598         * </p>
17599         *
17600         * @return The provider.
17601         *
17602         * @see AccessibilityNodeProvider
17603         */
17604        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17605            return null;
17606        }
17607    }
17608}
17609