View.java revision 6704c233390743890d23338a2329dcda5709b810
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.util.AttributeSet;
51import android.util.FloatProperty;
52import android.util.LocaleUtil;
53import android.util.Log;
54import android.util.Pool;
55import android.util.Poolable;
56import android.util.PoolableManager;
57import android.util.Pools;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.widget.ScrollBarDrawable;
78
79import static android.os.Build.VERSION_CODES.*;
80import static java.lang.Math.max;
81
82import com.android.internal.R;
83import com.android.internal.util.Predicate;
84import com.android.internal.view.menu.MenuBuilder;
85
86import java.lang.ref.WeakReference;
87import java.lang.reflect.InvocationTargetException;
88import java.lang.reflect.Method;
89import java.util.ArrayList;
90import java.util.Arrays;
91import java.util.Locale;
92import java.util.concurrent.CopyOnWriteArrayList;
93
94/**
95 * <p>
96 * This class represents the basic building block for user interface components. A View
97 * occupies a rectangular area on the screen and is responsible for drawing and
98 * event handling. View is the base class for <em>widgets</em>, which are
99 * used to create interactive UI components (buttons, text fields, etc.). The
100 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
101 * are invisible containers that hold other Views (or other ViewGroups) and define
102 * their layout properties.
103 * </p>
104 *
105 * <div class="special reference">
106 * <h3>Developer Guides</h3>
107 * <p>For information about using this class to develop your application's user interface,
108 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
109 * </div>
110 *
111 * <a name="Using"></a>
112 * <h3>Using Views</h3>
113 * <p>
114 * All of the views in a window are arranged in a single tree. You can add views
115 * either from code or by specifying a tree of views in one or more XML layout
116 * files. There are many specialized subclasses of views that act as controls or
117 * are capable of displaying text, images, or other content.
118 * </p>
119 * <p>
120 * Once you have created a tree of views, there are typically a few types of
121 * common operations you may wish to perform:
122 * <ul>
123 * <li><strong>Set properties:</strong> for example setting the text of a
124 * {@link android.widget.TextView}. The available properties and the methods
125 * that set them will vary among the different subclasses of views. Note that
126 * properties that are known at build time can be set in the XML layout
127 * files.</li>
128 * <li><strong>Set focus:</strong> The framework will handled moving focus in
129 * response to user input. To force focus to a specific view, call
130 * {@link #requestFocus}.</li>
131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
132 * that will be notified when something interesting happens to the view. For
133 * example, all views will let you set a listener to be notified when the view
134 * gains or loses focus. You can register such a listener using
135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
136 * Other view subclasses offer more specialized listeners. For example, a Button
137 * exposes a listener to notify clients when the button is clicked.</li>
138 * <li><strong>Set visibility:</strong> You can hide or show views using
139 * {@link #setVisibility(int)}.</li>
140 * </ul>
141 * </p>
142 * <p><em>
143 * Note: The Android framework is responsible for measuring, laying out and
144 * drawing views. You should not call methods that perform these actions on
145 * views yourself unless you are actually implementing a
146 * {@link android.view.ViewGroup}.
147 * </em></p>
148 *
149 * <a name="Lifecycle"></a>
150 * <h3>Implementing a Custom View</h3>
151 *
152 * <p>
153 * To implement a custom view, you will usually begin by providing overrides for
154 * some of the standard methods that the framework calls on all views. You do
155 * not need to override all of these methods. In fact, you can start by just
156 * overriding {@link #onDraw(android.graphics.Canvas)}.
157 * <table border="2" width="85%" align="center" cellpadding="5">
158 *     <thead>
159 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
160 *     </thead>
161 *
162 *     <tbody>
163 *     <tr>
164 *         <td rowspan="2">Creation</td>
165 *         <td>Constructors</td>
166 *         <td>There is a form of the constructor that are called when the view
167 *         is created from code and a form that is called when the view is
168 *         inflated from a layout file. The second form should parse and apply
169 *         any attributes defined in the layout file.
170 *         </td>
171 *     </tr>
172 *     <tr>
173 *         <td><code>{@link #onFinishInflate()}</code></td>
174 *         <td>Called after a view and all of its children has been inflated
175 *         from XML.</td>
176 *     </tr>
177 *
178 *     <tr>
179 *         <td rowspan="3">Layout</td>
180 *         <td><code>{@link #onMeasure(int, int)}</code></td>
181 *         <td>Called to determine the size requirements for this view and all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
187 *         <td>Called when this view should assign a size and position to all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
193 *         <td>Called when the size of this view has changed.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td>Drawing</td>
199 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
200 *         <td>Called when the view should render its content.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td rowspan="4">Event processing</td>
206 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
207 *         <td>Called when a new key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a key up event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
217 *         <td>Called when a trackball motion event occurs.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
222 *         <td>Called when a touch screen motion event occurs.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="2">Focus</td>
228 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
229 *         <td>Called when the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
235 *         <td>Called when the window containing the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="3">Attaching</td>
241 *         <td><code>{@link #onAttachedToWindow()}</code></td>
242 *         <td>Called when the view is attached to a window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onDetachedFromWindow}</code></td>
248 *         <td>Called when the view is detached from its window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
254 *         <td>Called when the visibility of the window containing the view
255 *         has changed.
256 *         </td>
257 *     </tr>
258 *     </tbody>
259 *
260 * </table>
261 * </p>
262 *
263 * <a name="IDs"></a>
264 * <h3>IDs</h3>
265 * Views may have an integer id associated with them. These ids are typically
266 * assigned in the layout XML files, and are used to find specific views within
267 * the view tree. A common pattern is to:
268 * <ul>
269 * <li>Define a Button in the layout file and assign it a unique ID.
270 * <pre>
271 * &lt;Button
272 *     android:id="@+id/my_button"
273 *     android:layout_width="wrap_content"
274 *     android:layout_height="wrap_content"
275 *     android:text="@string/my_button_text"/&gt;
276 * </pre></li>
277 * <li>From the onCreate method of an Activity, find the Button
278 * <pre class="prettyprint">
279 *      Button myButton = (Button) findViewById(R.id.my_button);
280 * </pre></li>
281 * </ul>
282 * <p>
283 * View IDs need not be unique throughout the tree, but it is good practice to
284 * ensure that they are at least unique within the part of the tree you are
285 * searching.
286 * </p>
287 *
288 * <a name="Position"></a>
289 * <h3>Position</h3>
290 * <p>
291 * The geometry of a view is that of a rectangle. A view has a location,
292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
293 * two dimensions, expressed as a width and a height. The unit for location
294 * and dimensions is the pixel.
295 * </p>
296 *
297 * <p>
298 * It is possible to retrieve the location of a view by invoking the methods
299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
300 * coordinate of the rectangle representing the view. The latter returns the
301 * top, or Y, coordinate of the rectangle representing the view. These methods
302 * both return the location of the view relative to its parent. For instance,
303 * when getLeft() returns 20, that means the view is located 20 pixels to the
304 * right of the left edge of its direct parent.
305 * </p>
306 *
307 * <p>
308 * In addition, several convenience methods are offered to avoid unnecessary
309 * computations, namely {@link #getRight()} and {@link #getBottom()}.
310 * These methods return the coordinates of the right and bottom edges of the
311 * rectangle representing the view. For instance, calling {@link #getRight()}
312 * is similar to the following computation: <code>getLeft() + getWidth()</code>
313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
314 * </p>
315 *
316 * <a name="SizePaddingMargins"></a>
317 * <h3>Size, padding and margins</h3>
318 * <p>
319 * The size of a view is expressed with a width and a height. A view actually
320 * possess two pairs of width and height values.
321 * </p>
322 *
323 * <p>
324 * The first pair is known as <em>measured width</em> and
325 * <em>measured height</em>. These dimensions define how big a view wants to be
326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
328 * and {@link #getMeasuredHeight()}.
329 * </p>
330 *
331 * <p>
332 * The second pair is simply known as <em>width</em> and <em>height</em>, or
333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
334 * dimensions define the actual size of the view on screen, at drawing time and
335 * after layout. These values may, but do not have to, be different from the
336 * measured width and height. The width and height can be obtained by calling
337 * {@link #getWidth()} and {@link #getHeight()}.
338 * </p>
339 *
340 * <p>
341 * To measure its dimensions, a view takes into account its padding. The padding
342 * is expressed in pixels for the left, top, right and bottom parts of the view.
343 * Padding can be used to offset the content of the view by a specific amount of
344 * pixels. For instance, a left padding of 2 will push the view's content by
345 * 2 pixels to the right of the left edge. Padding can be set using the
346 * {@link #setPadding(int, int, int, int)} method and queried by calling
347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, {@link #getPaddingRight()},
348 * {@link #getPaddingBottom()}.
349 * </p>
350 *
351 * <p>
352 * Even though a view can define a padding, it does not provide any support for
353 * margins. However, view groups provide such a support. Refer to
354 * {@link android.view.ViewGroup} and
355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
356 * </p>
357 *
358 * <a name="Layout"></a>
359 * <h3>Layout</h3>
360 * <p>
361 * Layout is a two pass process: a measure pass and a layout pass. The measuring
362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
363 * of the view tree. Each view pushes dimension specifications down the tree
364 * during the recursion. At the end of the measure pass, every view has stored
365 * its measurements. The second pass happens in
366 * {@link #layout(int,int,int,int)} and is also top-down. During
367 * this pass each parent is responsible for positioning all of its children
368 * using the sizes computed in the measure pass.
369 * </p>
370 *
371 * <p>
372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
373 * {@link #getMeasuredHeight()} values must be set, along with those for all of
374 * that view's descendants. A view's measured width and measured height values
375 * must respect the constraints imposed by the view's parents. This guarantees
376 * that at the end of the measure pass, all parents accept all of their
377 * children's measurements. A parent view may call measure() more than once on
378 * its children. For example, the parent may measure each child once with
379 * unspecified dimensions to find out how big they want to be, then call
380 * measure() on them again with actual numbers if the sum of all the children's
381 * unconstrained sizes is too big or too small.
382 * </p>
383 *
384 * <p>
385 * The measure pass uses two classes to communicate dimensions. The
386 * {@link MeasureSpec} class is used by views to tell their parents how they
387 * want to be measured and positioned. The base LayoutParams class just
388 * describes how big the view wants to be for both width and height. For each
389 * dimension, it can specify one of:
390 * <ul>
391 * <li> an exact number
392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
393 * (minus padding)
394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
395 * enclose its content (plus padding).
396 * </ul>
397 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
399 * an X and Y value.
400 * </p>
401 *
402 * <p>
403 * MeasureSpecs are used to push requirements down the tree from parent to
404 * child. A MeasureSpec can be in one of three modes:
405 * <ul>
406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
407 * of a child view. For example, a LinearLayout may call measure() on its child
408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
409 * tall the child view wants to be given a width of 240 pixels.
410 * <li>EXACTLY: This is used by the parent to impose an exact size on the
411 * child. The child must use this size, and guarantee that all of its
412 * descendants will fit within this size.
413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
414 * child. The child must gurantee that it and all of its descendants will fit
415 * within this size.
416 * </ul>
417 * </p>
418 *
419 * <p>
420 * To intiate a layout, call {@link #requestLayout}. This method is typically
421 * called by a view on itself when it believes that is can no longer fit within
422 * its current bounds.
423 * </p>
424 *
425 * <a name="Drawing"></a>
426 * <h3>Drawing</h3>
427 * <p>
428 * Drawing is handled by walking the tree and rendering each view that
429 * intersects the invalid region. Because the tree is traversed in-order,
430 * this means that parents will draw before (i.e., behind) their children, with
431 * siblings drawn in the order they appear in the tree.
432 * If you set a background drawable for a View, then the View will draw it for you
433 * before calling back to its <code>onDraw()</code> method.
434 * </p>
435 *
436 * <p>
437 * Note that the framework will not draw views that are not in the invalid region.
438 * </p>
439 *
440 * <p>
441 * To force a view to draw, call {@link #invalidate()}.
442 * </p>
443 *
444 * <a name="EventHandlingThreading"></a>
445 * <h3>Event Handling and Threading</h3>
446 * <p>
447 * The basic cycle of a view is as follows:
448 * <ol>
449 * <li>An event comes in and is dispatched to the appropriate view. The view
450 * handles the event and notifies any listeners.</li>
451 * <li>If in the course of processing the event, the view's bounds may need
452 * to be changed, the view will call {@link #requestLayout()}.</li>
453 * <li>Similarly, if in the course of processing the event the view's appearance
454 * may need to be changed, the view will call {@link #invalidate()}.</li>
455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
456 * the framework will take care of measuring, laying out, and drawing the tree
457 * as appropriate.</li>
458 * </ol>
459 * </p>
460 *
461 * <p><em>Note: The entire view tree is single threaded. You must always be on
462 * the UI thread when calling any method on any view.</em>
463 * If you are doing work on other threads and want to update the state of a view
464 * from that thread, you should use a {@link Handler}.
465 * </p>
466 *
467 * <a name="FocusHandling"></a>
468 * <h3>Focus Handling</h3>
469 * <p>
470 * The framework will handle routine focus movement in response to user input.
471 * This includes changing the focus as views are removed or hidden, or as new
472 * views become available. Views indicate their willingness to take focus
473 * through the {@link #isFocusable} method. To change whether a view can take
474 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
476 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
477 * </p>
478 * <p>
479 * Focus movement is based on an algorithm which finds the nearest neighbor in a
480 * given direction. In rare cases, the default algorithm may not match the
481 * intended behavior of the developer. In these situations, you can provide
482 * explicit overrides by using these XML attributes in the layout file:
483 * <pre>
484 * nextFocusDown
485 * nextFocusLeft
486 * nextFocusRight
487 * nextFocusUp
488 * </pre>
489 * </p>
490 *
491 *
492 * <p>
493 * To get a particular view to take focus, call {@link #requestFocus()}.
494 * </p>
495 *
496 * <a name="TouchMode"></a>
497 * <h3>Touch Mode</h3>
498 * <p>
499 * When a user is navigating a user interface via directional keys such as a D-pad, it is
500 * necessary to give focus to actionable items such as buttons so the user can see
501 * what will take input.  If the device has touch capabilities, however, and the user
502 * begins interacting with the interface by touching it, it is no longer necessary to
503 * always highlight, or give focus to, a particular view.  This motivates a mode
504 * for interaction named 'touch mode'.
505 * </p>
506 * <p>
507 * For a touch capable device, once the user touches the screen, the device
508 * will enter touch mode.  From this point onward, only views for which
509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
510 * Other views that are touchable, like buttons, will not take focus when touched; they will
511 * only fire the on click listeners.
512 * </p>
513 * <p>
514 * Any time a user hits a directional key, such as a D-pad direction, the view device will
515 * exit touch mode, and find a view to take focus, so that the user may resume interacting
516 * with the user interface without touching the screen again.
517 * </p>
518 * <p>
519 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
520 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
521 * </p>
522 *
523 * <a name="Scrolling"></a>
524 * <h3>Scrolling</h3>
525 * <p>
526 * The framework provides basic support for views that wish to internally
527 * scroll their content. This includes keeping track of the X and Y scroll
528 * offset as well as mechanisms for drawing scrollbars. See
529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
530 * {@link #awakenScrollBars()} for more details.
531 * </p>
532 *
533 * <a name="Tags"></a>
534 * <h3>Tags</h3>
535 * <p>
536 * Unlike IDs, tags are not used to identify views. Tags are essentially an
537 * extra piece of information that can be associated with a view. They are most
538 * often used as a convenience to store data related to views in the views
539 * themselves rather than by putting them in a separate structure.
540 * </p>
541 *
542 * <a name="Properties"></a>
543 * <h3>Properties</h3>
544 * <p>
545 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
546 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
547 * available both in the {@link Property} form as well as in similarly-named setter/getter
548 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
549 * be used to set persistent state associated with these rendering-related properties on the view.
550 * The properties and methods can also be used in conjunction with
551 * {@link android.animation.Animator Animator}-based animations, described more in the
552 * <a href="#Animation">Animation</a> section.
553 * </p>
554 *
555 * <a name="Animation"></a>
556 * <h3>Animation</h3>
557 * <p>
558 * Starting with Android 3.0, the preferred way of animating views is to use the
559 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
560 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
561 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
562 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
563 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
564 * makes animating these View properties particularly easy and efficient.
565 * </p>
566 * <p>
567 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
568 * You can attach an {@link Animation} object to a view using
569 * {@link #setAnimation(Animation)} or
570 * {@link #startAnimation(Animation)}. The animation can alter the scale,
571 * rotation, translation and alpha of a view over time. If the animation is
572 * attached to a view that has children, the animation will affect the entire
573 * subtree rooted by that node. When an animation is started, the framework will
574 * take care of redrawing the appropriate views until the animation completes.
575 * </p>
576 *
577 * <a name="Security"></a>
578 * <h3>Security</h3>
579 * <p>
580 * Sometimes it is essential that an application be able to verify that an action
581 * is being performed with the full knowledge and consent of the user, such as
582 * granting a permission request, making a purchase or clicking on an advertisement.
583 * Unfortunately, a malicious application could try to spoof the user into
584 * performing these actions, unaware, by concealing the intended purpose of the view.
585 * As a remedy, the framework offers a touch filtering mechanism that can be used to
586 * improve the security of views that provide access to sensitive functionality.
587 * </p><p>
588 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
589 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
590 * will discard touches that are received whenever the view's window is obscured by
591 * another visible window.  As a result, the view will not receive touches whenever a
592 * toast, dialog or other window appears above the view's window.
593 * </p><p>
594 * For more fine-grained control over security, consider overriding the
595 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
596 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
597 * </p>
598 *
599 * @attr ref android.R.styleable#View_alpha
600 * @attr ref android.R.styleable#View_background
601 * @attr ref android.R.styleable#View_clickable
602 * @attr ref android.R.styleable#View_contentDescription
603 * @attr ref android.R.styleable#View_drawingCacheQuality
604 * @attr ref android.R.styleable#View_duplicateParentState
605 * @attr ref android.R.styleable#View_id
606 * @attr ref android.R.styleable#View_requiresFadingEdge
607 * @attr ref android.R.styleable#View_fadeScrollbars
608 * @attr ref android.R.styleable#View_fadingEdgeLength
609 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
610 * @attr ref android.R.styleable#View_fitsSystemWindows
611 * @attr ref android.R.styleable#View_isScrollContainer
612 * @attr ref android.R.styleable#View_focusable
613 * @attr ref android.R.styleable#View_focusableInTouchMode
614 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
615 * @attr ref android.R.styleable#View_keepScreenOn
616 * @attr ref android.R.styleable#View_layerType
617 * @attr ref android.R.styleable#View_longClickable
618 * @attr ref android.R.styleable#View_minHeight
619 * @attr ref android.R.styleable#View_minWidth
620 * @attr ref android.R.styleable#View_nextFocusDown
621 * @attr ref android.R.styleable#View_nextFocusLeft
622 * @attr ref android.R.styleable#View_nextFocusRight
623 * @attr ref android.R.styleable#View_nextFocusUp
624 * @attr ref android.R.styleable#View_onClick
625 * @attr ref android.R.styleable#View_padding
626 * @attr ref android.R.styleable#View_paddingBottom
627 * @attr ref android.R.styleable#View_paddingLeft
628 * @attr ref android.R.styleable#View_paddingRight
629 * @attr ref android.R.styleable#View_paddingTop
630 * @attr ref android.R.styleable#View_saveEnabled
631 * @attr ref android.R.styleable#View_rotation
632 * @attr ref android.R.styleable#View_rotationX
633 * @attr ref android.R.styleable#View_rotationY
634 * @attr ref android.R.styleable#View_scaleX
635 * @attr ref android.R.styleable#View_scaleY
636 * @attr ref android.R.styleable#View_scrollX
637 * @attr ref android.R.styleable#View_scrollY
638 * @attr ref android.R.styleable#View_scrollbarSize
639 * @attr ref android.R.styleable#View_scrollbarStyle
640 * @attr ref android.R.styleable#View_scrollbars
641 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
642 * @attr ref android.R.styleable#View_scrollbarFadeDuration
643 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
644 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
645 * @attr ref android.R.styleable#View_scrollbarThumbVertical
646 * @attr ref android.R.styleable#View_scrollbarTrackVertical
647 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
648 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
649 * @attr ref android.R.styleable#View_soundEffectsEnabled
650 * @attr ref android.R.styleable#View_tag
651 * @attr ref android.R.styleable#View_transformPivotX
652 * @attr ref android.R.styleable#View_transformPivotY
653 * @attr ref android.R.styleable#View_translationX
654 * @attr ref android.R.styleable#View_translationY
655 * @attr ref android.R.styleable#View_visibility
656 *
657 * @see android.view.ViewGroup
658 */
659public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
660        AccessibilityEventSource {
661    private static final boolean DBG = false;
662
663    /**
664     * The logging tag used by this class with android.util.Log.
665     */
666    protected static final String VIEW_LOG_TAG = "View";
667
668    /**
669     * When set to true, apps will draw debugging information about their layouts.
670     *
671     * @hide
672     */
673    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
674
675    /**
676     * Used to mark a View that has no ID.
677     */
678    public static final int NO_ID = -1;
679
680    /**
681     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
682     * calling setFlags.
683     */
684    private static final int NOT_FOCUSABLE = 0x00000000;
685
686    /**
687     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
688     * setFlags.
689     */
690    private static final int FOCUSABLE = 0x00000001;
691
692    /**
693     * Mask for use with setFlags indicating bits used for focus.
694     */
695    private static final int FOCUSABLE_MASK = 0x00000001;
696
697    /**
698     * This view will adjust its padding to fit sytem windows (e.g. status bar)
699     */
700    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
701
702    /**
703     * This view is visible.
704     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
705     * android:visibility}.
706     */
707    public static final int VISIBLE = 0x00000000;
708
709    /**
710     * This view is invisible, but it still takes up space for layout purposes.
711     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
712     * android:visibility}.
713     */
714    public static final int INVISIBLE = 0x00000004;
715
716    /**
717     * This view is invisible, and it doesn't take any space for layout
718     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
719     * android:visibility}.
720     */
721    public static final int GONE = 0x00000008;
722
723    /**
724     * Mask for use with setFlags indicating bits used for visibility.
725     * {@hide}
726     */
727    static final int VISIBILITY_MASK = 0x0000000C;
728
729    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
730
731    /**
732     * This view is enabled. Interpretation varies by subclass.
733     * Use with ENABLED_MASK when calling setFlags.
734     * {@hide}
735     */
736    static final int ENABLED = 0x00000000;
737
738    /**
739     * This view is disabled. Interpretation varies by subclass.
740     * Use with ENABLED_MASK when calling setFlags.
741     * {@hide}
742     */
743    static final int DISABLED = 0x00000020;
744
745   /**
746    * Mask for use with setFlags indicating bits used for indicating whether
747    * this view is enabled
748    * {@hide}
749    */
750    static final int ENABLED_MASK = 0x00000020;
751
752    /**
753     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
754     * called and further optimizations will be performed. It is okay to have
755     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
756     * {@hide}
757     */
758    static final int WILL_NOT_DRAW = 0x00000080;
759
760    /**
761     * Mask for use with setFlags indicating bits used for indicating whether
762     * this view is will draw
763     * {@hide}
764     */
765    static final int DRAW_MASK = 0x00000080;
766
767    /**
768     * <p>This view doesn't show scrollbars.</p>
769     * {@hide}
770     */
771    static final int SCROLLBARS_NONE = 0x00000000;
772
773    /**
774     * <p>This view shows horizontal scrollbars.</p>
775     * {@hide}
776     */
777    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
778
779    /**
780     * <p>This view shows vertical scrollbars.</p>
781     * {@hide}
782     */
783    static final int SCROLLBARS_VERTICAL = 0x00000200;
784
785    /**
786     * <p>Mask for use with setFlags indicating bits used for indicating which
787     * scrollbars are enabled.</p>
788     * {@hide}
789     */
790    static final int SCROLLBARS_MASK = 0x00000300;
791
792    /**
793     * Indicates that the view should filter touches when its window is obscured.
794     * Refer to the class comments for more information about this security feature.
795     * {@hide}
796     */
797    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
798
799    /**
800     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
801     * that they are optional and should be skipped if the window has
802     * requested system UI flags that ignore those insets for layout.
803     */
804    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
805
806    /**
807     * <p>This view doesn't show fading edges.</p>
808     * {@hide}
809     */
810    static final int FADING_EDGE_NONE = 0x00000000;
811
812    /**
813     * <p>This view shows horizontal fading edges.</p>
814     * {@hide}
815     */
816    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
817
818    /**
819     * <p>This view shows vertical fading edges.</p>
820     * {@hide}
821     */
822    static final int FADING_EDGE_VERTICAL = 0x00002000;
823
824    /**
825     * <p>Mask for use with setFlags indicating bits used for indicating which
826     * fading edges are enabled.</p>
827     * {@hide}
828     */
829    static final int FADING_EDGE_MASK = 0x00003000;
830
831    /**
832     * <p>Indicates this view can be clicked. When clickable, a View reacts
833     * to clicks by notifying the OnClickListener.<p>
834     * {@hide}
835     */
836    static final int CLICKABLE = 0x00004000;
837
838    /**
839     * <p>Indicates this view is caching its drawing into a bitmap.</p>
840     * {@hide}
841     */
842    static final int DRAWING_CACHE_ENABLED = 0x00008000;
843
844    /**
845     * <p>Indicates that no icicle should be saved for this view.<p>
846     * {@hide}
847     */
848    static final int SAVE_DISABLED = 0x000010000;
849
850    /**
851     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
852     * property.</p>
853     * {@hide}
854     */
855    static final int SAVE_DISABLED_MASK = 0x000010000;
856
857    /**
858     * <p>Indicates that no drawing cache should ever be created for this view.<p>
859     * {@hide}
860     */
861    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
862
863    /**
864     * <p>Indicates this view can take / keep focus when int touch mode.</p>
865     * {@hide}
866     */
867    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
868
869    /**
870     * <p>Enables low quality mode for the drawing cache.</p>
871     */
872    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
873
874    /**
875     * <p>Enables high quality mode for the drawing cache.</p>
876     */
877    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
878
879    /**
880     * <p>Enables automatic quality mode for the drawing cache.</p>
881     */
882    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
883
884    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
885            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
886    };
887
888    /**
889     * <p>Mask for use with setFlags indicating bits used for the cache
890     * quality property.</p>
891     * {@hide}
892     */
893    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
894
895    /**
896     * <p>
897     * Indicates this view can be long clicked. When long clickable, a View
898     * reacts to long clicks by notifying the OnLongClickListener or showing a
899     * context menu.
900     * </p>
901     * {@hide}
902     */
903    static final int LONG_CLICKABLE = 0x00200000;
904
905    /**
906     * <p>Indicates that this view gets its drawable states from its direct parent
907     * and ignores its original internal states.</p>
908     *
909     * @hide
910     */
911    static final int DUPLICATE_PARENT_STATE = 0x00400000;
912
913    /**
914     * The scrollbar style to display the scrollbars inside the content area,
915     * without increasing the padding. The scrollbars will be overlaid with
916     * translucency on the view's content.
917     */
918    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
919
920    /**
921     * The scrollbar style to display the scrollbars inside the padded area,
922     * increasing the padding of the view. The scrollbars will not overlap the
923     * content area of the view.
924     */
925    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
926
927    /**
928     * The scrollbar style to display the scrollbars at the edge of the view,
929     * without increasing the padding. The scrollbars will be overlaid with
930     * translucency.
931     */
932    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
933
934    /**
935     * The scrollbar style to display the scrollbars at the edge of the view,
936     * increasing the padding of the view. The scrollbars will only overlap the
937     * background, if any.
938     */
939    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
940
941    /**
942     * Mask to check if the scrollbar style is overlay or inset.
943     * {@hide}
944     */
945    static final int SCROLLBARS_INSET_MASK = 0x01000000;
946
947    /**
948     * Mask to check if the scrollbar style is inside or outside.
949     * {@hide}
950     */
951    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
952
953    /**
954     * Mask for scrollbar style.
955     * {@hide}
956     */
957    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
958
959    /**
960     * View flag indicating that the screen should remain on while the
961     * window containing this view is visible to the user.  This effectively
962     * takes care of automatically setting the WindowManager's
963     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
964     */
965    public static final int KEEP_SCREEN_ON = 0x04000000;
966
967    /**
968     * View flag indicating whether this view should have sound effects enabled
969     * for events such as clicking and touching.
970     */
971    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
972
973    /**
974     * View flag indicating whether this view should have haptic feedback
975     * enabled for events such as long presses.
976     */
977    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
978
979    /**
980     * <p>Indicates that the view hierarchy should stop saving state when
981     * it reaches this view.  If state saving is initiated immediately at
982     * the view, it will be allowed.
983     * {@hide}
984     */
985    static final int PARENT_SAVE_DISABLED = 0x20000000;
986
987    /**
988     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
989     * {@hide}
990     */
991    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
992
993    /**
994     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
995     * should add all focusable Views regardless if they are focusable in touch mode.
996     */
997    public static final int FOCUSABLES_ALL = 0x00000000;
998
999    /**
1000     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1001     * should add only Views focusable in touch mode.
1002     */
1003    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1004
1005    /**
1006     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1007     * should add only accessibility focusable Views.
1008     *
1009     * @hide
1010     */
1011    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1012
1013    /**
1014     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1015     * item.
1016     */
1017    public static final int FOCUS_BACKWARD = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1021     * item.
1022     */
1023    public static final int FOCUS_FORWARD = 0x00000002;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the left.
1027     */
1028    public static final int FOCUS_LEFT = 0x00000011;
1029
1030    /**
1031     * Use with {@link #focusSearch(int)}. Move focus up.
1032     */
1033    public static final int FOCUS_UP = 0x00000021;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move focus to the right.
1037     */
1038    public static final int FOCUS_RIGHT = 0x00000042;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move focus down.
1042     */
1043    public static final int FOCUS_DOWN = 0x00000082;
1044
1045    // Accessibility focus directions.
1046
1047    /**
1048     * The accessibility focus which is the current user position when
1049     * interacting with the accessibility framework.
1050     */
1051    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1052
1053    /**
1054     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1055     */
1056    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1057
1058    /**
1059     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1060     */
1061    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1062
1063    /**
1064     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1065     */
1066    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1067
1068    /**
1069     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1070     */
1071    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1072
1073    /**
1074     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1075     */
1076    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1077
1078    /**
1079     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1080     */
1081    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1082
1083    /**
1084     * Bits of {@link #getMeasuredWidthAndState()} and
1085     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1086     */
1087    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1088
1089    /**
1090     * Bits of {@link #getMeasuredWidthAndState()} and
1091     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1092     */
1093    public static final int MEASURED_STATE_MASK = 0xff000000;
1094
1095    /**
1096     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1097     * for functions that combine both width and height into a single int,
1098     * such as {@link #getMeasuredState()} and the childState argument of
1099     * {@link #resolveSizeAndState(int, int, int)}.
1100     */
1101    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1102
1103    /**
1104     * Bit of {@link #getMeasuredWidthAndState()} and
1105     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1106     * is smaller that the space the view would like to have.
1107     */
1108    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1109
1110    /**
1111     * Base View state sets
1112     */
1113    // Singles
1114    /**
1115     * Indicates the view has no states set. States are used with
1116     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1117     * view depending on its state.
1118     *
1119     * @see android.graphics.drawable.Drawable
1120     * @see #getDrawableState()
1121     */
1122    protected static final int[] EMPTY_STATE_SET;
1123    /**
1124     * Indicates the view is enabled. States are used with
1125     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1126     * view depending on its state.
1127     *
1128     * @see android.graphics.drawable.Drawable
1129     * @see #getDrawableState()
1130     */
1131    protected static final int[] ENABLED_STATE_SET;
1132    /**
1133     * Indicates the view is focused. States are used with
1134     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1135     * view depending on its state.
1136     *
1137     * @see android.graphics.drawable.Drawable
1138     * @see #getDrawableState()
1139     */
1140    protected static final int[] FOCUSED_STATE_SET;
1141    /**
1142     * Indicates the view is selected. States are used with
1143     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1144     * view depending on its state.
1145     *
1146     * @see android.graphics.drawable.Drawable
1147     * @see #getDrawableState()
1148     */
1149    protected static final int[] SELECTED_STATE_SET;
1150    /**
1151     * Indicates the view is pressed. States are used with
1152     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1153     * view depending on its state.
1154     *
1155     * @see android.graphics.drawable.Drawable
1156     * @see #getDrawableState()
1157     * @hide
1158     */
1159    protected static final int[] PRESSED_STATE_SET;
1160    /**
1161     * Indicates the view's window has focus. States are used with
1162     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1163     * view depending on its state.
1164     *
1165     * @see android.graphics.drawable.Drawable
1166     * @see #getDrawableState()
1167     */
1168    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1169    // Doubles
1170    /**
1171     * Indicates the view is enabled and has the focus.
1172     *
1173     * @see #ENABLED_STATE_SET
1174     * @see #FOCUSED_STATE_SET
1175     */
1176    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1177    /**
1178     * Indicates the view is enabled and selected.
1179     *
1180     * @see #ENABLED_STATE_SET
1181     * @see #SELECTED_STATE_SET
1182     */
1183    protected static final int[] ENABLED_SELECTED_STATE_SET;
1184    /**
1185     * Indicates the view is enabled and that its window has focus.
1186     *
1187     * @see #ENABLED_STATE_SET
1188     * @see #WINDOW_FOCUSED_STATE_SET
1189     */
1190    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1191    /**
1192     * Indicates the view is focused and selected.
1193     *
1194     * @see #FOCUSED_STATE_SET
1195     * @see #SELECTED_STATE_SET
1196     */
1197    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1198    /**
1199     * Indicates the view has the focus and that its window has the focus.
1200     *
1201     * @see #FOCUSED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is selected and that its window has the focus.
1207     *
1208     * @see #SELECTED_STATE_SET
1209     * @see #WINDOW_FOCUSED_STATE_SET
1210     */
1211    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1212    // Triples
1213    /**
1214     * Indicates the view is enabled, focused and selected.
1215     *
1216     * @see #ENABLED_STATE_SET
1217     * @see #FOCUSED_STATE_SET
1218     * @see #SELECTED_STATE_SET
1219     */
1220    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1221    /**
1222     * Indicates the view is enabled, focused and its window has the focus.
1223     *
1224     * @see #ENABLED_STATE_SET
1225     * @see #FOCUSED_STATE_SET
1226     * @see #WINDOW_FOCUSED_STATE_SET
1227     */
1228    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1229    /**
1230     * Indicates the view is enabled, selected and its window has the focus.
1231     *
1232     * @see #ENABLED_STATE_SET
1233     * @see #SELECTED_STATE_SET
1234     * @see #WINDOW_FOCUSED_STATE_SET
1235     */
1236    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1237    /**
1238     * Indicates the view is focused, selected and its window has the focus.
1239     *
1240     * @see #FOCUSED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is enabled, focused, selected and its window
1247     * has the focus.
1248     *
1249     * @see #ENABLED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     * @see #SELECTED_STATE_SET
1252     * @see #WINDOW_FOCUSED_STATE_SET
1253     */
1254    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1255    /**
1256     * Indicates the view is pressed and its window has the focus.
1257     *
1258     * @see #PRESSED_STATE_SET
1259     * @see #WINDOW_FOCUSED_STATE_SET
1260     */
1261    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1262    /**
1263     * Indicates the view is pressed and selected.
1264     *
1265     * @see #PRESSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed and focused.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #FOCUSED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, focused and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #FOCUSED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, focused and selected.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #SELECTED_STATE_SET
1297     * @see #FOCUSED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, focused, selected and its window has the focus.
1302     *
1303     * @see #PRESSED_STATE_SET
1304     * @see #FOCUSED_STATE_SET
1305     * @see #SELECTED_STATE_SET
1306     * @see #WINDOW_FOCUSED_STATE_SET
1307     */
1308    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1309    /**
1310     * Indicates the view is pressed and enabled.
1311     *
1312     * @see #PRESSED_STATE_SET
1313     * @see #ENABLED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_ENABLED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed, enabled and its window has the focus.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #ENABLED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, enabled and selected.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #ENABLED_STATE_SET
1329     * @see #SELECTED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, enabled, selected and its window has the
1334     * focus.
1335     *
1336     * @see #PRESSED_STATE_SET
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     * @see #WINDOW_FOCUSED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1342    /**
1343     * Indicates the view is pressed, enabled and focused.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #ENABLED_STATE_SET
1347     * @see #FOCUSED_STATE_SET
1348     */
1349    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1350    /**
1351     * Indicates the view is pressed, enabled, focused and its window has the
1352     * focus.
1353     *
1354     * @see #PRESSED_STATE_SET
1355     * @see #ENABLED_STATE_SET
1356     * @see #FOCUSED_STATE_SET
1357     * @see #WINDOW_FOCUSED_STATE_SET
1358     */
1359    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1360    /**
1361     * Indicates the view is pressed, enabled, focused and selected.
1362     *
1363     * @see #PRESSED_STATE_SET
1364     * @see #ENABLED_STATE_SET
1365     * @see #SELECTED_STATE_SET
1366     * @see #FOCUSED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed, enabled, focused, selected and its window
1371     * has the focus.
1372     *
1373     * @see #PRESSED_STATE_SET
1374     * @see #ENABLED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     * @see #FOCUSED_STATE_SET
1377     * @see #WINDOW_FOCUSED_STATE_SET
1378     */
1379    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1380
1381    /**
1382     * The order here is very important to {@link #getDrawableState()}
1383     */
1384    private static final int[][] VIEW_STATE_SETS;
1385
1386    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1387    static final int VIEW_STATE_SELECTED = 1 << 1;
1388    static final int VIEW_STATE_FOCUSED = 1 << 2;
1389    static final int VIEW_STATE_ENABLED = 1 << 3;
1390    static final int VIEW_STATE_PRESSED = 1 << 4;
1391    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1392    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1393    static final int VIEW_STATE_HOVERED = 1 << 7;
1394    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1395    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1396
1397    static final int[] VIEW_STATE_IDS = new int[] {
1398        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1399        R.attr.state_selected,          VIEW_STATE_SELECTED,
1400        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1401        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1402        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1403        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1404        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1405        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1406        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1407        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1408    };
1409
1410    static {
1411        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1412            throw new IllegalStateException(
1413                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1414        }
1415        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1416        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1417            int viewState = R.styleable.ViewDrawableStates[i];
1418            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1419                if (VIEW_STATE_IDS[j] == viewState) {
1420                    orderedIds[i * 2] = viewState;
1421                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1422                }
1423            }
1424        }
1425        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1426        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1427        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1428            int numBits = Integer.bitCount(i);
1429            int[] set = new int[numBits];
1430            int pos = 0;
1431            for (int j = 0; j < orderedIds.length; j += 2) {
1432                if ((i & orderedIds[j+1]) != 0) {
1433                    set[pos++] = orderedIds[j];
1434                }
1435            }
1436            VIEW_STATE_SETS[i] = set;
1437        }
1438
1439        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1440        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1441        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1442        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1444        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1445        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1447        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1449        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1451                | VIEW_STATE_FOCUSED];
1452        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1453        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1455        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1457        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_ENABLED];
1460        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1462        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1464                | VIEW_STATE_ENABLED];
1465        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1467                | VIEW_STATE_ENABLED];
1468        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1471
1472        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1473        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1475        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1477        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1479                | VIEW_STATE_PRESSED];
1480        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1482        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1483                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1484                | VIEW_STATE_PRESSED];
1485        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1486                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1487                | VIEW_STATE_PRESSED];
1488        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1490                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1491        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1493        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1495                | VIEW_STATE_PRESSED];
1496        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1498                | VIEW_STATE_PRESSED];
1499        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1501                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1502        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1504                | VIEW_STATE_PRESSED];
1505        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1507                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1508        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1510                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1511        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1512                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1513                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1514                | VIEW_STATE_PRESSED];
1515    }
1516
1517    /**
1518     * Accessibility event types that are dispatched for text population.
1519     */
1520    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1521            AccessibilityEvent.TYPE_VIEW_CLICKED
1522            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1523            | AccessibilityEvent.TYPE_VIEW_SELECTED
1524            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1525            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1526            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1527            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1528            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1529            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1530            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1531            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1532
1533    /**
1534     * Temporary Rect currently for use in setBackground().  This will probably
1535     * be extended in the future to hold our own class with more than just
1536     * a Rect. :)
1537     */
1538    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1539
1540    /**
1541     * Map used to store views' tags.
1542     */
1543    private SparseArray<Object> mKeyedTags;
1544
1545    /**
1546     * The next available accessiiblity id.
1547     */
1548    private static int sNextAccessibilityViewId;
1549
1550    /**
1551     * The animation currently associated with this view.
1552     * @hide
1553     */
1554    protected Animation mCurrentAnimation = null;
1555
1556    /**
1557     * Width as measured during measure pass.
1558     * {@hide}
1559     */
1560    @ViewDebug.ExportedProperty(category = "measurement")
1561    int mMeasuredWidth;
1562
1563    /**
1564     * Height as measured during measure pass.
1565     * {@hide}
1566     */
1567    @ViewDebug.ExportedProperty(category = "measurement")
1568    int mMeasuredHeight;
1569
1570    /**
1571     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1572     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1573     * its display list. This flag, used only when hw accelerated, allows us to clear the
1574     * flag while retaining this information until it's needed (at getDisplayList() time and
1575     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1576     *
1577     * {@hide}
1578     */
1579    boolean mRecreateDisplayList = false;
1580
1581    /**
1582     * The view's identifier.
1583     * {@hide}
1584     *
1585     * @see #setId(int)
1586     * @see #getId()
1587     */
1588    @ViewDebug.ExportedProperty(resolveId = true)
1589    int mID = NO_ID;
1590
1591    /**
1592     * The stable ID of this view for accessibility purposes.
1593     */
1594    int mAccessibilityViewId = NO_ID;
1595
1596    /**
1597     * @hide
1598     */
1599    private int mAccessibilityCursorPosition = -1;
1600
1601    /**
1602     * The view's tag.
1603     * {@hide}
1604     *
1605     * @see #setTag(Object)
1606     * @see #getTag()
1607     */
1608    protected Object mTag;
1609
1610    // for mPrivateFlags:
1611    /** {@hide} */
1612    static final int WANTS_FOCUS                    = 0x00000001;
1613    /** {@hide} */
1614    static final int FOCUSED                        = 0x00000002;
1615    /** {@hide} */
1616    static final int SELECTED                       = 0x00000004;
1617    /** {@hide} */
1618    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1619    /** {@hide} */
1620    static final int HAS_BOUNDS                     = 0x00000010;
1621    /** {@hide} */
1622    static final int DRAWN                          = 0x00000020;
1623    /**
1624     * When this flag is set, this view is running an animation on behalf of its
1625     * children and should therefore not cancel invalidate requests, even if they
1626     * lie outside of this view's bounds.
1627     *
1628     * {@hide}
1629     */
1630    static final int DRAW_ANIMATION                 = 0x00000040;
1631    /** {@hide} */
1632    static final int SKIP_DRAW                      = 0x00000080;
1633    /** {@hide} */
1634    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1635    /** {@hide} */
1636    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1637    /** {@hide} */
1638    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1639    /** {@hide} */
1640    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1641    /** {@hide} */
1642    static final int FORCE_LAYOUT                   = 0x00001000;
1643    /** {@hide} */
1644    static final int LAYOUT_REQUIRED                = 0x00002000;
1645
1646    private static final int PRESSED                = 0x00004000;
1647
1648    /** {@hide} */
1649    static final int DRAWING_CACHE_VALID            = 0x00008000;
1650    /**
1651     * Flag used to indicate that this view should be drawn once more (and only once
1652     * more) after its animation has completed.
1653     * {@hide}
1654     */
1655    static final int ANIMATION_STARTED              = 0x00010000;
1656
1657    private static final int SAVE_STATE_CALLED      = 0x00020000;
1658
1659    /**
1660     * Indicates that the View returned true when onSetAlpha() was called and that
1661     * the alpha must be restored.
1662     * {@hide}
1663     */
1664    static final int ALPHA_SET                      = 0x00040000;
1665
1666    /**
1667     * Set by {@link #setScrollContainer(boolean)}.
1668     */
1669    static final int SCROLL_CONTAINER               = 0x00080000;
1670
1671    /**
1672     * Set by {@link #setScrollContainer(boolean)}.
1673     */
1674    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1675
1676    /**
1677     * View flag indicating whether this view was invalidated (fully or partially.)
1678     *
1679     * @hide
1680     */
1681    static final int DIRTY                          = 0x00200000;
1682
1683    /**
1684     * View flag indicating whether this view was invalidated by an opaque
1685     * invalidate request.
1686     *
1687     * @hide
1688     */
1689    static final int DIRTY_OPAQUE                   = 0x00400000;
1690
1691    /**
1692     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1693     *
1694     * @hide
1695     */
1696    static final int DIRTY_MASK                     = 0x00600000;
1697
1698    /**
1699     * Indicates whether the background is opaque.
1700     *
1701     * @hide
1702     */
1703    static final int OPAQUE_BACKGROUND              = 0x00800000;
1704
1705    /**
1706     * Indicates whether the scrollbars are opaque.
1707     *
1708     * @hide
1709     */
1710    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1711
1712    /**
1713     * Indicates whether the view is opaque.
1714     *
1715     * @hide
1716     */
1717    static final int OPAQUE_MASK                    = 0x01800000;
1718
1719    /**
1720     * Indicates a prepressed state;
1721     * the short time between ACTION_DOWN and recognizing
1722     * a 'real' press. Prepressed is used to recognize quick taps
1723     * even when they are shorter than ViewConfiguration.getTapTimeout().
1724     *
1725     * @hide
1726     */
1727    private static final int PREPRESSED             = 0x02000000;
1728
1729    /**
1730     * Indicates whether the view is temporarily detached.
1731     *
1732     * @hide
1733     */
1734    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1735
1736    /**
1737     * Indicates that we should awaken scroll bars once attached
1738     *
1739     * @hide
1740     */
1741    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1742
1743    /**
1744     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1745     * @hide
1746     */
1747    private static final int HOVERED              = 0x10000000;
1748
1749    /**
1750     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1751     * for transform operations
1752     *
1753     * @hide
1754     */
1755    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1756
1757    /** {@hide} */
1758    static final int ACTIVATED                    = 0x40000000;
1759
1760    /**
1761     * Indicates that this view was specifically invalidated, not just dirtied because some
1762     * child view was invalidated. The flag is used to determine when we need to recreate
1763     * a view's display list (as opposed to just returning a reference to its existing
1764     * display list).
1765     *
1766     * @hide
1767     */
1768    static final int INVALIDATED                  = 0x80000000;
1769
1770    /* Masks for mPrivateFlags2 */
1771
1772    /**
1773     * Indicates that this view has reported that it can accept the current drag's content.
1774     * Cleared when the drag operation concludes.
1775     * @hide
1776     */
1777    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1778
1779    /**
1780     * Indicates that this view is currently directly under the drag location in a
1781     * drag-and-drop operation involving content that it can accept.  Cleared when
1782     * the drag exits the view, or when the drag operation concludes.
1783     * @hide
1784     */
1785    static final int DRAG_HOVERED                 = 0x00000002;
1786
1787    /**
1788     * Horizontal layout direction of this view is from Left to Right.
1789     * Use with {@link #setLayoutDirection}.
1790     * @hide
1791     */
1792    public static final int LAYOUT_DIRECTION_LTR = 0;
1793
1794    /**
1795     * Horizontal layout direction of this view is from Right to Left.
1796     * Use with {@link #setLayoutDirection}.
1797     * @hide
1798     */
1799    public static final int LAYOUT_DIRECTION_RTL = 1;
1800
1801    /**
1802     * Horizontal layout direction of this view is inherited from its parent.
1803     * Use with {@link #setLayoutDirection}.
1804     * @hide
1805     */
1806    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1807
1808    /**
1809     * Horizontal layout direction of this view is from deduced from the default language
1810     * script for the locale. Use with {@link #setLayoutDirection}.
1811     * @hide
1812     */
1813    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1814
1815    /**
1816     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1817     * @hide
1818     */
1819    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1820
1821    /**
1822     * Mask for use with private flags indicating bits used for horizontal layout direction.
1823     * @hide
1824     */
1825    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1826
1827    /**
1828     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1829     * right-to-left direction.
1830     * @hide
1831     */
1832    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1833
1834    /**
1835     * Indicates whether the view horizontal layout direction has been resolved.
1836     * @hide
1837     */
1838    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1839
1840    /**
1841     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1842     * @hide
1843     */
1844    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1845
1846    /*
1847     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1848     * flag value.
1849     * @hide
1850     */
1851    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1852            LAYOUT_DIRECTION_LTR,
1853            LAYOUT_DIRECTION_RTL,
1854            LAYOUT_DIRECTION_INHERIT,
1855            LAYOUT_DIRECTION_LOCALE
1856    };
1857
1858    /**
1859     * Default horizontal layout direction.
1860     * @hide
1861     */
1862    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1863
1864    /**
1865     * Indicates that the view is tracking some sort of transient state
1866     * that the app should not need to be aware of, but that the framework
1867     * should take special care to preserve.
1868     *
1869     * @hide
1870     */
1871    static final int HAS_TRANSIENT_STATE = 0x00000100;
1872
1873
1874    /**
1875     * Text direction is inherited thru {@link ViewGroup}
1876     * @hide
1877     */
1878    public static final int TEXT_DIRECTION_INHERIT = 0;
1879
1880    /**
1881     * Text direction is using "first strong algorithm". The first strong directional character
1882     * determines the paragraph direction. If there is no strong directional character, the
1883     * paragraph direction is the view's resolved layout direction.
1884     * @hide
1885     */
1886    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1887
1888    /**
1889     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1890     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1891     * If there are neither, the paragraph direction is the view's resolved layout direction.
1892     * @hide
1893     */
1894    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1895
1896    /**
1897     * Text direction is forced to LTR.
1898     * @hide
1899     */
1900    public static final int TEXT_DIRECTION_LTR = 3;
1901
1902    /**
1903     * Text direction is forced to RTL.
1904     * @hide
1905     */
1906    public static final int TEXT_DIRECTION_RTL = 4;
1907
1908    /**
1909     * Text direction is coming from the system Locale.
1910     * @hide
1911     */
1912    public static final int TEXT_DIRECTION_LOCALE = 5;
1913
1914    /**
1915     * Default text direction is inherited
1916     * @hide
1917     */
1918    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1919
1920    /**
1921     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1922     * @hide
1923     */
1924    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1925
1926    /**
1927     * Mask for use with private flags indicating bits used for text direction.
1928     * @hide
1929     */
1930    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1931
1932    /**
1933     * Array of text direction flags for mapping attribute "textDirection" to correct
1934     * flag value.
1935     * @hide
1936     */
1937    private static final int[] TEXT_DIRECTION_FLAGS = {
1938            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1939            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1940            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1941            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1942            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1943            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1944    };
1945
1946    /**
1947     * Indicates whether the view text direction has been resolved.
1948     * @hide
1949     */
1950    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1951
1952    /**
1953     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1954     * @hide
1955     */
1956    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1957
1958    /**
1959     * Mask for use with private flags indicating bits used for resolved text direction.
1960     * @hide
1961     */
1962    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1963
1964    /**
1965     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1966     * @hide
1967     */
1968    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1969            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1970
1971    /*
1972     * Default text alignment. The text alignment of this View is inherited from its parent.
1973     * Use with {@link #setTextAlignment(int)}
1974     * @hide
1975     */
1976    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1977
1978    /**
1979     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1980     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1981     *
1982     * Use with {@link #setTextAlignment(int)}
1983     * @hide
1984     */
1985    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1986
1987    /**
1988     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1989     *
1990     * Use with {@link #setTextAlignment(int)}
1991     * @hide
1992     */
1993    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1994
1995    /**
1996     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1997     *
1998     * Use with {@link #setTextAlignment(int)}
1999     * @hide
2000     */
2001    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2002
2003    /**
2004     * Center the paragraph, e.g. ALIGN_CENTER.
2005     *
2006     * Use with {@link #setTextAlignment(int)}
2007     * @hide
2008     */
2009    public static final int TEXT_ALIGNMENT_CENTER = 4;
2010
2011    /**
2012     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2013     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2014     *
2015     * Use with {@link #setTextAlignment(int)}
2016     * @hide
2017     */
2018    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2019
2020    /**
2021     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2022     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2023     *
2024     * Use with {@link #setTextAlignment(int)}
2025     * @hide
2026     */
2027    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2028
2029    /**
2030     * Default text alignment is inherited
2031     * @hide
2032     */
2033    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2034
2035    /**
2036      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2037      * @hide
2038      */
2039    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2040
2041    /**
2042      * Mask for use with private flags indicating bits used for text alignment.
2043      * @hide
2044      */
2045    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2046
2047    /**
2048     * Array of text direction flags for mapping attribute "textAlignment" to correct
2049     * flag value.
2050     * @hide
2051     */
2052    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2053            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2054            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2055            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2056            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2057            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2058            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2059            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2060    };
2061
2062    /**
2063     * Indicates whether the view text alignment has been resolved.
2064     * @hide
2065     */
2066    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2067
2068    /**
2069     * Bit shift to get the resolved text alignment.
2070     * @hide
2071     */
2072    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2073
2074    /**
2075     * Mask for use with private flags indicating bits used for text alignment.
2076     * @hide
2077     */
2078    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2079
2080    /**
2081     * Indicates whether if the view text alignment has been resolved to gravity
2082     */
2083    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2084            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2085
2086    // Accessiblity constants for mPrivateFlags2
2087
2088    /**
2089     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2090     */
2091    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2092
2093    /**
2094     * Automatically determine whether a view is important for accessibility.
2095     */
2096    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2097
2098    /**
2099     * The view is important for accessibility.
2100     */
2101    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2102
2103    /**
2104     * The view is not important for accessibility.
2105     */
2106    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2107
2108    /**
2109     * The default whether the view is important for accessiblity.
2110     */
2111    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2112
2113    /**
2114     * Mask for obtainig the bits which specify how to determine
2115     * whether a view is important for accessibility.
2116     */
2117    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2118        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2119        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2120
2121    /**
2122     * Flag indicating whether a view has accessibility focus.
2123     */
2124    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2125
2126    /**
2127     * Flag indicating whether a view state for accessibility has changed.
2128     */
2129    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2130
2131    /* End of masks for mPrivateFlags2 */
2132
2133    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2134
2135    /**
2136     * Always allow a user to over-scroll this view, provided it is a
2137     * view that can scroll.
2138     *
2139     * @see #getOverScrollMode()
2140     * @see #setOverScrollMode(int)
2141     */
2142    public static final int OVER_SCROLL_ALWAYS = 0;
2143
2144    /**
2145     * Allow a user to over-scroll this view only if the content is large
2146     * enough to meaningfully scroll, provided it is a view that can scroll.
2147     *
2148     * @see #getOverScrollMode()
2149     * @see #setOverScrollMode(int)
2150     */
2151    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2152
2153    /**
2154     * Never allow a user to over-scroll this view.
2155     *
2156     * @see #getOverScrollMode()
2157     * @see #setOverScrollMode(int)
2158     */
2159    public static final int OVER_SCROLL_NEVER = 2;
2160
2161    /**
2162     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2163     * requested the system UI (status bar) to be visible (the default).
2164     *
2165     * @see #setSystemUiVisibility(int)
2166     */
2167    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2168
2169    /**
2170     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2171     * system UI to enter an unobtrusive "low profile" mode.
2172     *
2173     * <p>This is for use in games, book readers, video players, or any other
2174     * "immersive" application where the usual system chrome is deemed too distracting.
2175     *
2176     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2177     *
2178     * @see #setSystemUiVisibility(int)
2179     */
2180    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2181
2182    /**
2183     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2184     * system navigation be temporarily hidden.
2185     *
2186     * <p>This is an even less obtrusive state than that called for by
2187     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2188     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2189     * those to disappear. This is useful (in conjunction with the
2190     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2191     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2192     * window flags) for displaying content using every last pixel on the display.
2193     *
2194     * <p>There is a limitation: because navigation controls are so important, the least user
2195     * interaction will cause them to reappear immediately.  When this happens, both
2196     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2197     * so that both elements reappear at the same time.
2198     *
2199     * @see #setSystemUiVisibility(int)
2200     */
2201    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2202
2203    /**
2204     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2205     * into the normal fullscreen mode so that its content can take over the screen
2206     * while still allowing the user to interact with the application.
2207     *
2208     * <p>This has the same visual effect as
2209     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2210     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2211     * meaning that non-critical screen decorations (such as the status bar) will be
2212     * hidden while the user is in the View's window, focusing the experience on
2213     * that content.  Unlike the window flag, if you are using ActionBar in
2214     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2215     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2216     * hide the action bar.
2217     *
2218     * <p>This approach to going fullscreen is best used over the window flag when
2219     * it is a transient state -- that is, the application does this at certain
2220     * points in its user interaction where it wants to allow the user to focus
2221     * on content, but not as a continuous state.  For situations where the application
2222     * would like to simply stay full screen the entire time (such as a game that
2223     * wants to take over the screen), the
2224     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2225     * is usually a better approach.  The state set here will be removed by the system
2226     * in various situations (such as the user moving to another application) like
2227     * the other system UI states.
2228     *
2229     * <p>When using this flag, the application should provide some easy facility
2230     * for the user to go out of it.  A common example would be in an e-book
2231     * reader, where tapping on the screen brings back whatever screen and UI
2232     * decorations that had been hidden while the user was immersed in reading
2233     * the book.
2234     *
2235     * @see #setSystemUiVisibility(int)
2236     */
2237    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2238
2239    /**
2240     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2241     * flags, we would like a stable view of the content insets given to
2242     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2243     * will always represent the worst case that the application can expect
2244     * as a continue state.  In practice this means with any of system bar,
2245     * nav bar, and status bar shown, but not the space that would be needed
2246     * for an input method.
2247     *
2248     * <p>If you are using ActionBar in
2249     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2250     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2251     * insets it adds to those given to the application.
2252     */
2253    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2254
2255    /**
2256     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2257     * to be layed out as if it has requested
2258     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2259     * allows it to avoid artifacts when switching in and out of that mode, at
2260     * the expense that some of its user interface may be covered by screen
2261     * decorations when they are shown.  You can perform layout of your inner
2262     * UI elements to account for the navagation system UI through the
2263     * {@link #fitSystemWindows(Rect)} method.
2264     */
2265    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2266
2267    /**
2268     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2269     * to be layed out as if it has requested
2270     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2271     * allows it to avoid artifacts when switching in and out of that mode, at
2272     * the expense that some of its user interface may be covered by screen
2273     * decorations when they are shown.  You can perform layout of your inner
2274     * UI elements to account for non-fullscreen system UI through the
2275     * {@link #fitSystemWindows(Rect)} method.
2276     */
2277    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2278
2279    /**
2280     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2281     */
2282    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2283
2284    /**
2285     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2286     */
2287    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2288
2289    /**
2290     * @hide
2291     *
2292     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2293     * out of the public fields to keep the undefined bits out of the developer's way.
2294     *
2295     * Flag to make the status bar not expandable.  Unless you also
2296     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2297     */
2298    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2299
2300    /**
2301     * @hide
2302     *
2303     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2304     * out of the public fields to keep the undefined bits out of the developer's way.
2305     *
2306     * Flag to hide notification icons and scrolling ticker text.
2307     */
2308    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2309
2310    /**
2311     * @hide
2312     *
2313     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2314     * out of the public fields to keep the undefined bits out of the developer's way.
2315     *
2316     * Flag to disable incoming notification alerts.  This will not block
2317     * icons, but it will block sound, vibrating and other visual or aural notifications.
2318     */
2319    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2320
2321    /**
2322     * @hide
2323     *
2324     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2325     * out of the public fields to keep the undefined bits out of the developer's way.
2326     *
2327     * Flag to hide only the scrolling ticker.  Note that
2328     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2329     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2330     */
2331    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2332
2333    /**
2334     * @hide
2335     *
2336     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2337     * out of the public fields to keep the undefined bits out of the developer's way.
2338     *
2339     * Flag to hide the center system info area.
2340     */
2341    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2342
2343    /**
2344     * @hide
2345     *
2346     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2347     * out of the public fields to keep the undefined bits out of the developer's way.
2348     *
2349     * Flag to hide only the home button.  Don't use this
2350     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2351     */
2352    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2353
2354    /**
2355     * @hide
2356     *
2357     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2358     * out of the public fields to keep the undefined bits out of the developer's way.
2359     *
2360     * Flag to hide only the back button. Don't use this
2361     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2362     */
2363    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2364
2365    /**
2366     * @hide
2367     *
2368     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2369     * out of the public fields to keep the undefined bits out of the developer's way.
2370     *
2371     * Flag to hide only the clock.  You might use this if your activity has
2372     * its own clock making the status bar's clock redundant.
2373     */
2374    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2375
2376    /**
2377     * @hide
2378     *
2379     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2380     * out of the public fields to keep the undefined bits out of the developer's way.
2381     *
2382     * Flag to hide only the recent apps button. Don't use this
2383     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2384     */
2385    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2386
2387    /**
2388     * @hide
2389     */
2390    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2391
2392    /**
2393     * These are the system UI flags that can be cleared by events outside
2394     * of an application.  Currently this is just the ability to tap on the
2395     * screen while hiding the navigation bar to have it return.
2396     * @hide
2397     */
2398    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2399            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2400            | SYSTEM_UI_FLAG_FULLSCREEN;
2401
2402    /**
2403     * Flags that can impact the layout in relation to system UI.
2404     */
2405    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2406            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2407            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2408
2409    /**
2410     * Find views that render the specified text.
2411     *
2412     * @see #findViewsWithText(ArrayList, CharSequence, int)
2413     */
2414    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2415
2416    /**
2417     * Find find views that contain the specified content description.
2418     *
2419     * @see #findViewsWithText(ArrayList, CharSequence, int)
2420     */
2421    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2422
2423    /**
2424     * Find views that contain {@link AccessibilityNodeProvider}. Such
2425     * a View is a root of virtual view hierarchy and may contain the searched
2426     * text. If this flag is set Views with providers are automatically
2427     * added and it is a responsibility of the client to call the APIs of
2428     * the provider to determine whether the virtual tree rooted at this View
2429     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2430     * represeting the virtual views with this text.
2431     *
2432     * @see #findViewsWithText(ArrayList, CharSequence, int)
2433     *
2434     * @hide
2435     */
2436    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2437
2438    /**
2439     * Indicates that the screen has changed state and is now off.
2440     *
2441     * @see #onScreenStateChanged(int)
2442     */
2443    public static final int SCREEN_STATE_OFF = 0x0;
2444
2445    /**
2446     * Indicates that the screen has changed state and is now on.
2447     *
2448     * @see #onScreenStateChanged(int)
2449     */
2450    public static final int SCREEN_STATE_ON = 0x1;
2451
2452    /**
2453     * Controls the over-scroll mode for this view.
2454     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2455     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2456     * and {@link #OVER_SCROLL_NEVER}.
2457     */
2458    private int mOverScrollMode;
2459
2460    /**
2461     * The parent this view is attached to.
2462     * {@hide}
2463     *
2464     * @see #getParent()
2465     */
2466    protected ViewParent mParent;
2467
2468    /**
2469     * {@hide}
2470     */
2471    AttachInfo mAttachInfo;
2472
2473    /**
2474     * {@hide}
2475     */
2476    @ViewDebug.ExportedProperty(flagMapping = {
2477        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2478                name = "FORCE_LAYOUT"),
2479        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2480                name = "LAYOUT_REQUIRED"),
2481        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2482            name = "DRAWING_CACHE_INVALID", outputIf = false),
2483        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2484        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2485        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2486        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2487    })
2488    int mPrivateFlags;
2489    int mPrivateFlags2;
2490
2491    /**
2492     * This view's request for the visibility of the status bar.
2493     * @hide
2494     */
2495    @ViewDebug.ExportedProperty(flagMapping = {
2496        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2497                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2498                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2499        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2500                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2501                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2502        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2503                                equals = SYSTEM_UI_FLAG_VISIBLE,
2504                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2505    })
2506    int mSystemUiVisibility;
2507
2508    /**
2509     * Reference count for transient state.
2510     * @see #setHasTransientState(boolean)
2511     */
2512    int mTransientStateCount = 0;
2513
2514    /**
2515     * Count of how many windows this view has been attached to.
2516     */
2517    int mWindowAttachCount;
2518
2519    /**
2520     * The layout parameters associated with this view and used by the parent
2521     * {@link android.view.ViewGroup} to determine how this view should be
2522     * laid out.
2523     * {@hide}
2524     */
2525    protected ViewGroup.LayoutParams mLayoutParams;
2526
2527    /**
2528     * The view flags hold various views states.
2529     * {@hide}
2530     */
2531    @ViewDebug.ExportedProperty
2532    int mViewFlags;
2533
2534    static class TransformationInfo {
2535        /**
2536         * The transform matrix for the View. This transform is calculated internally
2537         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2538         * is used by default. Do *not* use this variable directly; instead call
2539         * getMatrix(), which will automatically recalculate the matrix if necessary
2540         * to get the correct matrix based on the latest rotation and scale properties.
2541         */
2542        private final Matrix mMatrix = new Matrix();
2543
2544        /**
2545         * The transform matrix for the View. This transform is calculated internally
2546         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2547         * is used by default. Do *not* use this variable directly; instead call
2548         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2549         * to get the correct matrix based on the latest rotation and scale properties.
2550         */
2551        private Matrix mInverseMatrix;
2552
2553        /**
2554         * An internal variable that tracks whether we need to recalculate the
2555         * transform matrix, based on whether the rotation or scaleX/Y properties
2556         * have changed since the matrix was last calculated.
2557         */
2558        boolean mMatrixDirty = false;
2559
2560        /**
2561         * An internal variable that tracks whether we need to recalculate the
2562         * transform matrix, based on whether the rotation or scaleX/Y properties
2563         * have changed since the matrix was last calculated.
2564         */
2565        private boolean mInverseMatrixDirty = true;
2566
2567        /**
2568         * A variable that tracks whether we need to recalculate the
2569         * transform matrix, based on whether the rotation or scaleX/Y properties
2570         * have changed since the matrix was last calculated. This variable
2571         * is only valid after a call to updateMatrix() or to a function that
2572         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2573         */
2574        private boolean mMatrixIsIdentity = true;
2575
2576        /**
2577         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2578         */
2579        private Camera mCamera = null;
2580
2581        /**
2582         * This matrix is used when computing the matrix for 3D rotations.
2583         */
2584        private Matrix matrix3D = null;
2585
2586        /**
2587         * These prev values are used to recalculate a centered pivot point when necessary. The
2588         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2589         * set), so thes values are only used then as well.
2590         */
2591        private int mPrevWidth = -1;
2592        private int mPrevHeight = -1;
2593
2594        /**
2595         * The degrees rotation around the vertical axis through the pivot point.
2596         */
2597        @ViewDebug.ExportedProperty
2598        float mRotationY = 0f;
2599
2600        /**
2601         * The degrees rotation around the horizontal axis through the pivot point.
2602         */
2603        @ViewDebug.ExportedProperty
2604        float mRotationX = 0f;
2605
2606        /**
2607         * The degrees rotation around the pivot point.
2608         */
2609        @ViewDebug.ExportedProperty
2610        float mRotation = 0f;
2611
2612        /**
2613         * The amount of translation of the object away from its left property (post-layout).
2614         */
2615        @ViewDebug.ExportedProperty
2616        float mTranslationX = 0f;
2617
2618        /**
2619         * The amount of translation of the object away from its top property (post-layout).
2620         */
2621        @ViewDebug.ExportedProperty
2622        float mTranslationY = 0f;
2623
2624        /**
2625         * The amount of scale in the x direction around the pivot point. A
2626         * value of 1 means no scaling is applied.
2627         */
2628        @ViewDebug.ExportedProperty
2629        float mScaleX = 1f;
2630
2631        /**
2632         * The amount of scale in the y direction around the pivot point. A
2633         * value of 1 means no scaling is applied.
2634         */
2635        @ViewDebug.ExportedProperty
2636        float mScaleY = 1f;
2637
2638        /**
2639         * The x location of the point around which the view is rotated and scaled.
2640         */
2641        @ViewDebug.ExportedProperty
2642        float mPivotX = 0f;
2643
2644        /**
2645         * The y location of the point around which the view is rotated and scaled.
2646         */
2647        @ViewDebug.ExportedProperty
2648        float mPivotY = 0f;
2649
2650        /**
2651         * The opacity of the View. This is a value from 0 to 1, where 0 means
2652         * completely transparent and 1 means completely opaque.
2653         */
2654        @ViewDebug.ExportedProperty
2655        float mAlpha = 1f;
2656    }
2657
2658    TransformationInfo mTransformationInfo;
2659
2660    private boolean mLastIsOpaque;
2661
2662    /**
2663     * Convenience value to check for float values that are close enough to zero to be considered
2664     * zero.
2665     */
2666    private static final float NONZERO_EPSILON = .001f;
2667
2668    /**
2669     * The distance in pixels from the left edge of this view's parent
2670     * to the left edge of this view.
2671     * {@hide}
2672     */
2673    @ViewDebug.ExportedProperty(category = "layout")
2674    protected int mLeft;
2675    /**
2676     * The distance in pixels from the left edge of this view's parent
2677     * to the right edge of this view.
2678     * {@hide}
2679     */
2680    @ViewDebug.ExportedProperty(category = "layout")
2681    protected int mRight;
2682    /**
2683     * The distance in pixels from the top edge of this view's parent
2684     * to the top edge of this view.
2685     * {@hide}
2686     */
2687    @ViewDebug.ExportedProperty(category = "layout")
2688    protected int mTop;
2689    /**
2690     * The distance in pixels from the top edge of this view's parent
2691     * to the bottom edge of this view.
2692     * {@hide}
2693     */
2694    @ViewDebug.ExportedProperty(category = "layout")
2695    protected int mBottom;
2696
2697    /**
2698     * The offset, in pixels, by which the content of this view is scrolled
2699     * horizontally.
2700     * {@hide}
2701     */
2702    @ViewDebug.ExportedProperty(category = "scrolling")
2703    protected int mScrollX;
2704    /**
2705     * The offset, in pixels, by which the content of this view is scrolled
2706     * vertically.
2707     * {@hide}
2708     */
2709    @ViewDebug.ExportedProperty(category = "scrolling")
2710    protected int mScrollY;
2711
2712    /**
2713     * The left padding in pixels, that is the distance in pixels between the
2714     * left edge of this view and the left edge of its content.
2715     * {@hide}
2716     */
2717    @ViewDebug.ExportedProperty(category = "padding")
2718    protected int mPaddingLeft;
2719    /**
2720     * The right padding in pixels, that is the distance in pixels between the
2721     * right edge of this view and the right edge of its content.
2722     * {@hide}
2723     */
2724    @ViewDebug.ExportedProperty(category = "padding")
2725    protected int mPaddingRight;
2726    /**
2727     * The top padding in pixels, that is the distance in pixels between the
2728     * top edge of this view and the top edge of its content.
2729     * {@hide}
2730     */
2731    @ViewDebug.ExportedProperty(category = "padding")
2732    protected int mPaddingTop;
2733    /**
2734     * The bottom padding in pixels, that is the distance in pixels between the
2735     * bottom edge of this view and the bottom edge of its content.
2736     * {@hide}
2737     */
2738    @ViewDebug.ExportedProperty(category = "padding")
2739    protected int mPaddingBottom;
2740
2741    /**
2742     * The layout insets in pixels, that is the distance in pixels between the
2743     * visible edges of this view its bounds.
2744     */
2745    private Insets mLayoutInsets;
2746
2747    /**
2748     * Briefly describes the view and is primarily used for accessibility support.
2749     */
2750    private CharSequence mContentDescription;
2751
2752    /**
2753     * Cache the paddingRight set by the user to append to the scrollbar's size.
2754     *
2755     * @hide
2756     */
2757    @ViewDebug.ExportedProperty(category = "padding")
2758    protected int mUserPaddingRight;
2759
2760    /**
2761     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2762     *
2763     * @hide
2764     */
2765    @ViewDebug.ExportedProperty(category = "padding")
2766    protected int mUserPaddingBottom;
2767
2768    /**
2769     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2770     *
2771     * @hide
2772     */
2773    @ViewDebug.ExportedProperty(category = "padding")
2774    protected int mUserPaddingLeft;
2775
2776    /**
2777     * Cache if the user padding is relative.
2778     *
2779     */
2780    @ViewDebug.ExportedProperty(category = "padding")
2781    boolean mUserPaddingRelative;
2782
2783    /**
2784     * Cache the paddingStart set by the user to append to the scrollbar's size.
2785     *
2786     */
2787    @ViewDebug.ExportedProperty(category = "padding")
2788    int mUserPaddingStart;
2789
2790    /**
2791     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2792     *
2793     */
2794    @ViewDebug.ExportedProperty(category = "padding")
2795    int mUserPaddingEnd;
2796
2797    /**
2798     * @hide
2799     */
2800    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2801    /**
2802     * @hide
2803     */
2804    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2805
2806    private Drawable mBackground;
2807
2808    private int mBackgroundResource;
2809    private boolean mBackgroundSizeChanged;
2810
2811    static class ListenerInfo {
2812        /**
2813         * Listener used to dispatch focus change events.
2814         * This field should be made private, so it is hidden from the SDK.
2815         * {@hide}
2816         */
2817        protected OnFocusChangeListener mOnFocusChangeListener;
2818
2819        /**
2820         * Listeners for layout change events.
2821         */
2822        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2823
2824        /**
2825         * Listeners for attach events.
2826         */
2827        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2828
2829        /**
2830         * Listener used to dispatch click events.
2831         * This field should be made private, so it is hidden from the SDK.
2832         * {@hide}
2833         */
2834        public OnClickListener mOnClickListener;
2835
2836        /**
2837         * Listener used to dispatch long click events.
2838         * This field should be made private, so it is hidden from the SDK.
2839         * {@hide}
2840         */
2841        protected OnLongClickListener mOnLongClickListener;
2842
2843        /**
2844         * Listener used to build the context menu.
2845         * This field should be made private, so it is hidden from the SDK.
2846         * {@hide}
2847         */
2848        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2849
2850        private OnKeyListener mOnKeyListener;
2851
2852        private OnTouchListener mOnTouchListener;
2853
2854        private OnHoverListener mOnHoverListener;
2855
2856        private OnGenericMotionListener mOnGenericMotionListener;
2857
2858        private OnDragListener mOnDragListener;
2859
2860        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2861    }
2862
2863    ListenerInfo mListenerInfo;
2864
2865    /**
2866     * The application environment this view lives in.
2867     * This field should be made private, so it is hidden from the SDK.
2868     * {@hide}
2869     */
2870    protected Context mContext;
2871
2872    private final Resources mResources;
2873
2874    private ScrollabilityCache mScrollCache;
2875
2876    private int[] mDrawableState = null;
2877
2878    /**
2879     * Set to true when drawing cache is enabled and cannot be created.
2880     *
2881     * @hide
2882     */
2883    public boolean mCachingFailed;
2884
2885    private Bitmap mDrawingCache;
2886    private Bitmap mUnscaledDrawingCache;
2887    private HardwareLayer mHardwareLayer;
2888    DisplayList mDisplayList;
2889
2890    /**
2891     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2892     * the user may specify which view to go to next.
2893     */
2894    private int mNextFocusLeftId = View.NO_ID;
2895
2896    /**
2897     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2898     * the user may specify which view to go to next.
2899     */
2900    private int mNextFocusRightId = View.NO_ID;
2901
2902    /**
2903     * When this view has focus and the next focus is {@link #FOCUS_UP},
2904     * the user may specify which view to go to next.
2905     */
2906    private int mNextFocusUpId = View.NO_ID;
2907
2908    /**
2909     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2910     * the user may specify which view to go to next.
2911     */
2912    private int mNextFocusDownId = View.NO_ID;
2913
2914    /**
2915     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2916     * the user may specify which view to go to next.
2917     */
2918    int mNextFocusForwardId = View.NO_ID;
2919
2920    private CheckForLongPress mPendingCheckForLongPress;
2921    private CheckForTap mPendingCheckForTap = null;
2922    private PerformClick mPerformClick;
2923    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2924
2925    private UnsetPressedState mUnsetPressedState;
2926
2927    /**
2928     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2929     * up event while a long press is invoked as soon as the long press duration is reached, so
2930     * a long press could be performed before the tap is checked, in which case the tap's action
2931     * should not be invoked.
2932     */
2933    private boolean mHasPerformedLongPress;
2934
2935    /**
2936     * The minimum height of the view. We'll try our best to have the height
2937     * of this view to at least this amount.
2938     */
2939    @ViewDebug.ExportedProperty(category = "measurement")
2940    private int mMinHeight;
2941
2942    /**
2943     * The minimum width of the view. We'll try our best to have the width
2944     * of this view to at least this amount.
2945     */
2946    @ViewDebug.ExportedProperty(category = "measurement")
2947    private int mMinWidth;
2948
2949    /**
2950     * The delegate to handle touch events that are physically in this view
2951     * but should be handled by another view.
2952     */
2953    private TouchDelegate mTouchDelegate = null;
2954
2955    /**
2956     * Solid color to use as a background when creating the drawing cache. Enables
2957     * the cache to use 16 bit bitmaps instead of 32 bit.
2958     */
2959    private int mDrawingCacheBackgroundColor = 0;
2960
2961    /**
2962     * Special tree observer used when mAttachInfo is null.
2963     */
2964    private ViewTreeObserver mFloatingTreeObserver;
2965
2966    /**
2967     * Cache the touch slop from the context that created the view.
2968     */
2969    private int mTouchSlop;
2970
2971    /**
2972     * Object that handles automatic animation of view properties.
2973     */
2974    private ViewPropertyAnimator mAnimator = null;
2975
2976    /**
2977     * Flag indicating that a drag can cross window boundaries.  When
2978     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2979     * with this flag set, all visible applications will be able to participate
2980     * in the drag operation and receive the dragged content.
2981     *
2982     * @hide
2983     */
2984    public static final int DRAG_FLAG_GLOBAL = 1;
2985
2986    /**
2987     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2988     */
2989    private float mVerticalScrollFactor;
2990
2991    /**
2992     * Position of the vertical scroll bar.
2993     */
2994    private int mVerticalScrollbarPosition;
2995
2996    /**
2997     * Position the scroll bar at the default position as determined by the system.
2998     */
2999    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3000
3001    /**
3002     * Position the scroll bar along the left edge.
3003     */
3004    public static final int SCROLLBAR_POSITION_LEFT = 1;
3005
3006    /**
3007     * Position the scroll bar along the right edge.
3008     */
3009    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3010
3011    /**
3012     * Indicates that the view does not have a layer.
3013     *
3014     * @see #getLayerType()
3015     * @see #setLayerType(int, android.graphics.Paint)
3016     * @see #LAYER_TYPE_SOFTWARE
3017     * @see #LAYER_TYPE_HARDWARE
3018     */
3019    public static final int LAYER_TYPE_NONE = 0;
3020
3021    /**
3022     * <p>Indicates that the view has a software layer. A software layer is backed
3023     * by a bitmap and causes the view to be rendered using Android's software
3024     * rendering pipeline, even if hardware acceleration is enabled.</p>
3025     *
3026     * <p>Software layers have various usages:</p>
3027     * <p>When the application is not using hardware acceleration, a software layer
3028     * is useful to apply a specific color filter and/or blending mode and/or
3029     * translucency to a view and all its children.</p>
3030     * <p>When the application is using hardware acceleration, a software layer
3031     * is useful to render drawing primitives not supported by the hardware
3032     * accelerated pipeline. It can also be used to cache a complex view tree
3033     * into a texture and reduce the complexity of drawing operations. For instance,
3034     * when animating a complex view tree with a translation, a software layer can
3035     * be used to render the view tree only once.</p>
3036     * <p>Software layers should be avoided when the affected view tree updates
3037     * often. Every update will require to re-render the software layer, which can
3038     * potentially be slow (particularly when hardware acceleration is turned on
3039     * since the layer will have to be uploaded into a hardware texture after every
3040     * update.)</p>
3041     *
3042     * @see #getLayerType()
3043     * @see #setLayerType(int, android.graphics.Paint)
3044     * @see #LAYER_TYPE_NONE
3045     * @see #LAYER_TYPE_HARDWARE
3046     */
3047    public static final int LAYER_TYPE_SOFTWARE = 1;
3048
3049    /**
3050     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3051     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3052     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3053     * rendering pipeline, but only if hardware acceleration is turned on for the
3054     * view hierarchy. When hardware acceleration is turned off, hardware layers
3055     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3056     *
3057     * <p>A hardware layer is useful to apply a specific color filter and/or
3058     * blending mode and/or translucency to a view and all its children.</p>
3059     * <p>A hardware layer can be used to cache a complex view tree into a
3060     * texture and reduce the complexity of drawing operations. For instance,
3061     * when animating a complex view tree with a translation, a hardware layer can
3062     * be used to render the view tree only once.</p>
3063     * <p>A hardware layer can also be used to increase the rendering quality when
3064     * rotation transformations are applied on a view. It can also be used to
3065     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3066     *
3067     * @see #getLayerType()
3068     * @see #setLayerType(int, android.graphics.Paint)
3069     * @see #LAYER_TYPE_NONE
3070     * @see #LAYER_TYPE_SOFTWARE
3071     */
3072    public static final int LAYER_TYPE_HARDWARE = 2;
3073
3074    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3075            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3076            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3077            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3078    })
3079    int mLayerType = LAYER_TYPE_NONE;
3080    Paint mLayerPaint;
3081    Rect mLocalDirtyRect;
3082
3083    /**
3084     * Set to true when the view is sending hover accessibility events because it
3085     * is the innermost hovered view.
3086     */
3087    private boolean mSendingHoverAccessibilityEvents;
3088
3089    /**
3090     * Simple constructor to use when creating a view from code.
3091     *
3092     * @param context The Context the view is running in, through which it can
3093     *        access the current theme, resources, etc.
3094     */
3095    public View(Context context) {
3096        mContext = context;
3097        mResources = context != null ? context.getResources() : null;
3098        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3099        // Set layout and text direction defaults
3100        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3101                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3102                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3103                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3104        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3105        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3106        mUserPaddingStart = -1;
3107        mUserPaddingEnd = -1;
3108        mUserPaddingRelative = false;
3109    }
3110
3111    /**
3112     * Delegate for injecting accessiblity functionality.
3113     */
3114    AccessibilityDelegate mAccessibilityDelegate;
3115
3116    /**
3117     * Consistency verifier for debugging purposes.
3118     * @hide
3119     */
3120    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3121            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3122                    new InputEventConsistencyVerifier(this, 0) : null;
3123
3124    /**
3125     * Constructor that is called when inflating a view from XML. This is called
3126     * when a view is being constructed from an XML file, supplying attributes
3127     * that were specified in the XML file. This version uses a default style of
3128     * 0, so the only attribute values applied are those in the Context's Theme
3129     * and the given AttributeSet.
3130     *
3131     * <p>
3132     * The method onFinishInflate() will be called after all children have been
3133     * added.
3134     *
3135     * @param context The Context the view is running in, through which it can
3136     *        access the current theme, resources, etc.
3137     * @param attrs The attributes of the XML tag that is inflating the view.
3138     * @see #View(Context, AttributeSet, int)
3139     */
3140    public View(Context context, AttributeSet attrs) {
3141        this(context, attrs, 0);
3142    }
3143
3144    /**
3145     * Perform inflation from XML and apply a class-specific base style. This
3146     * constructor of View allows subclasses to use their own base style when
3147     * they are inflating. For example, a Button class's constructor would call
3148     * this version of the super class constructor and supply
3149     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3150     * the theme's button style to modify all of the base view attributes (in
3151     * particular its background) as well as the Button class's attributes.
3152     *
3153     * @param context The Context the view is running in, through which it can
3154     *        access the current theme, resources, etc.
3155     * @param attrs The attributes of the XML tag that is inflating the view.
3156     * @param defStyle The default style to apply to this view. If 0, no style
3157     *        will be applied (beyond what is included in the theme). This may
3158     *        either be an attribute resource, whose value will be retrieved
3159     *        from the current theme, or an explicit style resource.
3160     * @see #View(Context, AttributeSet)
3161     */
3162    public View(Context context, AttributeSet attrs, int defStyle) {
3163        this(context);
3164
3165        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3166                defStyle, 0);
3167
3168        Drawable background = null;
3169
3170        int leftPadding = -1;
3171        int topPadding = -1;
3172        int rightPadding = -1;
3173        int bottomPadding = -1;
3174        int startPadding = -1;
3175        int endPadding = -1;
3176
3177        int padding = -1;
3178
3179        int viewFlagValues = 0;
3180        int viewFlagMasks = 0;
3181
3182        boolean setScrollContainer = false;
3183
3184        int x = 0;
3185        int y = 0;
3186
3187        float tx = 0;
3188        float ty = 0;
3189        float rotation = 0;
3190        float rotationX = 0;
3191        float rotationY = 0;
3192        float sx = 1f;
3193        float sy = 1f;
3194        boolean transformSet = false;
3195
3196        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3197
3198        int overScrollMode = mOverScrollMode;
3199        final int N = a.getIndexCount();
3200        for (int i = 0; i < N; i++) {
3201            int attr = a.getIndex(i);
3202            switch (attr) {
3203                case com.android.internal.R.styleable.View_background:
3204                    background = a.getDrawable(attr);
3205                    break;
3206                case com.android.internal.R.styleable.View_padding:
3207                    padding = a.getDimensionPixelSize(attr, -1);
3208                    break;
3209                 case com.android.internal.R.styleable.View_paddingLeft:
3210                    leftPadding = a.getDimensionPixelSize(attr, -1);
3211                    break;
3212                case com.android.internal.R.styleable.View_paddingTop:
3213                    topPadding = a.getDimensionPixelSize(attr, -1);
3214                    break;
3215                case com.android.internal.R.styleable.View_paddingRight:
3216                    rightPadding = a.getDimensionPixelSize(attr, -1);
3217                    break;
3218                case com.android.internal.R.styleable.View_paddingBottom:
3219                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3220                    break;
3221                case com.android.internal.R.styleable.View_paddingStart:
3222                    startPadding = a.getDimensionPixelSize(attr, -1);
3223                    break;
3224                case com.android.internal.R.styleable.View_paddingEnd:
3225                    endPadding = a.getDimensionPixelSize(attr, -1);
3226                    break;
3227                case com.android.internal.R.styleable.View_scrollX:
3228                    x = a.getDimensionPixelOffset(attr, 0);
3229                    break;
3230                case com.android.internal.R.styleable.View_scrollY:
3231                    y = a.getDimensionPixelOffset(attr, 0);
3232                    break;
3233                case com.android.internal.R.styleable.View_alpha:
3234                    setAlpha(a.getFloat(attr, 1f));
3235                    break;
3236                case com.android.internal.R.styleable.View_transformPivotX:
3237                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3238                    break;
3239                case com.android.internal.R.styleable.View_transformPivotY:
3240                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3241                    break;
3242                case com.android.internal.R.styleable.View_translationX:
3243                    tx = a.getDimensionPixelOffset(attr, 0);
3244                    transformSet = true;
3245                    break;
3246                case com.android.internal.R.styleable.View_translationY:
3247                    ty = a.getDimensionPixelOffset(attr, 0);
3248                    transformSet = true;
3249                    break;
3250                case com.android.internal.R.styleable.View_rotation:
3251                    rotation = a.getFloat(attr, 0);
3252                    transformSet = true;
3253                    break;
3254                case com.android.internal.R.styleable.View_rotationX:
3255                    rotationX = a.getFloat(attr, 0);
3256                    transformSet = true;
3257                    break;
3258                case com.android.internal.R.styleable.View_rotationY:
3259                    rotationY = a.getFloat(attr, 0);
3260                    transformSet = true;
3261                    break;
3262                case com.android.internal.R.styleable.View_scaleX:
3263                    sx = a.getFloat(attr, 1f);
3264                    transformSet = true;
3265                    break;
3266                case com.android.internal.R.styleable.View_scaleY:
3267                    sy = a.getFloat(attr, 1f);
3268                    transformSet = true;
3269                    break;
3270                case com.android.internal.R.styleable.View_id:
3271                    mID = a.getResourceId(attr, NO_ID);
3272                    break;
3273                case com.android.internal.R.styleable.View_tag:
3274                    mTag = a.getText(attr);
3275                    break;
3276                case com.android.internal.R.styleable.View_fitsSystemWindows:
3277                    if (a.getBoolean(attr, false)) {
3278                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3279                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3280                    }
3281                    break;
3282                case com.android.internal.R.styleable.View_focusable:
3283                    if (a.getBoolean(attr, false)) {
3284                        viewFlagValues |= FOCUSABLE;
3285                        viewFlagMasks |= FOCUSABLE_MASK;
3286                    }
3287                    break;
3288                case com.android.internal.R.styleable.View_focusableInTouchMode:
3289                    if (a.getBoolean(attr, false)) {
3290                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3291                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3292                    }
3293                    break;
3294                case com.android.internal.R.styleable.View_clickable:
3295                    if (a.getBoolean(attr, false)) {
3296                        viewFlagValues |= CLICKABLE;
3297                        viewFlagMasks |= CLICKABLE;
3298                    }
3299                    break;
3300                case com.android.internal.R.styleable.View_longClickable:
3301                    if (a.getBoolean(attr, false)) {
3302                        viewFlagValues |= LONG_CLICKABLE;
3303                        viewFlagMasks |= LONG_CLICKABLE;
3304                    }
3305                    break;
3306                case com.android.internal.R.styleable.View_saveEnabled:
3307                    if (!a.getBoolean(attr, true)) {
3308                        viewFlagValues |= SAVE_DISABLED;
3309                        viewFlagMasks |= SAVE_DISABLED_MASK;
3310                    }
3311                    break;
3312                case com.android.internal.R.styleable.View_duplicateParentState:
3313                    if (a.getBoolean(attr, false)) {
3314                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3315                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3316                    }
3317                    break;
3318                case com.android.internal.R.styleable.View_visibility:
3319                    final int visibility = a.getInt(attr, 0);
3320                    if (visibility != 0) {
3321                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3322                        viewFlagMasks |= VISIBILITY_MASK;
3323                    }
3324                    break;
3325                case com.android.internal.R.styleable.View_layoutDirection:
3326                    // Clear any layout direction flags (included resolved bits) already set
3327                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3328                    // Set the layout direction flags depending on the value of the attribute
3329                    final int layoutDirection = a.getInt(attr, -1);
3330                    final int value = (layoutDirection != -1) ?
3331                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3332                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3333                    break;
3334                case com.android.internal.R.styleable.View_drawingCacheQuality:
3335                    final int cacheQuality = a.getInt(attr, 0);
3336                    if (cacheQuality != 0) {
3337                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3338                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3339                    }
3340                    break;
3341                case com.android.internal.R.styleable.View_contentDescription:
3342                    mContentDescription = a.getString(attr);
3343                    break;
3344                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3345                    if (!a.getBoolean(attr, true)) {
3346                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3347                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3348                    }
3349                    break;
3350                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3351                    if (!a.getBoolean(attr, true)) {
3352                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3353                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3354                    }
3355                    break;
3356                case R.styleable.View_scrollbars:
3357                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3358                    if (scrollbars != SCROLLBARS_NONE) {
3359                        viewFlagValues |= scrollbars;
3360                        viewFlagMasks |= SCROLLBARS_MASK;
3361                        initializeScrollbars(a);
3362                    }
3363                    break;
3364                //noinspection deprecation
3365                case R.styleable.View_fadingEdge:
3366                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3367                        // Ignore the attribute starting with ICS
3368                        break;
3369                    }
3370                    // With builds < ICS, fall through and apply fading edges
3371                case R.styleable.View_requiresFadingEdge:
3372                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3373                    if (fadingEdge != FADING_EDGE_NONE) {
3374                        viewFlagValues |= fadingEdge;
3375                        viewFlagMasks |= FADING_EDGE_MASK;
3376                        initializeFadingEdge(a);
3377                    }
3378                    break;
3379                case R.styleable.View_scrollbarStyle:
3380                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3381                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3382                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3383                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3384                    }
3385                    break;
3386                case R.styleable.View_isScrollContainer:
3387                    setScrollContainer = true;
3388                    if (a.getBoolean(attr, false)) {
3389                        setScrollContainer(true);
3390                    }
3391                    break;
3392                case com.android.internal.R.styleable.View_keepScreenOn:
3393                    if (a.getBoolean(attr, false)) {
3394                        viewFlagValues |= KEEP_SCREEN_ON;
3395                        viewFlagMasks |= KEEP_SCREEN_ON;
3396                    }
3397                    break;
3398                case R.styleable.View_filterTouchesWhenObscured:
3399                    if (a.getBoolean(attr, false)) {
3400                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3401                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3402                    }
3403                    break;
3404                case R.styleable.View_nextFocusLeft:
3405                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3406                    break;
3407                case R.styleable.View_nextFocusRight:
3408                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3409                    break;
3410                case R.styleable.View_nextFocusUp:
3411                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3412                    break;
3413                case R.styleable.View_nextFocusDown:
3414                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3415                    break;
3416                case R.styleable.View_nextFocusForward:
3417                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3418                    break;
3419                case R.styleable.View_minWidth:
3420                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3421                    break;
3422                case R.styleable.View_minHeight:
3423                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3424                    break;
3425                case R.styleable.View_onClick:
3426                    if (context.isRestricted()) {
3427                        throw new IllegalStateException("The android:onClick attribute cannot "
3428                                + "be used within a restricted context");
3429                    }
3430
3431                    final String handlerName = a.getString(attr);
3432                    if (handlerName != null) {
3433                        setOnClickListener(new OnClickListener() {
3434                            private Method mHandler;
3435
3436                            public void onClick(View v) {
3437                                if (mHandler == null) {
3438                                    try {
3439                                        mHandler = getContext().getClass().getMethod(handlerName,
3440                                                View.class);
3441                                    } catch (NoSuchMethodException e) {
3442                                        int id = getId();
3443                                        String idText = id == NO_ID ? "" : " with id '"
3444                                                + getContext().getResources().getResourceEntryName(
3445                                                    id) + "'";
3446                                        throw new IllegalStateException("Could not find a method " +
3447                                                handlerName + "(View) in the activity "
3448                                                + getContext().getClass() + " for onClick handler"
3449                                                + " on view " + View.this.getClass() + idText, e);
3450                                    }
3451                                }
3452
3453                                try {
3454                                    mHandler.invoke(getContext(), View.this);
3455                                } catch (IllegalAccessException e) {
3456                                    throw new IllegalStateException("Could not execute non "
3457                                            + "public method of the activity", e);
3458                                } catch (InvocationTargetException e) {
3459                                    throw new IllegalStateException("Could not execute "
3460                                            + "method of the activity", e);
3461                                }
3462                            }
3463                        });
3464                    }
3465                    break;
3466                case R.styleable.View_overScrollMode:
3467                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3468                    break;
3469                case R.styleable.View_verticalScrollbarPosition:
3470                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3471                    break;
3472                case R.styleable.View_layerType:
3473                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3474                    break;
3475                case R.styleable.View_textDirection:
3476                    // Clear any text direction flag already set
3477                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3478                    // Set the text direction flags depending on the value of the attribute
3479                    final int textDirection = a.getInt(attr, -1);
3480                    if (textDirection != -1) {
3481                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3482                    }
3483                    break;
3484                case R.styleable.View_textAlignment:
3485                    // Clear any text alignment flag already set
3486                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3487                    // Set the text alignment flag depending on the value of the attribute
3488                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3489                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3490                    break;
3491                case R.styleable.View_importantForAccessibility:
3492                    setImportantForAccessibility(a.getInt(attr,
3493                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3494            }
3495        }
3496
3497        a.recycle();
3498
3499        setOverScrollMode(overScrollMode);
3500
3501        if (background != null) {
3502            setBackground(background);
3503        }
3504
3505        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3506        // layout direction). Those cached values will be used later during padding resolution.
3507        mUserPaddingStart = startPadding;
3508        mUserPaddingEnd = endPadding;
3509
3510        updateUserPaddingRelative();
3511
3512        if (padding >= 0) {
3513            leftPadding = padding;
3514            topPadding = padding;
3515            rightPadding = padding;
3516            bottomPadding = padding;
3517        }
3518
3519        // If the user specified the padding (either with android:padding or
3520        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3521        // use the default padding or the padding from the background drawable
3522        // (stored at this point in mPadding*)
3523        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3524                topPadding >= 0 ? topPadding : mPaddingTop,
3525                rightPadding >= 0 ? rightPadding : mPaddingRight,
3526                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3527
3528        if (viewFlagMasks != 0) {
3529            setFlags(viewFlagValues, viewFlagMasks);
3530        }
3531
3532        // Needs to be called after mViewFlags is set
3533        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3534            recomputePadding();
3535        }
3536
3537        if (x != 0 || y != 0) {
3538            scrollTo(x, y);
3539        }
3540
3541        if (transformSet) {
3542            setTranslationX(tx);
3543            setTranslationY(ty);
3544            setRotation(rotation);
3545            setRotationX(rotationX);
3546            setRotationY(rotationY);
3547            setScaleX(sx);
3548            setScaleY(sy);
3549        }
3550
3551        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3552            setScrollContainer(true);
3553        }
3554
3555        computeOpaqueFlags();
3556    }
3557
3558    private void updateUserPaddingRelative() {
3559        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3560    }
3561
3562    /**
3563     * Non-public constructor for use in testing
3564     */
3565    View() {
3566        mResources = null;
3567    }
3568
3569    /**
3570     * <p>
3571     * Initializes the fading edges from a given set of styled attributes. This
3572     * method should be called by subclasses that need fading edges and when an
3573     * instance of these subclasses is created programmatically rather than
3574     * being inflated from XML. This method is automatically called when the XML
3575     * is inflated.
3576     * </p>
3577     *
3578     * @param a the styled attributes set to initialize the fading edges from
3579     */
3580    protected void initializeFadingEdge(TypedArray a) {
3581        initScrollCache();
3582
3583        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3584                R.styleable.View_fadingEdgeLength,
3585                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3586    }
3587
3588    /**
3589     * Returns the size of the vertical faded edges used to indicate that more
3590     * content in this view is visible.
3591     *
3592     * @return The size in pixels of the vertical faded edge or 0 if vertical
3593     *         faded edges are not enabled for this view.
3594     * @attr ref android.R.styleable#View_fadingEdgeLength
3595     */
3596    public int getVerticalFadingEdgeLength() {
3597        if (isVerticalFadingEdgeEnabled()) {
3598            ScrollabilityCache cache = mScrollCache;
3599            if (cache != null) {
3600                return cache.fadingEdgeLength;
3601            }
3602        }
3603        return 0;
3604    }
3605
3606    /**
3607     * Set the size of the faded edge used to indicate that more content in this
3608     * view is available.  Will not change whether the fading edge is enabled; use
3609     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3610     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3611     * for the vertical or horizontal fading edges.
3612     *
3613     * @param length The size in pixels of the faded edge used to indicate that more
3614     *        content in this view is visible.
3615     */
3616    public void setFadingEdgeLength(int length) {
3617        initScrollCache();
3618        mScrollCache.fadingEdgeLength = length;
3619    }
3620
3621    /**
3622     * Returns the size of the horizontal faded edges used to indicate that more
3623     * content in this view is visible.
3624     *
3625     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3626     *         faded edges are not enabled for this view.
3627     * @attr ref android.R.styleable#View_fadingEdgeLength
3628     */
3629    public int getHorizontalFadingEdgeLength() {
3630        if (isHorizontalFadingEdgeEnabled()) {
3631            ScrollabilityCache cache = mScrollCache;
3632            if (cache != null) {
3633                return cache.fadingEdgeLength;
3634            }
3635        }
3636        return 0;
3637    }
3638
3639    /**
3640     * Returns the width of the vertical scrollbar.
3641     *
3642     * @return The width in pixels of the vertical scrollbar or 0 if there
3643     *         is no vertical scrollbar.
3644     */
3645    public int getVerticalScrollbarWidth() {
3646        ScrollabilityCache cache = mScrollCache;
3647        if (cache != null) {
3648            ScrollBarDrawable scrollBar = cache.scrollBar;
3649            if (scrollBar != null) {
3650                int size = scrollBar.getSize(true);
3651                if (size <= 0) {
3652                    size = cache.scrollBarSize;
3653                }
3654                return size;
3655            }
3656            return 0;
3657        }
3658        return 0;
3659    }
3660
3661    /**
3662     * Returns the height of the horizontal scrollbar.
3663     *
3664     * @return The height in pixels of the horizontal scrollbar or 0 if
3665     *         there is no horizontal scrollbar.
3666     */
3667    protected int getHorizontalScrollbarHeight() {
3668        ScrollabilityCache cache = mScrollCache;
3669        if (cache != null) {
3670            ScrollBarDrawable scrollBar = cache.scrollBar;
3671            if (scrollBar != null) {
3672                int size = scrollBar.getSize(false);
3673                if (size <= 0) {
3674                    size = cache.scrollBarSize;
3675                }
3676                return size;
3677            }
3678            return 0;
3679        }
3680        return 0;
3681    }
3682
3683    /**
3684     * <p>
3685     * Initializes the scrollbars from a given set of styled attributes. This
3686     * method should be called by subclasses that need scrollbars and when an
3687     * instance of these subclasses is created programmatically rather than
3688     * being inflated from XML. This method is automatically called when the XML
3689     * is inflated.
3690     * </p>
3691     *
3692     * @param a the styled attributes set to initialize the scrollbars from
3693     */
3694    protected void initializeScrollbars(TypedArray a) {
3695        initScrollCache();
3696
3697        final ScrollabilityCache scrollabilityCache = mScrollCache;
3698
3699        if (scrollabilityCache.scrollBar == null) {
3700            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3701        }
3702
3703        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3704
3705        if (!fadeScrollbars) {
3706            scrollabilityCache.state = ScrollabilityCache.ON;
3707        }
3708        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3709
3710
3711        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3712                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3713                        .getScrollBarFadeDuration());
3714        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3715                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3716                ViewConfiguration.getScrollDefaultDelay());
3717
3718
3719        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3720                com.android.internal.R.styleable.View_scrollbarSize,
3721                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3722
3723        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3724        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3725
3726        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3727        if (thumb != null) {
3728            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3729        }
3730
3731        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3732                false);
3733        if (alwaysDraw) {
3734            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3735        }
3736
3737        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3738        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3739
3740        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3741        if (thumb != null) {
3742            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3743        }
3744
3745        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3746                false);
3747        if (alwaysDraw) {
3748            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3749        }
3750
3751        // Re-apply user/background padding so that scrollbar(s) get added
3752        resolvePadding();
3753    }
3754
3755    /**
3756     * <p>
3757     * Initalizes the scrollability cache if necessary.
3758     * </p>
3759     */
3760    private void initScrollCache() {
3761        if (mScrollCache == null) {
3762            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3763        }
3764    }
3765
3766    private ScrollabilityCache getScrollCache() {
3767        initScrollCache();
3768        return mScrollCache;
3769    }
3770
3771    /**
3772     * Set the position of the vertical scroll bar. Should be one of
3773     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3774     * {@link #SCROLLBAR_POSITION_RIGHT}.
3775     *
3776     * @param position Where the vertical scroll bar should be positioned.
3777     */
3778    public void setVerticalScrollbarPosition(int position) {
3779        if (mVerticalScrollbarPosition != position) {
3780            mVerticalScrollbarPosition = position;
3781            computeOpaqueFlags();
3782            resolvePadding();
3783        }
3784    }
3785
3786    /**
3787     * @return The position where the vertical scroll bar will show, if applicable.
3788     * @see #setVerticalScrollbarPosition(int)
3789     */
3790    public int getVerticalScrollbarPosition() {
3791        return mVerticalScrollbarPosition;
3792    }
3793
3794    ListenerInfo getListenerInfo() {
3795        if (mListenerInfo != null) {
3796            return mListenerInfo;
3797        }
3798        mListenerInfo = new ListenerInfo();
3799        return mListenerInfo;
3800    }
3801
3802    /**
3803     * Register a callback to be invoked when focus of this view changed.
3804     *
3805     * @param l The callback that will run.
3806     */
3807    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3808        getListenerInfo().mOnFocusChangeListener = l;
3809    }
3810
3811    /**
3812     * Add a listener that will be called when the bounds of the view change due to
3813     * layout processing.
3814     *
3815     * @param listener The listener that will be called when layout bounds change.
3816     */
3817    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3818        ListenerInfo li = getListenerInfo();
3819        if (li.mOnLayoutChangeListeners == null) {
3820            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3821        }
3822        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3823            li.mOnLayoutChangeListeners.add(listener);
3824        }
3825    }
3826
3827    /**
3828     * Remove a listener for layout changes.
3829     *
3830     * @param listener The listener for layout bounds change.
3831     */
3832    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3833        ListenerInfo li = mListenerInfo;
3834        if (li == null || li.mOnLayoutChangeListeners == null) {
3835            return;
3836        }
3837        li.mOnLayoutChangeListeners.remove(listener);
3838    }
3839
3840    /**
3841     * Add a listener for attach state changes.
3842     *
3843     * This listener will be called whenever this view is attached or detached
3844     * from a window. Remove the listener using
3845     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3846     *
3847     * @param listener Listener to attach
3848     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3849     */
3850    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3851        ListenerInfo li = getListenerInfo();
3852        if (li.mOnAttachStateChangeListeners == null) {
3853            li.mOnAttachStateChangeListeners
3854                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3855        }
3856        li.mOnAttachStateChangeListeners.add(listener);
3857    }
3858
3859    /**
3860     * Remove a listener for attach state changes. The listener will receive no further
3861     * notification of window attach/detach events.
3862     *
3863     * @param listener Listener to remove
3864     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3865     */
3866    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3867        ListenerInfo li = mListenerInfo;
3868        if (li == null || li.mOnAttachStateChangeListeners == null) {
3869            return;
3870        }
3871        li.mOnAttachStateChangeListeners.remove(listener);
3872    }
3873
3874    /**
3875     * Returns the focus-change callback registered for this view.
3876     *
3877     * @return The callback, or null if one is not registered.
3878     */
3879    public OnFocusChangeListener getOnFocusChangeListener() {
3880        ListenerInfo li = mListenerInfo;
3881        return li != null ? li.mOnFocusChangeListener : null;
3882    }
3883
3884    /**
3885     * Register a callback to be invoked when this view is clicked. If this view is not
3886     * clickable, it becomes clickable.
3887     *
3888     * @param l The callback that will run
3889     *
3890     * @see #setClickable(boolean)
3891     */
3892    public void setOnClickListener(OnClickListener l) {
3893        if (!isClickable()) {
3894            setClickable(true);
3895        }
3896        getListenerInfo().mOnClickListener = l;
3897    }
3898
3899    /**
3900     * Return whether this view has an attached OnClickListener.  Returns
3901     * true if there is a listener, false if there is none.
3902     */
3903    public boolean hasOnClickListeners() {
3904        ListenerInfo li = mListenerInfo;
3905        return (li != null && li.mOnClickListener != null);
3906    }
3907
3908    /**
3909     * Register a callback to be invoked when this view is clicked and held. If this view is not
3910     * long clickable, it becomes long clickable.
3911     *
3912     * @param l The callback that will run
3913     *
3914     * @see #setLongClickable(boolean)
3915     */
3916    public void setOnLongClickListener(OnLongClickListener l) {
3917        if (!isLongClickable()) {
3918            setLongClickable(true);
3919        }
3920        getListenerInfo().mOnLongClickListener = l;
3921    }
3922
3923    /**
3924     * Register a callback to be invoked when the context menu for this view is
3925     * being built. If this view is not long clickable, it becomes long clickable.
3926     *
3927     * @param l The callback that will run
3928     *
3929     */
3930    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3931        if (!isLongClickable()) {
3932            setLongClickable(true);
3933        }
3934        getListenerInfo().mOnCreateContextMenuListener = l;
3935    }
3936
3937    /**
3938     * Call this view's OnClickListener, if it is defined.  Performs all normal
3939     * actions associated with clicking: reporting accessibility event, playing
3940     * a sound, etc.
3941     *
3942     * @return True there was an assigned OnClickListener that was called, false
3943     *         otherwise is returned.
3944     */
3945    public boolean performClick() {
3946        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3947
3948        ListenerInfo li = mListenerInfo;
3949        if (li != null && li.mOnClickListener != null) {
3950            playSoundEffect(SoundEffectConstants.CLICK);
3951            li.mOnClickListener.onClick(this);
3952            return true;
3953        }
3954
3955        return false;
3956    }
3957
3958    /**
3959     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3960     * this only calls the listener, and does not do any associated clicking
3961     * actions like reporting an accessibility event.
3962     *
3963     * @return True there was an assigned OnClickListener that was called, false
3964     *         otherwise is returned.
3965     */
3966    public boolean callOnClick() {
3967        ListenerInfo li = mListenerInfo;
3968        if (li != null && li.mOnClickListener != null) {
3969            li.mOnClickListener.onClick(this);
3970            return true;
3971        }
3972        return false;
3973    }
3974
3975    /**
3976     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3977     * OnLongClickListener did not consume the event.
3978     *
3979     * @return True if one of the above receivers consumed the event, false otherwise.
3980     */
3981    public boolean performLongClick() {
3982        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3983
3984        boolean handled = false;
3985        ListenerInfo li = mListenerInfo;
3986        if (li != null && li.mOnLongClickListener != null) {
3987            handled = li.mOnLongClickListener.onLongClick(View.this);
3988        }
3989        if (!handled) {
3990            handled = showContextMenu();
3991        }
3992        if (handled) {
3993            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3994        }
3995        return handled;
3996    }
3997
3998    /**
3999     * Performs button-related actions during a touch down event.
4000     *
4001     * @param event The event.
4002     * @return True if the down was consumed.
4003     *
4004     * @hide
4005     */
4006    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4007        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4008            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4009                return true;
4010            }
4011        }
4012        return false;
4013    }
4014
4015    /**
4016     * Bring up the context menu for this view.
4017     *
4018     * @return Whether a context menu was displayed.
4019     */
4020    public boolean showContextMenu() {
4021        return getParent().showContextMenuForChild(this);
4022    }
4023
4024    /**
4025     * Bring up the context menu for this view, referring to the item under the specified point.
4026     *
4027     * @param x The referenced x coordinate.
4028     * @param y The referenced y coordinate.
4029     * @param metaState The keyboard modifiers that were pressed.
4030     * @return Whether a context menu was displayed.
4031     *
4032     * @hide
4033     */
4034    public boolean showContextMenu(float x, float y, int metaState) {
4035        return showContextMenu();
4036    }
4037
4038    /**
4039     * Start an action mode.
4040     *
4041     * @param callback Callback that will control the lifecycle of the action mode
4042     * @return The new action mode if it is started, null otherwise
4043     *
4044     * @see ActionMode
4045     */
4046    public ActionMode startActionMode(ActionMode.Callback callback) {
4047        ViewParent parent = getParent();
4048        if (parent == null) return null;
4049        return parent.startActionModeForChild(this, callback);
4050    }
4051
4052    /**
4053     * Register a callback to be invoked when a key is pressed in this view.
4054     * @param l the key listener to attach to this view
4055     */
4056    public void setOnKeyListener(OnKeyListener l) {
4057        getListenerInfo().mOnKeyListener = l;
4058    }
4059
4060    /**
4061     * Register a callback to be invoked when a touch event is sent to this view.
4062     * @param l the touch listener to attach to this view
4063     */
4064    public void setOnTouchListener(OnTouchListener l) {
4065        getListenerInfo().mOnTouchListener = l;
4066    }
4067
4068    /**
4069     * Register a callback to be invoked when a generic motion event is sent to this view.
4070     * @param l the generic motion listener to attach to this view
4071     */
4072    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4073        getListenerInfo().mOnGenericMotionListener = l;
4074    }
4075
4076    /**
4077     * Register a callback to be invoked when a hover event is sent to this view.
4078     * @param l the hover listener to attach to this view
4079     */
4080    public void setOnHoverListener(OnHoverListener l) {
4081        getListenerInfo().mOnHoverListener = l;
4082    }
4083
4084    /**
4085     * Register a drag event listener callback object for this View. The parameter is
4086     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4087     * View, the system calls the
4088     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4089     * @param l An implementation of {@link android.view.View.OnDragListener}.
4090     */
4091    public void setOnDragListener(OnDragListener l) {
4092        getListenerInfo().mOnDragListener = l;
4093    }
4094
4095    /**
4096     * Give this view focus. This will cause
4097     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4098     *
4099     * Note: this does not check whether this {@link View} should get focus, it just
4100     * gives it focus no matter what.  It should only be called internally by framework
4101     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4102     *
4103     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4104     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4105     *        focus moved when requestFocus() is called. It may not always
4106     *        apply, in which case use the default View.FOCUS_DOWN.
4107     * @param previouslyFocusedRect The rectangle of the view that had focus
4108     *        prior in this View's coordinate system.
4109     */
4110    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4111        if (DBG) {
4112            System.out.println(this + " requestFocus()");
4113        }
4114
4115        if ((mPrivateFlags & FOCUSED) == 0) {
4116            mPrivateFlags |= FOCUSED;
4117
4118            if (mParent != null) {
4119                mParent.requestChildFocus(this, this);
4120            }
4121
4122            onFocusChanged(true, direction, previouslyFocusedRect);
4123            refreshDrawableState();
4124
4125            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4126                notifyAccessibilityStateChanged();
4127            }
4128        }
4129    }
4130
4131    /**
4132     * Request that a rectangle of this view be visible on the screen,
4133     * scrolling if necessary just enough.
4134     *
4135     * <p>A View should call this if it maintains some notion of which part
4136     * of its content is interesting.  For example, a text editing view
4137     * should call this when its cursor moves.
4138     *
4139     * @param rectangle The rectangle.
4140     * @return Whether any parent scrolled.
4141     */
4142    public boolean requestRectangleOnScreen(Rect rectangle) {
4143        return requestRectangleOnScreen(rectangle, false);
4144    }
4145
4146    /**
4147     * Request that a rectangle of this view be visible on the screen,
4148     * scrolling if necessary just enough.
4149     *
4150     * <p>A View should call this if it maintains some notion of which part
4151     * of its content is interesting.  For example, a text editing view
4152     * should call this when its cursor moves.
4153     *
4154     * <p>When <code>immediate</code> is set to true, scrolling will not be
4155     * animated.
4156     *
4157     * @param rectangle The rectangle.
4158     * @param immediate True to forbid animated scrolling, false otherwise
4159     * @return Whether any parent scrolled.
4160     */
4161    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4162        View child = this;
4163        ViewParent parent = mParent;
4164        boolean scrolled = false;
4165        while (parent != null) {
4166            scrolled |= parent.requestChildRectangleOnScreen(child,
4167                    rectangle, immediate);
4168
4169            // offset rect so next call has the rectangle in the
4170            // coordinate system of its direct child.
4171            rectangle.offset(child.getLeft(), child.getTop());
4172            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4173
4174            if (!(parent instanceof View)) {
4175                break;
4176            }
4177
4178            child = (View) parent;
4179            parent = child.getParent();
4180        }
4181        return scrolled;
4182    }
4183
4184    /**
4185     * Called when this view wants to give up focus. If focus is cleared
4186     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4187     * <p>
4188     * <strong>Note:</strong> When a View clears focus the framework is trying
4189     * to give focus to the first focusable View from the top. Hence, if this
4190     * View is the first from the top that can take focus, then all callbacks
4191     * related to clearing focus will be invoked after wich the framework will
4192     * give focus to this view.
4193     * </p>
4194     */
4195    public void clearFocus() {
4196        if (DBG) {
4197            System.out.println(this + " clearFocus()");
4198        }
4199
4200        if ((mPrivateFlags & FOCUSED) != 0) {
4201            mPrivateFlags &= ~FOCUSED;
4202
4203            if (mParent != null) {
4204                mParent.clearChildFocus(this);
4205            }
4206
4207            onFocusChanged(false, 0, null);
4208
4209            refreshDrawableState();
4210
4211            ensureInputFocusOnFirstFocusable();
4212
4213            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4214                notifyAccessibilityStateChanged();
4215            }
4216        }
4217    }
4218
4219    void ensureInputFocusOnFirstFocusable() {
4220        View root = getRootView();
4221        if (root != null) {
4222            root.requestFocus();
4223        }
4224    }
4225
4226    /**
4227     * Called internally by the view system when a new view is getting focus.
4228     * This is what clears the old focus.
4229     */
4230    void unFocus() {
4231        if (DBG) {
4232            System.out.println(this + " unFocus()");
4233        }
4234
4235        if ((mPrivateFlags & FOCUSED) != 0) {
4236            mPrivateFlags &= ~FOCUSED;
4237
4238            onFocusChanged(false, 0, null);
4239            refreshDrawableState();
4240
4241            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4242                notifyAccessibilityStateChanged();
4243            }
4244        }
4245    }
4246
4247    /**
4248     * Returns true if this view has focus iteself, or is the ancestor of the
4249     * view that has focus.
4250     *
4251     * @return True if this view has or contains focus, false otherwise.
4252     */
4253    @ViewDebug.ExportedProperty(category = "focus")
4254    public boolean hasFocus() {
4255        return (mPrivateFlags & FOCUSED) != 0;
4256    }
4257
4258    /**
4259     * Returns true if this view is focusable or if it contains a reachable View
4260     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4261     * is a View whose parents do not block descendants focus.
4262     *
4263     * Only {@link #VISIBLE} views are considered focusable.
4264     *
4265     * @return True if the view is focusable or if the view contains a focusable
4266     *         View, false otherwise.
4267     *
4268     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4269     */
4270    public boolean hasFocusable() {
4271        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4272    }
4273
4274    /**
4275     * Called by the view system when the focus state of this view changes.
4276     * When the focus change event is caused by directional navigation, direction
4277     * and previouslyFocusedRect provide insight into where the focus is coming from.
4278     * When overriding, be sure to call up through to the super class so that
4279     * the standard focus handling will occur.
4280     *
4281     * @param gainFocus True if the View has focus; false otherwise.
4282     * @param direction The direction focus has moved when requestFocus()
4283     *                  is called to give this view focus. Values are
4284     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4285     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4286     *                  It may not always apply, in which case use the default.
4287     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4288     *        system, of the previously focused view.  If applicable, this will be
4289     *        passed in as finer grained information about where the focus is coming
4290     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4291     */
4292    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4293        if (gainFocus) {
4294            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4295                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4296                requestAccessibilityFocus();
4297            }
4298        }
4299
4300        InputMethodManager imm = InputMethodManager.peekInstance();
4301        if (!gainFocus) {
4302            if (isPressed()) {
4303                setPressed(false);
4304            }
4305            if (imm != null && mAttachInfo != null
4306                    && mAttachInfo.mHasWindowFocus) {
4307                imm.focusOut(this);
4308            }
4309            onFocusLost();
4310        } else if (imm != null && mAttachInfo != null
4311                && mAttachInfo.mHasWindowFocus) {
4312            imm.focusIn(this);
4313        }
4314
4315        invalidate(true);
4316        ListenerInfo li = mListenerInfo;
4317        if (li != null && li.mOnFocusChangeListener != null) {
4318            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4319        }
4320
4321        if (mAttachInfo != null) {
4322            mAttachInfo.mKeyDispatchState.reset(this);
4323        }
4324    }
4325
4326    /**
4327     * Sends an accessibility event of the given type. If accessiiblity is
4328     * not enabled this method has no effect. The default implementation calls
4329     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4330     * to populate information about the event source (this View), then calls
4331     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4332     * populate the text content of the event source including its descendants,
4333     * and last calls
4334     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4335     * on its parent to resuest sending of the event to interested parties.
4336     * <p>
4337     * If an {@link AccessibilityDelegate} has been specified via calling
4338     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4339     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4340     * responsible for handling this call.
4341     * </p>
4342     *
4343     * @param eventType The type of the event to send, as defined by several types from
4344     * {@link android.view.accessibility.AccessibilityEvent}, such as
4345     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4346     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4347     *
4348     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4349     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4350     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4351     * @see AccessibilityDelegate
4352     */
4353    public void sendAccessibilityEvent(int eventType) {
4354        if (mAccessibilityDelegate != null) {
4355            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4356        } else {
4357            sendAccessibilityEventInternal(eventType);
4358        }
4359    }
4360
4361    /**
4362     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4363     * {@link AccessibilityEvent} to make an announcement which is related to some
4364     * sort of a context change for which none of the events representing UI transitions
4365     * is a good fit. For example, announcing a new page in a book. If accessibility
4366     * is not enabled this method does nothing.
4367     *
4368     * @param text The announcement text.
4369     */
4370    public void announceForAccessibility(CharSequence text) {
4371        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4372            AccessibilityEvent event = AccessibilityEvent.obtain(
4373                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4374            event.getText().add(text);
4375            sendAccessibilityEventUnchecked(event);
4376        }
4377    }
4378
4379    /**
4380     * @see #sendAccessibilityEvent(int)
4381     *
4382     * Note: Called from the default {@link AccessibilityDelegate}.
4383     */
4384    void sendAccessibilityEventInternal(int eventType) {
4385        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4386            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4387        }
4388    }
4389
4390    /**
4391     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4392     * takes as an argument an empty {@link AccessibilityEvent} and does not
4393     * perform a check whether accessibility is enabled.
4394     * <p>
4395     * If an {@link AccessibilityDelegate} has been specified via calling
4396     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4397     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4398     * is responsible for handling this call.
4399     * </p>
4400     *
4401     * @param event The event to send.
4402     *
4403     * @see #sendAccessibilityEvent(int)
4404     */
4405    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4406        if (mAccessibilityDelegate != null) {
4407            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4408        } else {
4409            sendAccessibilityEventUncheckedInternal(event);
4410        }
4411    }
4412
4413    /**
4414     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4415     *
4416     * Note: Called from the default {@link AccessibilityDelegate}.
4417     */
4418    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4419        if (!isShown()) {
4420            return;
4421        }
4422        onInitializeAccessibilityEvent(event);
4423        // Only a subset of accessibility events populates text content.
4424        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4425            dispatchPopulateAccessibilityEvent(event);
4426        }
4427        // Intercept accessibility focus events fired by virtual nodes to keep
4428        // track of accessibility focus position in such nodes.
4429        final int eventType = event.getEventType();
4430        switch (eventType) {
4431            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4432                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4433                        event.getSourceNodeId());
4434                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4435                    ViewRootImpl viewRootImpl = getViewRootImpl();
4436                    if (viewRootImpl != null) {
4437                        viewRootImpl.setAccessibilityFocusedHost(this);
4438                    }
4439                }
4440            } break;
4441            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4442                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4443                        event.getSourceNodeId());
4444                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4445                    ViewRootImpl viewRootImpl = getViewRootImpl();
4446                    if (viewRootImpl != null) {
4447                        viewRootImpl.setAccessibilityFocusedHost(null);
4448                    }
4449                }
4450            } break;
4451        }
4452        // In the beginning we called #isShown(), so we know that getParent() is not null.
4453        getParent().requestSendAccessibilityEvent(this, event);
4454    }
4455
4456    /**
4457     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4458     * to its children for adding their text content to the event. Note that the
4459     * event text is populated in a separate dispatch path since we add to the
4460     * event not only the text of the source but also the text of all its descendants.
4461     * A typical implementation will call
4462     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4463     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4464     * on each child. Override this method if custom population of the event text
4465     * content is required.
4466     * <p>
4467     * If an {@link AccessibilityDelegate} has been specified via calling
4468     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4469     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4470     * is responsible for handling this call.
4471     * </p>
4472     * <p>
4473     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4474     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4475     * </p>
4476     *
4477     * @param event The event.
4478     *
4479     * @return True if the event population was completed.
4480     */
4481    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4482        if (mAccessibilityDelegate != null) {
4483            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4484        } else {
4485            return dispatchPopulateAccessibilityEventInternal(event);
4486        }
4487    }
4488
4489    /**
4490     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4491     *
4492     * Note: Called from the default {@link AccessibilityDelegate}.
4493     */
4494    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4495        onPopulateAccessibilityEvent(event);
4496        return false;
4497    }
4498
4499    /**
4500     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4501     * giving a chance to this View to populate the accessibility event with its
4502     * text content. While this method is free to modify event
4503     * attributes other than text content, doing so should normally be performed in
4504     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4505     * <p>
4506     * Example: Adding formatted date string to an accessibility event in addition
4507     *          to the text added by the super implementation:
4508     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4509     *     super.onPopulateAccessibilityEvent(event);
4510     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4511     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4512     *         mCurrentDate.getTimeInMillis(), flags);
4513     *     event.getText().add(selectedDateUtterance);
4514     * }</pre>
4515     * <p>
4516     * If an {@link AccessibilityDelegate} has been specified via calling
4517     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4518     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4519     * is responsible for handling this call.
4520     * </p>
4521     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4522     * information to the event, in case the default implementation has basic information to add.
4523     * </p>
4524     *
4525     * @param event The accessibility event which to populate.
4526     *
4527     * @see #sendAccessibilityEvent(int)
4528     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4529     */
4530    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4531        if (mAccessibilityDelegate != null) {
4532            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4533        } else {
4534            onPopulateAccessibilityEventInternal(event);
4535        }
4536    }
4537
4538    /**
4539     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4540     *
4541     * Note: Called from the default {@link AccessibilityDelegate}.
4542     */
4543    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4544
4545    }
4546
4547    /**
4548     * Initializes an {@link AccessibilityEvent} with information about
4549     * this View which is the event source. In other words, the source of
4550     * an accessibility event is the view whose state change triggered firing
4551     * the event.
4552     * <p>
4553     * Example: Setting the password property of an event in addition
4554     *          to properties set by the super implementation:
4555     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4556     *     super.onInitializeAccessibilityEvent(event);
4557     *     event.setPassword(true);
4558     * }</pre>
4559     * <p>
4560     * If an {@link AccessibilityDelegate} has been specified via calling
4561     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4562     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4563     * is responsible for handling this call.
4564     * </p>
4565     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4566     * information to the event, in case the default implementation has basic information to add.
4567     * </p>
4568     * @param event The event to initialize.
4569     *
4570     * @see #sendAccessibilityEvent(int)
4571     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4572     */
4573    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4574        if (mAccessibilityDelegate != null) {
4575            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4576        } else {
4577            onInitializeAccessibilityEventInternal(event);
4578        }
4579    }
4580
4581    /**
4582     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4583     *
4584     * Note: Called from the default {@link AccessibilityDelegate}.
4585     */
4586    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4587        event.setSource(this);
4588        event.setClassName(View.class.getName());
4589        event.setPackageName(getContext().getPackageName());
4590        event.setEnabled(isEnabled());
4591        event.setContentDescription(mContentDescription);
4592
4593        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4594            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4595            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4596                    FOCUSABLES_ALL);
4597            event.setItemCount(focusablesTempList.size());
4598            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4599            focusablesTempList.clear();
4600        }
4601    }
4602
4603    /**
4604     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4605     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4606     * This method is responsible for obtaining an accessibility node info from a
4607     * pool of reusable instances and calling
4608     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4609     * initialize the former.
4610     * <p>
4611     * Note: The client is responsible for recycling the obtained instance by calling
4612     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4613     * </p>
4614     *
4615     * @return A populated {@link AccessibilityNodeInfo}.
4616     *
4617     * @see AccessibilityNodeInfo
4618     */
4619    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4620        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4621        if (provider != null) {
4622            return provider.createAccessibilityNodeInfo(View.NO_ID);
4623        } else {
4624            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4625            onInitializeAccessibilityNodeInfo(info);
4626            return info;
4627        }
4628    }
4629
4630    /**
4631     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4632     * The base implementation sets:
4633     * <ul>
4634     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4635     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4636     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4637     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4638     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4639     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4640     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4641     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4642     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4643     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4644     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4645     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4646     * </ul>
4647     * <p>
4648     * Subclasses should override this method, call the super implementation,
4649     * and set additional attributes.
4650     * </p>
4651     * <p>
4652     * If an {@link AccessibilityDelegate} has been specified via calling
4653     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4654     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4655     * is responsible for handling this call.
4656     * </p>
4657     *
4658     * @param info The instance to initialize.
4659     */
4660    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4661        if (mAccessibilityDelegate != null) {
4662            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4663        } else {
4664            onInitializeAccessibilityNodeInfoInternal(info);
4665        }
4666    }
4667
4668    /**
4669     * Gets the location of this view in screen coordintates.
4670     *
4671     * @param outRect The output location
4672     */
4673    private void getBoundsOnScreen(Rect outRect) {
4674        if (mAttachInfo == null) {
4675            return;
4676        }
4677
4678        RectF position = mAttachInfo.mTmpTransformRect;
4679        position.setEmpty();
4680
4681        if (!hasIdentityMatrix()) {
4682            getMatrix().mapRect(position);
4683        }
4684
4685        position.offset(mLeft, mRight);
4686
4687        ViewParent parent = mParent;
4688        while (parent instanceof View) {
4689            View parentView = (View) parent;
4690
4691            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4692
4693            if (!parentView.hasIdentityMatrix()) {
4694                parentView.getMatrix().mapRect(position);
4695            }
4696
4697            position.offset(parentView.mLeft, parentView.mTop);
4698
4699            parent = parentView.mParent;
4700        }
4701
4702        if (parent instanceof ViewRootImpl) {
4703            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4704            position.offset(0, -viewRootImpl.mCurScrollY);
4705        }
4706
4707        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4708
4709        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4710                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4711    }
4712
4713    /**
4714     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4715     *
4716     * Note: Called from the default {@link AccessibilityDelegate}.
4717     */
4718    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4719        Rect bounds = mAttachInfo.mTmpInvalRect;
4720        getDrawingRect(bounds);
4721        info.setBoundsInParent(bounds);
4722
4723        getBoundsOnScreen(bounds);
4724        info.setBoundsInScreen(bounds);
4725
4726        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4727            ViewParent parent = getParentForAccessibility();
4728            if (parent instanceof View) {
4729                info.setParent((View) parent);
4730            }
4731        }
4732
4733        info.setVisibleToUser(isVisibleToUser());
4734
4735        info.setPackageName(mContext.getPackageName());
4736        info.setClassName(View.class.getName());
4737        info.setContentDescription(getContentDescription());
4738
4739        info.setEnabled(isEnabled());
4740        info.setClickable(isClickable());
4741        info.setFocusable(isFocusable());
4742        info.setFocused(isFocused());
4743        info.setAccessibilityFocused(isAccessibilityFocused());
4744        info.setSelected(isSelected());
4745        info.setLongClickable(isLongClickable());
4746
4747        // TODO: These make sense only if we are in an AdapterView but all
4748        // views can be selected. Maybe from accessiiblity perspective
4749        // we should report as selectable view in an AdapterView.
4750        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4751        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4752
4753        if (isFocusable()) {
4754            if (isFocused()) {
4755                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4756            } else {
4757                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4758            }
4759        }
4760
4761        if (!isAccessibilityFocused()) {
4762            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4763        } else {
4764            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4765        }
4766
4767        if (isClickable()) {
4768            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4769        }
4770
4771        if (isLongClickable()) {
4772            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4773        }
4774
4775        if (mContentDescription != null && mContentDescription.length() > 0) {
4776            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4777            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4778            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4779                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4780                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4781        }
4782    }
4783
4784    /**
4785     * Computes whether this view is visible to the user. Such a view is
4786     * attached, visible, all its predecessors are visible, it is not clipped
4787     * entirely by its predecessors, and has an alpha greater than zero.
4788     *
4789     * @return Whether the view is visible on the screen.
4790     */
4791    private boolean isVisibleToUser() {
4792        // The first two checks are made also made by isShown() which
4793        // however traverses the tree up to the parent to catch that.
4794        // Therefore, we do some fail fast check to minimize the up
4795        // tree traversal.
4796        return (mAttachInfo != null
4797                && mAttachInfo.mWindowVisibility == View.VISIBLE
4798                && getAlpha() > 0
4799                && isShown()
4800                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
4801    }
4802
4803    /**
4804     * Sets a delegate for implementing accessibility support via compositon as
4805     * opposed to inheritance. The delegate's primary use is for implementing
4806     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4807     *
4808     * @param delegate The delegate instance.
4809     *
4810     * @see AccessibilityDelegate
4811     */
4812    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4813        mAccessibilityDelegate = delegate;
4814    }
4815
4816    /**
4817     * Gets the provider for managing a virtual view hierarchy rooted at this View
4818     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4819     * that explore the window content.
4820     * <p>
4821     * If this method returns an instance, this instance is responsible for managing
4822     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4823     * View including the one representing the View itself. Similarly the returned
4824     * instance is responsible for performing accessibility actions on any virtual
4825     * view or the root view itself.
4826     * </p>
4827     * <p>
4828     * If an {@link AccessibilityDelegate} has been specified via calling
4829     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4830     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4831     * is responsible for handling this call.
4832     * </p>
4833     *
4834     * @return The provider.
4835     *
4836     * @see AccessibilityNodeProvider
4837     */
4838    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4839        if (mAccessibilityDelegate != null) {
4840            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4841        } else {
4842            return null;
4843        }
4844    }
4845
4846    /**
4847     * Gets the unique identifier of this view on the screen for accessibility purposes.
4848     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4849     *
4850     * @return The view accessibility id.
4851     *
4852     * @hide
4853     */
4854    public int getAccessibilityViewId() {
4855        if (mAccessibilityViewId == NO_ID) {
4856            mAccessibilityViewId = sNextAccessibilityViewId++;
4857        }
4858        return mAccessibilityViewId;
4859    }
4860
4861    /**
4862     * Gets the unique identifier of the window in which this View reseides.
4863     *
4864     * @return The window accessibility id.
4865     *
4866     * @hide
4867     */
4868    public int getAccessibilityWindowId() {
4869        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4870    }
4871
4872    /**
4873     * Gets the {@link View} description. It briefly describes the view and is
4874     * primarily used for accessibility support. Set this property to enable
4875     * better accessibility support for your application. This is especially
4876     * true for views that do not have textual representation (For example,
4877     * ImageButton).
4878     *
4879     * @return The content description.
4880     *
4881     * @attr ref android.R.styleable#View_contentDescription
4882     */
4883    @ViewDebug.ExportedProperty(category = "accessibility")
4884    public CharSequence getContentDescription() {
4885        return mContentDescription;
4886    }
4887
4888    /**
4889     * Sets the {@link View} description. It briefly describes the view and is
4890     * primarily used for accessibility support. Set this property to enable
4891     * better accessibility support for your application. This is especially
4892     * true for views that do not have textual representation (For example,
4893     * ImageButton).
4894     *
4895     * @param contentDescription The content description.
4896     *
4897     * @attr ref android.R.styleable#View_contentDescription
4898     */
4899    @RemotableViewMethod
4900    public void setContentDescription(CharSequence contentDescription) {
4901        mContentDescription = contentDescription;
4902    }
4903
4904    /**
4905     * Invoked whenever this view loses focus, either by losing window focus or by losing
4906     * focus within its window. This method can be used to clear any state tied to the
4907     * focus. For instance, if a button is held pressed with the trackball and the window
4908     * loses focus, this method can be used to cancel the press.
4909     *
4910     * Subclasses of View overriding this method should always call super.onFocusLost().
4911     *
4912     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4913     * @see #onWindowFocusChanged(boolean)
4914     *
4915     * @hide pending API council approval
4916     */
4917    protected void onFocusLost() {
4918        resetPressedState();
4919    }
4920
4921    private void resetPressedState() {
4922        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4923            return;
4924        }
4925
4926        if (isPressed()) {
4927            setPressed(false);
4928
4929            if (!mHasPerformedLongPress) {
4930                removeLongPressCallback();
4931            }
4932        }
4933    }
4934
4935    /**
4936     * Returns true if this view has focus
4937     *
4938     * @return True if this view has focus, false otherwise.
4939     */
4940    @ViewDebug.ExportedProperty(category = "focus")
4941    public boolean isFocused() {
4942        return (mPrivateFlags & FOCUSED) != 0;
4943    }
4944
4945    /**
4946     * Find the view in the hierarchy rooted at this view that currently has
4947     * focus.
4948     *
4949     * @return The view that currently has focus, or null if no focused view can
4950     *         be found.
4951     */
4952    public View findFocus() {
4953        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4954    }
4955
4956    /**
4957     * Indicates whether this view is one of the set of scrollable containers in
4958     * its window.
4959     *
4960     * @return whether this view is one of the set of scrollable containers in
4961     * its window
4962     *
4963     * @attr ref android.R.styleable#View_isScrollContainer
4964     */
4965    public boolean isScrollContainer() {
4966        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4967    }
4968
4969    /**
4970     * Change whether this view is one of the set of scrollable containers in
4971     * its window.  This will be used to determine whether the window can
4972     * resize or must pan when a soft input area is open -- scrollable
4973     * containers allow the window to use resize mode since the container
4974     * will appropriately shrink.
4975     *
4976     * @attr ref android.R.styleable#View_isScrollContainer
4977     */
4978    public void setScrollContainer(boolean isScrollContainer) {
4979        if (isScrollContainer) {
4980            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4981                mAttachInfo.mScrollContainers.add(this);
4982                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4983            }
4984            mPrivateFlags |= SCROLL_CONTAINER;
4985        } else {
4986            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4987                mAttachInfo.mScrollContainers.remove(this);
4988            }
4989            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4990        }
4991    }
4992
4993    /**
4994     * Returns the quality of the drawing cache.
4995     *
4996     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4997     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4998     *
4999     * @see #setDrawingCacheQuality(int)
5000     * @see #setDrawingCacheEnabled(boolean)
5001     * @see #isDrawingCacheEnabled()
5002     *
5003     * @attr ref android.R.styleable#View_drawingCacheQuality
5004     */
5005    public int getDrawingCacheQuality() {
5006        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5007    }
5008
5009    /**
5010     * Set the drawing cache quality of this view. This value is used only when the
5011     * drawing cache is enabled
5012     *
5013     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5014     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5015     *
5016     * @see #getDrawingCacheQuality()
5017     * @see #setDrawingCacheEnabled(boolean)
5018     * @see #isDrawingCacheEnabled()
5019     *
5020     * @attr ref android.R.styleable#View_drawingCacheQuality
5021     */
5022    public void setDrawingCacheQuality(int quality) {
5023        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5024    }
5025
5026    /**
5027     * Returns whether the screen should remain on, corresponding to the current
5028     * value of {@link #KEEP_SCREEN_ON}.
5029     *
5030     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5031     *
5032     * @see #setKeepScreenOn(boolean)
5033     *
5034     * @attr ref android.R.styleable#View_keepScreenOn
5035     */
5036    public boolean getKeepScreenOn() {
5037        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5038    }
5039
5040    /**
5041     * Controls whether the screen should remain on, modifying the
5042     * value of {@link #KEEP_SCREEN_ON}.
5043     *
5044     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5045     *
5046     * @see #getKeepScreenOn()
5047     *
5048     * @attr ref android.R.styleable#View_keepScreenOn
5049     */
5050    public void setKeepScreenOn(boolean keepScreenOn) {
5051        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5052    }
5053
5054    /**
5055     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5056     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5057     *
5058     * @attr ref android.R.styleable#View_nextFocusLeft
5059     */
5060    public int getNextFocusLeftId() {
5061        return mNextFocusLeftId;
5062    }
5063
5064    /**
5065     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5066     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5067     * decide automatically.
5068     *
5069     * @attr ref android.R.styleable#View_nextFocusLeft
5070     */
5071    public void setNextFocusLeftId(int nextFocusLeftId) {
5072        mNextFocusLeftId = nextFocusLeftId;
5073    }
5074
5075    /**
5076     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5077     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5078     *
5079     * @attr ref android.R.styleable#View_nextFocusRight
5080     */
5081    public int getNextFocusRightId() {
5082        return mNextFocusRightId;
5083    }
5084
5085    /**
5086     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5087     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5088     * decide automatically.
5089     *
5090     * @attr ref android.R.styleable#View_nextFocusRight
5091     */
5092    public void setNextFocusRightId(int nextFocusRightId) {
5093        mNextFocusRightId = nextFocusRightId;
5094    }
5095
5096    /**
5097     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5098     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5099     *
5100     * @attr ref android.R.styleable#View_nextFocusUp
5101     */
5102    public int getNextFocusUpId() {
5103        return mNextFocusUpId;
5104    }
5105
5106    /**
5107     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5108     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5109     * decide automatically.
5110     *
5111     * @attr ref android.R.styleable#View_nextFocusUp
5112     */
5113    public void setNextFocusUpId(int nextFocusUpId) {
5114        mNextFocusUpId = nextFocusUpId;
5115    }
5116
5117    /**
5118     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5119     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5120     *
5121     * @attr ref android.R.styleable#View_nextFocusDown
5122     */
5123    public int getNextFocusDownId() {
5124        return mNextFocusDownId;
5125    }
5126
5127    /**
5128     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5129     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5130     * decide automatically.
5131     *
5132     * @attr ref android.R.styleable#View_nextFocusDown
5133     */
5134    public void setNextFocusDownId(int nextFocusDownId) {
5135        mNextFocusDownId = nextFocusDownId;
5136    }
5137
5138    /**
5139     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5140     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5141     *
5142     * @attr ref android.R.styleable#View_nextFocusForward
5143     */
5144    public int getNextFocusForwardId() {
5145        return mNextFocusForwardId;
5146    }
5147
5148    /**
5149     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5150     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5151     * decide automatically.
5152     *
5153     * @attr ref android.R.styleable#View_nextFocusForward
5154     */
5155    public void setNextFocusForwardId(int nextFocusForwardId) {
5156        mNextFocusForwardId = nextFocusForwardId;
5157    }
5158
5159    /**
5160     * Returns the visibility of this view and all of its ancestors
5161     *
5162     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5163     */
5164    public boolean isShown() {
5165        View current = this;
5166        //noinspection ConstantConditions
5167        do {
5168            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5169                return false;
5170            }
5171            ViewParent parent = current.mParent;
5172            if (parent == null) {
5173                return false; // We are not attached to the view root
5174            }
5175            if (!(parent instanceof View)) {
5176                return true;
5177            }
5178            current = (View) parent;
5179        } while (current != null);
5180
5181        return false;
5182    }
5183
5184    /**
5185     * Called by the view hierarchy when the content insets for a window have
5186     * changed, to allow it to adjust its content to fit within those windows.
5187     * The content insets tell you the space that the status bar, input method,
5188     * and other system windows infringe on the application's window.
5189     *
5190     * <p>You do not normally need to deal with this function, since the default
5191     * window decoration given to applications takes care of applying it to the
5192     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5193     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5194     * and your content can be placed under those system elements.  You can then
5195     * use this method within your view hierarchy if you have parts of your UI
5196     * which you would like to ensure are not being covered.
5197     *
5198     * <p>The default implementation of this method simply applies the content
5199     * inset's to the view's padding.  This can be enabled through
5200     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5201     * the method and handle the insets however you would like.  Note that the
5202     * insets provided by the framework are always relative to the far edges
5203     * of the window, not accounting for the location of the called view within
5204     * that window.  (In fact when this method is called you do not yet know
5205     * where the layout will place the view, as it is done before layout happens.)
5206     *
5207     * <p>Note: unlike many View methods, there is no dispatch phase to this
5208     * call.  If you are overriding it in a ViewGroup and want to allow the
5209     * call to continue to your children, you must be sure to call the super
5210     * implementation.
5211     *
5212     * @param insets Current content insets of the window.  Prior to
5213     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5214     * the insets or else you and Android will be unhappy.
5215     *
5216     * @return Return true if this view applied the insets and it should not
5217     * continue propagating further down the hierarchy, false otherwise.
5218     */
5219    protected boolean fitSystemWindows(Rect insets) {
5220        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5221            mUserPaddingStart = -1;
5222            mUserPaddingEnd = -1;
5223            mUserPaddingRelative = false;
5224            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5225                    || mAttachInfo == null
5226                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5227                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5228                return true;
5229            } else {
5230                internalSetPadding(0, 0, 0, 0);
5231                return false;
5232            }
5233        }
5234        return false;
5235    }
5236
5237    /**
5238     * Set whether or not this view should account for system screen decorations
5239     * such as the status bar and inset its content. This allows this view to be
5240     * positioned in absolute screen coordinates and remain visible to the user.
5241     *
5242     * <p>This should only be used by top-level window decor views.
5243     *
5244     * @param fitSystemWindows true to inset content for system screen decorations, false for
5245     *                         default behavior.
5246     *
5247     * @attr ref android.R.styleable#View_fitsSystemWindows
5248     */
5249    public void setFitsSystemWindows(boolean fitSystemWindows) {
5250        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5251    }
5252
5253    /**
5254     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5255     * will account for system screen decorations such as the status bar and inset its
5256     * content. This allows the view to be positioned in absolute screen coordinates
5257     * and remain visible to the user.
5258     *
5259     * @return true if this view will adjust its content bounds for system screen decorations.
5260     *
5261     * @attr ref android.R.styleable#View_fitsSystemWindows
5262     */
5263    public boolean fitsSystemWindows() {
5264        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5265    }
5266
5267    /**
5268     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5269     */
5270    public void requestFitSystemWindows() {
5271        if (mParent != null) {
5272            mParent.requestFitSystemWindows();
5273        }
5274    }
5275
5276    /**
5277     * For use by PhoneWindow to make its own system window fitting optional.
5278     * @hide
5279     */
5280    public void makeOptionalFitsSystemWindows() {
5281        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5282    }
5283
5284    /**
5285     * Returns the visibility status for this view.
5286     *
5287     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5288     * @attr ref android.R.styleable#View_visibility
5289     */
5290    @ViewDebug.ExportedProperty(mapping = {
5291        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5292        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5293        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5294    })
5295    public int getVisibility() {
5296        return mViewFlags & VISIBILITY_MASK;
5297    }
5298
5299    /**
5300     * Set the enabled state of this view.
5301     *
5302     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5303     * @attr ref android.R.styleable#View_visibility
5304     */
5305    @RemotableViewMethod
5306    public void setVisibility(int visibility) {
5307        setFlags(visibility, VISIBILITY_MASK);
5308        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5309    }
5310
5311    /**
5312     * Returns the enabled status for this view. The interpretation of the
5313     * enabled state varies by subclass.
5314     *
5315     * @return True if this view is enabled, false otherwise.
5316     */
5317    @ViewDebug.ExportedProperty
5318    public boolean isEnabled() {
5319        return (mViewFlags & ENABLED_MASK) == ENABLED;
5320    }
5321
5322    /**
5323     * Set the enabled state of this view. The interpretation of the enabled
5324     * state varies by subclass.
5325     *
5326     * @param enabled True if this view is enabled, false otherwise.
5327     */
5328    @RemotableViewMethod
5329    public void setEnabled(boolean enabled) {
5330        if (enabled == isEnabled()) return;
5331
5332        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5333
5334        /*
5335         * The View most likely has to change its appearance, so refresh
5336         * the drawable state.
5337         */
5338        refreshDrawableState();
5339
5340        // Invalidate too, since the default behavior for views is to be
5341        // be drawn at 50% alpha rather than to change the drawable.
5342        invalidate(true);
5343    }
5344
5345    /**
5346     * Set whether this view can receive the focus.
5347     *
5348     * Setting this to false will also ensure that this view is not focusable
5349     * in touch mode.
5350     *
5351     * @param focusable If true, this view can receive the focus.
5352     *
5353     * @see #setFocusableInTouchMode(boolean)
5354     * @attr ref android.R.styleable#View_focusable
5355     */
5356    public void setFocusable(boolean focusable) {
5357        if (!focusable) {
5358            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5359        }
5360        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5361    }
5362
5363    /**
5364     * Set whether this view can receive focus while in touch mode.
5365     *
5366     * Setting this to true will also ensure that this view is focusable.
5367     *
5368     * @param focusableInTouchMode If true, this view can receive the focus while
5369     *   in touch mode.
5370     *
5371     * @see #setFocusable(boolean)
5372     * @attr ref android.R.styleable#View_focusableInTouchMode
5373     */
5374    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5375        // Focusable in touch mode should always be set before the focusable flag
5376        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5377        // which, in touch mode, will not successfully request focus on this view
5378        // because the focusable in touch mode flag is not set
5379        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5380        if (focusableInTouchMode) {
5381            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5382        }
5383    }
5384
5385    /**
5386     * Set whether this view should have sound effects enabled for events such as
5387     * clicking and touching.
5388     *
5389     * <p>You may wish to disable sound effects for a view if you already play sounds,
5390     * for instance, a dial key that plays dtmf tones.
5391     *
5392     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5393     * @see #isSoundEffectsEnabled()
5394     * @see #playSoundEffect(int)
5395     * @attr ref android.R.styleable#View_soundEffectsEnabled
5396     */
5397    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5398        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5399    }
5400
5401    /**
5402     * @return whether this view should have sound effects enabled for events such as
5403     *     clicking and touching.
5404     *
5405     * @see #setSoundEffectsEnabled(boolean)
5406     * @see #playSoundEffect(int)
5407     * @attr ref android.R.styleable#View_soundEffectsEnabled
5408     */
5409    @ViewDebug.ExportedProperty
5410    public boolean isSoundEffectsEnabled() {
5411        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5412    }
5413
5414    /**
5415     * Set whether this view should have haptic feedback for events such as
5416     * long presses.
5417     *
5418     * <p>You may wish to disable haptic feedback if your view already controls
5419     * its own haptic feedback.
5420     *
5421     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5422     * @see #isHapticFeedbackEnabled()
5423     * @see #performHapticFeedback(int)
5424     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5425     */
5426    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5427        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5428    }
5429
5430    /**
5431     * @return whether this view should have haptic feedback enabled for events
5432     * long presses.
5433     *
5434     * @see #setHapticFeedbackEnabled(boolean)
5435     * @see #performHapticFeedback(int)
5436     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5437     */
5438    @ViewDebug.ExportedProperty
5439    public boolean isHapticFeedbackEnabled() {
5440        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5441    }
5442
5443    /**
5444     * Returns the layout direction for this view.
5445     *
5446     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5447     *   {@link #LAYOUT_DIRECTION_RTL},
5448     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5449     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5450     *
5451     * @attr ref android.R.styleable#View_layoutDirection
5452     * @hide
5453     */
5454    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5455        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5456        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5457        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5458        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5459    })
5460    public int getLayoutDirection() {
5461        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5462    }
5463
5464    /**
5465     * Set the layout direction for this view. This will propagate a reset of layout direction
5466     * resolution to the view's children and resolve layout direction for this view.
5467     *
5468     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5469     *   {@link #LAYOUT_DIRECTION_RTL},
5470     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5471     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5472     *
5473     * @attr ref android.R.styleable#View_layoutDirection
5474     * @hide
5475     */
5476    @RemotableViewMethod
5477    public void setLayoutDirection(int layoutDirection) {
5478        if (getLayoutDirection() != layoutDirection) {
5479            // Reset the current layout direction and the resolved one
5480            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5481            resetResolvedLayoutDirection();
5482            // Set the new layout direction (filtered) and ask for a layout pass
5483            mPrivateFlags2 |=
5484                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5485            requestLayout();
5486        }
5487    }
5488
5489    /**
5490     * Returns the resolved layout direction for this view.
5491     *
5492     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5493     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5494     * @hide
5495     */
5496    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5497        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5498        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5499    })
5500    public int getResolvedLayoutDirection() {
5501        // The layout diretion will be resolved only if needed
5502        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5503            resolveLayoutDirection();
5504        }
5505        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5506                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5507    }
5508
5509    /**
5510     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5511     * layout attribute and/or the inherited value from the parent
5512     *
5513     * @return true if the layout is right-to-left.
5514     * @hide
5515     */
5516    @ViewDebug.ExportedProperty(category = "layout")
5517    public boolean isLayoutRtl() {
5518        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5519    }
5520
5521    /**
5522     * Indicates whether the view is currently tracking transient state that the
5523     * app should not need to concern itself with saving and restoring, but that
5524     * the framework should take special note to preserve when possible.
5525     *
5526     * <p>A view with transient state cannot be trivially rebound from an external
5527     * data source, such as an adapter binding item views in a list. This may be
5528     * because the view is performing an animation, tracking user selection
5529     * of content, or similar.</p>
5530     *
5531     * @return true if the view has transient state
5532     */
5533    @ViewDebug.ExportedProperty(category = "layout")
5534    public boolean hasTransientState() {
5535        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5536    }
5537
5538    /**
5539     * Set whether this view is currently tracking transient state that the
5540     * framework should attempt to preserve when possible. This flag is reference counted,
5541     * so every call to setHasTransientState(true) should be paired with a later call
5542     * to setHasTransientState(false).
5543     *
5544     * <p>A view with transient state cannot be trivially rebound from an external
5545     * data source, such as an adapter binding item views in a list. This may be
5546     * because the view is performing an animation, tracking user selection
5547     * of content, or similar.</p>
5548     *
5549     * @param hasTransientState true if this view has transient state
5550     */
5551    public void setHasTransientState(boolean hasTransientState) {
5552        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5553                mTransientStateCount - 1;
5554        if (mTransientStateCount < 0) {
5555            mTransientStateCount = 0;
5556            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5557                    "unmatched pair of setHasTransientState calls");
5558        }
5559        if ((hasTransientState && mTransientStateCount == 1) ||
5560                (hasTransientState && mTransientStateCount == 0)) {
5561            // update flag if we've just incremented up from 0 or decremented down to 0
5562            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5563                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5564            if (mParent != null) {
5565                try {
5566                    mParent.childHasTransientStateChanged(this, hasTransientState);
5567                } catch (AbstractMethodError e) {
5568                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5569                            " does not fully implement ViewParent", e);
5570                }
5571            }
5572        }
5573    }
5574
5575    /**
5576     * If this view doesn't do any drawing on its own, set this flag to
5577     * allow further optimizations. By default, this flag is not set on
5578     * View, but could be set on some View subclasses such as ViewGroup.
5579     *
5580     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5581     * you should clear this flag.
5582     *
5583     * @param willNotDraw whether or not this View draw on its own
5584     */
5585    public void setWillNotDraw(boolean willNotDraw) {
5586        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5587    }
5588
5589    /**
5590     * Returns whether or not this View draws on its own.
5591     *
5592     * @return true if this view has nothing to draw, false otherwise
5593     */
5594    @ViewDebug.ExportedProperty(category = "drawing")
5595    public boolean willNotDraw() {
5596        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5597    }
5598
5599    /**
5600     * When a View's drawing cache is enabled, drawing is redirected to an
5601     * offscreen bitmap. Some views, like an ImageView, must be able to
5602     * bypass this mechanism if they already draw a single bitmap, to avoid
5603     * unnecessary usage of the memory.
5604     *
5605     * @param willNotCacheDrawing true if this view does not cache its
5606     *        drawing, false otherwise
5607     */
5608    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5609        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5610    }
5611
5612    /**
5613     * Returns whether or not this View can cache its drawing or not.
5614     *
5615     * @return true if this view does not cache its drawing, false otherwise
5616     */
5617    @ViewDebug.ExportedProperty(category = "drawing")
5618    public boolean willNotCacheDrawing() {
5619        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5620    }
5621
5622    /**
5623     * Indicates whether this view reacts to click events or not.
5624     *
5625     * @return true if the view is clickable, false otherwise
5626     *
5627     * @see #setClickable(boolean)
5628     * @attr ref android.R.styleable#View_clickable
5629     */
5630    @ViewDebug.ExportedProperty
5631    public boolean isClickable() {
5632        return (mViewFlags & CLICKABLE) == CLICKABLE;
5633    }
5634
5635    /**
5636     * Enables or disables click events for this view. When a view
5637     * is clickable it will change its state to "pressed" on every click.
5638     * Subclasses should set the view clickable to visually react to
5639     * user's clicks.
5640     *
5641     * @param clickable true to make the view clickable, false otherwise
5642     *
5643     * @see #isClickable()
5644     * @attr ref android.R.styleable#View_clickable
5645     */
5646    public void setClickable(boolean clickable) {
5647        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5648    }
5649
5650    /**
5651     * Indicates whether this view reacts to long click events or not.
5652     *
5653     * @return true if the view is long clickable, false otherwise
5654     *
5655     * @see #setLongClickable(boolean)
5656     * @attr ref android.R.styleable#View_longClickable
5657     */
5658    public boolean isLongClickable() {
5659        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5660    }
5661
5662    /**
5663     * Enables or disables long click events for this view. When a view is long
5664     * clickable it reacts to the user holding down the button for a longer
5665     * duration than a tap. This event can either launch the listener or a
5666     * context menu.
5667     *
5668     * @param longClickable true to make the view long clickable, false otherwise
5669     * @see #isLongClickable()
5670     * @attr ref android.R.styleable#View_longClickable
5671     */
5672    public void setLongClickable(boolean longClickable) {
5673        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5674    }
5675
5676    /**
5677     * Sets the pressed state for this view.
5678     *
5679     * @see #isClickable()
5680     * @see #setClickable(boolean)
5681     *
5682     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5683     *        the View's internal state from a previously set "pressed" state.
5684     */
5685    public void setPressed(boolean pressed) {
5686        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5687
5688        if (pressed) {
5689            mPrivateFlags |= PRESSED;
5690        } else {
5691            mPrivateFlags &= ~PRESSED;
5692        }
5693
5694        if (needsRefresh) {
5695            refreshDrawableState();
5696        }
5697        dispatchSetPressed(pressed);
5698    }
5699
5700    /**
5701     * Dispatch setPressed to all of this View's children.
5702     *
5703     * @see #setPressed(boolean)
5704     *
5705     * @param pressed The new pressed state
5706     */
5707    protected void dispatchSetPressed(boolean pressed) {
5708    }
5709
5710    /**
5711     * Indicates whether the view is currently in pressed state. Unless
5712     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5713     * the pressed state.
5714     *
5715     * @see #setPressed(boolean)
5716     * @see #isClickable()
5717     * @see #setClickable(boolean)
5718     *
5719     * @return true if the view is currently pressed, false otherwise
5720     */
5721    public boolean isPressed() {
5722        return (mPrivateFlags & PRESSED) == PRESSED;
5723    }
5724
5725    /**
5726     * Indicates whether this view will save its state (that is,
5727     * whether its {@link #onSaveInstanceState} method will be called).
5728     *
5729     * @return Returns true if the view state saving is enabled, else false.
5730     *
5731     * @see #setSaveEnabled(boolean)
5732     * @attr ref android.R.styleable#View_saveEnabled
5733     */
5734    public boolean isSaveEnabled() {
5735        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5736    }
5737
5738    /**
5739     * Controls whether the saving of this view's state is
5740     * enabled (that is, whether its {@link #onSaveInstanceState} method
5741     * will be called).  Note that even if freezing is enabled, the
5742     * view still must have an id assigned to it (via {@link #setId(int)})
5743     * for its state to be saved.  This flag can only disable the
5744     * saving of this view; any child views may still have their state saved.
5745     *
5746     * @param enabled Set to false to <em>disable</em> state saving, or true
5747     * (the default) to allow it.
5748     *
5749     * @see #isSaveEnabled()
5750     * @see #setId(int)
5751     * @see #onSaveInstanceState()
5752     * @attr ref android.R.styleable#View_saveEnabled
5753     */
5754    public void setSaveEnabled(boolean enabled) {
5755        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5756    }
5757
5758    /**
5759     * Gets whether the framework should discard touches when the view's
5760     * window is obscured by another visible window.
5761     * Refer to the {@link View} security documentation for more details.
5762     *
5763     * @return True if touch filtering is enabled.
5764     *
5765     * @see #setFilterTouchesWhenObscured(boolean)
5766     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5767     */
5768    @ViewDebug.ExportedProperty
5769    public boolean getFilterTouchesWhenObscured() {
5770        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5771    }
5772
5773    /**
5774     * Sets whether the framework should discard touches when the view's
5775     * window is obscured by another visible window.
5776     * Refer to the {@link View} security documentation for more details.
5777     *
5778     * @param enabled True if touch filtering should be enabled.
5779     *
5780     * @see #getFilterTouchesWhenObscured
5781     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5782     */
5783    public void setFilterTouchesWhenObscured(boolean enabled) {
5784        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5785                FILTER_TOUCHES_WHEN_OBSCURED);
5786    }
5787
5788    /**
5789     * Indicates whether the entire hierarchy under this view will save its
5790     * state when a state saving traversal occurs from its parent.  The default
5791     * is true; if false, these views will not be saved unless
5792     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5793     *
5794     * @return Returns true if the view state saving from parent is enabled, else false.
5795     *
5796     * @see #setSaveFromParentEnabled(boolean)
5797     */
5798    public boolean isSaveFromParentEnabled() {
5799        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5800    }
5801
5802    /**
5803     * Controls whether the entire hierarchy under this view will save its
5804     * state when a state saving traversal occurs from its parent.  The default
5805     * is true; if false, these views will not be saved unless
5806     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5807     *
5808     * @param enabled Set to false to <em>disable</em> state saving, or true
5809     * (the default) to allow it.
5810     *
5811     * @see #isSaveFromParentEnabled()
5812     * @see #setId(int)
5813     * @see #onSaveInstanceState()
5814     */
5815    public void setSaveFromParentEnabled(boolean enabled) {
5816        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5817    }
5818
5819
5820    /**
5821     * Returns whether this View is able to take focus.
5822     *
5823     * @return True if this view can take focus, or false otherwise.
5824     * @attr ref android.R.styleable#View_focusable
5825     */
5826    @ViewDebug.ExportedProperty(category = "focus")
5827    public final boolean isFocusable() {
5828        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5829    }
5830
5831    /**
5832     * When a view is focusable, it may not want to take focus when in touch mode.
5833     * For example, a button would like focus when the user is navigating via a D-pad
5834     * so that the user can click on it, but once the user starts touching the screen,
5835     * the button shouldn't take focus
5836     * @return Whether the view is focusable in touch mode.
5837     * @attr ref android.R.styleable#View_focusableInTouchMode
5838     */
5839    @ViewDebug.ExportedProperty
5840    public final boolean isFocusableInTouchMode() {
5841        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5842    }
5843
5844    /**
5845     * Find the nearest view in the specified direction that can take focus.
5846     * This does not actually give focus to that view.
5847     *
5848     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5849     *
5850     * @return The nearest focusable in the specified direction, or null if none
5851     *         can be found.
5852     */
5853    public View focusSearch(int direction) {
5854        if (mParent != null) {
5855            return mParent.focusSearch(this, direction);
5856        } else {
5857            return null;
5858        }
5859    }
5860
5861    /**
5862     * This method is the last chance for the focused view and its ancestors to
5863     * respond to an arrow key. This is called when the focused view did not
5864     * consume the key internally, nor could the view system find a new view in
5865     * the requested direction to give focus to.
5866     *
5867     * @param focused The currently focused view.
5868     * @param direction The direction focus wants to move. One of FOCUS_UP,
5869     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5870     * @return True if the this view consumed this unhandled move.
5871     */
5872    public boolean dispatchUnhandledMove(View focused, int direction) {
5873        return false;
5874    }
5875
5876    /**
5877     * If a user manually specified the next view id for a particular direction,
5878     * use the root to look up the view.
5879     * @param root The root view of the hierarchy containing this view.
5880     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5881     * or FOCUS_BACKWARD.
5882     * @return The user specified next view, or null if there is none.
5883     */
5884    View findUserSetNextFocus(View root, int direction) {
5885        switch (direction) {
5886            case FOCUS_LEFT:
5887                if (mNextFocusLeftId == View.NO_ID) return null;
5888                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5889            case FOCUS_RIGHT:
5890                if (mNextFocusRightId == View.NO_ID) return null;
5891                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5892            case FOCUS_UP:
5893                if (mNextFocusUpId == View.NO_ID) return null;
5894                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5895            case FOCUS_DOWN:
5896                if (mNextFocusDownId == View.NO_ID) return null;
5897                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5898            case FOCUS_FORWARD:
5899                if (mNextFocusForwardId == View.NO_ID) return null;
5900                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5901            case FOCUS_BACKWARD: {
5902                if (mID == View.NO_ID) return null;
5903                final int id = mID;
5904                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5905                    @Override
5906                    public boolean apply(View t) {
5907                        return t.mNextFocusForwardId == id;
5908                    }
5909                });
5910            }
5911        }
5912        return null;
5913    }
5914
5915    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5916        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5917            @Override
5918            public boolean apply(View t) {
5919                return t.mID == childViewId;
5920            }
5921        });
5922
5923        if (result == null) {
5924            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5925                    + "by user for id " + childViewId);
5926        }
5927        return result;
5928    }
5929
5930    /**
5931     * Find and return all focusable views that are descendants of this view,
5932     * possibly including this view if it is focusable itself.
5933     *
5934     * @param direction The direction of the focus
5935     * @return A list of focusable views
5936     */
5937    public ArrayList<View> getFocusables(int direction) {
5938        ArrayList<View> result = new ArrayList<View>(24);
5939        addFocusables(result, direction);
5940        return result;
5941    }
5942
5943    /**
5944     * Add any focusable views that are descendants of this view (possibly
5945     * including this view if it is focusable itself) to views.  If we are in touch mode,
5946     * only add views that are also focusable in touch mode.
5947     *
5948     * @param views Focusable views found so far
5949     * @param direction The direction of the focus
5950     */
5951    public void addFocusables(ArrayList<View> views, int direction) {
5952        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5953    }
5954
5955    /**
5956     * Adds any focusable views that are descendants of this view (possibly
5957     * including this view if it is focusable itself) to views. This method
5958     * adds all focusable views regardless if we are in touch mode or
5959     * only views focusable in touch mode if we are in touch mode or
5960     * only views that can take accessibility focus if accessibility is enabeld
5961     * depending on the focusable mode paramater.
5962     *
5963     * @param views Focusable views found so far or null if all we are interested is
5964     *        the number of focusables.
5965     * @param direction The direction of the focus.
5966     * @param focusableMode The type of focusables to be added.
5967     *
5968     * @see #FOCUSABLES_ALL
5969     * @see #FOCUSABLES_TOUCH_MODE
5970     */
5971    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5972        if (views == null) {
5973            return;
5974        }
5975        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5976            if (AccessibilityManager.getInstance(mContext).isEnabled()
5977                    && includeForAccessibility()) {
5978                views.add(this);
5979                return;
5980            }
5981        }
5982        if (!isFocusable()) {
5983            return;
5984        }
5985        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5986                && isInTouchMode() && !isFocusableInTouchMode()) {
5987            return;
5988        }
5989        views.add(this);
5990    }
5991
5992    /**
5993     * Finds the Views that contain given text. The containment is case insensitive.
5994     * The search is performed by either the text that the View renders or the content
5995     * description that describes the view for accessibility purposes and the view does
5996     * not render or both. Clients can specify how the search is to be performed via
5997     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5998     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5999     *
6000     * @param outViews The output list of matching Views.
6001     * @param searched The text to match against.
6002     *
6003     * @see #FIND_VIEWS_WITH_TEXT
6004     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6005     * @see #setContentDescription(CharSequence)
6006     */
6007    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6008        if (getAccessibilityNodeProvider() != null) {
6009            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6010                outViews.add(this);
6011            }
6012        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6013                && (searched != null && searched.length() > 0)
6014                && (mContentDescription != null && mContentDescription.length() > 0)) {
6015            String searchedLowerCase = searched.toString().toLowerCase();
6016            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6017            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6018                outViews.add(this);
6019            }
6020        }
6021    }
6022
6023    /**
6024     * Find and return all touchable views that are descendants of this view,
6025     * possibly including this view if it is touchable itself.
6026     *
6027     * @return A list of touchable views
6028     */
6029    public ArrayList<View> getTouchables() {
6030        ArrayList<View> result = new ArrayList<View>();
6031        addTouchables(result);
6032        return result;
6033    }
6034
6035    /**
6036     * Add any touchable views that are descendants of this view (possibly
6037     * including this view if it is touchable itself) to views.
6038     *
6039     * @param views Touchable views found so far
6040     */
6041    public void addTouchables(ArrayList<View> views) {
6042        final int viewFlags = mViewFlags;
6043
6044        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6045                && (viewFlags & ENABLED_MASK) == ENABLED) {
6046            views.add(this);
6047        }
6048    }
6049
6050    /**
6051     * Returns whether this View is accessibility focused.
6052     *
6053     * @return True if this View is accessibility focused.
6054     */
6055    boolean isAccessibilityFocused() {
6056        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6057    }
6058
6059    /**
6060     * Call this to try to give accessibility focus to this view.
6061     *
6062     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6063     * returns false or the view is no visible or the view already has accessibility
6064     * focus.
6065     *
6066     * See also {@link #focusSearch(int)}, which is what you call to say that you
6067     * have focus, and you want your parent to look for the next one.
6068     *
6069     * @return Whether this view actually took accessibility focus.
6070     *
6071     * @hide
6072     */
6073    public boolean requestAccessibilityFocus() {
6074        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6075        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6076            return false;
6077        }
6078        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6079            return false;
6080        }
6081        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6082            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6083            ViewRootImpl viewRootImpl = getViewRootImpl();
6084            if (viewRootImpl != null) {
6085                viewRootImpl.setAccessibilityFocusedHost(this);
6086            }
6087            invalidate();
6088            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6089            notifyAccessibilityStateChanged();
6090            // Try to give input focus to this view - not a descendant.
6091            requestFocusNoSearch(View.FOCUS_DOWN, null);
6092            return true;
6093        }
6094        return false;
6095    }
6096
6097    /**
6098     * Call this to try to clear accessibility focus of this view.
6099     *
6100     * See also {@link #focusSearch(int)}, which is what you call to say that you
6101     * have focus, and you want your parent to look for the next one.
6102     *
6103     * @hide
6104     */
6105    public void clearAccessibilityFocus() {
6106        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6107            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6108            ViewRootImpl viewRootImpl = getViewRootImpl();
6109            if (viewRootImpl != null) {
6110                viewRootImpl.setAccessibilityFocusedHost(null);
6111            }
6112            invalidate();
6113            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6114            notifyAccessibilityStateChanged();
6115
6116            // Clear the text navigation state.
6117            setAccessibilityCursorPosition(-1);
6118
6119            // Try to move accessibility focus to the input focus.
6120            View rootView = getRootView();
6121            if (rootView != null) {
6122                View inputFocus = rootView.findFocus();
6123                if (inputFocus != null) {
6124                    inputFocus.requestAccessibilityFocus();
6125                }
6126            }
6127        }
6128    }
6129
6130    /**
6131     * Find the best view to take accessibility focus from a hover.
6132     * This function finds the deepest actionable view and if that
6133     * fails ask the parent to take accessibility focus from hover.
6134     *
6135     * @param x The X hovered location in this view coorditantes.
6136     * @param y The Y hovered location in this view coorditantes.
6137     * @return Whether the request was handled.
6138     *
6139     * @hide
6140     */
6141    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6142        if (onRequestAccessibilityFocusFromHover(x, y)) {
6143            return true;
6144        }
6145        ViewParent parent = mParent;
6146        if (parent instanceof View) {
6147            View parentView = (View) parent;
6148
6149            float[] position = mAttachInfo.mTmpTransformLocation;
6150            position[0] = x;
6151            position[1] = y;
6152
6153            // Compensate for the transformation of the current matrix.
6154            if (!hasIdentityMatrix()) {
6155                getMatrix().mapPoints(position);
6156            }
6157
6158            // Compensate for the parent scroll and the offset
6159            // of this view stop from the parent top.
6160            position[0] += mLeft - parentView.mScrollX;
6161            position[1] += mTop - parentView.mScrollY;
6162
6163            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6164        }
6165        return false;
6166    }
6167
6168    /**
6169     * Requests to give this View focus from hover.
6170     *
6171     * @param x The X hovered location in this view coorditantes.
6172     * @param y The Y hovered location in this view coorditantes.
6173     * @return Whether the request was handled.
6174     *
6175     * @hide
6176     */
6177    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6178        if (includeForAccessibility()
6179                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6180            return requestAccessibilityFocus();
6181        }
6182        return false;
6183    }
6184
6185    /**
6186     * Clears accessibility focus without calling any callback methods
6187     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6188     * is used for clearing accessibility focus when giving this focus to
6189     * another view.
6190     */
6191    void clearAccessibilityFocusNoCallbacks() {
6192        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6193            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6194            invalidate();
6195        }
6196    }
6197
6198    /**
6199     * Call this to try to give focus to a specific view or to one of its
6200     * descendants.
6201     *
6202     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6203     * false), or if it is focusable and it is not focusable in touch mode
6204     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6205     *
6206     * See also {@link #focusSearch(int)}, which is what you call to say that you
6207     * have focus, and you want your parent to look for the next one.
6208     *
6209     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6210     * {@link #FOCUS_DOWN} and <code>null</code>.
6211     *
6212     * @return Whether this view or one of its descendants actually took focus.
6213     */
6214    public final boolean requestFocus() {
6215        return requestFocus(View.FOCUS_DOWN);
6216    }
6217
6218    /**
6219     * Call this to try to give focus to a specific view or to one of its
6220     * descendants and give it a hint about what direction focus is heading.
6221     *
6222     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6223     * false), or if it is focusable and it is not focusable in touch mode
6224     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6225     *
6226     * See also {@link #focusSearch(int)}, which is what you call to say that you
6227     * have focus, and you want your parent to look for the next one.
6228     *
6229     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6230     * <code>null</code> set for the previously focused rectangle.
6231     *
6232     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6233     * @return Whether this view or one of its descendants actually took focus.
6234     */
6235    public final boolean requestFocus(int direction) {
6236        return requestFocus(direction, null);
6237    }
6238
6239    /**
6240     * Call this to try to give focus to a specific view or to one of its descendants
6241     * and give it hints about the direction and a specific rectangle that the focus
6242     * is coming from.  The rectangle can help give larger views a finer grained hint
6243     * about where focus is coming from, and therefore, where to show selection, or
6244     * forward focus change internally.
6245     *
6246     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6247     * false), or if it is focusable and it is not focusable in touch mode
6248     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6249     *
6250     * A View will not take focus if it is not visible.
6251     *
6252     * A View will not take focus if one of its parents has
6253     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6254     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6255     *
6256     * See also {@link #focusSearch(int)}, which is what you call to say that you
6257     * have focus, and you want your parent to look for the next one.
6258     *
6259     * You may wish to override this method if your custom {@link View} has an internal
6260     * {@link View} that it wishes to forward the request to.
6261     *
6262     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6263     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6264     *        to give a finer grained hint about where focus is coming from.  May be null
6265     *        if there is no hint.
6266     * @return Whether this view or one of its descendants actually took focus.
6267     */
6268    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6269        return requestFocusNoSearch(direction, previouslyFocusedRect);
6270    }
6271
6272    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6273        // need to be focusable
6274        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6275                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6276            return false;
6277        }
6278
6279        // need to be focusable in touch mode if in touch mode
6280        if (isInTouchMode() &&
6281            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6282               return false;
6283        }
6284
6285        // need to not have any parents blocking us
6286        if (hasAncestorThatBlocksDescendantFocus()) {
6287            return false;
6288        }
6289
6290        handleFocusGainInternal(direction, previouslyFocusedRect);
6291        return true;
6292    }
6293
6294    /**
6295     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6296     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6297     * touch mode to request focus when they are touched.
6298     *
6299     * @return Whether this view or one of its descendants actually took focus.
6300     *
6301     * @see #isInTouchMode()
6302     *
6303     */
6304    public final boolean requestFocusFromTouch() {
6305        // Leave touch mode if we need to
6306        if (isInTouchMode()) {
6307            ViewRootImpl viewRoot = getViewRootImpl();
6308            if (viewRoot != null) {
6309                viewRoot.ensureTouchMode(false);
6310            }
6311        }
6312        return requestFocus(View.FOCUS_DOWN);
6313    }
6314
6315    /**
6316     * @return Whether any ancestor of this view blocks descendant focus.
6317     */
6318    private boolean hasAncestorThatBlocksDescendantFocus() {
6319        ViewParent ancestor = mParent;
6320        while (ancestor instanceof ViewGroup) {
6321            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6322            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6323                return true;
6324            } else {
6325                ancestor = vgAncestor.getParent();
6326            }
6327        }
6328        return false;
6329    }
6330
6331    /**
6332     * Gets the mode for determining whether this View is important for accessibility
6333     * which is if it fires accessibility events and if it is reported to
6334     * accessibility services that query the screen.
6335     *
6336     * @return The mode for determining whether a View is important for accessibility.
6337     *
6338     * @attr ref android.R.styleable#View_importantForAccessibility
6339     *
6340     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6341     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6342     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6343     */
6344    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6345            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6346                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6347            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6348                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6349            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6350                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6351        })
6352    public int getImportantForAccessibility() {
6353        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6354                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6355    }
6356
6357    /**
6358     * Sets how to determine whether this view is important for accessibility
6359     * which is if it fires accessibility events and if it is reported to
6360     * accessibility services that query the screen.
6361     *
6362     * @param mode How to determine whether this view is important for accessibility.
6363     *
6364     * @attr ref android.R.styleable#View_importantForAccessibility
6365     *
6366     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6367     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6368     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6369     */
6370    public void setImportantForAccessibility(int mode) {
6371        if (mode != getImportantForAccessibility()) {
6372            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6373            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6374                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6375            notifyAccessibilityStateChanged();
6376        }
6377    }
6378
6379    /**
6380     * Gets whether this view should be exposed for accessibility.
6381     *
6382     * @return Whether the view is exposed for accessibility.
6383     *
6384     * @hide
6385     */
6386    public boolean isImportantForAccessibility() {
6387        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6388                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6389        switch (mode) {
6390            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6391                return true;
6392            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6393                return false;
6394            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6395                return isActionableForAccessibility() || hasListenersForAccessibility();
6396            default:
6397                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6398                        + mode);
6399        }
6400    }
6401
6402    /**
6403     * Gets the parent for accessibility purposes. Note that the parent for
6404     * accessibility is not necessary the immediate parent. It is the first
6405     * predecessor that is important for accessibility.
6406     *
6407     * @return The parent for accessibility purposes.
6408     */
6409    public ViewParent getParentForAccessibility() {
6410        if (mParent instanceof View) {
6411            View parentView = (View) mParent;
6412            if (parentView.includeForAccessibility()) {
6413                return mParent;
6414            } else {
6415                return mParent.getParentForAccessibility();
6416            }
6417        }
6418        return null;
6419    }
6420
6421    /**
6422     * Adds the children of a given View for accessibility. Since some Views are
6423     * not important for accessibility the children for accessibility are not
6424     * necessarily direct children of the riew, rather they are the first level of
6425     * descendants important for accessibility.
6426     *
6427     * @param children The list of children for accessibility.
6428     */
6429    public void addChildrenForAccessibility(ArrayList<View> children) {
6430        if (includeForAccessibility()) {
6431            children.add(this);
6432        }
6433    }
6434
6435    /**
6436     * Whether to regard this view for accessibility. A view is regarded for
6437     * accessibility if it is important for accessibility or the querying
6438     * accessibility service has explicitly requested that view not
6439     * important for accessibility are regarded.
6440     *
6441     * @return Whether to regard the view for accessibility.
6442     */
6443    boolean includeForAccessibility() {
6444        if (mAttachInfo != null) {
6445            if (!mAttachInfo.mIncludeNotImportantViews) {
6446                return isImportantForAccessibility();
6447            } else {
6448                return true;
6449            }
6450        }
6451        return false;
6452    }
6453
6454    /**
6455     * Returns whether the View is considered actionable from
6456     * accessibility perspective. Such view are important for
6457     * accessiiblity.
6458     *
6459     * @return True if the view is actionable for accessibility.
6460     */
6461    private boolean isActionableForAccessibility() {
6462        return (isClickable() || isLongClickable() || isFocusable());
6463    }
6464
6465    /**
6466     * Returns whether the View has registered callbacks wich makes it
6467     * important for accessiiblity.
6468     *
6469     * @return True if the view is actionable for accessibility.
6470     */
6471    private boolean hasListenersForAccessibility() {
6472        ListenerInfo info = getListenerInfo();
6473        return mTouchDelegate != null || info.mOnKeyListener != null
6474                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6475                || info.mOnHoverListener != null || info.mOnDragListener != null;
6476    }
6477
6478    /**
6479     * Notifies accessibility services that some view's important for
6480     * accessibility state has changed. Note that such notifications
6481     * are made at most once every
6482     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6483     * to avoid unnecessary load to the system. Also once a view has
6484     * made a notifucation this method is a NOP until the notification has
6485     * been sent to clients.
6486     *
6487     * @hide
6488     *
6489     * TODO: Makse sure this method is called for any view state change
6490     *       that is interesting for accessilility purposes.
6491     */
6492    public void notifyAccessibilityStateChanged() {
6493        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6494            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6495            if (mParent != null) {
6496                mParent.childAccessibilityStateChanged(this);
6497            }
6498        }
6499    }
6500
6501    /**
6502     * Reset the state indicating the this view has requested clients
6503     * interested in its accessiblity state to be notified.
6504     *
6505     * @hide
6506     */
6507    public void resetAccessibilityStateChanged() {
6508        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6509    }
6510
6511    /**
6512     * Performs the specified accessibility action on the view. For
6513     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6514     *
6515     * @param action The action to perform.
6516     * @param arguments Optional action arguments.
6517     * @return Whether the action was performed.
6518     */
6519    public boolean performAccessibilityAction(int action, Bundle arguments) {
6520        switch (action) {
6521            case AccessibilityNodeInfo.ACTION_CLICK: {
6522                if (isClickable()) {
6523                    return performClick();
6524                }
6525            } break;
6526            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6527                if (isLongClickable()) {
6528                    return performLongClick();
6529                }
6530            } break;
6531            case AccessibilityNodeInfo.ACTION_FOCUS: {
6532                if (!hasFocus()) {
6533                    // Get out of touch mode since accessibility
6534                    // wants to move focus around.
6535                    getViewRootImpl().ensureTouchMode(false);
6536                    return requestFocus();
6537                }
6538            } break;
6539            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6540                if (hasFocus()) {
6541                    clearFocus();
6542                    return !isFocused();
6543                }
6544            } break;
6545            case AccessibilityNodeInfo.ACTION_SELECT: {
6546                if (!isSelected()) {
6547                    setSelected(true);
6548                    return isSelected();
6549                }
6550            } break;
6551            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6552                if (isSelected()) {
6553                    setSelected(false);
6554                    return !isSelected();
6555                }
6556            } break;
6557            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6558                if (!isAccessibilityFocused()) {
6559                    return requestAccessibilityFocus();
6560                }
6561            } break;
6562            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6563                if (isAccessibilityFocused()) {
6564                    clearAccessibilityFocus();
6565                    return true;
6566                }
6567            } break;
6568            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6569                if (arguments != null) {
6570                    final int granularity = arguments.getInt(
6571                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6572                    return nextAtGranularity(granularity);
6573                }
6574            } break;
6575            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6576                if (arguments != null) {
6577                    final int granularity = arguments.getInt(
6578                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6579                    return previousAtGranularity(granularity);
6580                }
6581            } break;
6582        }
6583        return false;
6584    }
6585
6586    private boolean nextAtGranularity(int granularity) {
6587        CharSequence text = getIterableTextForAccessibility();
6588        if (text != null && text.length() > 0) {
6589            return false;
6590        }
6591        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6592        if (iterator == null) {
6593            return false;
6594        }
6595        final int current = getAccessibilityCursorPosition();
6596        final int[] range = iterator.following(current);
6597        if (range == null) {
6598            setAccessibilityCursorPosition(-1);
6599            return false;
6600        }
6601        final int start = range[0];
6602        final int end = range[1];
6603        setAccessibilityCursorPosition(start);
6604        sendViewTextTraversedAtGranularityEvent(
6605                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6606                granularity, start, end);
6607        return true;
6608    }
6609
6610    private boolean previousAtGranularity(int granularity) {
6611        CharSequence text = getIterableTextForAccessibility();
6612        if (text != null && text.length() > 0) {
6613            return false;
6614        }
6615        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6616        if (iterator == null) {
6617            return false;
6618        }
6619        final int selectionStart = getAccessibilityCursorPosition();
6620        final int current = selectionStart >= 0 ? selectionStart : text.length() + 1;
6621        final int[] range = iterator.preceding(current);
6622        if (range == null) {
6623            setAccessibilityCursorPosition(-1);
6624            return false;
6625        }
6626        final int start = range[0];
6627        final int end = range[1];
6628        setAccessibilityCursorPosition(end);
6629        sendViewTextTraversedAtGranularityEvent(
6630                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6631                granularity, start, end);
6632        return true;
6633    }
6634
6635    /**
6636     * Gets the text reported for accessibility purposes.
6637     *
6638     * @return The accessibility text.
6639     *
6640     * @hide
6641     */
6642    public CharSequence getIterableTextForAccessibility() {
6643        return mContentDescription;
6644    }
6645
6646    /**
6647     * @hide
6648     */
6649    public int getAccessibilityCursorPosition() {
6650        return mAccessibilityCursorPosition;
6651    }
6652
6653    /**
6654     * @hide
6655     */
6656    public void setAccessibilityCursorPosition(int position) {
6657        mAccessibilityCursorPosition = position;
6658    }
6659
6660    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6661            int fromIndex, int toIndex) {
6662        if (mParent == null) {
6663            return;
6664        }
6665        AccessibilityEvent event = AccessibilityEvent.obtain(
6666                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6667        onInitializeAccessibilityEvent(event);
6668        onPopulateAccessibilityEvent(event);
6669        event.setFromIndex(fromIndex);
6670        event.setToIndex(toIndex);
6671        event.setAction(action);
6672        event.setMovementGranularity(granularity);
6673        mParent.requestSendAccessibilityEvent(this, event);
6674    }
6675
6676    /**
6677     * @hide
6678     */
6679    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6680        switch (granularity) {
6681            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6682                CharSequence text = getIterableTextForAccessibility();
6683                if (text != null && text.length() > 0) {
6684                    CharacterTextSegmentIterator iterator =
6685                        CharacterTextSegmentIterator.getInstance(mContext);
6686                    iterator.initialize(text.toString());
6687                    return iterator;
6688                }
6689            } break;
6690            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6691                CharSequence text = getIterableTextForAccessibility();
6692                if (text != null && text.length() > 0) {
6693                    WordTextSegmentIterator iterator =
6694                        WordTextSegmentIterator.getInstance(mContext);
6695                    iterator.initialize(text.toString());
6696                    return iterator;
6697                }
6698            } break;
6699            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6700                CharSequence text = getIterableTextForAccessibility();
6701                if (text != null && text.length() > 0) {
6702                    ParagraphTextSegmentIterator iterator =
6703                        ParagraphTextSegmentIterator.getInstance();
6704                    iterator.initialize(text.toString());
6705                    return iterator;
6706                }
6707            } break;
6708        }
6709        return null;
6710    }
6711
6712    /**
6713     * @hide
6714     */
6715    public void dispatchStartTemporaryDetach() {
6716        clearAccessibilityFocus();
6717        onStartTemporaryDetach();
6718    }
6719
6720    /**
6721     * This is called when a container is going to temporarily detach a child, with
6722     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6723     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6724     * {@link #onDetachedFromWindow()} when the container is done.
6725     */
6726    public void onStartTemporaryDetach() {
6727        removeUnsetPressCallback();
6728        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6729    }
6730
6731    /**
6732     * @hide
6733     */
6734    public void dispatchFinishTemporaryDetach() {
6735        onFinishTemporaryDetach();
6736    }
6737
6738    /**
6739     * Called after {@link #onStartTemporaryDetach} when the container is done
6740     * changing the view.
6741     */
6742    public void onFinishTemporaryDetach() {
6743    }
6744
6745    /**
6746     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6747     * for this view's window.  Returns null if the view is not currently attached
6748     * to the window.  Normally you will not need to use this directly, but
6749     * just use the standard high-level event callbacks like
6750     * {@link #onKeyDown(int, KeyEvent)}.
6751     */
6752    public KeyEvent.DispatcherState getKeyDispatcherState() {
6753        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6754    }
6755
6756    /**
6757     * Dispatch a key event before it is processed by any input method
6758     * associated with the view hierarchy.  This can be used to intercept
6759     * key events in special situations before the IME consumes them; a
6760     * typical example would be handling the BACK key to update the application's
6761     * UI instead of allowing the IME to see it and close itself.
6762     *
6763     * @param event The key event to be dispatched.
6764     * @return True if the event was handled, false otherwise.
6765     */
6766    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6767        return onKeyPreIme(event.getKeyCode(), event);
6768    }
6769
6770    /**
6771     * Dispatch a key event to the next view on the focus path. This path runs
6772     * from the top of the view tree down to the currently focused view. If this
6773     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6774     * the next node down the focus path. This method also fires any key
6775     * listeners.
6776     *
6777     * @param event The key event to be dispatched.
6778     * @return True if the event was handled, false otherwise.
6779     */
6780    public boolean dispatchKeyEvent(KeyEvent event) {
6781        if (mInputEventConsistencyVerifier != null) {
6782            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6783        }
6784
6785        // Give any attached key listener a first crack at the event.
6786        //noinspection SimplifiableIfStatement
6787        ListenerInfo li = mListenerInfo;
6788        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6789                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6790            return true;
6791        }
6792
6793        if (event.dispatch(this, mAttachInfo != null
6794                ? mAttachInfo.mKeyDispatchState : null, this)) {
6795            return true;
6796        }
6797
6798        if (mInputEventConsistencyVerifier != null) {
6799            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6800        }
6801        return false;
6802    }
6803
6804    /**
6805     * Dispatches a key shortcut event.
6806     *
6807     * @param event The key event to be dispatched.
6808     * @return True if the event was handled by the view, false otherwise.
6809     */
6810    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6811        return onKeyShortcut(event.getKeyCode(), event);
6812    }
6813
6814    /**
6815     * Pass the touch screen motion event down to the target view, or this
6816     * view if it is the target.
6817     *
6818     * @param event The motion event to be dispatched.
6819     * @return True if the event was handled by the view, false otherwise.
6820     */
6821    public boolean dispatchTouchEvent(MotionEvent event) {
6822        if (mInputEventConsistencyVerifier != null) {
6823            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6824        }
6825
6826        if (onFilterTouchEventForSecurity(event)) {
6827            //noinspection SimplifiableIfStatement
6828            ListenerInfo li = mListenerInfo;
6829            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6830                    && li.mOnTouchListener.onTouch(this, event)) {
6831                return true;
6832            }
6833
6834            if (onTouchEvent(event)) {
6835                return true;
6836            }
6837        }
6838
6839        if (mInputEventConsistencyVerifier != null) {
6840            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6841        }
6842        return false;
6843    }
6844
6845    /**
6846     * Filter the touch event to apply security policies.
6847     *
6848     * @param event The motion event to be filtered.
6849     * @return True if the event should be dispatched, false if the event should be dropped.
6850     *
6851     * @see #getFilterTouchesWhenObscured
6852     */
6853    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6854        //noinspection RedundantIfStatement
6855        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6856                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6857            // Window is obscured, drop this touch.
6858            return false;
6859        }
6860        return true;
6861    }
6862
6863    /**
6864     * Pass a trackball motion event down to the focused view.
6865     *
6866     * @param event The motion event to be dispatched.
6867     * @return True if the event was handled by the view, false otherwise.
6868     */
6869    public boolean dispatchTrackballEvent(MotionEvent event) {
6870        if (mInputEventConsistencyVerifier != null) {
6871            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6872        }
6873
6874        return onTrackballEvent(event);
6875    }
6876
6877    /**
6878     * Dispatch a generic motion event.
6879     * <p>
6880     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6881     * are delivered to the view under the pointer.  All other generic motion events are
6882     * delivered to the focused view.  Hover events are handled specially and are delivered
6883     * to {@link #onHoverEvent(MotionEvent)}.
6884     * </p>
6885     *
6886     * @param event The motion event to be dispatched.
6887     * @return True if the event was handled by the view, false otherwise.
6888     */
6889    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6890        if (mInputEventConsistencyVerifier != null) {
6891            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6892        }
6893
6894        final int source = event.getSource();
6895        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6896            final int action = event.getAction();
6897            if (action == MotionEvent.ACTION_HOVER_ENTER
6898                    || action == MotionEvent.ACTION_HOVER_MOVE
6899                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6900                if (dispatchHoverEvent(event)) {
6901                    return true;
6902                }
6903            } else if (dispatchGenericPointerEvent(event)) {
6904                return true;
6905            }
6906        } else if (dispatchGenericFocusedEvent(event)) {
6907            return true;
6908        }
6909
6910        if (dispatchGenericMotionEventInternal(event)) {
6911            return true;
6912        }
6913
6914        if (mInputEventConsistencyVerifier != null) {
6915            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6916        }
6917        return false;
6918    }
6919
6920    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6921        //noinspection SimplifiableIfStatement
6922        ListenerInfo li = mListenerInfo;
6923        if (li != null && li.mOnGenericMotionListener != null
6924                && (mViewFlags & ENABLED_MASK) == ENABLED
6925                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6926            return true;
6927        }
6928
6929        if (onGenericMotionEvent(event)) {
6930            return true;
6931        }
6932
6933        if (mInputEventConsistencyVerifier != null) {
6934            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6935        }
6936        return false;
6937    }
6938
6939    /**
6940     * Dispatch a hover event.
6941     * <p>
6942     * Do not call this method directly.
6943     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6944     * </p>
6945     *
6946     * @param event The motion event to be dispatched.
6947     * @return True if the event was handled by the view, false otherwise.
6948     */
6949    protected boolean dispatchHoverEvent(MotionEvent event) {
6950        //noinspection SimplifiableIfStatement
6951        ListenerInfo li = mListenerInfo;
6952        if (li != null && li.mOnHoverListener != null
6953                && (mViewFlags & ENABLED_MASK) == ENABLED
6954                && li.mOnHoverListener.onHover(this, event)) {
6955            return true;
6956        }
6957
6958        return onHoverEvent(event);
6959    }
6960
6961    /**
6962     * Returns true if the view has a child to which it has recently sent
6963     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6964     * it does not have a hovered child, then it must be the innermost hovered view.
6965     * @hide
6966     */
6967    protected boolean hasHoveredChild() {
6968        return false;
6969    }
6970
6971    /**
6972     * Dispatch a generic motion event to the view under the first pointer.
6973     * <p>
6974     * Do not call this method directly.
6975     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6976     * </p>
6977     *
6978     * @param event The motion event to be dispatched.
6979     * @return True if the event was handled by the view, false otherwise.
6980     */
6981    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6982        return false;
6983    }
6984
6985    /**
6986     * Dispatch a generic motion event to the currently focused view.
6987     * <p>
6988     * Do not call this method directly.
6989     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6990     * </p>
6991     *
6992     * @param event The motion event to be dispatched.
6993     * @return True if the event was handled by the view, false otherwise.
6994     */
6995    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6996        return false;
6997    }
6998
6999    /**
7000     * Dispatch a pointer event.
7001     * <p>
7002     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7003     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7004     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7005     * and should not be expected to handle other pointing device features.
7006     * </p>
7007     *
7008     * @param event The motion event to be dispatched.
7009     * @return True if the event was handled by the view, false otherwise.
7010     * @hide
7011     */
7012    public final boolean dispatchPointerEvent(MotionEvent event) {
7013        if (event.isTouchEvent()) {
7014            return dispatchTouchEvent(event);
7015        } else {
7016            return dispatchGenericMotionEvent(event);
7017        }
7018    }
7019
7020    /**
7021     * Called when the window containing this view gains or loses window focus.
7022     * ViewGroups should override to route to their children.
7023     *
7024     * @param hasFocus True if the window containing this view now has focus,
7025     *        false otherwise.
7026     */
7027    public void dispatchWindowFocusChanged(boolean hasFocus) {
7028        onWindowFocusChanged(hasFocus);
7029    }
7030
7031    /**
7032     * Called when the window containing this view gains or loses focus.  Note
7033     * that this is separate from view focus: to receive key events, both
7034     * your view and its window must have focus.  If a window is displayed
7035     * on top of yours that takes input focus, then your own window will lose
7036     * focus but the view focus will remain unchanged.
7037     *
7038     * @param hasWindowFocus True if the window containing this view now has
7039     *        focus, false otherwise.
7040     */
7041    public void onWindowFocusChanged(boolean hasWindowFocus) {
7042        InputMethodManager imm = InputMethodManager.peekInstance();
7043        if (!hasWindowFocus) {
7044            if (isPressed()) {
7045                setPressed(false);
7046            }
7047            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7048                imm.focusOut(this);
7049            }
7050            removeLongPressCallback();
7051            removeTapCallback();
7052            onFocusLost();
7053        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7054            imm.focusIn(this);
7055        }
7056        refreshDrawableState();
7057    }
7058
7059    /**
7060     * Returns true if this view is in a window that currently has window focus.
7061     * Note that this is not the same as the view itself having focus.
7062     *
7063     * @return True if this view is in a window that currently has window focus.
7064     */
7065    public boolean hasWindowFocus() {
7066        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7067    }
7068
7069    /**
7070     * Dispatch a view visibility change down the view hierarchy.
7071     * ViewGroups should override to route to their children.
7072     * @param changedView The view whose visibility changed. Could be 'this' or
7073     * an ancestor view.
7074     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7075     * {@link #INVISIBLE} or {@link #GONE}.
7076     */
7077    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7078        onVisibilityChanged(changedView, visibility);
7079    }
7080
7081    /**
7082     * Called when the visibility of the view or an ancestor of the view is changed.
7083     * @param changedView The view whose visibility changed. Could be 'this' or
7084     * an ancestor view.
7085     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7086     * {@link #INVISIBLE} or {@link #GONE}.
7087     */
7088    protected void onVisibilityChanged(View changedView, int visibility) {
7089        if (visibility == VISIBLE) {
7090            if (mAttachInfo != null) {
7091                initialAwakenScrollBars();
7092            } else {
7093                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7094            }
7095        }
7096    }
7097
7098    /**
7099     * Dispatch a hint about whether this view is displayed. For instance, when
7100     * a View moves out of the screen, it might receives a display hint indicating
7101     * the view is not displayed. Applications should not <em>rely</em> on this hint
7102     * as there is no guarantee that they will receive one.
7103     *
7104     * @param hint A hint about whether or not this view is displayed:
7105     * {@link #VISIBLE} or {@link #INVISIBLE}.
7106     */
7107    public void dispatchDisplayHint(int hint) {
7108        onDisplayHint(hint);
7109    }
7110
7111    /**
7112     * Gives this view a hint about whether is displayed or not. For instance, when
7113     * a View moves out of the screen, it might receives a display hint indicating
7114     * the view is not displayed. Applications should not <em>rely</em> on this hint
7115     * as there is no guarantee that they will receive one.
7116     *
7117     * @param hint A hint about whether or not this view is displayed:
7118     * {@link #VISIBLE} or {@link #INVISIBLE}.
7119     */
7120    protected void onDisplayHint(int hint) {
7121    }
7122
7123    /**
7124     * Dispatch a window visibility change down the view hierarchy.
7125     * ViewGroups should override to route to their children.
7126     *
7127     * @param visibility The new visibility of the window.
7128     *
7129     * @see #onWindowVisibilityChanged(int)
7130     */
7131    public void dispatchWindowVisibilityChanged(int visibility) {
7132        onWindowVisibilityChanged(visibility);
7133    }
7134
7135    /**
7136     * Called when the window containing has change its visibility
7137     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7138     * that this tells you whether or not your window is being made visible
7139     * to the window manager; this does <em>not</em> tell you whether or not
7140     * your window is obscured by other windows on the screen, even if it
7141     * is itself visible.
7142     *
7143     * @param visibility The new visibility of the window.
7144     */
7145    protected void onWindowVisibilityChanged(int visibility) {
7146        if (visibility == VISIBLE) {
7147            initialAwakenScrollBars();
7148        }
7149    }
7150
7151    /**
7152     * Returns the current visibility of the window this view is attached to
7153     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7154     *
7155     * @return Returns the current visibility of the view's window.
7156     */
7157    public int getWindowVisibility() {
7158        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7159    }
7160
7161    /**
7162     * Retrieve the overall visible display size in which the window this view is
7163     * attached to has been positioned in.  This takes into account screen
7164     * decorations above the window, for both cases where the window itself
7165     * is being position inside of them or the window is being placed under
7166     * then and covered insets are used for the window to position its content
7167     * inside.  In effect, this tells you the available area where content can
7168     * be placed and remain visible to users.
7169     *
7170     * <p>This function requires an IPC back to the window manager to retrieve
7171     * the requested information, so should not be used in performance critical
7172     * code like drawing.
7173     *
7174     * @param outRect Filled in with the visible display frame.  If the view
7175     * is not attached to a window, this is simply the raw display size.
7176     */
7177    public void getWindowVisibleDisplayFrame(Rect outRect) {
7178        if (mAttachInfo != null) {
7179            try {
7180                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7181            } catch (RemoteException e) {
7182                return;
7183            }
7184            // XXX This is really broken, and probably all needs to be done
7185            // in the window manager, and we need to know more about whether
7186            // we want the area behind or in front of the IME.
7187            final Rect insets = mAttachInfo.mVisibleInsets;
7188            outRect.left += insets.left;
7189            outRect.top += insets.top;
7190            outRect.right -= insets.right;
7191            outRect.bottom -= insets.bottom;
7192            return;
7193        }
7194        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7195        d.getRectSize(outRect);
7196    }
7197
7198    /**
7199     * Dispatch a notification about a resource configuration change down
7200     * the view hierarchy.
7201     * ViewGroups should override to route to their children.
7202     *
7203     * @param newConfig The new resource configuration.
7204     *
7205     * @see #onConfigurationChanged(android.content.res.Configuration)
7206     */
7207    public void dispatchConfigurationChanged(Configuration newConfig) {
7208        onConfigurationChanged(newConfig);
7209    }
7210
7211    /**
7212     * Called when the current configuration of the resources being used
7213     * by the application have changed.  You can use this to decide when
7214     * to reload resources that can changed based on orientation and other
7215     * configuration characterstics.  You only need to use this if you are
7216     * not relying on the normal {@link android.app.Activity} mechanism of
7217     * recreating the activity instance upon a configuration change.
7218     *
7219     * @param newConfig The new resource configuration.
7220     */
7221    protected void onConfigurationChanged(Configuration newConfig) {
7222    }
7223
7224    /**
7225     * Private function to aggregate all per-view attributes in to the view
7226     * root.
7227     */
7228    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7229        performCollectViewAttributes(attachInfo, visibility);
7230    }
7231
7232    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7233        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7234            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7235                attachInfo.mKeepScreenOn = true;
7236            }
7237            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7238            ListenerInfo li = mListenerInfo;
7239            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7240                attachInfo.mHasSystemUiListeners = true;
7241            }
7242        }
7243    }
7244
7245    void needGlobalAttributesUpdate(boolean force) {
7246        final AttachInfo ai = mAttachInfo;
7247        if (ai != null) {
7248            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7249                    || ai.mHasSystemUiListeners) {
7250                ai.mRecomputeGlobalAttributes = true;
7251            }
7252        }
7253    }
7254
7255    /**
7256     * Returns whether the device is currently in touch mode.  Touch mode is entered
7257     * once the user begins interacting with the device by touch, and affects various
7258     * things like whether focus is always visible to the user.
7259     *
7260     * @return Whether the device is in touch mode.
7261     */
7262    @ViewDebug.ExportedProperty
7263    public boolean isInTouchMode() {
7264        if (mAttachInfo != null) {
7265            return mAttachInfo.mInTouchMode;
7266        } else {
7267            return ViewRootImpl.isInTouchMode();
7268        }
7269    }
7270
7271    /**
7272     * Returns the context the view is running in, through which it can
7273     * access the current theme, resources, etc.
7274     *
7275     * @return The view's Context.
7276     */
7277    @ViewDebug.CapturedViewProperty
7278    public final Context getContext() {
7279        return mContext;
7280    }
7281
7282    /**
7283     * Handle a key event before it is processed by any input method
7284     * associated with the view hierarchy.  This can be used to intercept
7285     * key events in special situations before the IME consumes them; a
7286     * typical example would be handling the BACK key to update the application's
7287     * UI instead of allowing the IME to see it and close itself.
7288     *
7289     * @param keyCode The value in event.getKeyCode().
7290     * @param event Description of the key event.
7291     * @return If you handled the event, return true. If you want to allow the
7292     *         event to be handled by the next receiver, return false.
7293     */
7294    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7295        return false;
7296    }
7297
7298    /**
7299     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7300     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7301     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7302     * is released, if the view is enabled and clickable.
7303     *
7304     * @param keyCode A key code that represents the button pressed, from
7305     *                {@link android.view.KeyEvent}.
7306     * @param event   The KeyEvent object that defines the button action.
7307     */
7308    public boolean onKeyDown(int keyCode, KeyEvent event) {
7309        boolean result = false;
7310
7311        switch (keyCode) {
7312            case KeyEvent.KEYCODE_DPAD_CENTER:
7313            case KeyEvent.KEYCODE_ENTER: {
7314                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7315                    return true;
7316                }
7317                // Long clickable items don't necessarily have to be clickable
7318                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7319                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7320                        (event.getRepeatCount() == 0)) {
7321                    setPressed(true);
7322                    checkForLongClick(0);
7323                    return true;
7324                }
7325                break;
7326            }
7327        }
7328        return result;
7329    }
7330
7331    /**
7332     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7333     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7334     * the event).
7335     */
7336    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7337        return false;
7338    }
7339
7340    /**
7341     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7342     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7343     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7344     * {@link KeyEvent#KEYCODE_ENTER} is released.
7345     *
7346     * @param keyCode A key code that represents the button pressed, from
7347     *                {@link android.view.KeyEvent}.
7348     * @param event   The KeyEvent object that defines the button action.
7349     */
7350    public boolean onKeyUp(int keyCode, KeyEvent event) {
7351        boolean result = false;
7352
7353        switch (keyCode) {
7354            case KeyEvent.KEYCODE_DPAD_CENTER:
7355            case KeyEvent.KEYCODE_ENTER: {
7356                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7357                    return true;
7358                }
7359                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7360                    setPressed(false);
7361
7362                    if (!mHasPerformedLongPress) {
7363                        // This is a tap, so remove the longpress check
7364                        removeLongPressCallback();
7365
7366                        result = performClick();
7367                    }
7368                }
7369                break;
7370            }
7371        }
7372        return result;
7373    }
7374
7375    /**
7376     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7377     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7378     * the event).
7379     *
7380     * @param keyCode     A key code that represents the button pressed, from
7381     *                    {@link android.view.KeyEvent}.
7382     * @param repeatCount The number of times the action was made.
7383     * @param event       The KeyEvent object that defines the button action.
7384     */
7385    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7386        return false;
7387    }
7388
7389    /**
7390     * Called on the focused view when a key shortcut event is not handled.
7391     * Override this method to implement local key shortcuts for the View.
7392     * Key shortcuts can also be implemented by setting the
7393     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7394     *
7395     * @param keyCode The value in event.getKeyCode().
7396     * @param event Description of the key event.
7397     * @return If you handled the event, return true. If you want to allow the
7398     *         event to be handled by the next receiver, return false.
7399     */
7400    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7401        return false;
7402    }
7403
7404    /**
7405     * Check whether the called view is a text editor, in which case it
7406     * would make sense to automatically display a soft input window for
7407     * it.  Subclasses should override this if they implement
7408     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7409     * a call on that method would return a non-null InputConnection, and
7410     * they are really a first-class editor that the user would normally
7411     * start typing on when the go into a window containing your view.
7412     *
7413     * <p>The default implementation always returns false.  This does
7414     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7415     * will not be called or the user can not otherwise perform edits on your
7416     * view; it is just a hint to the system that this is not the primary
7417     * purpose of this view.
7418     *
7419     * @return Returns true if this view is a text editor, else false.
7420     */
7421    public boolean onCheckIsTextEditor() {
7422        return false;
7423    }
7424
7425    /**
7426     * Create a new InputConnection for an InputMethod to interact
7427     * with the view.  The default implementation returns null, since it doesn't
7428     * support input methods.  You can override this to implement such support.
7429     * This is only needed for views that take focus and text input.
7430     *
7431     * <p>When implementing this, you probably also want to implement
7432     * {@link #onCheckIsTextEditor()} to indicate you will return a
7433     * non-null InputConnection.
7434     *
7435     * @param outAttrs Fill in with attribute information about the connection.
7436     */
7437    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7438        return null;
7439    }
7440
7441    /**
7442     * Called by the {@link android.view.inputmethod.InputMethodManager}
7443     * when a view who is not the current
7444     * input connection target is trying to make a call on the manager.  The
7445     * default implementation returns false; you can override this to return
7446     * true for certain views if you are performing InputConnection proxying
7447     * to them.
7448     * @param view The View that is making the InputMethodManager call.
7449     * @return Return true to allow the call, false to reject.
7450     */
7451    public boolean checkInputConnectionProxy(View view) {
7452        return false;
7453    }
7454
7455    /**
7456     * Show the context menu for this view. It is not safe to hold on to the
7457     * menu after returning from this method.
7458     *
7459     * You should normally not overload this method. Overload
7460     * {@link #onCreateContextMenu(ContextMenu)} or define an
7461     * {@link OnCreateContextMenuListener} to add items to the context menu.
7462     *
7463     * @param menu The context menu to populate
7464     */
7465    public void createContextMenu(ContextMenu menu) {
7466        ContextMenuInfo menuInfo = getContextMenuInfo();
7467
7468        // Sets the current menu info so all items added to menu will have
7469        // my extra info set.
7470        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7471
7472        onCreateContextMenu(menu);
7473        ListenerInfo li = mListenerInfo;
7474        if (li != null && li.mOnCreateContextMenuListener != null) {
7475            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7476        }
7477
7478        // Clear the extra information so subsequent items that aren't mine don't
7479        // have my extra info.
7480        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7481
7482        if (mParent != null) {
7483            mParent.createContextMenu(menu);
7484        }
7485    }
7486
7487    /**
7488     * Views should implement this if they have extra information to associate
7489     * with the context menu. The return result is supplied as a parameter to
7490     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7491     * callback.
7492     *
7493     * @return Extra information about the item for which the context menu
7494     *         should be shown. This information will vary across different
7495     *         subclasses of View.
7496     */
7497    protected ContextMenuInfo getContextMenuInfo() {
7498        return null;
7499    }
7500
7501    /**
7502     * Views should implement this if the view itself is going to add items to
7503     * the context menu.
7504     *
7505     * @param menu the context menu to populate
7506     */
7507    protected void onCreateContextMenu(ContextMenu menu) {
7508    }
7509
7510    /**
7511     * Implement this method to handle trackball motion events.  The
7512     * <em>relative</em> movement of the trackball since the last event
7513     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7514     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7515     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7516     * they will often be fractional values, representing the more fine-grained
7517     * movement information available from a trackball).
7518     *
7519     * @param event The motion event.
7520     * @return True if the event was handled, false otherwise.
7521     */
7522    public boolean onTrackballEvent(MotionEvent event) {
7523        return false;
7524    }
7525
7526    /**
7527     * Implement this method to handle generic motion events.
7528     * <p>
7529     * Generic motion events describe joystick movements, mouse hovers, track pad
7530     * touches, scroll wheel movements and other input events.  The
7531     * {@link MotionEvent#getSource() source} of the motion event specifies
7532     * the class of input that was received.  Implementations of this method
7533     * must examine the bits in the source before processing the event.
7534     * The following code example shows how this is done.
7535     * </p><p>
7536     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7537     * are delivered to the view under the pointer.  All other generic motion events are
7538     * delivered to the focused view.
7539     * </p>
7540     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7541     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7542     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7543     *             // process the joystick movement...
7544     *             return true;
7545     *         }
7546     *     }
7547     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7548     *         switch (event.getAction()) {
7549     *             case MotionEvent.ACTION_HOVER_MOVE:
7550     *                 // process the mouse hover movement...
7551     *                 return true;
7552     *             case MotionEvent.ACTION_SCROLL:
7553     *                 // process the scroll wheel movement...
7554     *                 return true;
7555     *         }
7556     *     }
7557     *     return super.onGenericMotionEvent(event);
7558     * }</pre>
7559     *
7560     * @param event The generic motion event being processed.
7561     * @return True if the event was handled, false otherwise.
7562     */
7563    public boolean onGenericMotionEvent(MotionEvent event) {
7564        return false;
7565    }
7566
7567    /**
7568     * Implement this method to handle hover events.
7569     * <p>
7570     * This method is called whenever a pointer is hovering into, over, or out of the
7571     * bounds of a view and the view is not currently being touched.
7572     * Hover events are represented as pointer events with action
7573     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7574     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7575     * </p>
7576     * <ul>
7577     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7578     * when the pointer enters the bounds of the view.</li>
7579     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7580     * when the pointer has already entered the bounds of the view and has moved.</li>
7581     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7582     * when the pointer has exited the bounds of the view or when the pointer is
7583     * about to go down due to a button click, tap, or similar user action that
7584     * causes the view to be touched.</li>
7585     * </ul>
7586     * <p>
7587     * The view should implement this method to return true to indicate that it is
7588     * handling the hover event, such as by changing its drawable state.
7589     * </p><p>
7590     * The default implementation calls {@link #setHovered} to update the hovered state
7591     * of the view when a hover enter or hover exit event is received, if the view
7592     * is enabled and is clickable.  The default implementation also sends hover
7593     * accessibility events.
7594     * </p>
7595     *
7596     * @param event The motion event that describes the hover.
7597     * @return True if the view handled the hover event.
7598     *
7599     * @see #isHovered
7600     * @see #setHovered
7601     * @see #onHoverChanged
7602     */
7603    public boolean onHoverEvent(MotionEvent event) {
7604        // The root view may receive hover (or touch) events that are outside the bounds of
7605        // the window.  This code ensures that we only send accessibility events for
7606        // hovers that are actually within the bounds of the root view.
7607        final int action = event.getActionMasked();
7608        if (!mSendingHoverAccessibilityEvents) {
7609            if ((action == MotionEvent.ACTION_HOVER_ENTER
7610                    || action == MotionEvent.ACTION_HOVER_MOVE)
7611                    && !hasHoveredChild()
7612                    && pointInView(event.getX(), event.getY())) {
7613                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7614                mSendingHoverAccessibilityEvents = true;
7615                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7616            }
7617        } else {
7618            if (action == MotionEvent.ACTION_HOVER_EXIT
7619                    || (action == MotionEvent.ACTION_MOVE
7620                            && !pointInView(event.getX(), event.getY()))) {
7621                mSendingHoverAccessibilityEvents = false;
7622                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7623                // If the window does not have input focus we take away accessibility
7624                // focus as soon as the user stop hovering over the view.
7625                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7626                    getViewRootImpl().setAccessibilityFocusedHost(null);
7627                }
7628            }
7629        }
7630
7631        if (isHoverable()) {
7632            switch (action) {
7633                case MotionEvent.ACTION_HOVER_ENTER:
7634                    setHovered(true);
7635                    break;
7636                case MotionEvent.ACTION_HOVER_EXIT:
7637                    setHovered(false);
7638                    break;
7639            }
7640
7641            // Dispatch the event to onGenericMotionEvent before returning true.
7642            // This is to provide compatibility with existing applications that
7643            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7644            // break because of the new default handling for hoverable views
7645            // in onHoverEvent.
7646            // Note that onGenericMotionEvent will be called by default when
7647            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7648            dispatchGenericMotionEventInternal(event);
7649            return true;
7650        }
7651
7652        return false;
7653    }
7654
7655    /**
7656     * Returns true if the view should handle {@link #onHoverEvent}
7657     * by calling {@link #setHovered} to change its hovered state.
7658     *
7659     * @return True if the view is hoverable.
7660     */
7661    private boolean isHoverable() {
7662        final int viewFlags = mViewFlags;
7663        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7664            return false;
7665        }
7666
7667        return (viewFlags & CLICKABLE) == CLICKABLE
7668                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7669    }
7670
7671    /**
7672     * Returns true if the view is currently hovered.
7673     *
7674     * @return True if the view is currently hovered.
7675     *
7676     * @see #setHovered
7677     * @see #onHoverChanged
7678     */
7679    @ViewDebug.ExportedProperty
7680    public boolean isHovered() {
7681        return (mPrivateFlags & HOVERED) != 0;
7682    }
7683
7684    /**
7685     * Sets whether the view is currently hovered.
7686     * <p>
7687     * Calling this method also changes the drawable state of the view.  This
7688     * enables the view to react to hover by using different drawable resources
7689     * to change its appearance.
7690     * </p><p>
7691     * The {@link #onHoverChanged} method is called when the hovered state changes.
7692     * </p>
7693     *
7694     * @param hovered True if the view is hovered.
7695     *
7696     * @see #isHovered
7697     * @see #onHoverChanged
7698     */
7699    public void setHovered(boolean hovered) {
7700        if (hovered) {
7701            if ((mPrivateFlags & HOVERED) == 0) {
7702                mPrivateFlags |= HOVERED;
7703                refreshDrawableState();
7704                onHoverChanged(true);
7705            }
7706        } else {
7707            if ((mPrivateFlags & HOVERED) != 0) {
7708                mPrivateFlags &= ~HOVERED;
7709                refreshDrawableState();
7710                onHoverChanged(false);
7711            }
7712        }
7713    }
7714
7715    /**
7716     * Implement this method to handle hover state changes.
7717     * <p>
7718     * This method is called whenever the hover state changes as a result of a
7719     * call to {@link #setHovered}.
7720     * </p>
7721     *
7722     * @param hovered The current hover state, as returned by {@link #isHovered}.
7723     *
7724     * @see #isHovered
7725     * @see #setHovered
7726     */
7727    public void onHoverChanged(boolean hovered) {
7728    }
7729
7730    /**
7731     * Implement this method to handle touch screen motion events.
7732     *
7733     * @param event The motion event.
7734     * @return True if the event was handled, false otherwise.
7735     */
7736    public boolean onTouchEvent(MotionEvent event) {
7737        final int viewFlags = mViewFlags;
7738
7739        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7740            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7741                setPressed(false);
7742            }
7743            // A disabled view that is clickable still consumes the touch
7744            // events, it just doesn't respond to them.
7745            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7746                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7747        }
7748
7749        if (mTouchDelegate != null) {
7750            if (mTouchDelegate.onTouchEvent(event)) {
7751                return true;
7752            }
7753        }
7754
7755        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7756                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7757            switch (event.getAction()) {
7758                case MotionEvent.ACTION_UP:
7759                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7760                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7761                        // take focus if we don't have it already and we should in
7762                        // touch mode.
7763                        boolean focusTaken = false;
7764                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7765                            focusTaken = requestFocus();
7766                        }
7767
7768                        if (prepressed) {
7769                            // The button is being released before we actually
7770                            // showed it as pressed.  Make it show the pressed
7771                            // state now (before scheduling the click) to ensure
7772                            // the user sees it.
7773                            setPressed(true);
7774                       }
7775
7776                        if (!mHasPerformedLongPress) {
7777                            // This is a tap, so remove the longpress check
7778                            removeLongPressCallback();
7779
7780                            // Only perform take click actions if we were in the pressed state
7781                            if (!focusTaken) {
7782                                // Use a Runnable and post this rather than calling
7783                                // performClick directly. This lets other visual state
7784                                // of the view update before click actions start.
7785                                if (mPerformClick == null) {
7786                                    mPerformClick = new PerformClick();
7787                                }
7788                                if (!post(mPerformClick)) {
7789                                    performClick();
7790                                }
7791                            }
7792                        }
7793
7794                        if (mUnsetPressedState == null) {
7795                            mUnsetPressedState = new UnsetPressedState();
7796                        }
7797
7798                        if (prepressed) {
7799                            postDelayed(mUnsetPressedState,
7800                                    ViewConfiguration.getPressedStateDuration());
7801                        } else if (!post(mUnsetPressedState)) {
7802                            // If the post failed, unpress right now
7803                            mUnsetPressedState.run();
7804                        }
7805                        removeTapCallback();
7806                    }
7807                    break;
7808
7809                case MotionEvent.ACTION_DOWN:
7810                    mHasPerformedLongPress = false;
7811
7812                    if (performButtonActionOnTouchDown(event)) {
7813                        break;
7814                    }
7815
7816                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7817                    boolean isInScrollingContainer = isInScrollingContainer();
7818
7819                    // For views inside a scrolling container, delay the pressed feedback for
7820                    // a short period in case this is a scroll.
7821                    if (isInScrollingContainer) {
7822                        mPrivateFlags |= PREPRESSED;
7823                        if (mPendingCheckForTap == null) {
7824                            mPendingCheckForTap = new CheckForTap();
7825                        }
7826                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7827                    } else {
7828                        // Not inside a scrolling container, so show the feedback right away
7829                        setPressed(true);
7830                        checkForLongClick(0);
7831                    }
7832                    break;
7833
7834                case MotionEvent.ACTION_CANCEL:
7835                    setPressed(false);
7836                    removeTapCallback();
7837                    break;
7838
7839                case MotionEvent.ACTION_MOVE:
7840                    final int x = (int) event.getX();
7841                    final int y = (int) event.getY();
7842
7843                    // Be lenient about moving outside of buttons
7844                    if (!pointInView(x, y, mTouchSlop)) {
7845                        // Outside button
7846                        removeTapCallback();
7847                        if ((mPrivateFlags & PRESSED) != 0) {
7848                            // Remove any future long press/tap checks
7849                            removeLongPressCallback();
7850
7851                            setPressed(false);
7852                        }
7853                    }
7854                    break;
7855            }
7856            return true;
7857        }
7858
7859        return false;
7860    }
7861
7862    /**
7863     * @hide
7864     */
7865    public boolean isInScrollingContainer() {
7866        ViewParent p = getParent();
7867        while (p != null && p instanceof ViewGroup) {
7868            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7869                return true;
7870            }
7871            p = p.getParent();
7872        }
7873        return false;
7874    }
7875
7876    /**
7877     * Remove the longpress detection timer.
7878     */
7879    private void removeLongPressCallback() {
7880        if (mPendingCheckForLongPress != null) {
7881          removeCallbacks(mPendingCheckForLongPress);
7882        }
7883    }
7884
7885    /**
7886     * Remove the pending click action
7887     */
7888    private void removePerformClickCallback() {
7889        if (mPerformClick != null) {
7890            removeCallbacks(mPerformClick);
7891        }
7892    }
7893
7894    /**
7895     * Remove the prepress detection timer.
7896     */
7897    private void removeUnsetPressCallback() {
7898        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7899            setPressed(false);
7900            removeCallbacks(mUnsetPressedState);
7901        }
7902    }
7903
7904    /**
7905     * Remove the tap detection timer.
7906     */
7907    private void removeTapCallback() {
7908        if (mPendingCheckForTap != null) {
7909            mPrivateFlags &= ~PREPRESSED;
7910            removeCallbacks(mPendingCheckForTap);
7911        }
7912    }
7913
7914    /**
7915     * Cancels a pending long press.  Your subclass can use this if you
7916     * want the context menu to come up if the user presses and holds
7917     * at the same place, but you don't want it to come up if they press
7918     * and then move around enough to cause scrolling.
7919     */
7920    public void cancelLongPress() {
7921        removeLongPressCallback();
7922
7923        /*
7924         * The prepressed state handled by the tap callback is a display
7925         * construct, but the tap callback will post a long press callback
7926         * less its own timeout. Remove it here.
7927         */
7928        removeTapCallback();
7929    }
7930
7931    /**
7932     * Remove the pending callback for sending a
7933     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7934     */
7935    private void removeSendViewScrolledAccessibilityEventCallback() {
7936        if (mSendViewScrolledAccessibilityEvent != null) {
7937            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7938        }
7939    }
7940
7941    /**
7942     * Sets the TouchDelegate for this View.
7943     */
7944    public void setTouchDelegate(TouchDelegate delegate) {
7945        mTouchDelegate = delegate;
7946    }
7947
7948    /**
7949     * Gets the TouchDelegate for this View.
7950     */
7951    public TouchDelegate getTouchDelegate() {
7952        return mTouchDelegate;
7953    }
7954
7955    /**
7956     * Set flags controlling behavior of this view.
7957     *
7958     * @param flags Constant indicating the value which should be set
7959     * @param mask Constant indicating the bit range that should be changed
7960     */
7961    void setFlags(int flags, int mask) {
7962        int old = mViewFlags;
7963        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7964
7965        int changed = mViewFlags ^ old;
7966        if (changed == 0) {
7967            return;
7968        }
7969        int privateFlags = mPrivateFlags;
7970
7971        /* Check if the FOCUSABLE bit has changed */
7972        if (((changed & FOCUSABLE_MASK) != 0) &&
7973                ((privateFlags & HAS_BOUNDS) !=0)) {
7974            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7975                    && ((privateFlags & FOCUSED) != 0)) {
7976                /* Give up focus if we are no longer focusable */
7977                clearFocus();
7978            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7979                    && ((privateFlags & FOCUSED) == 0)) {
7980                /*
7981                 * Tell the view system that we are now available to take focus
7982                 * if no one else already has it.
7983                 */
7984                if (mParent != null) mParent.focusableViewAvailable(this);
7985            }
7986            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7987                notifyAccessibilityStateChanged();
7988            }
7989        }
7990
7991        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7992            if ((changed & VISIBILITY_MASK) != 0) {
7993                /*
7994                 * If this view is becoming visible, invalidate it in case it changed while
7995                 * it was not visible. Marking it drawn ensures that the invalidation will
7996                 * go through.
7997                 */
7998                mPrivateFlags |= DRAWN;
7999                invalidate(true);
8000
8001                needGlobalAttributesUpdate(true);
8002
8003                // a view becoming visible is worth notifying the parent
8004                // about in case nothing has focus.  even if this specific view
8005                // isn't focusable, it may contain something that is, so let
8006                // the root view try to give this focus if nothing else does.
8007                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8008                    mParent.focusableViewAvailable(this);
8009                }
8010            }
8011        }
8012
8013        /* Check if the GONE bit has changed */
8014        if ((changed & GONE) != 0) {
8015            needGlobalAttributesUpdate(false);
8016            requestLayout();
8017
8018            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8019                if (hasFocus()) clearFocus();
8020                clearAccessibilityFocus();
8021                destroyDrawingCache();
8022                if (mParent instanceof View) {
8023                    // GONE views noop invalidation, so invalidate the parent
8024                    ((View) mParent).invalidate(true);
8025                }
8026                // Mark the view drawn to ensure that it gets invalidated properly the next
8027                // time it is visible and gets invalidated
8028                mPrivateFlags |= DRAWN;
8029            }
8030            if (mAttachInfo != null) {
8031                mAttachInfo.mViewVisibilityChanged = true;
8032            }
8033        }
8034
8035        /* Check if the VISIBLE bit has changed */
8036        if ((changed & INVISIBLE) != 0) {
8037            needGlobalAttributesUpdate(false);
8038            /*
8039             * If this view is becoming invisible, set the DRAWN flag so that
8040             * the next invalidate() will not be skipped.
8041             */
8042            mPrivateFlags |= DRAWN;
8043
8044            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8045                // root view becoming invisible shouldn't clear focus and accessibility focus
8046                if (getRootView() != this) {
8047                    clearFocus();
8048                    clearAccessibilityFocus();
8049                }
8050            }
8051            if (mAttachInfo != null) {
8052                mAttachInfo.mViewVisibilityChanged = true;
8053            }
8054        }
8055
8056        if ((changed & VISIBILITY_MASK) != 0) {
8057            if (mParent instanceof ViewGroup) {
8058                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8059                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8060                ((View) mParent).invalidate(true);
8061            } else if (mParent != null) {
8062                mParent.invalidateChild(this, null);
8063            }
8064            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8065        }
8066
8067        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8068            destroyDrawingCache();
8069        }
8070
8071        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8072            destroyDrawingCache();
8073            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8074            invalidateParentCaches();
8075        }
8076
8077        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8078            destroyDrawingCache();
8079            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8080        }
8081
8082        if ((changed & DRAW_MASK) != 0) {
8083            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8084                if (mBackground != null) {
8085                    mPrivateFlags &= ~SKIP_DRAW;
8086                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8087                } else {
8088                    mPrivateFlags |= SKIP_DRAW;
8089                }
8090            } else {
8091                mPrivateFlags &= ~SKIP_DRAW;
8092            }
8093            requestLayout();
8094            invalidate(true);
8095        }
8096
8097        if ((changed & KEEP_SCREEN_ON) != 0) {
8098            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8099                mParent.recomputeViewAttributes(this);
8100            }
8101        }
8102
8103        if (AccessibilityManager.getInstance(mContext).isEnabled()
8104                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8105                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8106            notifyAccessibilityStateChanged();
8107        }
8108    }
8109
8110    /**
8111     * Change the view's z order in the tree, so it's on top of other sibling
8112     * views
8113     */
8114    public void bringToFront() {
8115        if (mParent != null) {
8116            mParent.bringChildToFront(this);
8117        }
8118    }
8119
8120    /**
8121     * This is called in response to an internal scroll in this view (i.e., the
8122     * view scrolled its own contents). This is typically as a result of
8123     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8124     * called.
8125     *
8126     * @param l Current horizontal scroll origin.
8127     * @param t Current vertical scroll origin.
8128     * @param oldl Previous horizontal scroll origin.
8129     * @param oldt Previous vertical scroll origin.
8130     */
8131    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8132        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8133            postSendViewScrolledAccessibilityEventCallback();
8134        }
8135
8136        mBackgroundSizeChanged = true;
8137
8138        final AttachInfo ai = mAttachInfo;
8139        if (ai != null) {
8140            ai.mViewScrollChanged = true;
8141        }
8142    }
8143
8144    /**
8145     * Interface definition for a callback to be invoked when the layout bounds of a view
8146     * changes due to layout processing.
8147     */
8148    public interface OnLayoutChangeListener {
8149        /**
8150         * Called when the focus state of a view has changed.
8151         *
8152         * @param v The view whose state has changed.
8153         * @param left The new value of the view's left property.
8154         * @param top The new value of the view's top property.
8155         * @param right The new value of the view's right property.
8156         * @param bottom The new value of the view's bottom property.
8157         * @param oldLeft The previous value of the view's left property.
8158         * @param oldTop The previous value of the view's top property.
8159         * @param oldRight The previous value of the view's right property.
8160         * @param oldBottom The previous value of the view's bottom property.
8161         */
8162        void onLayoutChange(View v, int left, int top, int right, int bottom,
8163            int oldLeft, int oldTop, int oldRight, int oldBottom);
8164    }
8165
8166    /**
8167     * This is called during layout when the size of this view has changed. If
8168     * you were just added to the view hierarchy, you're called with the old
8169     * values of 0.
8170     *
8171     * @param w Current width of this view.
8172     * @param h Current height of this view.
8173     * @param oldw Old width of this view.
8174     * @param oldh Old height of this view.
8175     */
8176    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8177    }
8178
8179    /**
8180     * Called by draw to draw the child views. This may be overridden
8181     * by derived classes to gain control just before its children are drawn
8182     * (but after its own view has been drawn).
8183     * @param canvas the canvas on which to draw the view
8184     */
8185    protected void dispatchDraw(Canvas canvas) {
8186
8187    }
8188
8189    /**
8190     * Gets the parent of this view. Note that the parent is a
8191     * ViewParent and not necessarily a View.
8192     *
8193     * @return Parent of this view.
8194     */
8195    public final ViewParent getParent() {
8196        return mParent;
8197    }
8198
8199    /**
8200     * Set the horizontal scrolled position of your view. This will cause a call to
8201     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8202     * invalidated.
8203     * @param value the x position to scroll to
8204     */
8205    public void setScrollX(int value) {
8206        scrollTo(value, mScrollY);
8207    }
8208
8209    /**
8210     * Set the vertical scrolled position of your view. This will cause a call to
8211     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8212     * invalidated.
8213     * @param value the y position to scroll to
8214     */
8215    public void setScrollY(int value) {
8216        scrollTo(mScrollX, value);
8217    }
8218
8219    /**
8220     * Return the scrolled left position of this view. This is the left edge of
8221     * the displayed part of your view. You do not need to draw any pixels
8222     * farther left, since those are outside of the frame of your view on
8223     * screen.
8224     *
8225     * @return The left edge of the displayed part of your view, in pixels.
8226     */
8227    public final int getScrollX() {
8228        return mScrollX;
8229    }
8230
8231    /**
8232     * Return the scrolled top position of this view. This is the top edge of
8233     * the displayed part of your view. You do not need to draw any pixels above
8234     * it, since those are outside of the frame of your view on screen.
8235     *
8236     * @return The top edge of the displayed part of your view, in pixels.
8237     */
8238    public final int getScrollY() {
8239        return mScrollY;
8240    }
8241
8242    /**
8243     * Return the width of the your view.
8244     *
8245     * @return The width of your view, in pixels.
8246     */
8247    @ViewDebug.ExportedProperty(category = "layout")
8248    public final int getWidth() {
8249        return mRight - mLeft;
8250    }
8251
8252    /**
8253     * Return the height of your view.
8254     *
8255     * @return The height of your view, in pixels.
8256     */
8257    @ViewDebug.ExportedProperty(category = "layout")
8258    public final int getHeight() {
8259        return mBottom - mTop;
8260    }
8261
8262    /**
8263     * Return the visible drawing bounds of your view. Fills in the output
8264     * rectangle with the values from getScrollX(), getScrollY(),
8265     * getWidth(), and getHeight().
8266     *
8267     * @param outRect The (scrolled) drawing bounds of the view.
8268     */
8269    public void getDrawingRect(Rect outRect) {
8270        outRect.left = mScrollX;
8271        outRect.top = mScrollY;
8272        outRect.right = mScrollX + (mRight - mLeft);
8273        outRect.bottom = mScrollY + (mBottom - mTop);
8274    }
8275
8276    /**
8277     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8278     * raw width component (that is the result is masked by
8279     * {@link #MEASURED_SIZE_MASK}).
8280     *
8281     * @return The raw measured width of this view.
8282     */
8283    public final int getMeasuredWidth() {
8284        return mMeasuredWidth & MEASURED_SIZE_MASK;
8285    }
8286
8287    /**
8288     * Return the full width measurement information for this view as computed
8289     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8290     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8291     * This should be used during measurement and layout calculations only. Use
8292     * {@link #getWidth()} to see how wide a view is after layout.
8293     *
8294     * @return The measured width of this view as a bit mask.
8295     */
8296    public final int getMeasuredWidthAndState() {
8297        return mMeasuredWidth;
8298    }
8299
8300    /**
8301     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8302     * raw width component (that is the result is masked by
8303     * {@link #MEASURED_SIZE_MASK}).
8304     *
8305     * @return The raw measured height of this view.
8306     */
8307    public final int getMeasuredHeight() {
8308        return mMeasuredHeight & MEASURED_SIZE_MASK;
8309    }
8310
8311    /**
8312     * Return the full height measurement information for this view as computed
8313     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8314     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8315     * This should be used during measurement and layout calculations only. Use
8316     * {@link #getHeight()} to see how wide a view is after layout.
8317     *
8318     * @return The measured width of this view as a bit mask.
8319     */
8320    public final int getMeasuredHeightAndState() {
8321        return mMeasuredHeight;
8322    }
8323
8324    /**
8325     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8326     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8327     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8328     * and the height component is at the shifted bits
8329     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8330     */
8331    public final int getMeasuredState() {
8332        return (mMeasuredWidth&MEASURED_STATE_MASK)
8333                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8334                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8335    }
8336
8337    /**
8338     * The transform matrix of this view, which is calculated based on the current
8339     * roation, scale, and pivot properties.
8340     *
8341     * @see #getRotation()
8342     * @see #getScaleX()
8343     * @see #getScaleY()
8344     * @see #getPivotX()
8345     * @see #getPivotY()
8346     * @return The current transform matrix for the view
8347     */
8348    public Matrix getMatrix() {
8349        if (mTransformationInfo != null) {
8350            updateMatrix();
8351            return mTransformationInfo.mMatrix;
8352        }
8353        return Matrix.IDENTITY_MATRIX;
8354    }
8355
8356    /**
8357     * Utility function to determine if the value is far enough away from zero to be
8358     * considered non-zero.
8359     * @param value A floating point value to check for zero-ness
8360     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8361     */
8362    private static boolean nonzero(float value) {
8363        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8364    }
8365
8366    /**
8367     * Returns true if the transform matrix is the identity matrix.
8368     * Recomputes the matrix if necessary.
8369     *
8370     * @return True if the transform matrix is the identity matrix, false otherwise.
8371     */
8372    final boolean hasIdentityMatrix() {
8373        if (mTransformationInfo != null) {
8374            updateMatrix();
8375            return mTransformationInfo.mMatrixIsIdentity;
8376        }
8377        return true;
8378    }
8379
8380    void ensureTransformationInfo() {
8381        if (mTransformationInfo == null) {
8382            mTransformationInfo = new TransformationInfo();
8383        }
8384    }
8385
8386    /**
8387     * Recomputes the transform matrix if necessary.
8388     */
8389    private void updateMatrix() {
8390        final TransformationInfo info = mTransformationInfo;
8391        if (info == null) {
8392            return;
8393        }
8394        if (info.mMatrixDirty) {
8395            // transform-related properties have changed since the last time someone
8396            // asked for the matrix; recalculate it with the current values
8397
8398            // Figure out if we need to update the pivot point
8399            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8400                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8401                    info.mPrevWidth = mRight - mLeft;
8402                    info.mPrevHeight = mBottom - mTop;
8403                    info.mPivotX = info.mPrevWidth / 2f;
8404                    info.mPivotY = info.mPrevHeight / 2f;
8405                }
8406            }
8407            info.mMatrix.reset();
8408            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8409                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8410                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8411                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8412            } else {
8413                if (info.mCamera == null) {
8414                    info.mCamera = new Camera();
8415                    info.matrix3D = new Matrix();
8416                }
8417                info.mCamera.save();
8418                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8419                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8420                info.mCamera.getMatrix(info.matrix3D);
8421                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8422                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8423                        info.mPivotY + info.mTranslationY);
8424                info.mMatrix.postConcat(info.matrix3D);
8425                info.mCamera.restore();
8426            }
8427            info.mMatrixDirty = false;
8428            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8429            info.mInverseMatrixDirty = true;
8430        }
8431    }
8432
8433    /**
8434     * Utility method to retrieve the inverse of the current mMatrix property.
8435     * We cache the matrix to avoid recalculating it when transform properties
8436     * have not changed.
8437     *
8438     * @return The inverse of the current matrix of this view.
8439     */
8440    final Matrix getInverseMatrix() {
8441        final TransformationInfo info = mTransformationInfo;
8442        if (info != null) {
8443            updateMatrix();
8444            if (info.mInverseMatrixDirty) {
8445                if (info.mInverseMatrix == null) {
8446                    info.mInverseMatrix = new Matrix();
8447                }
8448                info.mMatrix.invert(info.mInverseMatrix);
8449                info.mInverseMatrixDirty = false;
8450            }
8451            return info.mInverseMatrix;
8452        }
8453        return Matrix.IDENTITY_MATRIX;
8454    }
8455
8456    /**
8457     * Gets the distance along the Z axis from the camera to this view.
8458     *
8459     * @see #setCameraDistance(float)
8460     *
8461     * @return The distance along the Z axis.
8462     */
8463    public float getCameraDistance() {
8464        ensureTransformationInfo();
8465        final float dpi = mResources.getDisplayMetrics().densityDpi;
8466        final TransformationInfo info = mTransformationInfo;
8467        if (info.mCamera == null) {
8468            info.mCamera = new Camera();
8469            info.matrix3D = new Matrix();
8470        }
8471        return -(info.mCamera.getLocationZ() * dpi);
8472    }
8473
8474    /**
8475     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8476     * views are drawn) from the camera to this view. The camera's distance
8477     * affects 3D transformations, for instance rotations around the X and Y
8478     * axis. If the rotationX or rotationY properties are changed and this view is
8479     * large (more than half the size of the screen), it is recommended to always
8480     * use a camera distance that's greater than the height (X axis rotation) or
8481     * the width (Y axis rotation) of this view.</p>
8482     *
8483     * <p>The distance of the camera from the view plane can have an affect on the
8484     * perspective distortion of the view when it is rotated around the x or y axis.
8485     * For example, a large distance will result in a large viewing angle, and there
8486     * will not be much perspective distortion of the view as it rotates. A short
8487     * distance may cause much more perspective distortion upon rotation, and can
8488     * also result in some drawing artifacts if the rotated view ends up partially
8489     * behind the camera (which is why the recommendation is to use a distance at
8490     * least as far as the size of the view, if the view is to be rotated.)</p>
8491     *
8492     * <p>The distance is expressed in "depth pixels." The default distance depends
8493     * on the screen density. For instance, on a medium density display, the
8494     * default distance is 1280. On a high density display, the default distance
8495     * is 1920.</p>
8496     *
8497     * <p>If you want to specify a distance that leads to visually consistent
8498     * results across various densities, use the following formula:</p>
8499     * <pre>
8500     * float scale = context.getResources().getDisplayMetrics().density;
8501     * view.setCameraDistance(distance * scale);
8502     * </pre>
8503     *
8504     * <p>The density scale factor of a high density display is 1.5,
8505     * and 1920 = 1280 * 1.5.</p>
8506     *
8507     * @param distance The distance in "depth pixels", if negative the opposite
8508     *        value is used
8509     *
8510     * @see #setRotationX(float)
8511     * @see #setRotationY(float)
8512     */
8513    public void setCameraDistance(float distance) {
8514        invalidateViewProperty(true, false);
8515
8516        ensureTransformationInfo();
8517        final float dpi = mResources.getDisplayMetrics().densityDpi;
8518        final TransformationInfo info = mTransformationInfo;
8519        if (info.mCamera == null) {
8520            info.mCamera = new Camera();
8521            info.matrix3D = new Matrix();
8522        }
8523
8524        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8525        info.mMatrixDirty = true;
8526
8527        invalidateViewProperty(false, false);
8528        if (mDisplayList != null) {
8529            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8530        }
8531    }
8532
8533    /**
8534     * The degrees that the view is rotated around the pivot point.
8535     *
8536     * @see #setRotation(float)
8537     * @see #getPivotX()
8538     * @see #getPivotY()
8539     *
8540     * @return The degrees of rotation.
8541     */
8542    @ViewDebug.ExportedProperty(category = "drawing")
8543    public float getRotation() {
8544        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8545    }
8546
8547    /**
8548     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8549     * result in clockwise rotation.
8550     *
8551     * @param rotation The degrees of rotation.
8552     *
8553     * @see #getRotation()
8554     * @see #getPivotX()
8555     * @see #getPivotY()
8556     * @see #setRotationX(float)
8557     * @see #setRotationY(float)
8558     *
8559     * @attr ref android.R.styleable#View_rotation
8560     */
8561    public void setRotation(float rotation) {
8562        ensureTransformationInfo();
8563        final TransformationInfo info = mTransformationInfo;
8564        if (info.mRotation != rotation) {
8565            // Double-invalidation is necessary to capture view's old and new areas
8566            invalidateViewProperty(true, false);
8567            info.mRotation = rotation;
8568            info.mMatrixDirty = true;
8569            invalidateViewProperty(false, true);
8570            if (mDisplayList != null) {
8571                mDisplayList.setRotation(rotation);
8572            }
8573        }
8574    }
8575
8576    /**
8577     * The degrees that the view is rotated around the vertical axis through the pivot point.
8578     *
8579     * @see #getPivotX()
8580     * @see #getPivotY()
8581     * @see #setRotationY(float)
8582     *
8583     * @return The degrees of Y rotation.
8584     */
8585    @ViewDebug.ExportedProperty(category = "drawing")
8586    public float getRotationY() {
8587        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8588    }
8589
8590    /**
8591     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8592     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8593     * down the y axis.
8594     *
8595     * When rotating large views, it is recommended to adjust the camera distance
8596     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8597     *
8598     * @param rotationY The degrees of Y rotation.
8599     *
8600     * @see #getRotationY()
8601     * @see #getPivotX()
8602     * @see #getPivotY()
8603     * @see #setRotation(float)
8604     * @see #setRotationX(float)
8605     * @see #setCameraDistance(float)
8606     *
8607     * @attr ref android.R.styleable#View_rotationY
8608     */
8609    public void setRotationY(float rotationY) {
8610        ensureTransformationInfo();
8611        final TransformationInfo info = mTransformationInfo;
8612        if (info.mRotationY != rotationY) {
8613            invalidateViewProperty(true, false);
8614            info.mRotationY = rotationY;
8615            info.mMatrixDirty = true;
8616            invalidateViewProperty(false, true);
8617            if (mDisplayList != null) {
8618                mDisplayList.setRotationY(rotationY);
8619            }
8620        }
8621    }
8622
8623    /**
8624     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8625     *
8626     * @see #getPivotX()
8627     * @see #getPivotY()
8628     * @see #setRotationX(float)
8629     *
8630     * @return The degrees of X rotation.
8631     */
8632    @ViewDebug.ExportedProperty(category = "drawing")
8633    public float getRotationX() {
8634        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8635    }
8636
8637    /**
8638     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8639     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8640     * x axis.
8641     *
8642     * When rotating large views, it is recommended to adjust the camera distance
8643     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8644     *
8645     * @param rotationX The degrees of X rotation.
8646     *
8647     * @see #getRotationX()
8648     * @see #getPivotX()
8649     * @see #getPivotY()
8650     * @see #setRotation(float)
8651     * @see #setRotationY(float)
8652     * @see #setCameraDistance(float)
8653     *
8654     * @attr ref android.R.styleable#View_rotationX
8655     */
8656    public void setRotationX(float rotationX) {
8657        ensureTransformationInfo();
8658        final TransformationInfo info = mTransformationInfo;
8659        if (info.mRotationX != rotationX) {
8660            invalidateViewProperty(true, false);
8661            info.mRotationX = rotationX;
8662            info.mMatrixDirty = true;
8663            invalidateViewProperty(false, true);
8664            if (mDisplayList != null) {
8665                mDisplayList.setRotationX(rotationX);
8666            }
8667        }
8668    }
8669
8670    /**
8671     * The amount that the view is scaled in x around the pivot point, as a proportion of
8672     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8673     *
8674     * <p>By default, this is 1.0f.
8675     *
8676     * @see #getPivotX()
8677     * @see #getPivotY()
8678     * @return The scaling factor.
8679     */
8680    @ViewDebug.ExportedProperty(category = "drawing")
8681    public float getScaleX() {
8682        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8683    }
8684
8685    /**
8686     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8687     * the view's unscaled width. A value of 1 means that no scaling is applied.
8688     *
8689     * @param scaleX The scaling factor.
8690     * @see #getPivotX()
8691     * @see #getPivotY()
8692     *
8693     * @attr ref android.R.styleable#View_scaleX
8694     */
8695    public void setScaleX(float scaleX) {
8696        ensureTransformationInfo();
8697        final TransformationInfo info = mTransformationInfo;
8698        if (info.mScaleX != scaleX) {
8699            invalidateViewProperty(true, false);
8700            info.mScaleX = scaleX;
8701            info.mMatrixDirty = true;
8702            invalidateViewProperty(false, true);
8703            if (mDisplayList != null) {
8704                mDisplayList.setScaleX(scaleX);
8705            }
8706        }
8707    }
8708
8709    /**
8710     * The amount that the view is scaled in y around the pivot point, as a proportion of
8711     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8712     *
8713     * <p>By default, this is 1.0f.
8714     *
8715     * @see #getPivotX()
8716     * @see #getPivotY()
8717     * @return The scaling factor.
8718     */
8719    @ViewDebug.ExportedProperty(category = "drawing")
8720    public float getScaleY() {
8721        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8722    }
8723
8724    /**
8725     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8726     * the view's unscaled width. A value of 1 means that no scaling is applied.
8727     *
8728     * @param scaleY The scaling factor.
8729     * @see #getPivotX()
8730     * @see #getPivotY()
8731     *
8732     * @attr ref android.R.styleable#View_scaleY
8733     */
8734    public void setScaleY(float scaleY) {
8735        ensureTransformationInfo();
8736        final TransformationInfo info = mTransformationInfo;
8737        if (info.mScaleY != scaleY) {
8738            invalidateViewProperty(true, false);
8739            info.mScaleY = scaleY;
8740            info.mMatrixDirty = true;
8741            invalidateViewProperty(false, true);
8742            if (mDisplayList != null) {
8743                mDisplayList.setScaleY(scaleY);
8744            }
8745        }
8746    }
8747
8748    /**
8749     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8750     * and {@link #setScaleX(float) scaled}.
8751     *
8752     * @see #getRotation()
8753     * @see #getScaleX()
8754     * @see #getScaleY()
8755     * @see #getPivotY()
8756     * @return The x location of the pivot point.
8757     *
8758     * @attr ref android.R.styleable#View_transformPivotX
8759     */
8760    @ViewDebug.ExportedProperty(category = "drawing")
8761    public float getPivotX() {
8762        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8763    }
8764
8765    /**
8766     * Sets the x location of the point around which the view is
8767     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8768     * By default, the pivot point is centered on the object.
8769     * Setting this property disables this behavior and causes the view to use only the
8770     * explicitly set pivotX and pivotY values.
8771     *
8772     * @param pivotX The x location of the pivot point.
8773     * @see #getRotation()
8774     * @see #getScaleX()
8775     * @see #getScaleY()
8776     * @see #getPivotY()
8777     *
8778     * @attr ref android.R.styleable#View_transformPivotX
8779     */
8780    public void setPivotX(float pivotX) {
8781        ensureTransformationInfo();
8782        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8783        final TransformationInfo info = mTransformationInfo;
8784        if (info.mPivotX != pivotX) {
8785            invalidateViewProperty(true, false);
8786            info.mPivotX = pivotX;
8787            info.mMatrixDirty = true;
8788            invalidateViewProperty(false, true);
8789            if (mDisplayList != null) {
8790                mDisplayList.setPivotX(pivotX);
8791            }
8792        }
8793    }
8794
8795    /**
8796     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8797     * and {@link #setScaleY(float) scaled}.
8798     *
8799     * @see #getRotation()
8800     * @see #getScaleX()
8801     * @see #getScaleY()
8802     * @see #getPivotY()
8803     * @return The y location of the pivot point.
8804     *
8805     * @attr ref android.R.styleable#View_transformPivotY
8806     */
8807    @ViewDebug.ExportedProperty(category = "drawing")
8808    public float getPivotY() {
8809        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8810    }
8811
8812    /**
8813     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8814     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8815     * Setting this property disables this behavior and causes the view to use only the
8816     * explicitly set pivotX and pivotY values.
8817     *
8818     * @param pivotY The y location of the pivot point.
8819     * @see #getRotation()
8820     * @see #getScaleX()
8821     * @see #getScaleY()
8822     * @see #getPivotY()
8823     *
8824     * @attr ref android.R.styleable#View_transformPivotY
8825     */
8826    public void setPivotY(float pivotY) {
8827        ensureTransformationInfo();
8828        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8829        final TransformationInfo info = mTransformationInfo;
8830        if (info.mPivotY != pivotY) {
8831            invalidateViewProperty(true, false);
8832            info.mPivotY = pivotY;
8833            info.mMatrixDirty = true;
8834            invalidateViewProperty(false, true);
8835            if (mDisplayList != null) {
8836                mDisplayList.setPivotY(pivotY);
8837            }
8838        }
8839    }
8840
8841    /**
8842     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8843     * completely transparent and 1 means the view is completely opaque.
8844     *
8845     * <p>By default this is 1.0f.
8846     * @return The opacity of the view.
8847     */
8848    @ViewDebug.ExportedProperty(category = "drawing")
8849    public float getAlpha() {
8850        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8851    }
8852
8853    /**
8854     * Returns whether this View has content which overlaps. This function, intended to be
8855     * overridden by specific View types, is an optimization when alpha is set on a view. If
8856     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8857     * and then composited it into place, which can be expensive. If the view has no overlapping
8858     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8859     * An example of overlapping rendering is a TextView with a background image, such as a
8860     * Button. An example of non-overlapping rendering is a TextView with no background, or
8861     * an ImageView with only the foreground image. The default implementation returns true;
8862     * subclasses should override if they have cases which can be optimized.
8863     *
8864     * @return true if the content in this view might overlap, false otherwise.
8865     */
8866    public boolean hasOverlappingRendering() {
8867        return true;
8868    }
8869
8870    /**
8871     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8872     * completely transparent and 1 means the view is completely opaque.</p>
8873     *
8874     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8875     * responsible for applying the opacity itself. Otherwise, calling this method is
8876     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8877     * setting a hardware layer.</p>
8878     *
8879     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8880     * performance implications. It is generally best to use the alpha property sparingly and
8881     * transiently, as in the case of fading animations.</p>
8882     *
8883     * @param alpha The opacity of the view.
8884     *
8885     * @see #setLayerType(int, android.graphics.Paint)
8886     *
8887     * @attr ref android.R.styleable#View_alpha
8888     */
8889    public void setAlpha(float alpha) {
8890        ensureTransformationInfo();
8891        if (mTransformationInfo.mAlpha != alpha) {
8892            mTransformationInfo.mAlpha = alpha;
8893            if (onSetAlpha((int) (alpha * 255))) {
8894                mPrivateFlags |= ALPHA_SET;
8895                // subclass is handling alpha - don't optimize rendering cache invalidation
8896                invalidateParentCaches();
8897                invalidate(true);
8898            } else {
8899                mPrivateFlags &= ~ALPHA_SET;
8900                invalidateViewProperty(true, false);
8901                if (mDisplayList != null) {
8902                    mDisplayList.setAlpha(alpha);
8903                }
8904            }
8905        }
8906    }
8907
8908    /**
8909     * Faster version of setAlpha() which performs the same steps except there are
8910     * no calls to invalidate(). The caller of this function should perform proper invalidation
8911     * on the parent and this object. The return value indicates whether the subclass handles
8912     * alpha (the return value for onSetAlpha()).
8913     *
8914     * @param alpha The new value for the alpha property
8915     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8916     *         the new value for the alpha property is different from the old value
8917     */
8918    boolean setAlphaNoInvalidation(float alpha) {
8919        ensureTransformationInfo();
8920        if (mTransformationInfo.mAlpha != alpha) {
8921            mTransformationInfo.mAlpha = alpha;
8922            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8923            if (subclassHandlesAlpha) {
8924                mPrivateFlags |= ALPHA_SET;
8925                return true;
8926            } else {
8927                mPrivateFlags &= ~ALPHA_SET;
8928                if (mDisplayList != null) {
8929                    mDisplayList.setAlpha(alpha);
8930                }
8931            }
8932        }
8933        return false;
8934    }
8935
8936    /**
8937     * Top position of this view relative to its parent.
8938     *
8939     * @return The top of this view, in pixels.
8940     */
8941    @ViewDebug.CapturedViewProperty
8942    public final int getTop() {
8943        return mTop;
8944    }
8945
8946    /**
8947     * Sets the top position of this view relative to its parent. This method is meant to be called
8948     * by the layout system and should not generally be called otherwise, because the property
8949     * may be changed at any time by the layout.
8950     *
8951     * @param top The top of this view, in pixels.
8952     */
8953    public final void setTop(int top) {
8954        if (top != mTop) {
8955            updateMatrix();
8956            final boolean matrixIsIdentity = mTransformationInfo == null
8957                    || mTransformationInfo.mMatrixIsIdentity;
8958            if (matrixIsIdentity) {
8959                if (mAttachInfo != null) {
8960                    int minTop;
8961                    int yLoc;
8962                    if (top < mTop) {
8963                        minTop = top;
8964                        yLoc = top - mTop;
8965                    } else {
8966                        minTop = mTop;
8967                        yLoc = 0;
8968                    }
8969                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8970                }
8971            } else {
8972                // Double-invalidation is necessary to capture view's old and new areas
8973                invalidate(true);
8974            }
8975
8976            int width = mRight - mLeft;
8977            int oldHeight = mBottom - mTop;
8978
8979            mTop = top;
8980            if (mDisplayList != null) {
8981                mDisplayList.setTop(mTop);
8982            }
8983
8984            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8985
8986            if (!matrixIsIdentity) {
8987                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8988                    // A change in dimension means an auto-centered pivot point changes, too
8989                    mTransformationInfo.mMatrixDirty = true;
8990                }
8991                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8992                invalidate(true);
8993            }
8994            mBackgroundSizeChanged = true;
8995            invalidateParentIfNeeded();
8996        }
8997    }
8998
8999    /**
9000     * Bottom position of this view relative to its parent.
9001     *
9002     * @return The bottom of this view, in pixels.
9003     */
9004    @ViewDebug.CapturedViewProperty
9005    public final int getBottom() {
9006        return mBottom;
9007    }
9008
9009    /**
9010     * True if this view has changed since the last time being drawn.
9011     *
9012     * @return The dirty state of this view.
9013     */
9014    public boolean isDirty() {
9015        return (mPrivateFlags & DIRTY_MASK) != 0;
9016    }
9017
9018    /**
9019     * Sets the bottom position of this view relative to its parent. This method is meant to be
9020     * called by the layout system and should not generally be called otherwise, because the
9021     * property may be changed at any time by the layout.
9022     *
9023     * @param bottom The bottom of this view, in pixels.
9024     */
9025    public final void setBottom(int bottom) {
9026        if (bottom != mBottom) {
9027            updateMatrix();
9028            final boolean matrixIsIdentity = mTransformationInfo == null
9029                    || mTransformationInfo.mMatrixIsIdentity;
9030            if (matrixIsIdentity) {
9031                if (mAttachInfo != null) {
9032                    int maxBottom;
9033                    if (bottom < mBottom) {
9034                        maxBottom = mBottom;
9035                    } else {
9036                        maxBottom = bottom;
9037                    }
9038                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9039                }
9040            } else {
9041                // Double-invalidation is necessary to capture view's old and new areas
9042                invalidate(true);
9043            }
9044
9045            int width = mRight - mLeft;
9046            int oldHeight = mBottom - mTop;
9047
9048            mBottom = bottom;
9049            if (mDisplayList != null) {
9050                mDisplayList.setBottom(mBottom);
9051            }
9052
9053            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9054
9055            if (!matrixIsIdentity) {
9056                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9057                    // A change in dimension means an auto-centered pivot point changes, too
9058                    mTransformationInfo.mMatrixDirty = true;
9059                }
9060                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9061                invalidate(true);
9062            }
9063            mBackgroundSizeChanged = true;
9064            invalidateParentIfNeeded();
9065        }
9066    }
9067
9068    /**
9069     * Left position of this view relative to its parent.
9070     *
9071     * @return The left edge of this view, in pixels.
9072     */
9073    @ViewDebug.CapturedViewProperty
9074    public final int getLeft() {
9075        return mLeft;
9076    }
9077
9078    /**
9079     * Sets the left position of this view relative to its parent. This method is meant to be called
9080     * by the layout system and should not generally be called otherwise, because the property
9081     * may be changed at any time by the layout.
9082     *
9083     * @param left The bottom of this view, in pixels.
9084     */
9085    public final void setLeft(int left) {
9086        if (left != mLeft) {
9087            updateMatrix();
9088            final boolean matrixIsIdentity = mTransformationInfo == null
9089                    || mTransformationInfo.mMatrixIsIdentity;
9090            if (matrixIsIdentity) {
9091                if (mAttachInfo != null) {
9092                    int minLeft;
9093                    int xLoc;
9094                    if (left < mLeft) {
9095                        minLeft = left;
9096                        xLoc = left - mLeft;
9097                    } else {
9098                        minLeft = mLeft;
9099                        xLoc = 0;
9100                    }
9101                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9102                }
9103            } else {
9104                // Double-invalidation is necessary to capture view's old and new areas
9105                invalidate(true);
9106            }
9107
9108            int oldWidth = mRight - mLeft;
9109            int height = mBottom - mTop;
9110
9111            mLeft = left;
9112            if (mDisplayList != null) {
9113                mDisplayList.setLeft(left);
9114            }
9115
9116            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9117
9118            if (!matrixIsIdentity) {
9119                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9120                    // A change in dimension means an auto-centered pivot point changes, too
9121                    mTransformationInfo.mMatrixDirty = true;
9122                }
9123                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9124                invalidate(true);
9125            }
9126            mBackgroundSizeChanged = true;
9127            invalidateParentIfNeeded();
9128        }
9129    }
9130
9131    /**
9132     * Right position of this view relative to its parent.
9133     *
9134     * @return The right edge of this view, in pixels.
9135     */
9136    @ViewDebug.CapturedViewProperty
9137    public final int getRight() {
9138        return mRight;
9139    }
9140
9141    /**
9142     * Sets the right position of this view relative to its parent. This method is meant to be called
9143     * by the layout system and should not generally be called otherwise, because the property
9144     * may be changed at any time by the layout.
9145     *
9146     * @param right The bottom of this view, in pixels.
9147     */
9148    public final void setRight(int right) {
9149        if (right != mRight) {
9150            updateMatrix();
9151            final boolean matrixIsIdentity = mTransformationInfo == null
9152                    || mTransformationInfo.mMatrixIsIdentity;
9153            if (matrixIsIdentity) {
9154                if (mAttachInfo != null) {
9155                    int maxRight;
9156                    if (right < mRight) {
9157                        maxRight = mRight;
9158                    } else {
9159                        maxRight = right;
9160                    }
9161                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9162                }
9163            } else {
9164                // Double-invalidation is necessary to capture view's old and new areas
9165                invalidate(true);
9166            }
9167
9168            int oldWidth = mRight - mLeft;
9169            int height = mBottom - mTop;
9170
9171            mRight = right;
9172            if (mDisplayList != null) {
9173                mDisplayList.setRight(mRight);
9174            }
9175
9176            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9177
9178            if (!matrixIsIdentity) {
9179                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9180                    // A change in dimension means an auto-centered pivot point changes, too
9181                    mTransformationInfo.mMatrixDirty = true;
9182                }
9183                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9184                invalidate(true);
9185            }
9186            mBackgroundSizeChanged = true;
9187            invalidateParentIfNeeded();
9188        }
9189    }
9190
9191    /**
9192     * The visual x position of this view, in pixels. This is equivalent to the
9193     * {@link #setTranslationX(float) translationX} property plus the current
9194     * {@link #getLeft() left} property.
9195     *
9196     * @return The visual x position of this view, in pixels.
9197     */
9198    @ViewDebug.ExportedProperty(category = "drawing")
9199    public float getX() {
9200        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9201    }
9202
9203    /**
9204     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9205     * {@link #setTranslationX(float) translationX} property to be the difference between
9206     * the x value passed in and the current {@link #getLeft() left} property.
9207     *
9208     * @param x The visual x position of this view, in pixels.
9209     */
9210    public void setX(float x) {
9211        setTranslationX(x - mLeft);
9212    }
9213
9214    /**
9215     * The visual y position of this view, in pixels. This is equivalent to the
9216     * {@link #setTranslationY(float) translationY} property plus the current
9217     * {@link #getTop() top} property.
9218     *
9219     * @return The visual y position of this view, in pixels.
9220     */
9221    @ViewDebug.ExportedProperty(category = "drawing")
9222    public float getY() {
9223        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9224    }
9225
9226    /**
9227     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9228     * {@link #setTranslationY(float) translationY} property to be the difference between
9229     * the y value passed in and the current {@link #getTop() top} property.
9230     *
9231     * @param y The visual y position of this view, in pixels.
9232     */
9233    public void setY(float y) {
9234        setTranslationY(y - mTop);
9235    }
9236
9237
9238    /**
9239     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9240     * This position is post-layout, in addition to wherever the object's
9241     * layout placed it.
9242     *
9243     * @return The horizontal position of this view relative to its left position, in pixels.
9244     */
9245    @ViewDebug.ExportedProperty(category = "drawing")
9246    public float getTranslationX() {
9247        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9248    }
9249
9250    /**
9251     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9252     * This effectively positions the object post-layout, in addition to wherever the object's
9253     * layout placed it.
9254     *
9255     * @param translationX The horizontal position of this view relative to its left position,
9256     * in pixels.
9257     *
9258     * @attr ref android.R.styleable#View_translationX
9259     */
9260    public void setTranslationX(float translationX) {
9261        ensureTransformationInfo();
9262        final TransformationInfo info = mTransformationInfo;
9263        if (info.mTranslationX != translationX) {
9264            // Double-invalidation is necessary to capture view's old and new areas
9265            invalidateViewProperty(true, false);
9266            info.mTranslationX = translationX;
9267            info.mMatrixDirty = true;
9268            invalidateViewProperty(false, true);
9269            if (mDisplayList != null) {
9270                mDisplayList.setTranslationX(translationX);
9271            }
9272        }
9273    }
9274
9275    /**
9276     * The horizontal location of this view relative to its {@link #getTop() top} position.
9277     * This position is post-layout, in addition to wherever the object's
9278     * layout placed it.
9279     *
9280     * @return The vertical position of this view relative to its top position,
9281     * in pixels.
9282     */
9283    @ViewDebug.ExportedProperty(category = "drawing")
9284    public float getTranslationY() {
9285        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9286    }
9287
9288    /**
9289     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9290     * This effectively positions the object post-layout, in addition to wherever the object's
9291     * layout placed it.
9292     *
9293     * @param translationY The vertical position of this view relative to its top position,
9294     * in pixels.
9295     *
9296     * @attr ref android.R.styleable#View_translationY
9297     */
9298    public void setTranslationY(float translationY) {
9299        ensureTransformationInfo();
9300        final TransformationInfo info = mTransformationInfo;
9301        if (info.mTranslationY != translationY) {
9302            invalidateViewProperty(true, false);
9303            info.mTranslationY = translationY;
9304            info.mMatrixDirty = true;
9305            invalidateViewProperty(false, true);
9306            if (mDisplayList != null) {
9307                mDisplayList.setTranslationY(translationY);
9308            }
9309        }
9310    }
9311
9312    /**
9313     * Hit rectangle in parent's coordinates
9314     *
9315     * @param outRect The hit rectangle of the view.
9316     */
9317    public void getHitRect(Rect outRect) {
9318        updateMatrix();
9319        final TransformationInfo info = mTransformationInfo;
9320        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9321            outRect.set(mLeft, mTop, mRight, mBottom);
9322        } else {
9323            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9324            tmpRect.set(-info.mPivotX, -info.mPivotY,
9325                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9326            info.mMatrix.mapRect(tmpRect);
9327            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9328                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9329        }
9330    }
9331
9332    /**
9333     * Determines whether the given point, in local coordinates is inside the view.
9334     */
9335    /*package*/ final boolean pointInView(float localX, float localY) {
9336        return localX >= 0 && localX < (mRight - mLeft)
9337                && localY >= 0 && localY < (mBottom - mTop);
9338    }
9339
9340    /**
9341     * Utility method to determine whether the given point, in local coordinates,
9342     * is inside the view, where the area of the view is expanded by the slop factor.
9343     * This method is called while processing touch-move events to determine if the event
9344     * is still within the view.
9345     */
9346    private boolean pointInView(float localX, float localY, float slop) {
9347        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9348                localY < ((mBottom - mTop) + slop);
9349    }
9350
9351    /**
9352     * When a view has focus and the user navigates away from it, the next view is searched for
9353     * starting from the rectangle filled in by this method.
9354     *
9355     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9356     * of the view.  However, if your view maintains some idea of internal selection,
9357     * such as a cursor, or a selected row or column, you should override this method and
9358     * fill in a more specific rectangle.
9359     *
9360     * @param r The rectangle to fill in, in this view's coordinates.
9361     */
9362    public void getFocusedRect(Rect r) {
9363        getDrawingRect(r);
9364    }
9365
9366    /**
9367     * If some part of this view is not clipped by any of its parents, then
9368     * return that area in r in global (root) coordinates. To convert r to local
9369     * coordinates (without taking possible View rotations into account), offset
9370     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9371     * If the view is completely clipped or translated out, return false.
9372     *
9373     * @param r If true is returned, r holds the global coordinates of the
9374     *        visible portion of this view.
9375     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9376     *        between this view and its root. globalOffet may be null.
9377     * @return true if r is non-empty (i.e. part of the view is visible at the
9378     *         root level.
9379     */
9380    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9381        int width = mRight - mLeft;
9382        int height = mBottom - mTop;
9383        if (width > 0 && height > 0) {
9384            r.set(0, 0, width, height);
9385            if (globalOffset != null) {
9386                globalOffset.set(-mScrollX, -mScrollY);
9387            }
9388            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9389        }
9390        return false;
9391    }
9392
9393    public final boolean getGlobalVisibleRect(Rect r) {
9394        return getGlobalVisibleRect(r, null);
9395    }
9396
9397    public final boolean getLocalVisibleRect(Rect r) {
9398        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9399        if (getGlobalVisibleRect(r, offset)) {
9400            r.offset(-offset.x, -offset.y); // make r local
9401            return true;
9402        }
9403        return false;
9404    }
9405
9406    /**
9407     * Offset this view's vertical location by the specified number of pixels.
9408     *
9409     * @param offset the number of pixels to offset the view by
9410     */
9411    public void offsetTopAndBottom(int offset) {
9412        if (offset != 0) {
9413            updateMatrix();
9414            final boolean matrixIsIdentity = mTransformationInfo == null
9415                    || mTransformationInfo.mMatrixIsIdentity;
9416            if (matrixIsIdentity) {
9417                if (mDisplayList != null) {
9418                    invalidateViewProperty(false, false);
9419                } else {
9420                    final ViewParent p = mParent;
9421                    if (p != null && mAttachInfo != null) {
9422                        final Rect r = mAttachInfo.mTmpInvalRect;
9423                        int minTop;
9424                        int maxBottom;
9425                        int yLoc;
9426                        if (offset < 0) {
9427                            minTop = mTop + offset;
9428                            maxBottom = mBottom;
9429                            yLoc = offset;
9430                        } else {
9431                            minTop = mTop;
9432                            maxBottom = mBottom + offset;
9433                            yLoc = 0;
9434                        }
9435                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9436                        p.invalidateChild(this, r);
9437                    }
9438                }
9439            } else {
9440                invalidateViewProperty(false, false);
9441            }
9442
9443            mTop += offset;
9444            mBottom += offset;
9445            if (mDisplayList != null) {
9446                mDisplayList.offsetTopBottom(offset);
9447                invalidateViewProperty(false, false);
9448            } else {
9449                if (!matrixIsIdentity) {
9450                    invalidateViewProperty(false, true);
9451                }
9452                invalidateParentIfNeeded();
9453            }
9454        }
9455    }
9456
9457    /**
9458     * Offset this view's horizontal location by the specified amount of pixels.
9459     *
9460     * @param offset the numer of pixels to offset the view by
9461     */
9462    public void offsetLeftAndRight(int offset) {
9463        if (offset != 0) {
9464            updateMatrix();
9465            final boolean matrixIsIdentity = mTransformationInfo == null
9466                    || mTransformationInfo.mMatrixIsIdentity;
9467            if (matrixIsIdentity) {
9468                if (mDisplayList != null) {
9469                    invalidateViewProperty(false, false);
9470                } else {
9471                    final ViewParent p = mParent;
9472                    if (p != null && mAttachInfo != null) {
9473                        final Rect r = mAttachInfo.mTmpInvalRect;
9474                        int minLeft;
9475                        int maxRight;
9476                        if (offset < 0) {
9477                            minLeft = mLeft + offset;
9478                            maxRight = mRight;
9479                        } else {
9480                            minLeft = mLeft;
9481                            maxRight = mRight + offset;
9482                        }
9483                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9484                        p.invalidateChild(this, r);
9485                    }
9486                }
9487            } else {
9488                invalidateViewProperty(false, false);
9489            }
9490
9491            mLeft += offset;
9492            mRight += offset;
9493            if (mDisplayList != null) {
9494                mDisplayList.offsetLeftRight(offset);
9495                invalidateViewProperty(false, false);
9496            } else {
9497                if (!matrixIsIdentity) {
9498                    invalidateViewProperty(false, true);
9499                }
9500                invalidateParentIfNeeded();
9501            }
9502        }
9503    }
9504
9505    /**
9506     * Get the LayoutParams associated with this view. All views should have
9507     * layout parameters. These supply parameters to the <i>parent</i> of this
9508     * view specifying how it should be arranged. There are many subclasses of
9509     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9510     * of ViewGroup that are responsible for arranging their children.
9511     *
9512     * This method may return null if this View is not attached to a parent
9513     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9514     * was not invoked successfully. When a View is attached to a parent
9515     * ViewGroup, this method must not return null.
9516     *
9517     * @return The LayoutParams associated with this view, or null if no
9518     *         parameters have been set yet
9519     */
9520    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9521    public ViewGroup.LayoutParams getLayoutParams() {
9522        return mLayoutParams;
9523    }
9524
9525    /**
9526     * Set the layout parameters associated with this view. These supply
9527     * parameters to the <i>parent</i> of this view specifying how it should be
9528     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9529     * correspond to the different subclasses of ViewGroup that are responsible
9530     * for arranging their children.
9531     *
9532     * @param params The layout parameters for this view, cannot be null
9533     */
9534    public void setLayoutParams(ViewGroup.LayoutParams params) {
9535        if (params == null) {
9536            throw new NullPointerException("Layout parameters cannot be null");
9537        }
9538        mLayoutParams = params;
9539        if (mParent instanceof ViewGroup) {
9540            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9541        }
9542        requestLayout();
9543    }
9544
9545    /**
9546     * Set the scrolled position of your view. This will cause a call to
9547     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9548     * invalidated.
9549     * @param x the x position to scroll to
9550     * @param y the y position to scroll to
9551     */
9552    public void scrollTo(int x, int y) {
9553        if (mScrollX != x || mScrollY != y) {
9554            int oldX = mScrollX;
9555            int oldY = mScrollY;
9556            mScrollX = x;
9557            mScrollY = y;
9558            invalidateParentCaches();
9559            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9560            if (!awakenScrollBars()) {
9561                postInvalidateOnAnimation();
9562            }
9563        }
9564    }
9565
9566    /**
9567     * Move the scrolled position of your view. This will cause a call to
9568     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9569     * invalidated.
9570     * @param x the amount of pixels to scroll by horizontally
9571     * @param y the amount of pixels to scroll by vertically
9572     */
9573    public void scrollBy(int x, int y) {
9574        scrollTo(mScrollX + x, mScrollY + y);
9575    }
9576
9577    /**
9578     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9579     * animation to fade the scrollbars out after a default delay. If a subclass
9580     * provides animated scrolling, the start delay should equal the duration
9581     * of the scrolling animation.</p>
9582     *
9583     * <p>The animation starts only if at least one of the scrollbars is
9584     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9585     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9586     * this method returns true, and false otherwise. If the animation is
9587     * started, this method calls {@link #invalidate()}; in that case the
9588     * caller should not call {@link #invalidate()}.</p>
9589     *
9590     * <p>This method should be invoked every time a subclass directly updates
9591     * the scroll parameters.</p>
9592     *
9593     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9594     * and {@link #scrollTo(int, int)}.</p>
9595     *
9596     * @return true if the animation is played, false otherwise
9597     *
9598     * @see #awakenScrollBars(int)
9599     * @see #scrollBy(int, int)
9600     * @see #scrollTo(int, int)
9601     * @see #isHorizontalScrollBarEnabled()
9602     * @see #isVerticalScrollBarEnabled()
9603     * @see #setHorizontalScrollBarEnabled(boolean)
9604     * @see #setVerticalScrollBarEnabled(boolean)
9605     */
9606    protected boolean awakenScrollBars() {
9607        return mScrollCache != null &&
9608                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9609    }
9610
9611    /**
9612     * Trigger the scrollbars to draw.
9613     * This method differs from awakenScrollBars() only in its default duration.
9614     * initialAwakenScrollBars() will show the scroll bars for longer than
9615     * usual to give the user more of a chance to notice them.
9616     *
9617     * @return true if the animation is played, false otherwise.
9618     */
9619    private boolean initialAwakenScrollBars() {
9620        return mScrollCache != null &&
9621                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9622    }
9623
9624    /**
9625     * <p>
9626     * Trigger the scrollbars to draw. When invoked this method starts an
9627     * animation to fade the scrollbars out after a fixed delay. If a subclass
9628     * provides animated scrolling, the start delay should equal the duration of
9629     * the scrolling animation.
9630     * </p>
9631     *
9632     * <p>
9633     * The animation starts only if at least one of the scrollbars is enabled,
9634     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9635     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9636     * this method returns true, and false otherwise. If the animation is
9637     * started, this method calls {@link #invalidate()}; in that case the caller
9638     * should not call {@link #invalidate()}.
9639     * </p>
9640     *
9641     * <p>
9642     * This method should be invoked everytime a subclass directly updates the
9643     * scroll parameters.
9644     * </p>
9645     *
9646     * @param startDelay the delay, in milliseconds, after which the animation
9647     *        should start; when the delay is 0, the animation starts
9648     *        immediately
9649     * @return true if the animation is played, false otherwise
9650     *
9651     * @see #scrollBy(int, int)
9652     * @see #scrollTo(int, int)
9653     * @see #isHorizontalScrollBarEnabled()
9654     * @see #isVerticalScrollBarEnabled()
9655     * @see #setHorizontalScrollBarEnabled(boolean)
9656     * @see #setVerticalScrollBarEnabled(boolean)
9657     */
9658    protected boolean awakenScrollBars(int startDelay) {
9659        return awakenScrollBars(startDelay, true);
9660    }
9661
9662    /**
9663     * <p>
9664     * Trigger the scrollbars to draw. When invoked this method starts an
9665     * animation to fade the scrollbars out after a fixed delay. If a subclass
9666     * provides animated scrolling, the start delay should equal the duration of
9667     * the scrolling animation.
9668     * </p>
9669     *
9670     * <p>
9671     * The animation starts only if at least one of the scrollbars is enabled,
9672     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9673     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9674     * this method returns true, and false otherwise. If the animation is
9675     * started, this method calls {@link #invalidate()} if the invalidate parameter
9676     * is set to true; in that case the caller
9677     * should not call {@link #invalidate()}.
9678     * </p>
9679     *
9680     * <p>
9681     * This method should be invoked everytime a subclass directly updates the
9682     * scroll parameters.
9683     * </p>
9684     *
9685     * @param startDelay the delay, in milliseconds, after which the animation
9686     *        should start; when the delay is 0, the animation starts
9687     *        immediately
9688     *
9689     * @param invalidate Wheter this method should call invalidate
9690     *
9691     * @return true if the animation is played, false otherwise
9692     *
9693     * @see #scrollBy(int, int)
9694     * @see #scrollTo(int, int)
9695     * @see #isHorizontalScrollBarEnabled()
9696     * @see #isVerticalScrollBarEnabled()
9697     * @see #setHorizontalScrollBarEnabled(boolean)
9698     * @see #setVerticalScrollBarEnabled(boolean)
9699     */
9700    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9701        final ScrollabilityCache scrollCache = mScrollCache;
9702
9703        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9704            return false;
9705        }
9706
9707        if (scrollCache.scrollBar == null) {
9708            scrollCache.scrollBar = new ScrollBarDrawable();
9709        }
9710
9711        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9712
9713            if (invalidate) {
9714                // Invalidate to show the scrollbars
9715                postInvalidateOnAnimation();
9716            }
9717
9718            if (scrollCache.state == ScrollabilityCache.OFF) {
9719                // FIXME: this is copied from WindowManagerService.
9720                // We should get this value from the system when it
9721                // is possible to do so.
9722                final int KEY_REPEAT_FIRST_DELAY = 750;
9723                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9724            }
9725
9726            // Tell mScrollCache when we should start fading. This may
9727            // extend the fade start time if one was already scheduled
9728            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9729            scrollCache.fadeStartTime = fadeStartTime;
9730            scrollCache.state = ScrollabilityCache.ON;
9731
9732            // Schedule our fader to run, unscheduling any old ones first
9733            if (mAttachInfo != null) {
9734                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9735                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9736            }
9737
9738            return true;
9739        }
9740
9741        return false;
9742    }
9743
9744    /**
9745     * Do not invalidate views which are not visible and which are not running an animation. They
9746     * will not get drawn and they should not set dirty flags as if they will be drawn
9747     */
9748    private boolean skipInvalidate() {
9749        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9750                (!(mParent instanceof ViewGroup) ||
9751                        !((ViewGroup) mParent).isViewTransitioning(this));
9752    }
9753    /**
9754     * Mark the area defined by dirty as needing to be drawn. If the view is
9755     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9756     * in the future. This must be called from a UI thread. To call from a non-UI
9757     * thread, call {@link #postInvalidate()}.
9758     *
9759     * WARNING: This method is destructive to dirty.
9760     * @param dirty the rectangle representing the bounds of the dirty region
9761     */
9762    public void invalidate(Rect dirty) {
9763        if (ViewDebug.TRACE_HIERARCHY) {
9764            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9765        }
9766
9767        if (skipInvalidate()) {
9768            return;
9769        }
9770        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9771                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9772                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9773            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9774            mPrivateFlags |= INVALIDATED;
9775            mPrivateFlags |= DIRTY;
9776            final ViewParent p = mParent;
9777            final AttachInfo ai = mAttachInfo;
9778            //noinspection PointlessBooleanExpression,ConstantConditions
9779            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9780                if (p != null && ai != null && ai.mHardwareAccelerated) {
9781                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9782                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9783                    p.invalidateChild(this, null);
9784                    return;
9785                }
9786            }
9787            if (p != null && ai != null) {
9788                final int scrollX = mScrollX;
9789                final int scrollY = mScrollY;
9790                final Rect r = ai.mTmpInvalRect;
9791                r.set(dirty.left - scrollX, dirty.top - scrollY,
9792                        dirty.right - scrollX, dirty.bottom - scrollY);
9793                mParent.invalidateChild(this, r);
9794            }
9795        }
9796    }
9797
9798    /**
9799     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9800     * The coordinates of the dirty rect are relative to the view.
9801     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9802     * will be called at some point in the future. This must be called from
9803     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9804     * @param l the left position of the dirty region
9805     * @param t the top position of the dirty region
9806     * @param r the right position of the dirty region
9807     * @param b the bottom position of the dirty region
9808     */
9809    public void invalidate(int l, int t, int r, int b) {
9810        if (ViewDebug.TRACE_HIERARCHY) {
9811            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9812        }
9813
9814        if (skipInvalidate()) {
9815            return;
9816        }
9817        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9818                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9819                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9820            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9821            mPrivateFlags |= INVALIDATED;
9822            mPrivateFlags |= DIRTY;
9823            final ViewParent p = mParent;
9824            final AttachInfo ai = mAttachInfo;
9825            //noinspection PointlessBooleanExpression,ConstantConditions
9826            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9827                if (p != null && ai != null && ai.mHardwareAccelerated) {
9828                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9829                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9830                    p.invalidateChild(this, null);
9831                    return;
9832                }
9833            }
9834            if (p != null && ai != null && l < r && t < b) {
9835                final int scrollX = mScrollX;
9836                final int scrollY = mScrollY;
9837                final Rect tmpr = ai.mTmpInvalRect;
9838                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9839                p.invalidateChild(this, tmpr);
9840            }
9841        }
9842    }
9843
9844    /**
9845     * Invalidate the whole view. If the view is visible,
9846     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9847     * the future. This must be called from a UI thread. To call from a non-UI thread,
9848     * call {@link #postInvalidate()}.
9849     */
9850    public void invalidate() {
9851        invalidate(true);
9852    }
9853
9854    /**
9855     * This is where the invalidate() work actually happens. A full invalidate()
9856     * causes the drawing cache to be invalidated, but this function can be called with
9857     * invalidateCache set to false to skip that invalidation step for cases that do not
9858     * need it (for example, a component that remains at the same dimensions with the same
9859     * content).
9860     *
9861     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9862     * well. This is usually true for a full invalidate, but may be set to false if the
9863     * View's contents or dimensions have not changed.
9864     */
9865    void invalidate(boolean invalidateCache) {
9866        if (ViewDebug.TRACE_HIERARCHY) {
9867            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9868        }
9869
9870        if (skipInvalidate()) {
9871            return;
9872        }
9873        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9874                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9875                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9876            mLastIsOpaque = isOpaque();
9877            mPrivateFlags &= ~DRAWN;
9878            mPrivateFlags |= DIRTY;
9879            if (invalidateCache) {
9880                mPrivateFlags |= INVALIDATED;
9881                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9882            }
9883            final AttachInfo ai = mAttachInfo;
9884            final ViewParent p = mParent;
9885            //noinspection PointlessBooleanExpression,ConstantConditions
9886            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9887                if (p != null && ai != null && ai.mHardwareAccelerated) {
9888                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9889                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9890                    p.invalidateChild(this, null);
9891                    return;
9892                }
9893            }
9894
9895            if (p != null && ai != null) {
9896                final Rect r = ai.mTmpInvalRect;
9897                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9898                // Don't call invalidate -- we don't want to internally scroll
9899                // our own bounds
9900                p.invalidateChild(this, r);
9901            }
9902        }
9903    }
9904
9905    /**
9906     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9907     * set any flags or handle all of the cases handled by the default invalidation methods.
9908     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9909     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9910     * walk up the hierarchy, transforming the dirty rect as necessary.
9911     *
9912     * The method also handles normal invalidation logic if display list properties are not
9913     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9914     * backup approach, to handle these cases used in the various property-setting methods.
9915     *
9916     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9917     * are not being used in this view
9918     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9919     * list properties are not being used in this view
9920     */
9921    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9922        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9923            if (invalidateParent) {
9924                invalidateParentCaches();
9925            }
9926            if (forceRedraw) {
9927                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9928            }
9929            invalidate(false);
9930        } else {
9931            final AttachInfo ai = mAttachInfo;
9932            final ViewParent p = mParent;
9933            if (p != null && ai != null) {
9934                final Rect r = ai.mTmpInvalRect;
9935                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9936                if (mParent instanceof ViewGroup) {
9937                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9938                } else {
9939                    mParent.invalidateChild(this, r);
9940                }
9941            }
9942        }
9943    }
9944
9945    /**
9946     * Utility method to transform a given Rect by the current matrix of this view.
9947     */
9948    void transformRect(final Rect rect) {
9949        if (!getMatrix().isIdentity()) {
9950            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9951            boundingRect.set(rect);
9952            getMatrix().mapRect(boundingRect);
9953            rect.set((int) (boundingRect.left - 0.5f),
9954                    (int) (boundingRect.top - 0.5f),
9955                    (int) (boundingRect.right + 0.5f),
9956                    (int) (boundingRect.bottom + 0.5f));
9957        }
9958    }
9959
9960    /**
9961     * Used to indicate that the parent of this view should clear its caches. This functionality
9962     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9963     * which is necessary when various parent-managed properties of the view change, such as
9964     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9965     * clears the parent caches and does not causes an invalidate event.
9966     *
9967     * @hide
9968     */
9969    protected void invalidateParentCaches() {
9970        if (mParent instanceof View) {
9971            ((View) mParent).mPrivateFlags |= INVALIDATED;
9972        }
9973    }
9974
9975    /**
9976     * Used to indicate that the parent of this view should be invalidated. This functionality
9977     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9978     * which is necessary when various parent-managed properties of the view change, such as
9979     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9980     * an invalidation event to the parent.
9981     *
9982     * @hide
9983     */
9984    protected void invalidateParentIfNeeded() {
9985        if (isHardwareAccelerated() && mParent instanceof View) {
9986            ((View) mParent).invalidate(true);
9987        }
9988    }
9989
9990    /**
9991     * Indicates whether this View is opaque. An opaque View guarantees that it will
9992     * draw all the pixels overlapping its bounds using a fully opaque color.
9993     *
9994     * Subclasses of View should override this method whenever possible to indicate
9995     * whether an instance is opaque. Opaque Views are treated in a special way by
9996     * the View hierarchy, possibly allowing it to perform optimizations during
9997     * invalidate/draw passes.
9998     *
9999     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10000     */
10001    @ViewDebug.ExportedProperty(category = "drawing")
10002    public boolean isOpaque() {
10003        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10004                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10005                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10006    }
10007
10008    /**
10009     * @hide
10010     */
10011    protected void computeOpaqueFlags() {
10012        // Opaque if:
10013        //   - Has a background
10014        //   - Background is opaque
10015        //   - Doesn't have scrollbars or scrollbars are inside overlay
10016
10017        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10018            mPrivateFlags |= OPAQUE_BACKGROUND;
10019        } else {
10020            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10021        }
10022
10023        final int flags = mViewFlags;
10024        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10025                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10026            mPrivateFlags |= OPAQUE_SCROLLBARS;
10027        } else {
10028            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10029        }
10030    }
10031
10032    /**
10033     * @hide
10034     */
10035    protected boolean hasOpaqueScrollbars() {
10036        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10037    }
10038
10039    /**
10040     * @return A handler associated with the thread running the View. This
10041     * handler can be used to pump events in the UI events queue.
10042     */
10043    public Handler getHandler() {
10044        if (mAttachInfo != null) {
10045            return mAttachInfo.mHandler;
10046        }
10047        return null;
10048    }
10049
10050    /**
10051     * Gets the view root associated with the View.
10052     * @return The view root, or null if none.
10053     * @hide
10054     */
10055    public ViewRootImpl getViewRootImpl() {
10056        if (mAttachInfo != null) {
10057            return mAttachInfo.mViewRootImpl;
10058        }
10059        return null;
10060    }
10061
10062    /**
10063     * <p>Causes the Runnable to be added to the message queue.
10064     * The runnable will be run on the user interface thread.</p>
10065     *
10066     * <p>This method can be invoked from outside of the UI thread
10067     * only when this View is attached to a window.</p>
10068     *
10069     * @param action The Runnable that will be executed.
10070     *
10071     * @return Returns true if the Runnable was successfully placed in to the
10072     *         message queue.  Returns false on failure, usually because the
10073     *         looper processing the message queue is exiting.
10074     *
10075     * @see #postDelayed
10076     * @see #removeCallbacks
10077     */
10078    public boolean post(Runnable action) {
10079        final AttachInfo attachInfo = mAttachInfo;
10080        if (attachInfo != null) {
10081            return attachInfo.mHandler.post(action);
10082        }
10083        // Assume that post will succeed later
10084        ViewRootImpl.getRunQueue().post(action);
10085        return true;
10086    }
10087
10088    /**
10089     * <p>Causes the Runnable to be added to the message queue, to be run
10090     * after the specified amount of time elapses.
10091     * The runnable will be run on the user interface thread.</p>
10092     *
10093     * <p>This method can be invoked from outside of the UI thread
10094     * only when this View is attached to a window.</p>
10095     *
10096     * @param action The Runnable that will be executed.
10097     * @param delayMillis The delay (in milliseconds) until the Runnable
10098     *        will be executed.
10099     *
10100     * @return true if the Runnable was successfully placed in to the
10101     *         message queue.  Returns false on failure, usually because the
10102     *         looper processing the message queue is exiting.  Note that a
10103     *         result of true does not mean the Runnable will be processed --
10104     *         if the looper is quit before the delivery time of the message
10105     *         occurs then the message will be dropped.
10106     *
10107     * @see #post
10108     * @see #removeCallbacks
10109     */
10110    public boolean postDelayed(Runnable action, long delayMillis) {
10111        final AttachInfo attachInfo = mAttachInfo;
10112        if (attachInfo != null) {
10113            return attachInfo.mHandler.postDelayed(action, delayMillis);
10114        }
10115        // Assume that post will succeed later
10116        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10117        return true;
10118    }
10119
10120    /**
10121     * <p>Causes the Runnable to execute on the next animation time step.
10122     * The runnable will be run on the user interface thread.</p>
10123     *
10124     * <p>This method can be invoked from outside of the UI thread
10125     * only when this View is attached to a window.</p>
10126     *
10127     * @param action The Runnable that will be executed.
10128     *
10129     * @see #postOnAnimationDelayed
10130     * @see #removeCallbacks
10131     */
10132    public void postOnAnimation(Runnable action) {
10133        final AttachInfo attachInfo = mAttachInfo;
10134        if (attachInfo != null) {
10135            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10136                    Choreographer.CALLBACK_ANIMATION, action, null);
10137        } else {
10138            // Assume that post will succeed later
10139            ViewRootImpl.getRunQueue().post(action);
10140        }
10141    }
10142
10143    /**
10144     * <p>Causes the Runnable to execute on the next animation time step,
10145     * after the specified amount of time elapses.
10146     * The runnable will be run on the user interface thread.</p>
10147     *
10148     * <p>This method can be invoked from outside of the UI thread
10149     * only when this View is attached to a window.</p>
10150     *
10151     * @param action The Runnable that will be executed.
10152     * @param delayMillis The delay (in milliseconds) until the Runnable
10153     *        will be executed.
10154     *
10155     * @see #postOnAnimation
10156     * @see #removeCallbacks
10157     */
10158    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10159        final AttachInfo attachInfo = mAttachInfo;
10160        if (attachInfo != null) {
10161            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10162                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10163        } else {
10164            // Assume that post will succeed later
10165            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10166        }
10167    }
10168
10169    /**
10170     * <p>Removes the specified Runnable from the message queue.</p>
10171     *
10172     * <p>This method can be invoked from outside of the UI thread
10173     * only when this View is attached to a window.</p>
10174     *
10175     * @param action The Runnable to remove from the message handling queue
10176     *
10177     * @return true if this view could ask the Handler to remove the Runnable,
10178     *         false otherwise. When the returned value is true, the Runnable
10179     *         may or may not have been actually removed from the message queue
10180     *         (for instance, if the Runnable was not in the queue already.)
10181     *
10182     * @see #post
10183     * @see #postDelayed
10184     * @see #postOnAnimation
10185     * @see #postOnAnimationDelayed
10186     */
10187    public boolean removeCallbacks(Runnable action) {
10188        if (action != null) {
10189            final AttachInfo attachInfo = mAttachInfo;
10190            if (attachInfo != null) {
10191                attachInfo.mHandler.removeCallbacks(action);
10192                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10193                        Choreographer.CALLBACK_ANIMATION, action, null);
10194            } else {
10195                // Assume that post will succeed later
10196                ViewRootImpl.getRunQueue().removeCallbacks(action);
10197            }
10198        }
10199        return true;
10200    }
10201
10202    /**
10203     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10204     * Use this to invalidate the View from a non-UI thread.</p>
10205     *
10206     * <p>This method can be invoked from outside of the UI thread
10207     * only when this View is attached to a window.</p>
10208     *
10209     * @see #invalidate()
10210     * @see #postInvalidateDelayed(long)
10211     */
10212    public void postInvalidate() {
10213        postInvalidateDelayed(0);
10214    }
10215
10216    /**
10217     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10218     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10219     *
10220     * <p>This method can be invoked from outside of the UI thread
10221     * only when this View is attached to a window.</p>
10222     *
10223     * @param left The left coordinate of the rectangle to invalidate.
10224     * @param top The top coordinate of the rectangle to invalidate.
10225     * @param right The right coordinate of the rectangle to invalidate.
10226     * @param bottom The bottom coordinate of the rectangle to invalidate.
10227     *
10228     * @see #invalidate(int, int, int, int)
10229     * @see #invalidate(Rect)
10230     * @see #postInvalidateDelayed(long, int, int, int, int)
10231     */
10232    public void postInvalidate(int left, int top, int right, int bottom) {
10233        postInvalidateDelayed(0, left, top, right, bottom);
10234    }
10235
10236    /**
10237     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10238     * loop. Waits for the specified amount of time.</p>
10239     *
10240     * <p>This method can be invoked from outside of the UI thread
10241     * only when this View is attached to a window.</p>
10242     *
10243     * @param delayMilliseconds the duration in milliseconds to delay the
10244     *         invalidation by
10245     *
10246     * @see #invalidate()
10247     * @see #postInvalidate()
10248     */
10249    public void postInvalidateDelayed(long delayMilliseconds) {
10250        // We try only with the AttachInfo because there's no point in invalidating
10251        // if we are not attached to our window
10252        final AttachInfo attachInfo = mAttachInfo;
10253        if (attachInfo != null) {
10254            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10255        }
10256    }
10257
10258    /**
10259     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10260     * through the event loop. Waits for the specified amount of time.</p>
10261     *
10262     * <p>This method can be invoked from outside of the UI thread
10263     * only when this View is attached to a window.</p>
10264     *
10265     * @param delayMilliseconds the duration in milliseconds to delay the
10266     *         invalidation by
10267     * @param left The left coordinate of the rectangle to invalidate.
10268     * @param top The top coordinate of the rectangle to invalidate.
10269     * @param right The right coordinate of the rectangle to invalidate.
10270     * @param bottom The bottom coordinate of the rectangle to invalidate.
10271     *
10272     * @see #invalidate(int, int, int, int)
10273     * @see #invalidate(Rect)
10274     * @see #postInvalidate(int, int, int, int)
10275     */
10276    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10277            int right, int bottom) {
10278
10279        // We try only with the AttachInfo because there's no point in invalidating
10280        // if we are not attached to our window
10281        final AttachInfo attachInfo = mAttachInfo;
10282        if (attachInfo != null) {
10283            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10284            info.target = this;
10285            info.left = left;
10286            info.top = top;
10287            info.right = right;
10288            info.bottom = bottom;
10289
10290            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10291        }
10292    }
10293
10294    /**
10295     * <p>Cause an invalidate to happen on the next animation time step, typically the
10296     * next display frame.</p>
10297     *
10298     * <p>This method can be invoked from outside of the UI thread
10299     * only when this View is attached to a window.</p>
10300     *
10301     * @see #invalidate()
10302     */
10303    public void postInvalidateOnAnimation() {
10304        // We try only with the AttachInfo because there's no point in invalidating
10305        // if we are not attached to our window
10306        final AttachInfo attachInfo = mAttachInfo;
10307        if (attachInfo != null) {
10308            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10309        }
10310    }
10311
10312    /**
10313     * <p>Cause an invalidate of the specified area to happen on the next animation
10314     * time step, typically the next display frame.</p>
10315     *
10316     * <p>This method can be invoked from outside of the UI thread
10317     * only when this View is attached to a window.</p>
10318     *
10319     * @param left The left coordinate of the rectangle to invalidate.
10320     * @param top The top coordinate of the rectangle to invalidate.
10321     * @param right The right coordinate of the rectangle to invalidate.
10322     * @param bottom The bottom coordinate of the rectangle to invalidate.
10323     *
10324     * @see #invalidate(int, int, int, int)
10325     * @see #invalidate(Rect)
10326     */
10327    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10328        // We try only with the AttachInfo because there's no point in invalidating
10329        // if we are not attached to our window
10330        final AttachInfo attachInfo = mAttachInfo;
10331        if (attachInfo != null) {
10332            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10333            info.target = this;
10334            info.left = left;
10335            info.top = top;
10336            info.right = right;
10337            info.bottom = bottom;
10338
10339            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10340        }
10341    }
10342
10343    /**
10344     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10345     * This event is sent at most once every
10346     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10347     */
10348    private void postSendViewScrolledAccessibilityEventCallback() {
10349        if (mSendViewScrolledAccessibilityEvent == null) {
10350            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10351        }
10352        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10353            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10354            postDelayed(mSendViewScrolledAccessibilityEvent,
10355                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10356        }
10357    }
10358
10359    /**
10360     * Called by a parent to request that a child update its values for mScrollX
10361     * and mScrollY if necessary. This will typically be done if the child is
10362     * animating a scroll using a {@link android.widget.Scroller Scroller}
10363     * object.
10364     */
10365    public void computeScroll() {
10366    }
10367
10368    /**
10369     * <p>Indicate whether the horizontal edges are faded when the view is
10370     * scrolled horizontally.</p>
10371     *
10372     * @return true if the horizontal edges should are faded on scroll, false
10373     *         otherwise
10374     *
10375     * @see #setHorizontalFadingEdgeEnabled(boolean)
10376     *
10377     * @attr ref android.R.styleable#View_requiresFadingEdge
10378     */
10379    public boolean isHorizontalFadingEdgeEnabled() {
10380        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10381    }
10382
10383    /**
10384     * <p>Define whether the horizontal edges should be faded when this view
10385     * is scrolled horizontally.</p>
10386     *
10387     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10388     *                                    be faded when the view is scrolled
10389     *                                    horizontally
10390     *
10391     * @see #isHorizontalFadingEdgeEnabled()
10392     *
10393     * @attr ref android.R.styleable#View_requiresFadingEdge
10394     */
10395    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10396        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10397            if (horizontalFadingEdgeEnabled) {
10398                initScrollCache();
10399            }
10400
10401            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10402        }
10403    }
10404
10405    /**
10406     * <p>Indicate whether the vertical edges are faded when the view is
10407     * scrolled horizontally.</p>
10408     *
10409     * @return true if the vertical edges should are faded on scroll, false
10410     *         otherwise
10411     *
10412     * @see #setVerticalFadingEdgeEnabled(boolean)
10413     *
10414     * @attr ref android.R.styleable#View_requiresFadingEdge
10415     */
10416    public boolean isVerticalFadingEdgeEnabled() {
10417        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10418    }
10419
10420    /**
10421     * <p>Define whether the vertical edges should be faded when this view
10422     * is scrolled vertically.</p>
10423     *
10424     * @param verticalFadingEdgeEnabled true if the vertical edges should
10425     *                                  be faded when the view is scrolled
10426     *                                  vertically
10427     *
10428     * @see #isVerticalFadingEdgeEnabled()
10429     *
10430     * @attr ref android.R.styleable#View_requiresFadingEdge
10431     */
10432    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10433        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10434            if (verticalFadingEdgeEnabled) {
10435                initScrollCache();
10436            }
10437
10438            mViewFlags ^= FADING_EDGE_VERTICAL;
10439        }
10440    }
10441
10442    /**
10443     * Returns the strength, or intensity, of the top faded edge. The strength is
10444     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10445     * returns 0.0 or 1.0 but no value in between.
10446     *
10447     * Subclasses should override this method to provide a smoother fade transition
10448     * when scrolling occurs.
10449     *
10450     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10451     */
10452    protected float getTopFadingEdgeStrength() {
10453        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10454    }
10455
10456    /**
10457     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10458     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10459     * returns 0.0 or 1.0 but no value in between.
10460     *
10461     * Subclasses should override this method to provide a smoother fade transition
10462     * when scrolling occurs.
10463     *
10464     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10465     */
10466    protected float getBottomFadingEdgeStrength() {
10467        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10468                computeVerticalScrollRange() ? 1.0f : 0.0f;
10469    }
10470
10471    /**
10472     * Returns the strength, or intensity, of the left faded edge. The strength is
10473     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10474     * returns 0.0 or 1.0 but no value in between.
10475     *
10476     * Subclasses should override this method to provide a smoother fade transition
10477     * when scrolling occurs.
10478     *
10479     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10480     */
10481    protected float getLeftFadingEdgeStrength() {
10482        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10483    }
10484
10485    /**
10486     * Returns the strength, or intensity, of the right faded edge. The strength is
10487     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10488     * returns 0.0 or 1.0 but no value in between.
10489     *
10490     * Subclasses should override this method to provide a smoother fade transition
10491     * when scrolling occurs.
10492     *
10493     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10494     */
10495    protected float getRightFadingEdgeStrength() {
10496        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10497                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10498    }
10499
10500    /**
10501     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10502     * scrollbar is not drawn by default.</p>
10503     *
10504     * @return true if the horizontal scrollbar should be painted, false
10505     *         otherwise
10506     *
10507     * @see #setHorizontalScrollBarEnabled(boolean)
10508     */
10509    public boolean isHorizontalScrollBarEnabled() {
10510        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10511    }
10512
10513    /**
10514     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10515     * scrollbar is not drawn by default.</p>
10516     *
10517     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10518     *                                   be painted
10519     *
10520     * @see #isHorizontalScrollBarEnabled()
10521     */
10522    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10523        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10524            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10525            computeOpaqueFlags();
10526            resolvePadding();
10527        }
10528    }
10529
10530    /**
10531     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10532     * scrollbar is not drawn by default.</p>
10533     *
10534     * @return true if the vertical scrollbar should be painted, false
10535     *         otherwise
10536     *
10537     * @see #setVerticalScrollBarEnabled(boolean)
10538     */
10539    public boolean isVerticalScrollBarEnabled() {
10540        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10541    }
10542
10543    /**
10544     * <p>Define whether the vertical scrollbar should be drawn or not. The
10545     * scrollbar is not drawn by default.</p>
10546     *
10547     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10548     *                                 be painted
10549     *
10550     * @see #isVerticalScrollBarEnabled()
10551     */
10552    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10553        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10554            mViewFlags ^= SCROLLBARS_VERTICAL;
10555            computeOpaqueFlags();
10556            resolvePadding();
10557        }
10558    }
10559
10560    /**
10561     * @hide
10562     */
10563    protected void recomputePadding() {
10564        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10565    }
10566
10567    /**
10568     * Define whether scrollbars will fade when the view is not scrolling.
10569     *
10570     * @param fadeScrollbars wheter to enable fading
10571     *
10572     * @attr ref android.R.styleable#View_fadeScrollbars
10573     */
10574    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10575        initScrollCache();
10576        final ScrollabilityCache scrollabilityCache = mScrollCache;
10577        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10578        if (fadeScrollbars) {
10579            scrollabilityCache.state = ScrollabilityCache.OFF;
10580        } else {
10581            scrollabilityCache.state = ScrollabilityCache.ON;
10582        }
10583    }
10584
10585    /**
10586     *
10587     * Returns true if scrollbars will fade when this view is not scrolling
10588     *
10589     * @return true if scrollbar fading is enabled
10590     *
10591     * @attr ref android.R.styleable#View_fadeScrollbars
10592     */
10593    public boolean isScrollbarFadingEnabled() {
10594        return mScrollCache != null && mScrollCache.fadeScrollBars;
10595    }
10596
10597    /**
10598     *
10599     * Returns the delay before scrollbars fade.
10600     *
10601     * @return the delay before scrollbars fade
10602     *
10603     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10604     */
10605    public int getScrollBarDefaultDelayBeforeFade() {
10606        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10607                mScrollCache.scrollBarDefaultDelayBeforeFade;
10608    }
10609
10610    /**
10611     * Define the delay before scrollbars fade.
10612     *
10613     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10614     *
10615     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10616     */
10617    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10618        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10619    }
10620
10621    /**
10622     *
10623     * Returns the scrollbar fade duration.
10624     *
10625     * @return the scrollbar fade duration
10626     *
10627     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10628     */
10629    public int getScrollBarFadeDuration() {
10630        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10631                mScrollCache.scrollBarFadeDuration;
10632    }
10633
10634    /**
10635     * Define the scrollbar fade duration.
10636     *
10637     * @param scrollBarFadeDuration - the scrollbar fade duration
10638     *
10639     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10640     */
10641    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10642        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10643    }
10644
10645    /**
10646     *
10647     * Returns the scrollbar size.
10648     *
10649     * @return the scrollbar size
10650     *
10651     * @attr ref android.R.styleable#View_scrollbarSize
10652     */
10653    public int getScrollBarSize() {
10654        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10655                mScrollCache.scrollBarSize;
10656    }
10657
10658    /**
10659     * Define the scrollbar size.
10660     *
10661     * @param scrollBarSize - the scrollbar size
10662     *
10663     * @attr ref android.R.styleable#View_scrollbarSize
10664     */
10665    public void setScrollBarSize(int scrollBarSize) {
10666        getScrollCache().scrollBarSize = scrollBarSize;
10667    }
10668
10669    /**
10670     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10671     * inset. When inset, they add to the padding of the view. And the scrollbars
10672     * can be drawn inside the padding area or on the edge of the view. For example,
10673     * if a view has a background drawable and you want to draw the scrollbars
10674     * inside the padding specified by the drawable, you can use
10675     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10676     * appear at the edge of the view, ignoring the padding, then you can use
10677     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10678     * @param style the style of the scrollbars. Should be one of
10679     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10680     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10681     * @see #SCROLLBARS_INSIDE_OVERLAY
10682     * @see #SCROLLBARS_INSIDE_INSET
10683     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10684     * @see #SCROLLBARS_OUTSIDE_INSET
10685     *
10686     * @attr ref android.R.styleable#View_scrollbarStyle
10687     */
10688    public void setScrollBarStyle(int style) {
10689        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10690            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10691            computeOpaqueFlags();
10692            resolvePadding();
10693        }
10694    }
10695
10696    /**
10697     * <p>Returns the current scrollbar style.</p>
10698     * @return the current scrollbar style
10699     * @see #SCROLLBARS_INSIDE_OVERLAY
10700     * @see #SCROLLBARS_INSIDE_INSET
10701     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10702     * @see #SCROLLBARS_OUTSIDE_INSET
10703     *
10704     * @attr ref android.R.styleable#View_scrollbarStyle
10705     */
10706    @ViewDebug.ExportedProperty(mapping = {
10707            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10708            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10709            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10710            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10711    })
10712    public int getScrollBarStyle() {
10713        return mViewFlags & SCROLLBARS_STYLE_MASK;
10714    }
10715
10716    /**
10717     * <p>Compute the horizontal range that the horizontal scrollbar
10718     * represents.</p>
10719     *
10720     * <p>The range is expressed in arbitrary units that must be the same as the
10721     * units used by {@link #computeHorizontalScrollExtent()} and
10722     * {@link #computeHorizontalScrollOffset()}.</p>
10723     *
10724     * <p>The default range is the drawing width of this view.</p>
10725     *
10726     * @return the total horizontal range represented by the horizontal
10727     *         scrollbar
10728     *
10729     * @see #computeHorizontalScrollExtent()
10730     * @see #computeHorizontalScrollOffset()
10731     * @see android.widget.ScrollBarDrawable
10732     */
10733    protected int computeHorizontalScrollRange() {
10734        return getWidth();
10735    }
10736
10737    /**
10738     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10739     * within the horizontal range. This value is used to compute the position
10740     * of the thumb within the scrollbar's track.</p>
10741     *
10742     * <p>The range is expressed in arbitrary units that must be the same as the
10743     * units used by {@link #computeHorizontalScrollRange()} and
10744     * {@link #computeHorizontalScrollExtent()}.</p>
10745     *
10746     * <p>The default offset is the scroll offset of this view.</p>
10747     *
10748     * @return the horizontal offset of the scrollbar's thumb
10749     *
10750     * @see #computeHorizontalScrollRange()
10751     * @see #computeHorizontalScrollExtent()
10752     * @see android.widget.ScrollBarDrawable
10753     */
10754    protected int computeHorizontalScrollOffset() {
10755        return mScrollX;
10756    }
10757
10758    /**
10759     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10760     * within the horizontal range. This value is used to compute the length
10761     * of the thumb within the scrollbar's track.</p>
10762     *
10763     * <p>The range is expressed in arbitrary units that must be the same as the
10764     * units used by {@link #computeHorizontalScrollRange()} and
10765     * {@link #computeHorizontalScrollOffset()}.</p>
10766     *
10767     * <p>The default extent is the drawing width of this view.</p>
10768     *
10769     * @return the horizontal extent of the scrollbar's thumb
10770     *
10771     * @see #computeHorizontalScrollRange()
10772     * @see #computeHorizontalScrollOffset()
10773     * @see android.widget.ScrollBarDrawable
10774     */
10775    protected int computeHorizontalScrollExtent() {
10776        return getWidth();
10777    }
10778
10779    /**
10780     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10781     *
10782     * <p>The range is expressed in arbitrary units that must be the same as the
10783     * units used by {@link #computeVerticalScrollExtent()} and
10784     * {@link #computeVerticalScrollOffset()}.</p>
10785     *
10786     * @return the total vertical range represented by the vertical scrollbar
10787     *
10788     * <p>The default range is the drawing height of this view.</p>
10789     *
10790     * @see #computeVerticalScrollExtent()
10791     * @see #computeVerticalScrollOffset()
10792     * @see android.widget.ScrollBarDrawable
10793     */
10794    protected int computeVerticalScrollRange() {
10795        return getHeight();
10796    }
10797
10798    /**
10799     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10800     * within the horizontal range. This value is used to compute the position
10801     * of the thumb within the scrollbar's track.</p>
10802     *
10803     * <p>The range is expressed in arbitrary units that must be the same as the
10804     * units used by {@link #computeVerticalScrollRange()} and
10805     * {@link #computeVerticalScrollExtent()}.</p>
10806     *
10807     * <p>The default offset is the scroll offset of this view.</p>
10808     *
10809     * @return the vertical offset of the scrollbar's thumb
10810     *
10811     * @see #computeVerticalScrollRange()
10812     * @see #computeVerticalScrollExtent()
10813     * @see android.widget.ScrollBarDrawable
10814     */
10815    protected int computeVerticalScrollOffset() {
10816        return mScrollY;
10817    }
10818
10819    /**
10820     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10821     * within the vertical range. This value is used to compute the length
10822     * of the thumb within the scrollbar's track.</p>
10823     *
10824     * <p>The range is expressed in arbitrary units that must be the same as the
10825     * units used by {@link #computeVerticalScrollRange()} and
10826     * {@link #computeVerticalScrollOffset()}.</p>
10827     *
10828     * <p>The default extent is the drawing height of this view.</p>
10829     *
10830     * @return the vertical extent of the scrollbar's thumb
10831     *
10832     * @see #computeVerticalScrollRange()
10833     * @see #computeVerticalScrollOffset()
10834     * @see android.widget.ScrollBarDrawable
10835     */
10836    protected int computeVerticalScrollExtent() {
10837        return getHeight();
10838    }
10839
10840    /**
10841     * Check if this view can be scrolled horizontally in a certain direction.
10842     *
10843     * @param direction Negative to check scrolling left, positive to check scrolling right.
10844     * @return true if this view can be scrolled in the specified direction, false otherwise.
10845     */
10846    public boolean canScrollHorizontally(int direction) {
10847        final int offset = computeHorizontalScrollOffset();
10848        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10849        if (range == 0) return false;
10850        if (direction < 0) {
10851            return offset > 0;
10852        } else {
10853            return offset < range - 1;
10854        }
10855    }
10856
10857    /**
10858     * Check if this view can be scrolled vertically in a certain direction.
10859     *
10860     * @param direction Negative to check scrolling up, positive to check scrolling down.
10861     * @return true if this view can be scrolled in the specified direction, false otherwise.
10862     */
10863    public boolean canScrollVertically(int direction) {
10864        final int offset = computeVerticalScrollOffset();
10865        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10866        if (range == 0) return false;
10867        if (direction < 0) {
10868            return offset > 0;
10869        } else {
10870            return offset < range - 1;
10871        }
10872    }
10873
10874    /**
10875     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10876     * scrollbars are painted only if they have been awakened first.</p>
10877     *
10878     * @param canvas the canvas on which to draw the scrollbars
10879     *
10880     * @see #awakenScrollBars(int)
10881     */
10882    protected final void onDrawScrollBars(Canvas canvas) {
10883        // scrollbars are drawn only when the animation is running
10884        final ScrollabilityCache cache = mScrollCache;
10885        if (cache != null) {
10886
10887            int state = cache.state;
10888
10889            if (state == ScrollabilityCache.OFF) {
10890                return;
10891            }
10892
10893            boolean invalidate = false;
10894
10895            if (state == ScrollabilityCache.FADING) {
10896                // We're fading -- get our fade interpolation
10897                if (cache.interpolatorValues == null) {
10898                    cache.interpolatorValues = new float[1];
10899                }
10900
10901                float[] values = cache.interpolatorValues;
10902
10903                // Stops the animation if we're done
10904                if (cache.scrollBarInterpolator.timeToValues(values) ==
10905                        Interpolator.Result.FREEZE_END) {
10906                    cache.state = ScrollabilityCache.OFF;
10907                } else {
10908                    cache.scrollBar.setAlpha(Math.round(values[0]));
10909                }
10910
10911                // This will make the scroll bars inval themselves after
10912                // drawing. We only want this when we're fading so that
10913                // we prevent excessive redraws
10914                invalidate = true;
10915            } else {
10916                // We're just on -- but we may have been fading before so
10917                // reset alpha
10918                cache.scrollBar.setAlpha(255);
10919            }
10920
10921
10922            final int viewFlags = mViewFlags;
10923
10924            final boolean drawHorizontalScrollBar =
10925                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10926            final boolean drawVerticalScrollBar =
10927                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10928                && !isVerticalScrollBarHidden();
10929
10930            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10931                final int width = mRight - mLeft;
10932                final int height = mBottom - mTop;
10933
10934                final ScrollBarDrawable scrollBar = cache.scrollBar;
10935
10936                final int scrollX = mScrollX;
10937                final int scrollY = mScrollY;
10938                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10939
10940                int left, top, right, bottom;
10941
10942                if (drawHorizontalScrollBar) {
10943                    int size = scrollBar.getSize(false);
10944                    if (size <= 0) {
10945                        size = cache.scrollBarSize;
10946                    }
10947
10948                    scrollBar.setParameters(computeHorizontalScrollRange(),
10949                                            computeHorizontalScrollOffset(),
10950                                            computeHorizontalScrollExtent(), false);
10951                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10952                            getVerticalScrollbarWidth() : 0;
10953                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10954                    left = scrollX + (mPaddingLeft & inside);
10955                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10956                    bottom = top + size;
10957                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10958                    if (invalidate) {
10959                        invalidate(left, top, right, bottom);
10960                    }
10961                }
10962
10963                if (drawVerticalScrollBar) {
10964                    int size = scrollBar.getSize(true);
10965                    if (size <= 0) {
10966                        size = cache.scrollBarSize;
10967                    }
10968
10969                    scrollBar.setParameters(computeVerticalScrollRange(),
10970                                            computeVerticalScrollOffset(),
10971                                            computeVerticalScrollExtent(), true);
10972                    switch (mVerticalScrollbarPosition) {
10973                        default:
10974                        case SCROLLBAR_POSITION_DEFAULT:
10975                        case SCROLLBAR_POSITION_RIGHT:
10976                            left = scrollX + width - size - (mUserPaddingRight & inside);
10977                            break;
10978                        case SCROLLBAR_POSITION_LEFT:
10979                            left = scrollX + (mUserPaddingLeft & inside);
10980                            break;
10981                    }
10982                    top = scrollY + (mPaddingTop & inside);
10983                    right = left + size;
10984                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10985                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10986                    if (invalidate) {
10987                        invalidate(left, top, right, bottom);
10988                    }
10989                }
10990            }
10991        }
10992    }
10993
10994    /**
10995     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10996     * FastScroller is visible.
10997     * @return whether to temporarily hide the vertical scrollbar
10998     * @hide
10999     */
11000    protected boolean isVerticalScrollBarHidden() {
11001        return false;
11002    }
11003
11004    /**
11005     * <p>Draw the horizontal scrollbar if
11006     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11007     *
11008     * @param canvas the canvas on which to draw the scrollbar
11009     * @param scrollBar the scrollbar's drawable
11010     *
11011     * @see #isHorizontalScrollBarEnabled()
11012     * @see #computeHorizontalScrollRange()
11013     * @see #computeHorizontalScrollExtent()
11014     * @see #computeHorizontalScrollOffset()
11015     * @see android.widget.ScrollBarDrawable
11016     * @hide
11017     */
11018    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11019            int l, int t, int r, int b) {
11020        scrollBar.setBounds(l, t, r, b);
11021        scrollBar.draw(canvas);
11022    }
11023
11024    /**
11025     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11026     * returns true.</p>
11027     *
11028     * @param canvas the canvas on which to draw the scrollbar
11029     * @param scrollBar the scrollbar's drawable
11030     *
11031     * @see #isVerticalScrollBarEnabled()
11032     * @see #computeVerticalScrollRange()
11033     * @see #computeVerticalScrollExtent()
11034     * @see #computeVerticalScrollOffset()
11035     * @see android.widget.ScrollBarDrawable
11036     * @hide
11037     */
11038    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11039            int l, int t, int r, int b) {
11040        scrollBar.setBounds(l, t, r, b);
11041        scrollBar.draw(canvas);
11042    }
11043
11044    /**
11045     * Implement this to do your drawing.
11046     *
11047     * @param canvas the canvas on which the background will be drawn
11048     */
11049    protected void onDraw(Canvas canvas) {
11050    }
11051
11052    /*
11053     * Caller is responsible for calling requestLayout if necessary.
11054     * (This allows addViewInLayout to not request a new layout.)
11055     */
11056    void assignParent(ViewParent parent) {
11057        if (mParent == null) {
11058            mParent = parent;
11059        } else if (parent == null) {
11060            mParent = null;
11061        } else {
11062            throw new RuntimeException("view " + this + " being added, but"
11063                    + " it already has a parent");
11064        }
11065    }
11066
11067    /**
11068     * This is called when the view is attached to a window.  At this point it
11069     * has a Surface and will start drawing.  Note that this function is
11070     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11071     * however it may be called any time before the first onDraw -- including
11072     * before or after {@link #onMeasure(int, int)}.
11073     *
11074     * @see #onDetachedFromWindow()
11075     */
11076    protected void onAttachedToWindow() {
11077        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11078            mParent.requestTransparentRegion(this);
11079        }
11080        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11081            initialAwakenScrollBars();
11082            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11083        }
11084        jumpDrawablesToCurrentState();
11085        // Order is important here: LayoutDirection MUST be resolved before Padding
11086        // and TextDirection
11087        resolveLayoutDirection();
11088        resolvePadding();
11089        resolveTextDirection();
11090        resolveTextAlignment();
11091        clearAccessibilityFocus();
11092        if (isFocused()) {
11093            InputMethodManager imm = InputMethodManager.peekInstance();
11094            imm.focusIn(this);
11095        }
11096    }
11097
11098    /**
11099     * @see #onScreenStateChanged(int)
11100     */
11101    void dispatchScreenStateChanged(int screenState) {
11102        onScreenStateChanged(screenState);
11103    }
11104
11105    /**
11106     * This method is called whenever the state of the screen this view is
11107     * attached to changes. A state change will usually occurs when the screen
11108     * turns on or off (whether it happens automatically or the user does it
11109     * manually.)
11110     *
11111     * @param screenState The new state of the screen. Can be either
11112     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11113     */
11114    public void onScreenStateChanged(int screenState) {
11115    }
11116
11117    /**
11118     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11119     */
11120    private boolean hasRtlSupport() {
11121        return mContext.getApplicationInfo().hasRtlSupport();
11122    }
11123
11124    /**
11125     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11126     * that the parent directionality can and will be resolved before its children.
11127     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11128     * @hide
11129     */
11130    public void resolveLayoutDirection() {
11131        // Clear any previous layout direction resolution
11132        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11133
11134        if (hasRtlSupport()) {
11135            // Set resolved depending on layout direction
11136            switch (getLayoutDirection()) {
11137                case LAYOUT_DIRECTION_INHERIT:
11138                    // If this is root view, no need to look at parent's layout dir.
11139                    if (canResolveLayoutDirection()) {
11140                        ViewGroup viewGroup = ((ViewGroup) mParent);
11141
11142                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11143                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11144                        }
11145                    } else {
11146                        // Nothing to do, LTR by default
11147                    }
11148                    break;
11149                case LAYOUT_DIRECTION_RTL:
11150                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11151                    break;
11152                case LAYOUT_DIRECTION_LOCALE:
11153                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11154                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11155                    }
11156                    break;
11157                default:
11158                    // Nothing to do, LTR by default
11159            }
11160        }
11161
11162        // Set to resolved
11163        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11164        onResolvedLayoutDirectionChanged();
11165        // Resolve padding
11166        resolvePadding();
11167    }
11168
11169    /**
11170     * Called when layout direction has been resolved.
11171     *
11172     * The default implementation does nothing.
11173     * @hide
11174     */
11175    public void onResolvedLayoutDirectionChanged() {
11176    }
11177
11178    /**
11179     * Resolve padding depending on layout direction.
11180     * @hide
11181     */
11182    public void resolvePadding() {
11183        // If the user specified the absolute padding (either with android:padding or
11184        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11185        // use the default padding or the padding from the background drawable
11186        // (stored at this point in mPadding*)
11187        int resolvedLayoutDirection = getResolvedLayoutDirection();
11188        switch (resolvedLayoutDirection) {
11189            case LAYOUT_DIRECTION_RTL:
11190                // Start user padding override Right user padding. Otherwise, if Right user
11191                // padding is not defined, use the default Right padding. If Right user padding
11192                // is defined, just use it.
11193                if (mUserPaddingStart >= 0) {
11194                    mUserPaddingRight = mUserPaddingStart;
11195                } else if (mUserPaddingRight < 0) {
11196                    mUserPaddingRight = mPaddingRight;
11197                }
11198                if (mUserPaddingEnd >= 0) {
11199                    mUserPaddingLeft = mUserPaddingEnd;
11200                } else if (mUserPaddingLeft < 0) {
11201                    mUserPaddingLeft = mPaddingLeft;
11202                }
11203                break;
11204            case LAYOUT_DIRECTION_LTR:
11205            default:
11206                // Start user padding override Left user padding. Otherwise, if Left user
11207                // padding is not defined, use the default left padding. If Left user padding
11208                // is defined, just use it.
11209                if (mUserPaddingStart >= 0) {
11210                    mUserPaddingLeft = mUserPaddingStart;
11211                } else if (mUserPaddingLeft < 0) {
11212                    mUserPaddingLeft = mPaddingLeft;
11213                }
11214                if (mUserPaddingEnd >= 0) {
11215                    mUserPaddingRight = mUserPaddingEnd;
11216                } else if (mUserPaddingRight < 0) {
11217                    mUserPaddingRight = mPaddingRight;
11218                }
11219        }
11220
11221        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11222
11223        if(isPaddingRelative()) {
11224            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11225        } else {
11226            recomputePadding();
11227        }
11228        onPaddingChanged(resolvedLayoutDirection);
11229    }
11230
11231    /**
11232     * Resolve padding depending on the layout direction. Subclasses that care about
11233     * padding resolution should override this method. The default implementation does
11234     * nothing.
11235     *
11236     * @param layoutDirection the direction of the layout
11237     *
11238     * @see {@link #LAYOUT_DIRECTION_LTR}
11239     * @see {@link #LAYOUT_DIRECTION_RTL}
11240     * @hide
11241     */
11242    public void onPaddingChanged(int layoutDirection) {
11243    }
11244
11245    /**
11246     * Check if layout direction resolution can be done.
11247     *
11248     * @return true if layout direction resolution can be done otherwise return false.
11249     * @hide
11250     */
11251    public boolean canResolveLayoutDirection() {
11252        switch (getLayoutDirection()) {
11253            case LAYOUT_DIRECTION_INHERIT:
11254                return (mParent != null) && (mParent instanceof ViewGroup);
11255            default:
11256                return true;
11257        }
11258    }
11259
11260    /**
11261     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11262     * when reset is done.
11263     * @hide
11264     */
11265    public void resetResolvedLayoutDirection() {
11266        // Reset the current resolved bits
11267        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11268        onResolvedLayoutDirectionReset();
11269        // Reset also the text direction
11270        resetResolvedTextDirection();
11271    }
11272
11273    /**
11274     * Called during reset of resolved layout direction.
11275     *
11276     * Subclasses need to override this method to clear cached information that depends on the
11277     * resolved layout direction, or to inform child views that inherit their layout direction.
11278     *
11279     * The default implementation does nothing.
11280     * @hide
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     * @hide
11291     */
11292    protected static boolean isLayoutDirectionRtl(Locale locale) {
11293        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11294    }
11295
11296    /**
11297     * This is called when the view is detached from a window.  At this point it
11298     * no longer has a surface for drawing.
11299     *
11300     * @see #onAttachedToWindow()
11301     */
11302    protected void onDetachedFromWindow() {
11303        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11304
11305        removeUnsetPressCallback();
11306        removeLongPressCallback();
11307        removePerformClickCallback();
11308        removeSendViewScrolledAccessibilityEventCallback();
11309
11310        destroyDrawingCache();
11311
11312        destroyLayer(false);
11313
11314        if (mAttachInfo != null) {
11315            if (mDisplayList != null) {
11316                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
11317            }
11318            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11319        } else {
11320            if (mDisplayList != null) {
11321                // Should never happen
11322                mDisplayList.invalidate();
11323            }
11324        }
11325
11326        mCurrentAnimation = null;
11327
11328        resetResolvedLayoutDirection();
11329        resetResolvedTextAlignment();
11330        resetAccessibilityStateChanged();
11331    }
11332
11333    /**
11334     * @return The number of times this view has been attached to a window
11335     */
11336    protected int getWindowAttachCount() {
11337        return mWindowAttachCount;
11338    }
11339
11340    /**
11341     * Retrieve a unique token identifying the window this view is attached to.
11342     * @return Return the window's token for use in
11343     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11344     */
11345    public IBinder getWindowToken() {
11346        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11347    }
11348
11349    /**
11350     * Retrieve a unique token identifying the top-level "real" window of
11351     * the window that this view is attached to.  That is, this is like
11352     * {@link #getWindowToken}, except if the window this view in is a panel
11353     * window (attached to another containing window), then the token of
11354     * the containing window is returned instead.
11355     *
11356     * @return Returns the associated window token, either
11357     * {@link #getWindowToken()} or the containing window's token.
11358     */
11359    public IBinder getApplicationWindowToken() {
11360        AttachInfo ai = mAttachInfo;
11361        if (ai != null) {
11362            IBinder appWindowToken = ai.mPanelParentWindowToken;
11363            if (appWindowToken == null) {
11364                appWindowToken = ai.mWindowToken;
11365            }
11366            return appWindowToken;
11367        }
11368        return null;
11369    }
11370
11371    /**
11372     * Retrieve private session object this view hierarchy is using to
11373     * communicate with the window manager.
11374     * @return the session object to communicate with the window manager
11375     */
11376    /*package*/ IWindowSession getWindowSession() {
11377        return mAttachInfo != null ? mAttachInfo.mSession : null;
11378    }
11379
11380    /**
11381     * @param info the {@link android.view.View.AttachInfo} to associated with
11382     *        this view
11383     */
11384    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11385        //System.out.println("Attached! " + this);
11386        mAttachInfo = info;
11387        mWindowAttachCount++;
11388        // We will need to evaluate the drawable state at least once.
11389        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11390        if (mFloatingTreeObserver != null) {
11391            info.mTreeObserver.merge(mFloatingTreeObserver);
11392            mFloatingTreeObserver = null;
11393        }
11394        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11395            mAttachInfo.mScrollContainers.add(this);
11396            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11397        }
11398        performCollectViewAttributes(mAttachInfo, visibility);
11399        onAttachedToWindow();
11400
11401        ListenerInfo li = mListenerInfo;
11402        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11403                li != null ? li.mOnAttachStateChangeListeners : null;
11404        if (listeners != null && listeners.size() > 0) {
11405            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11406            // perform the dispatching. The iterator is a safe guard against listeners that
11407            // could mutate the list by calling the various add/remove methods. This prevents
11408            // the array from being modified while we iterate it.
11409            for (OnAttachStateChangeListener listener : listeners) {
11410                listener.onViewAttachedToWindow(this);
11411            }
11412        }
11413
11414        int vis = info.mWindowVisibility;
11415        if (vis != GONE) {
11416            onWindowVisibilityChanged(vis);
11417        }
11418        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11419            // If nobody has evaluated the drawable state yet, then do it now.
11420            refreshDrawableState();
11421        }
11422    }
11423
11424    void dispatchDetachedFromWindow() {
11425        AttachInfo info = mAttachInfo;
11426        if (info != null) {
11427            int vis = info.mWindowVisibility;
11428            if (vis != GONE) {
11429                onWindowVisibilityChanged(GONE);
11430            }
11431        }
11432
11433        onDetachedFromWindow();
11434
11435        ListenerInfo li = mListenerInfo;
11436        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11437                li != null ? li.mOnAttachStateChangeListeners : null;
11438        if (listeners != null && listeners.size() > 0) {
11439            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11440            // perform the dispatching. The iterator is a safe guard against listeners that
11441            // could mutate the list by calling the various add/remove methods. This prevents
11442            // the array from being modified while we iterate it.
11443            for (OnAttachStateChangeListener listener : listeners) {
11444                listener.onViewDetachedFromWindow(this);
11445            }
11446        }
11447
11448        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11449            mAttachInfo.mScrollContainers.remove(this);
11450            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11451        }
11452
11453        mAttachInfo = null;
11454    }
11455
11456    /**
11457     * Store this view hierarchy's frozen state into the given container.
11458     *
11459     * @param container The SparseArray in which to save the view's state.
11460     *
11461     * @see #restoreHierarchyState(android.util.SparseArray)
11462     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11463     * @see #onSaveInstanceState()
11464     */
11465    public void saveHierarchyState(SparseArray<Parcelable> container) {
11466        dispatchSaveInstanceState(container);
11467    }
11468
11469    /**
11470     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11471     * this view and its children. May be overridden to modify how freezing happens to a
11472     * view's children; for example, some views may want to not store state for their children.
11473     *
11474     * @param container The SparseArray in which to save the view's state.
11475     *
11476     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11477     * @see #saveHierarchyState(android.util.SparseArray)
11478     * @see #onSaveInstanceState()
11479     */
11480    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11481        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11482            mPrivateFlags &= ~SAVE_STATE_CALLED;
11483            Parcelable state = onSaveInstanceState();
11484            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11485                throw new IllegalStateException(
11486                        "Derived class did not call super.onSaveInstanceState()");
11487            }
11488            if (state != null) {
11489                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11490                // + ": " + state);
11491                container.put(mID, state);
11492            }
11493        }
11494    }
11495
11496    /**
11497     * Hook allowing a view to generate a representation of its internal state
11498     * that can later be used to create a new instance with that same state.
11499     * This state should only contain information that is not persistent or can
11500     * not be reconstructed later. For example, you will never store your
11501     * current position on screen because that will be computed again when a
11502     * new instance of the view is placed in its view hierarchy.
11503     * <p>
11504     * Some examples of things you may store here: the current cursor position
11505     * in a text view (but usually not the text itself since that is stored in a
11506     * content provider or other persistent storage), the currently selected
11507     * item in a list view.
11508     *
11509     * @return Returns a Parcelable object containing the view's current dynamic
11510     *         state, or null if there is nothing interesting to save. The
11511     *         default implementation returns null.
11512     * @see #onRestoreInstanceState(android.os.Parcelable)
11513     * @see #saveHierarchyState(android.util.SparseArray)
11514     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11515     * @see #setSaveEnabled(boolean)
11516     */
11517    protected Parcelable onSaveInstanceState() {
11518        mPrivateFlags |= SAVE_STATE_CALLED;
11519        return BaseSavedState.EMPTY_STATE;
11520    }
11521
11522    /**
11523     * Restore this view hierarchy's frozen state from the given container.
11524     *
11525     * @param container The SparseArray which holds previously frozen states.
11526     *
11527     * @see #saveHierarchyState(android.util.SparseArray)
11528     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11529     * @see #onRestoreInstanceState(android.os.Parcelable)
11530     */
11531    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11532        dispatchRestoreInstanceState(container);
11533    }
11534
11535    /**
11536     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11537     * state for this view and its children. May be overridden to modify how restoring
11538     * happens to a view's children; for example, some views may want to not store state
11539     * for their children.
11540     *
11541     * @param container The SparseArray which holds previously saved state.
11542     *
11543     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11544     * @see #restoreHierarchyState(android.util.SparseArray)
11545     * @see #onRestoreInstanceState(android.os.Parcelable)
11546     */
11547    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11548        if (mID != NO_ID) {
11549            Parcelable state = container.get(mID);
11550            if (state != null) {
11551                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11552                // + ": " + state);
11553                mPrivateFlags &= ~SAVE_STATE_CALLED;
11554                onRestoreInstanceState(state);
11555                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11556                    throw new IllegalStateException(
11557                            "Derived class did not call super.onRestoreInstanceState()");
11558                }
11559            }
11560        }
11561    }
11562
11563    /**
11564     * Hook allowing a view to re-apply a representation of its internal state that had previously
11565     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11566     * null state.
11567     *
11568     * @param state The frozen state that had previously been returned by
11569     *        {@link #onSaveInstanceState}.
11570     *
11571     * @see #onSaveInstanceState()
11572     * @see #restoreHierarchyState(android.util.SparseArray)
11573     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11574     */
11575    protected void onRestoreInstanceState(Parcelable state) {
11576        mPrivateFlags |= SAVE_STATE_CALLED;
11577        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11578            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11579                    + "received " + state.getClass().toString() + " instead. This usually happens "
11580                    + "when two views of different type have the same id in the same hierarchy. "
11581                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11582                    + "other views do not use the same id.");
11583        }
11584    }
11585
11586    /**
11587     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11588     *
11589     * @return the drawing start time in milliseconds
11590     */
11591    public long getDrawingTime() {
11592        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11593    }
11594
11595    /**
11596     * <p>Enables or disables the duplication of the parent's state into this view. When
11597     * duplication is enabled, this view gets its drawable state from its parent rather
11598     * than from its own internal properties.</p>
11599     *
11600     * <p>Note: in the current implementation, setting this property to true after the
11601     * view was added to a ViewGroup might have no effect at all. This property should
11602     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11603     *
11604     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11605     * property is enabled, an exception will be thrown.</p>
11606     *
11607     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11608     * parent, these states should not be affected by this method.</p>
11609     *
11610     * @param enabled True to enable duplication of the parent's drawable state, false
11611     *                to disable it.
11612     *
11613     * @see #getDrawableState()
11614     * @see #isDuplicateParentStateEnabled()
11615     */
11616    public void setDuplicateParentStateEnabled(boolean enabled) {
11617        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11618    }
11619
11620    /**
11621     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11622     *
11623     * @return True if this view's drawable state is duplicated from the parent,
11624     *         false otherwise
11625     *
11626     * @see #getDrawableState()
11627     * @see #setDuplicateParentStateEnabled(boolean)
11628     */
11629    public boolean isDuplicateParentStateEnabled() {
11630        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11631    }
11632
11633    /**
11634     * <p>Specifies the type of layer backing this view. The layer can be
11635     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11636     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11637     *
11638     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11639     * instance that controls how the layer is composed on screen. The following
11640     * properties of the paint are taken into account when composing the layer:</p>
11641     * <ul>
11642     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11643     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11644     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11645     * </ul>
11646     *
11647     * <p>If this view has an alpha value set to < 1.0 by calling
11648     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11649     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11650     * equivalent to setting a hardware layer on this view and providing a paint with
11651     * the desired alpha value.<p>
11652     *
11653     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11654     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11655     * for more information on when and how to use layers.</p>
11656     *
11657     * @param layerType The ype of layer to use with this view, must be one of
11658     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11659     *        {@link #LAYER_TYPE_HARDWARE}
11660     * @param paint The paint used to compose the layer. This argument is optional
11661     *        and can be null. It is ignored when the layer type is
11662     *        {@link #LAYER_TYPE_NONE}
11663     *
11664     * @see #getLayerType()
11665     * @see #LAYER_TYPE_NONE
11666     * @see #LAYER_TYPE_SOFTWARE
11667     * @see #LAYER_TYPE_HARDWARE
11668     * @see #setAlpha(float)
11669     *
11670     * @attr ref android.R.styleable#View_layerType
11671     */
11672    public void setLayerType(int layerType, Paint paint) {
11673        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11674            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11675                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11676        }
11677
11678        if (layerType == mLayerType) {
11679            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11680                mLayerPaint = paint == null ? new Paint() : paint;
11681                invalidateParentCaches();
11682                invalidate(true);
11683            }
11684            return;
11685        }
11686
11687        // Destroy any previous software drawing cache if needed
11688        switch (mLayerType) {
11689            case LAYER_TYPE_HARDWARE:
11690                destroyLayer(false);
11691                // fall through - non-accelerated views may use software layer mechanism instead
11692            case LAYER_TYPE_SOFTWARE:
11693                destroyDrawingCache();
11694                break;
11695            default:
11696                break;
11697        }
11698
11699        mLayerType = layerType;
11700        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11701        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11702        mLocalDirtyRect = layerDisabled ? null : new Rect();
11703
11704        invalidateParentCaches();
11705        invalidate(true);
11706    }
11707
11708    /**
11709     * Indicates whether this view has a static layer. A view with layer type
11710     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11711     * dynamic.
11712     */
11713    boolean hasStaticLayer() {
11714        return true;
11715    }
11716
11717    /**
11718     * Indicates what type of layer is currently associated with this view. By default
11719     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11720     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11721     * for more information on the different types of layers.
11722     *
11723     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11724     *         {@link #LAYER_TYPE_HARDWARE}
11725     *
11726     * @see #setLayerType(int, android.graphics.Paint)
11727     * @see #buildLayer()
11728     * @see #LAYER_TYPE_NONE
11729     * @see #LAYER_TYPE_SOFTWARE
11730     * @see #LAYER_TYPE_HARDWARE
11731     */
11732    public int getLayerType() {
11733        return mLayerType;
11734    }
11735
11736    /**
11737     * Forces this view's layer to be created and this view to be rendered
11738     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11739     * invoking this method will have no effect.
11740     *
11741     * This method can for instance be used to render a view into its layer before
11742     * starting an animation. If this view is complex, rendering into the layer
11743     * before starting the animation will avoid skipping frames.
11744     *
11745     * @throws IllegalStateException If this view is not attached to a window
11746     *
11747     * @see #setLayerType(int, android.graphics.Paint)
11748     */
11749    public void buildLayer() {
11750        if (mLayerType == LAYER_TYPE_NONE) return;
11751
11752        if (mAttachInfo == null) {
11753            throw new IllegalStateException("This view must be attached to a window first");
11754        }
11755
11756        switch (mLayerType) {
11757            case LAYER_TYPE_HARDWARE:
11758                if (mAttachInfo.mHardwareRenderer != null &&
11759                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11760                        mAttachInfo.mHardwareRenderer.validate()) {
11761                    getHardwareLayer();
11762                }
11763                break;
11764            case LAYER_TYPE_SOFTWARE:
11765                buildDrawingCache(true);
11766                break;
11767        }
11768    }
11769
11770    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11771    void flushLayer() {
11772        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11773            mHardwareLayer.flush();
11774        }
11775    }
11776
11777    /**
11778     * <p>Returns a hardware layer that can be used to draw this view again
11779     * without executing its draw method.</p>
11780     *
11781     * @return A HardwareLayer ready to render, or null if an error occurred.
11782     */
11783    HardwareLayer getHardwareLayer() {
11784        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11785                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11786            return null;
11787        }
11788
11789        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11790
11791        final int width = mRight - mLeft;
11792        final int height = mBottom - mTop;
11793
11794        if (width == 0 || height == 0) {
11795            return null;
11796        }
11797
11798        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11799            if (mHardwareLayer == null) {
11800                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11801                        width, height, isOpaque());
11802                mLocalDirtyRect.set(0, 0, width, height);
11803            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11804                mHardwareLayer.resize(width, height);
11805                mLocalDirtyRect.set(0, 0, width, height);
11806            }
11807
11808            // The layer is not valid if the underlying GPU resources cannot be allocated
11809            if (!mHardwareLayer.isValid()) {
11810                return null;
11811            }
11812
11813            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11814            mLocalDirtyRect.setEmpty();
11815        }
11816
11817        return mHardwareLayer;
11818    }
11819
11820    /**
11821     * Destroys this View's hardware layer if possible.
11822     *
11823     * @return True if the layer was destroyed, false otherwise.
11824     *
11825     * @see #setLayerType(int, android.graphics.Paint)
11826     * @see #LAYER_TYPE_HARDWARE
11827     */
11828    boolean destroyLayer(boolean valid) {
11829        if (mHardwareLayer != null) {
11830            AttachInfo info = mAttachInfo;
11831            if (info != null && info.mHardwareRenderer != null &&
11832                    info.mHardwareRenderer.isEnabled() &&
11833                    (valid || info.mHardwareRenderer.validate())) {
11834                mHardwareLayer.destroy();
11835                mHardwareLayer = null;
11836
11837                invalidate(true);
11838                invalidateParentCaches();
11839            }
11840            return true;
11841        }
11842        return false;
11843    }
11844
11845    /**
11846     * Destroys all hardware rendering resources. This method is invoked
11847     * when the system needs to reclaim resources. Upon execution of this
11848     * method, you should free any OpenGL resources created by the view.
11849     *
11850     * Note: you <strong>must</strong> call
11851     * <code>super.destroyHardwareResources()</code> when overriding
11852     * this method.
11853     *
11854     * @hide
11855     */
11856    protected void destroyHardwareResources() {
11857        destroyLayer(true);
11858    }
11859
11860    /**
11861     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11862     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11863     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11864     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11865     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11866     * null.</p>
11867     *
11868     * <p>Enabling the drawing cache is similar to
11869     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11870     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11871     * drawing cache has no effect on rendering because the system uses a different mechanism
11872     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11873     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11874     * for information on how to enable software and hardware layers.</p>
11875     *
11876     * <p>This API can be used to manually generate
11877     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11878     * {@link #getDrawingCache()}.</p>
11879     *
11880     * @param enabled true to enable the drawing cache, false otherwise
11881     *
11882     * @see #isDrawingCacheEnabled()
11883     * @see #getDrawingCache()
11884     * @see #buildDrawingCache()
11885     * @see #setLayerType(int, android.graphics.Paint)
11886     */
11887    public void setDrawingCacheEnabled(boolean enabled) {
11888        mCachingFailed = false;
11889        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11890    }
11891
11892    /**
11893     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11894     *
11895     * @return true if the drawing cache is enabled
11896     *
11897     * @see #setDrawingCacheEnabled(boolean)
11898     * @see #getDrawingCache()
11899     */
11900    @ViewDebug.ExportedProperty(category = "drawing")
11901    public boolean isDrawingCacheEnabled() {
11902        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11903    }
11904
11905    /**
11906     * Debugging utility which recursively outputs the dirty state of a view and its
11907     * descendants.
11908     *
11909     * @hide
11910     */
11911    @SuppressWarnings({"UnusedDeclaration"})
11912    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11913        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11914                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11915                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11916                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11917        if (clear) {
11918            mPrivateFlags &= clearMask;
11919        }
11920        if (this instanceof ViewGroup) {
11921            ViewGroup parent = (ViewGroup) this;
11922            final int count = parent.getChildCount();
11923            for (int i = 0; i < count; i++) {
11924                final View child = parent.getChildAt(i);
11925                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11926            }
11927        }
11928    }
11929
11930    /**
11931     * This method is used by ViewGroup to cause its children to restore or recreate their
11932     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11933     * to recreate its own display list, which would happen if it went through the normal
11934     * draw/dispatchDraw mechanisms.
11935     *
11936     * @hide
11937     */
11938    protected void dispatchGetDisplayList() {}
11939
11940    /**
11941     * A view that is not attached or hardware accelerated cannot create a display list.
11942     * This method checks these conditions and returns the appropriate result.
11943     *
11944     * @return true if view has the ability to create a display list, false otherwise.
11945     *
11946     * @hide
11947     */
11948    public boolean canHaveDisplayList() {
11949        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11950    }
11951
11952    /**
11953     * @return The HardwareRenderer associated with that view or null if hardware rendering
11954     * is not supported or this this has not been attached to a window.
11955     *
11956     * @hide
11957     */
11958    public HardwareRenderer getHardwareRenderer() {
11959        if (mAttachInfo != null) {
11960            return mAttachInfo.mHardwareRenderer;
11961        }
11962        return null;
11963    }
11964
11965    /**
11966     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11967     * Otherwise, the same display list will be returned (after having been rendered into
11968     * along the way, depending on the invalidation state of the view).
11969     *
11970     * @param displayList The previous version of this displayList, could be null.
11971     * @param isLayer Whether the requester of the display list is a layer. If so,
11972     * the view will avoid creating a layer inside the resulting display list.
11973     * @return A new or reused DisplayList object.
11974     */
11975    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11976        if (!canHaveDisplayList()) {
11977            return null;
11978        }
11979
11980        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11981                displayList == null || !displayList.isValid() ||
11982                (!isLayer && mRecreateDisplayList))) {
11983            // Don't need to recreate the display list, just need to tell our
11984            // children to restore/recreate theirs
11985            if (displayList != null && displayList.isValid() &&
11986                    !isLayer && !mRecreateDisplayList) {
11987                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11988                mPrivateFlags &= ~DIRTY_MASK;
11989                dispatchGetDisplayList();
11990
11991                return displayList;
11992            }
11993
11994            if (!isLayer) {
11995                // If we got here, we're recreating it. Mark it as such to ensure that
11996                // we copy in child display lists into ours in drawChild()
11997                mRecreateDisplayList = true;
11998            }
11999            if (displayList == null) {
12000                final String name = getClass().getSimpleName();
12001                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12002                // If we're creating a new display list, make sure our parent gets invalidated
12003                // since they will need to recreate their display list to account for this
12004                // new child display list.
12005                invalidateParentCaches();
12006            }
12007
12008            boolean caching = false;
12009            final HardwareCanvas canvas = displayList.start();
12010            int restoreCount = 0;
12011            int width = mRight - mLeft;
12012            int height = mBottom - mTop;
12013
12014            try {
12015                canvas.setViewport(width, height);
12016                // The dirty rect should always be null for a display list
12017                canvas.onPreDraw(null);
12018                int layerType = (
12019                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12020                        getLayerType() : LAYER_TYPE_NONE;
12021                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12022                    if (layerType == LAYER_TYPE_HARDWARE) {
12023                        final HardwareLayer layer = getHardwareLayer();
12024                        if (layer != null && layer.isValid()) {
12025                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12026                        } else {
12027                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12028                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12029                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12030                        }
12031                        caching = true;
12032                    } else {
12033                        buildDrawingCache(true);
12034                        Bitmap cache = getDrawingCache(true);
12035                        if (cache != null) {
12036                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12037                            caching = true;
12038                        }
12039                    }
12040                } else {
12041
12042                    computeScroll();
12043
12044                    canvas.translate(-mScrollX, -mScrollY);
12045                    if (!isLayer) {
12046                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12047                        mPrivateFlags &= ~DIRTY_MASK;
12048                    }
12049
12050                    // Fast path for layouts with no backgrounds
12051                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12052                        dispatchDraw(canvas);
12053                    } else {
12054                        draw(canvas);
12055                    }
12056                }
12057            } finally {
12058                canvas.onPostDraw();
12059
12060                displayList.end();
12061                displayList.setCaching(caching);
12062                if (isLayer) {
12063                    displayList.setLeftTopRightBottom(0, 0, width, height);
12064                } else {
12065                    setDisplayListProperties(displayList);
12066                }
12067            }
12068        } else if (!isLayer) {
12069            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12070            mPrivateFlags &= ~DIRTY_MASK;
12071        }
12072
12073        return displayList;
12074    }
12075
12076    /**
12077     * Get the DisplayList for the HardwareLayer
12078     *
12079     * @param layer The HardwareLayer whose DisplayList we want
12080     * @return A DisplayList fopr the specified HardwareLayer
12081     */
12082    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12083        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12084        layer.setDisplayList(displayList);
12085        return displayList;
12086    }
12087
12088
12089    /**
12090     * <p>Returns a display list that can be used to draw this view again
12091     * without executing its draw method.</p>
12092     *
12093     * @return A DisplayList ready to replay, or null if caching is not enabled.
12094     *
12095     * @hide
12096     */
12097    public DisplayList getDisplayList() {
12098        mDisplayList = getDisplayList(mDisplayList, false);
12099        return mDisplayList;
12100    }
12101
12102    /**
12103     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12104     *
12105     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12106     *
12107     * @see #getDrawingCache(boolean)
12108     */
12109    public Bitmap getDrawingCache() {
12110        return getDrawingCache(false);
12111    }
12112
12113    /**
12114     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12115     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12116     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12117     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12118     * request the drawing cache by calling this method and draw it on screen if the
12119     * returned bitmap is not null.</p>
12120     *
12121     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12122     * this method will create a bitmap of the same size as this view. Because this bitmap
12123     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12124     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12125     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12126     * size than the view. This implies that your application must be able to handle this
12127     * size.</p>
12128     *
12129     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12130     *        the current density of the screen when the application is in compatibility
12131     *        mode.
12132     *
12133     * @return A bitmap representing this view or null if cache is disabled.
12134     *
12135     * @see #setDrawingCacheEnabled(boolean)
12136     * @see #isDrawingCacheEnabled()
12137     * @see #buildDrawingCache(boolean)
12138     * @see #destroyDrawingCache()
12139     */
12140    public Bitmap getDrawingCache(boolean autoScale) {
12141        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12142            return null;
12143        }
12144        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12145            buildDrawingCache(autoScale);
12146        }
12147        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12148    }
12149
12150    /**
12151     * <p>Frees the resources used by the drawing cache. If you call
12152     * {@link #buildDrawingCache()} manually without calling
12153     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12154     * should cleanup the cache with this method afterwards.</p>
12155     *
12156     * @see #setDrawingCacheEnabled(boolean)
12157     * @see #buildDrawingCache()
12158     * @see #getDrawingCache()
12159     */
12160    public void destroyDrawingCache() {
12161        if (mDrawingCache != null) {
12162            mDrawingCache.recycle();
12163            mDrawingCache = null;
12164        }
12165        if (mUnscaledDrawingCache != null) {
12166            mUnscaledDrawingCache.recycle();
12167            mUnscaledDrawingCache = null;
12168        }
12169    }
12170
12171    /**
12172     * Setting a solid background color for the drawing cache's bitmaps will improve
12173     * performance and memory usage. Note, though that this should only be used if this
12174     * view will always be drawn on top of a solid color.
12175     *
12176     * @param color The background color to use for the drawing cache's bitmap
12177     *
12178     * @see #setDrawingCacheEnabled(boolean)
12179     * @see #buildDrawingCache()
12180     * @see #getDrawingCache()
12181     */
12182    public void setDrawingCacheBackgroundColor(int color) {
12183        if (color != mDrawingCacheBackgroundColor) {
12184            mDrawingCacheBackgroundColor = color;
12185            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12186        }
12187    }
12188
12189    /**
12190     * @see #setDrawingCacheBackgroundColor(int)
12191     *
12192     * @return The background color to used for the drawing cache's bitmap
12193     */
12194    public int getDrawingCacheBackgroundColor() {
12195        return mDrawingCacheBackgroundColor;
12196    }
12197
12198    /**
12199     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12200     *
12201     * @see #buildDrawingCache(boolean)
12202     */
12203    public void buildDrawingCache() {
12204        buildDrawingCache(false);
12205    }
12206
12207    /**
12208     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12209     *
12210     * <p>If you call {@link #buildDrawingCache()} manually without calling
12211     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12212     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12213     *
12214     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12215     * this method will create a bitmap of the same size as this view. Because this bitmap
12216     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12217     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12218     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12219     * size than the view. This implies that your application must be able to handle this
12220     * size.</p>
12221     *
12222     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12223     * you do not need the drawing cache bitmap, calling this method will increase memory
12224     * usage and cause the view to be rendered in software once, thus negatively impacting
12225     * performance.</p>
12226     *
12227     * @see #getDrawingCache()
12228     * @see #destroyDrawingCache()
12229     */
12230    public void buildDrawingCache(boolean autoScale) {
12231        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12232                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12233            mCachingFailed = false;
12234
12235            if (ViewDebug.TRACE_HIERARCHY) {
12236                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
12237            }
12238
12239            int width = mRight - mLeft;
12240            int height = mBottom - mTop;
12241
12242            final AttachInfo attachInfo = mAttachInfo;
12243            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12244
12245            if (autoScale && scalingRequired) {
12246                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12247                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12248            }
12249
12250            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12251            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12252            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12253
12254            if (width <= 0 || height <= 0 ||
12255                     // Projected bitmap size in bytes
12256                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12257                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12258                destroyDrawingCache();
12259                mCachingFailed = true;
12260                return;
12261            }
12262
12263            boolean clear = true;
12264            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12265
12266            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12267                Bitmap.Config quality;
12268                if (!opaque) {
12269                    // Never pick ARGB_4444 because it looks awful
12270                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12271                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12272                        case DRAWING_CACHE_QUALITY_AUTO:
12273                            quality = Bitmap.Config.ARGB_8888;
12274                            break;
12275                        case DRAWING_CACHE_QUALITY_LOW:
12276                            quality = Bitmap.Config.ARGB_8888;
12277                            break;
12278                        case DRAWING_CACHE_QUALITY_HIGH:
12279                            quality = Bitmap.Config.ARGB_8888;
12280                            break;
12281                        default:
12282                            quality = Bitmap.Config.ARGB_8888;
12283                            break;
12284                    }
12285                } else {
12286                    // Optimization for translucent windows
12287                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12288                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12289                }
12290
12291                // Try to cleanup memory
12292                if (bitmap != null) bitmap.recycle();
12293
12294                try {
12295                    bitmap = Bitmap.createBitmap(width, height, quality);
12296                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12297                    if (autoScale) {
12298                        mDrawingCache = bitmap;
12299                    } else {
12300                        mUnscaledDrawingCache = bitmap;
12301                    }
12302                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12303                } catch (OutOfMemoryError e) {
12304                    // If there is not enough memory to create the bitmap cache, just
12305                    // ignore the issue as bitmap caches are not required to draw the
12306                    // view hierarchy
12307                    if (autoScale) {
12308                        mDrawingCache = null;
12309                    } else {
12310                        mUnscaledDrawingCache = null;
12311                    }
12312                    mCachingFailed = true;
12313                    return;
12314                }
12315
12316                clear = drawingCacheBackgroundColor != 0;
12317            }
12318
12319            Canvas canvas;
12320            if (attachInfo != null) {
12321                canvas = attachInfo.mCanvas;
12322                if (canvas == null) {
12323                    canvas = new Canvas();
12324                }
12325                canvas.setBitmap(bitmap);
12326                // Temporarily clobber the cached Canvas in case one of our children
12327                // is also using a drawing cache. Without this, the children would
12328                // steal the canvas by attaching their own bitmap to it and bad, bad
12329                // thing would happen (invisible views, corrupted drawings, etc.)
12330                attachInfo.mCanvas = null;
12331            } else {
12332                // This case should hopefully never or seldom happen
12333                canvas = new Canvas(bitmap);
12334            }
12335
12336            if (clear) {
12337                bitmap.eraseColor(drawingCacheBackgroundColor);
12338            }
12339
12340            computeScroll();
12341            final int restoreCount = canvas.save();
12342
12343            if (autoScale && scalingRequired) {
12344                final float scale = attachInfo.mApplicationScale;
12345                canvas.scale(scale, scale);
12346            }
12347
12348            canvas.translate(-mScrollX, -mScrollY);
12349
12350            mPrivateFlags |= DRAWN;
12351            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12352                    mLayerType != LAYER_TYPE_NONE) {
12353                mPrivateFlags |= DRAWING_CACHE_VALID;
12354            }
12355
12356            // Fast path for layouts with no backgrounds
12357            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12358                if (ViewDebug.TRACE_HIERARCHY) {
12359                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12360                }
12361                mPrivateFlags &= ~DIRTY_MASK;
12362                dispatchDraw(canvas);
12363            } else {
12364                draw(canvas);
12365            }
12366
12367            canvas.restoreToCount(restoreCount);
12368            canvas.setBitmap(null);
12369
12370            if (attachInfo != null) {
12371                // Restore the cached Canvas for our siblings
12372                attachInfo.mCanvas = canvas;
12373            }
12374        }
12375    }
12376
12377    /**
12378     * Create a snapshot of the view into a bitmap.  We should probably make
12379     * some form of this public, but should think about the API.
12380     */
12381    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12382        int width = mRight - mLeft;
12383        int height = mBottom - mTop;
12384
12385        final AttachInfo attachInfo = mAttachInfo;
12386        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12387        width = (int) ((width * scale) + 0.5f);
12388        height = (int) ((height * scale) + 0.5f);
12389
12390        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12391        if (bitmap == null) {
12392            throw new OutOfMemoryError();
12393        }
12394
12395        Resources resources = getResources();
12396        if (resources != null) {
12397            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12398        }
12399
12400        Canvas canvas;
12401        if (attachInfo != null) {
12402            canvas = attachInfo.mCanvas;
12403            if (canvas == null) {
12404                canvas = new Canvas();
12405            }
12406            canvas.setBitmap(bitmap);
12407            // Temporarily clobber the cached Canvas in case one of our children
12408            // is also using a drawing cache. Without this, the children would
12409            // steal the canvas by attaching their own bitmap to it and bad, bad
12410            // things would happen (invisible views, corrupted drawings, etc.)
12411            attachInfo.mCanvas = null;
12412        } else {
12413            // This case should hopefully never or seldom happen
12414            canvas = new Canvas(bitmap);
12415        }
12416
12417        if ((backgroundColor & 0xff000000) != 0) {
12418            bitmap.eraseColor(backgroundColor);
12419        }
12420
12421        computeScroll();
12422        final int restoreCount = canvas.save();
12423        canvas.scale(scale, scale);
12424        canvas.translate(-mScrollX, -mScrollY);
12425
12426        // Temporarily remove the dirty mask
12427        int flags = mPrivateFlags;
12428        mPrivateFlags &= ~DIRTY_MASK;
12429
12430        // Fast path for layouts with no backgrounds
12431        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12432            dispatchDraw(canvas);
12433        } else {
12434            draw(canvas);
12435        }
12436
12437        mPrivateFlags = flags;
12438
12439        canvas.restoreToCount(restoreCount);
12440        canvas.setBitmap(null);
12441
12442        if (attachInfo != null) {
12443            // Restore the cached Canvas for our siblings
12444            attachInfo.mCanvas = canvas;
12445        }
12446
12447        return bitmap;
12448    }
12449
12450    /**
12451     * Indicates whether this View is currently in edit mode. A View is usually
12452     * in edit mode when displayed within a developer tool. For instance, if
12453     * this View is being drawn by a visual user interface builder, this method
12454     * should return true.
12455     *
12456     * Subclasses should check the return value of this method to provide
12457     * different behaviors if their normal behavior might interfere with the
12458     * host environment. For instance: the class spawns a thread in its
12459     * constructor, the drawing code relies on device-specific features, etc.
12460     *
12461     * This method is usually checked in the drawing code of custom widgets.
12462     *
12463     * @return True if this View is in edit mode, false otherwise.
12464     */
12465    public boolean isInEditMode() {
12466        return false;
12467    }
12468
12469    /**
12470     * If the View draws content inside its padding and enables fading edges,
12471     * it needs to support padding offsets. Padding offsets are added to the
12472     * fading edges to extend the length of the fade so that it covers pixels
12473     * drawn inside the padding.
12474     *
12475     * Subclasses of this class should override this method if they need
12476     * to draw content inside the padding.
12477     *
12478     * @return True if padding offset must be applied, false otherwise.
12479     *
12480     * @see #getLeftPaddingOffset()
12481     * @see #getRightPaddingOffset()
12482     * @see #getTopPaddingOffset()
12483     * @see #getBottomPaddingOffset()
12484     *
12485     * @since CURRENT
12486     */
12487    protected boolean isPaddingOffsetRequired() {
12488        return false;
12489    }
12490
12491    /**
12492     * Amount by which to extend the left fading region. Called only when
12493     * {@link #isPaddingOffsetRequired()} returns true.
12494     *
12495     * @return The left padding offset in pixels.
12496     *
12497     * @see #isPaddingOffsetRequired()
12498     *
12499     * @since CURRENT
12500     */
12501    protected int getLeftPaddingOffset() {
12502        return 0;
12503    }
12504
12505    /**
12506     * Amount by which to extend the right fading region. Called only when
12507     * {@link #isPaddingOffsetRequired()} returns true.
12508     *
12509     * @return The right padding offset in pixels.
12510     *
12511     * @see #isPaddingOffsetRequired()
12512     *
12513     * @since CURRENT
12514     */
12515    protected int getRightPaddingOffset() {
12516        return 0;
12517    }
12518
12519    /**
12520     * Amount by which to extend the top fading region. Called only when
12521     * {@link #isPaddingOffsetRequired()} returns true.
12522     *
12523     * @return The top padding offset in pixels.
12524     *
12525     * @see #isPaddingOffsetRequired()
12526     *
12527     * @since CURRENT
12528     */
12529    protected int getTopPaddingOffset() {
12530        return 0;
12531    }
12532
12533    /**
12534     * Amount by which to extend the bottom fading region. Called only when
12535     * {@link #isPaddingOffsetRequired()} returns true.
12536     *
12537     * @return The bottom padding offset in pixels.
12538     *
12539     * @see #isPaddingOffsetRequired()
12540     *
12541     * @since CURRENT
12542     */
12543    protected int getBottomPaddingOffset() {
12544        return 0;
12545    }
12546
12547    /**
12548     * @hide
12549     * @param offsetRequired
12550     */
12551    protected int getFadeTop(boolean offsetRequired) {
12552        int top = mPaddingTop;
12553        if (offsetRequired) top += getTopPaddingOffset();
12554        return top;
12555    }
12556
12557    /**
12558     * @hide
12559     * @param offsetRequired
12560     */
12561    protected int getFadeHeight(boolean offsetRequired) {
12562        int padding = mPaddingTop;
12563        if (offsetRequired) padding += getTopPaddingOffset();
12564        return mBottom - mTop - mPaddingBottom - padding;
12565    }
12566
12567    /**
12568     * <p>Indicates whether this view is attached to a hardware accelerated
12569     * window or not.</p>
12570     *
12571     * <p>Even if this method returns true, it does not mean that every call
12572     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12573     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12574     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12575     * window is hardware accelerated,
12576     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12577     * return false, and this method will return true.</p>
12578     *
12579     * @return True if the view is attached to a window and the window is
12580     *         hardware accelerated; false in any other case.
12581     */
12582    public boolean isHardwareAccelerated() {
12583        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12584    }
12585
12586    /**
12587     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12588     * case of an active Animation being run on the view.
12589     */
12590    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12591            Animation a, boolean scalingRequired) {
12592        Transformation invalidationTransform;
12593        final int flags = parent.mGroupFlags;
12594        final boolean initialized = a.isInitialized();
12595        if (!initialized) {
12596            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12597            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12598            onAnimationStart();
12599        }
12600
12601        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12602        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12603            if (parent.mInvalidationTransformation == null) {
12604                parent.mInvalidationTransformation = new Transformation();
12605            }
12606            invalidationTransform = parent.mInvalidationTransformation;
12607            a.getTransformation(drawingTime, invalidationTransform, 1f);
12608        } else {
12609            invalidationTransform = parent.mChildTransformation;
12610        }
12611        if (more) {
12612            if (!a.willChangeBounds()) {
12613                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12614                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12615                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12616                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12617                    // The child need to draw an animation, potentially offscreen, so
12618                    // make sure we do not cancel invalidate requests
12619                    parent.mPrivateFlags |= DRAW_ANIMATION;
12620                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12621                }
12622            } else {
12623                if (parent.mInvalidateRegion == null) {
12624                    parent.mInvalidateRegion = new RectF();
12625                }
12626                final RectF region = parent.mInvalidateRegion;
12627                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12628                        invalidationTransform);
12629
12630                // The child need to draw an animation, potentially offscreen, so
12631                // make sure we do not cancel invalidate requests
12632                parent.mPrivateFlags |= DRAW_ANIMATION;
12633
12634                final int left = mLeft + (int) region.left;
12635                final int top = mTop + (int) region.top;
12636                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12637                        top + (int) (region.height() + .5f));
12638            }
12639        }
12640        return more;
12641    }
12642
12643    void setDisplayListProperties() {
12644        setDisplayListProperties(mDisplayList);
12645    }
12646
12647    /**
12648     * This method is called by getDisplayList() when a display list is created or re-rendered.
12649     * It sets or resets the current value of all properties on that display list (resetting is
12650     * necessary when a display list is being re-created, because we need to make sure that
12651     * previously-set transform values
12652     */
12653    void setDisplayListProperties(DisplayList displayList) {
12654        if (displayList != null) {
12655            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12656            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12657            if (mParent instanceof ViewGroup) {
12658                displayList.setClipChildren(
12659                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12660            }
12661            float alpha = 1;
12662            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12663                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12664                ViewGroup parentVG = (ViewGroup) mParent;
12665                final boolean hasTransform =
12666                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12667                if (hasTransform) {
12668                    Transformation transform = parentVG.mChildTransformation;
12669                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12670                    if (transformType != Transformation.TYPE_IDENTITY) {
12671                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12672                            alpha = transform.getAlpha();
12673                        }
12674                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12675                            displayList.setStaticMatrix(transform.getMatrix());
12676                        }
12677                    }
12678                }
12679            }
12680            if (mTransformationInfo != null) {
12681                alpha *= mTransformationInfo.mAlpha;
12682                if (alpha < 1) {
12683                    final int multipliedAlpha = (int) (255 * alpha);
12684                    if (onSetAlpha(multipliedAlpha)) {
12685                        alpha = 1;
12686                    }
12687                }
12688                displayList.setTransformationInfo(alpha,
12689                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12690                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12691                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12692                        mTransformationInfo.mScaleY);
12693                if (mTransformationInfo.mCamera == null) {
12694                    mTransformationInfo.mCamera = new Camera();
12695                    mTransformationInfo.matrix3D = new Matrix();
12696                }
12697                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12698                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12699                    displayList.setPivotX(getPivotX());
12700                    displayList.setPivotY(getPivotY());
12701                }
12702            } else if (alpha < 1) {
12703                displayList.setAlpha(alpha);
12704            }
12705        }
12706    }
12707
12708    /**
12709     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12710     * This draw() method is an implementation detail and is not intended to be overridden or
12711     * to be called from anywhere else other than ViewGroup.drawChild().
12712     */
12713    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12714        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12715        boolean more = false;
12716        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12717        final int flags = parent.mGroupFlags;
12718
12719        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12720            parent.mChildTransformation.clear();
12721            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12722        }
12723
12724        Transformation transformToApply = null;
12725        boolean concatMatrix = false;
12726
12727        boolean scalingRequired = false;
12728        boolean caching;
12729        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12730
12731        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12732        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12733                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12734            caching = true;
12735            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12736            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12737        } else {
12738            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12739        }
12740
12741        final Animation a = getAnimation();
12742        if (a != null) {
12743            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12744            concatMatrix = a.willChangeTransformationMatrix();
12745            transformToApply = parent.mChildTransformation;
12746        } else if (!useDisplayListProperties &&
12747                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12748            final boolean hasTransform =
12749                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12750            if (hasTransform) {
12751                final int transformType = parent.mChildTransformation.getTransformationType();
12752                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12753                        parent.mChildTransformation : null;
12754                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12755            }
12756        }
12757
12758        concatMatrix |= !childHasIdentityMatrix;
12759
12760        // Sets the flag as early as possible to allow draw() implementations
12761        // to call invalidate() successfully when doing animations
12762        mPrivateFlags |= DRAWN;
12763
12764        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12765                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12766            return more;
12767        }
12768
12769        if (hardwareAccelerated) {
12770            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12771            // retain the flag's value temporarily in the mRecreateDisplayList flag
12772            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12773            mPrivateFlags &= ~INVALIDATED;
12774        }
12775
12776        computeScroll();
12777
12778        final int sx = mScrollX;
12779        final int sy = mScrollY;
12780
12781        DisplayList displayList = null;
12782        Bitmap cache = null;
12783        boolean hasDisplayList = false;
12784        if (caching) {
12785            if (!hardwareAccelerated) {
12786                if (layerType != LAYER_TYPE_NONE) {
12787                    layerType = LAYER_TYPE_SOFTWARE;
12788                    buildDrawingCache(true);
12789                }
12790                cache = getDrawingCache(true);
12791            } else {
12792                switch (layerType) {
12793                    case LAYER_TYPE_SOFTWARE:
12794                        if (useDisplayListProperties) {
12795                            hasDisplayList = canHaveDisplayList();
12796                        } else {
12797                            buildDrawingCache(true);
12798                            cache = getDrawingCache(true);
12799                        }
12800                        break;
12801                    case LAYER_TYPE_HARDWARE:
12802                        if (useDisplayListProperties) {
12803                            hasDisplayList = canHaveDisplayList();
12804                        }
12805                        break;
12806                    case LAYER_TYPE_NONE:
12807                        // Delay getting the display list until animation-driven alpha values are
12808                        // set up and possibly passed on to the view
12809                        hasDisplayList = canHaveDisplayList();
12810                        break;
12811                }
12812            }
12813        }
12814        useDisplayListProperties &= hasDisplayList;
12815        if (useDisplayListProperties) {
12816            displayList = getDisplayList();
12817            if (!displayList.isValid()) {
12818                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12819                // to getDisplayList(), the display list will be marked invalid and we should not
12820                // try to use it again.
12821                displayList = null;
12822                hasDisplayList = false;
12823                useDisplayListProperties = false;
12824            }
12825        }
12826
12827        final boolean hasNoCache = cache == null || hasDisplayList;
12828        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12829                layerType != LAYER_TYPE_HARDWARE;
12830
12831        int restoreTo = -1;
12832        if (!useDisplayListProperties || transformToApply != null) {
12833            restoreTo = canvas.save();
12834        }
12835        if (offsetForScroll) {
12836            canvas.translate(mLeft - sx, mTop - sy);
12837        } else {
12838            if (!useDisplayListProperties) {
12839                canvas.translate(mLeft, mTop);
12840            }
12841            if (scalingRequired) {
12842                if (useDisplayListProperties) {
12843                    // TODO: Might not need this if we put everything inside the DL
12844                    restoreTo = canvas.save();
12845                }
12846                // mAttachInfo cannot be null, otherwise scalingRequired == false
12847                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12848                canvas.scale(scale, scale);
12849            }
12850        }
12851
12852        float alpha = useDisplayListProperties ? 1 : getAlpha();
12853        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12854            if (transformToApply != null || !childHasIdentityMatrix) {
12855                int transX = 0;
12856                int transY = 0;
12857
12858                if (offsetForScroll) {
12859                    transX = -sx;
12860                    transY = -sy;
12861                }
12862
12863                if (transformToApply != null) {
12864                    if (concatMatrix) {
12865                        if (useDisplayListProperties) {
12866                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12867                        } else {
12868                            // Undo the scroll translation, apply the transformation matrix,
12869                            // then redo the scroll translate to get the correct result.
12870                            canvas.translate(-transX, -transY);
12871                            canvas.concat(transformToApply.getMatrix());
12872                            canvas.translate(transX, transY);
12873                        }
12874                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12875                    }
12876
12877                    float transformAlpha = transformToApply.getAlpha();
12878                    if (transformAlpha < 1) {
12879                        alpha *= transformToApply.getAlpha();
12880                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12881                    }
12882                }
12883
12884                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12885                    canvas.translate(-transX, -transY);
12886                    canvas.concat(getMatrix());
12887                    canvas.translate(transX, transY);
12888                }
12889            }
12890
12891            if (alpha < 1) {
12892                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12893                if (hasNoCache) {
12894                    final int multipliedAlpha = (int) (255 * alpha);
12895                    if (!onSetAlpha(multipliedAlpha)) {
12896                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12897                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12898                                layerType != LAYER_TYPE_NONE) {
12899                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12900                        }
12901                        if (useDisplayListProperties) {
12902                            displayList.setAlpha(alpha * getAlpha());
12903                        } else  if (layerType == LAYER_TYPE_NONE) {
12904                            final int scrollX = hasDisplayList ? 0 : sx;
12905                            final int scrollY = hasDisplayList ? 0 : sy;
12906                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12907                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12908                        }
12909                    } else {
12910                        // Alpha is handled by the child directly, clobber the layer's alpha
12911                        mPrivateFlags |= ALPHA_SET;
12912                    }
12913                }
12914            }
12915        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12916            onSetAlpha(255);
12917            mPrivateFlags &= ~ALPHA_SET;
12918        }
12919
12920        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12921                !useDisplayListProperties) {
12922            if (offsetForScroll) {
12923                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12924            } else {
12925                if (!scalingRequired || cache == null) {
12926                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12927                } else {
12928                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12929                }
12930            }
12931        }
12932
12933        if (!useDisplayListProperties && hasDisplayList) {
12934            displayList = getDisplayList();
12935            if (!displayList.isValid()) {
12936                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12937                // to getDisplayList(), the display list will be marked invalid and we should not
12938                // try to use it again.
12939                displayList = null;
12940                hasDisplayList = false;
12941            }
12942        }
12943
12944        if (hasNoCache) {
12945            boolean layerRendered = false;
12946            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12947                final HardwareLayer layer = getHardwareLayer();
12948                if (layer != null && layer.isValid()) {
12949                    mLayerPaint.setAlpha((int) (alpha * 255));
12950                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12951                    layerRendered = true;
12952                } else {
12953                    final int scrollX = hasDisplayList ? 0 : sx;
12954                    final int scrollY = hasDisplayList ? 0 : sy;
12955                    canvas.saveLayer(scrollX, scrollY,
12956                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12957                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12958                }
12959            }
12960
12961            if (!layerRendered) {
12962                if (!hasDisplayList) {
12963                    // Fast path for layouts with no backgrounds
12964                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12965                        if (ViewDebug.TRACE_HIERARCHY) {
12966                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12967                        }
12968                        mPrivateFlags &= ~DIRTY_MASK;
12969                        dispatchDraw(canvas);
12970                    } else {
12971                        draw(canvas);
12972                    }
12973                } else {
12974                    mPrivateFlags &= ~DIRTY_MASK;
12975                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
12976                }
12977            }
12978        } else if (cache != null) {
12979            mPrivateFlags &= ~DIRTY_MASK;
12980            Paint cachePaint;
12981
12982            if (layerType == LAYER_TYPE_NONE) {
12983                cachePaint = parent.mCachePaint;
12984                if (cachePaint == null) {
12985                    cachePaint = new Paint();
12986                    cachePaint.setDither(false);
12987                    parent.mCachePaint = cachePaint;
12988                }
12989                if (alpha < 1) {
12990                    cachePaint.setAlpha((int) (alpha * 255));
12991                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12992                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12993                    cachePaint.setAlpha(255);
12994                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12995                }
12996            } else {
12997                cachePaint = mLayerPaint;
12998                cachePaint.setAlpha((int) (alpha * 255));
12999            }
13000            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13001        }
13002
13003        if (restoreTo >= 0) {
13004            canvas.restoreToCount(restoreTo);
13005        }
13006
13007        if (a != null && !more) {
13008            if (!hardwareAccelerated && !a.getFillAfter()) {
13009                onSetAlpha(255);
13010            }
13011            parent.finishAnimatingView(this, a);
13012        }
13013
13014        if (more && hardwareAccelerated) {
13015            // invalidation is the trigger to recreate display lists, so if we're using
13016            // display lists to render, force an invalidate to allow the animation to
13017            // continue drawing another frame
13018            parent.invalidate(true);
13019            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13020                // alpha animations should cause the child to recreate its display list
13021                invalidate(true);
13022            }
13023        }
13024
13025        mRecreateDisplayList = false;
13026
13027        return more;
13028    }
13029
13030    /**
13031     * Manually render this view (and all of its children) to the given Canvas.
13032     * The view must have already done a full layout before this function is
13033     * called.  When implementing a view, implement
13034     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13035     * If you do need to override this method, call the superclass version.
13036     *
13037     * @param canvas The Canvas to which the View is rendered.
13038     */
13039    public void draw(Canvas canvas) {
13040        if (ViewDebug.TRACE_HIERARCHY) {
13041            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
13042        }
13043
13044        final int privateFlags = mPrivateFlags;
13045        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13046                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13047        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13048
13049        /*
13050         * Draw traversal performs several drawing steps which must be executed
13051         * in the appropriate order:
13052         *
13053         *      1. Draw the background
13054         *      2. If necessary, save the canvas' layers to prepare for fading
13055         *      3. Draw view's content
13056         *      4. Draw children
13057         *      5. If necessary, draw the fading edges and restore layers
13058         *      6. Draw decorations (scrollbars for instance)
13059         */
13060
13061        // Step 1, draw the background, if needed
13062        int saveCount;
13063
13064        if (!dirtyOpaque) {
13065            final Drawable background = mBackground;
13066            if (background != null) {
13067                final int scrollX = mScrollX;
13068                final int scrollY = mScrollY;
13069
13070                if (mBackgroundSizeChanged) {
13071                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13072                    mBackgroundSizeChanged = false;
13073                }
13074
13075                if ((scrollX | scrollY) == 0) {
13076                    background.draw(canvas);
13077                } else {
13078                    canvas.translate(scrollX, scrollY);
13079                    background.draw(canvas);
13080                    canvas.translate(-scrollX, -scrollY);
13081                }
13082            }
13083        }
13084
13085        // skip step 2 & 5 if possible (common case)
13086        final int viewFlags = mViewFlags;
13087        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13088        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13089        if (!verticalEdges && !horizontalEdges) {
13090            // Step 3, draw the content
13091            if (!dirtyOpaque) onDraw(canvas);
13092
13093            // Step 4, draw the children
13094            dispatchDraw(canvas);
13095
13096            // Step 6, draw decorations (scrollbars)
13097            onDrawScrollBars(canvas);
13098
13099            // we're done...
13100            return;
13101        }
13102
13103        /*
13104         * Here we do the full fledged routine...
13105         * (this is an uncommon case where speed matters less,
13106         * this is why we repeat some of the tests that have been
13107         * done above)
13108         */
13109
13110        boolean drawTop = false;
13111        boolean drawBottom = false;
13112        boolean drawLeft = false;
13113        boolean drawRight = false;
13114
13115        float topFadeStrength = 0.0f;
13116        float bottomFadeStrength = 0.0f;
13117        float leftFadeStrength = 0.0f;
13118        float rightFadeStrength = 0.0f;
13119
13120        // Step 2, save the canvas' layers
13121        int paddingLeft = mPaddingLeft;
13122
13123        final boolean offsetRequired = isPaddingOffsetRequired();
13124        if (offsetRequired) {
13125            paddingLeft += getLeftPaddingOffset();
13126        }
13127
13128        int left = mScrollX + paddingLeft;
13129        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13130        int top = mScrollY + getFadeTop(offsetRequired);
13131        int bottom = top + getFadeHeight(offsetRequired);
13132
13133        if (offsetRequired) {
13134            right += getRightPaddingOffset();
13135            bottom += getBottomPaddingOffset();
13136        }
13137
13138        final ScrollabilityCache scrollabilityCache = mScrollCache;
13139        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13140        int length = (int) fadeHeight;
13141
13142        // clip the fade length if top and bottom fades overlap
13143        // overlapping fades produce odd-looking artifacts
13144        if (verticalEdges && (top + length > bottom - length)) {
13145            length = (bottom - top) / 2;
13146        }
13147
13148        // also clip horizontal fades if necessary
13149        if (horizontalEdges && (left + length > right - length)) {
13150            length = (right - left) / 2;
13151        }
13152
13153        if (verticalEdges) {
13154            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13155            drawTop = topFadeStrength * fadeHeight > 1.0f;
13156            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13157            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13158        }
13159
13160        if (horizontalEdges) {
13161            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13162            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13163            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13164            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13165        }
13166
13167        saveCount = canvas.getSaveCount();
13168
13169        int solidColor = getSolidColor();
13170        if (solidColor == 0) {
13171            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13172
13173            if (drawTop) {
13174                canvas.saveLayer(left, top, right, top + length, null, flags);
13175            }
13176
13177            if (drawBottom) {
13178                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13179            }
13180
13181            if (drawLeft) {
13182                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13183            }
13184
13185            if (drawRight) {
13186                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13187            }
13188        } else {
13189            scrollabilityCache.setFadeColor(solidColor);
13190        }
13191
13192        // Step 3, draw the content
13193        if (!dirtyOpaque) onDraw(canvas);
13194
13195        // Step 4, draw the children
13196        dispatchDraw(canvas);
13197
13198        // Step 5, draw the fade effect and restore layers
13199        final Paint p = scrollabilityCache.paint;
13200        final Matrix matrix = scrollabilityCache.matrix;
13201        final Shader fade = scrollabilityCache.shader;
13202
13203        if (drawTop) {
13204            matrix.setScale(1, fadeHeight * topFadeStrength);
13205            matrix.postTranslate(left, top);
13206            fade.setLocalMatrix(matrix);
13207            canvas.drawRect(left, top, right, top + length, p);
13208        }
13209
13210        if (drawBottom) {
13211            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13212            matrix.postRotate(180);
13213            matrix.postTranslate(left, bottom);
13214            fade.setLocalMatrix(matrix);
13215            canvas.drawRect(left, bottom - length, right, bottom, p);
13216        }
13217
13218        if (drawLeft) {
13219            matrix.setScale(1, fadeHeight * leftFadeStrength);
13220            matrix.postRotate(-90);
13221            matrix.postTranslate(left, top);
13222            fade.setLocalMatrix(matrix);
13223            canvas.drawRect(left, top, left + length, bottom, p);
13224        }
13225
13226        if (drawRight) {
13227            matrix.setScale(1, fadeHeight * rightFadeStrength);
13228            matrix.postRotate(90);
13229            matrix.postTranslate(right, top);
13230            fade.setLocalMatrix(matrix);
13231            canvas.drawRect(right - length, top, right, bottom, p);
13232        }
13233
13234        canvas.restoreToCount(saveCount);
13235
13236        // Step 6, draw decorations (scrollbars)
13237        onDrawScrollBars(canvas);
13238    }
13239
13240    /**
13241     * Override this if your view is known to always be drawn on top of a solid color background,
13242     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13243     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13244     * should be set to 0xFF.
13245     *
13246     * @see #setVerticalFadingEdgeEnabled(boolean)
13247     * @see #setHorizontalFadingEdgeEnabled(boolean)
13248     *
13249     * @return The known solid color background for this view, or 0 if the color may vary
13250     */
13251    @ViewDebug.ExportedProperty(category = "drawing")
13252    public int getSolidColor() {
13253        return 0;
13254    }
13255
13256    /**
13257     * Build a human readable string representation of the specified view flags.
13258     *
13259     * @param flags the view flags to convert to a string
13260     * @return a String representing the supplied flags
13261     */
13262    private static String printFlags(int flags) {
13263        String output = "";
13264        int numFlags = 0;
13265        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13266            output += "TAKES_FOCUS";
13267            numFlags++;
13268        }
13269
13270        switch (flags & VISIBILITY_MASK) {
13271        case INVISIBLE:
13272            if (numFlags > 0) {
13273                output += " ";
13274            }
13275            output += "INVISIBLE";
13276            // USELESS HERE numFlags++;
13277            break;
13278        case GONE:
13279            if (numFlags > 0) {
13280                output += " ";
13281            }
13282            output += "GONE";
13283            // USELESS HERE numFlags++;
13284            break;
13285        default:
13286            break;
13287        }
13288        return output;
13289    }
13290
13291    /**
13292     * Build a human readable string representation of the specified private
13293     * view flags.
13294     *
13295     * @param privateFlags the private view flags to convert to a string
13296     * @return a String representing the supplied flags
13297     */
13298    private static String printPrivateFlags(int privateFlags) {
13299        String output = "";
13300        int numFlags = 0;
13301
13302        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13303            output += "WANTS_FOCUS";
13304            numFlags++;
13305        }
13306
13307        if ((privateFlags & FOCUSED) == FOCUSED) {
13308            if (numFlags > 0) {
13309                output += " ";
13310            }
13311            output += "FOCUSED";
13312            numFlags++;
13313        }
13314
13315        if ((privateFlags & SELECTED) == SELECTED) {
13316            if (numFlags > 0) {
13317                output += " ";
13318            }
13319            output += "SELECTED";
13320            numFlags++;
13321        }
13322
13323        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13324            if (numFlags > 0) {
13325                output += " ";
13326            }
13327            output += "IS_ROOT_NAMESPACE";
13328            numFlags++;
13329        }
13330
13331        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13332            if (numFlags > 0) {
13333                output += " ";
13334            }
13335            output += "HAS_BOUNDS";
13336            numFlags++;
13337        }
13338
13339        if ((privateFlags & DRAWN) == DRAWN) {
13340            if (numFlags > 0) {
13341                output += " ";
13342            }
13343            output += "DRAWN";
13344            // USELESS HERE numFlags++;
13345        }
13346        return output;
13347    }
13348
13349    /**
13350     * <p>Indicates whether or not this view's layout will be requested during
13351     * the next hierarchy layout pass.</p>
13352     *
13353     * @return true if the layout will be forced during next layout pass
13354     */
13355    public boolean isLayoutRequested() {
13356        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13357    }
13358
13359    /**
13360     * Assign a size and position to a view and all of its
13361     * descendants
13362     *
13363     * <p>This is the second phase of the layout mechanism.
13364     * (The first is measuring). In this phase, each parent calls
13365     * layout on all of its children to position them.
13366     * This is typically done using the child measurements
13367     * that were stored in the measure pass().</p>
13368     *
13369     * <p>Derived classes should not override this method.
13370     * Derived classes with children should override
13371     * onLayout. In that method, they should
13372     * call layout on each of their children.</p>
13373     *
13374     * @param l Left position, relative to parent
13375     * @param t Top position, relative to parent
13376     * @param r Right position, relative to parent
13377     * @param b Bottom position, relative to parent
13378     */
13379    @SuppressWarnings({"unchecked"})
13380    public void layout(int l, int t, int r, int b) {
13381        int oldL = mLeft;
13382        int oldT = mTop;
13383        int oldB = mBottom;
13384        int oldR = mRight;
13385        boolean changed = setFrame(l, t, r, b);
13386        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13387            if (ViewDebug.TRACE_HIERARCHY) {
13388                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13389            }
13390
13391            onLayout(changed, l, t, r, b);
13392            mPrivateFlags &= ~LAYOUT_REQUIRED;
13393
13394            ListenerInfo li = mListenerInfo;
13395            if (li != null && li.mOnLayoutChangeListeners != null) {
13396                ArrayList<OnLayoutChangeListener> listenersCopy =
13397                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13398                int numListeners = listenersCopy.size();
13399                for (int i = 0; i < numListeners; ++i) {
13400                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13401                }
13402            }
13403        }
13404        mPrivateFlags &= ~FORCE_LAYOUT;
13405    }
13406
13407    /**
13408     * Called from layout when this view should
13409     * assign a size and position to each of its children.
13410     *
13411     * Derived classes with children should override
13412     * this method and call layout on each of
13413     * their children.
13414     * @param changed This is a new size or position for this view
13415     * @param left Left position, relative to parent
13416     * @param top Top position, relative to parent
13417     * @param right Right position, relative to parent
13418     * @param bottom Bottom position, relative to parent
13419     */
13420    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13421    }
13422
13423    /**
13424     * Assign a size and position to this view.
13425     *
13426     * This is called from layout.
13427     *
13428     * @param left Left position, relative to parent
13429     * @param top Top position, relative to parent
13430     * @param right Right position, relative to parent
13431     * @param bottom Bottom position, relative to parent
13432     * @return true if the new size and position are different than the
13433     *         previous ones
13434     * {@hide}
13435     */
13436    protected boolean setFrame(int left, int top, int right, int bottom) {
13437        boolean changed = false;
13438
13439        if (DBG) {
13440            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13441                    + right + "," + bottom + ")");
13442        }
13443
13444        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13445            changed = true;
13446
13447            // Remember our drawn bit
13448            int drawn = mPrivateFlags & DRAWN;
13449
13450            int oldWidth = mRight - mLeft;
13451            int oldHeight = mBottom - mTop;
13452            int newWidth = right - left;
13453            int newHeight = bottom - top;
13454            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13455
13456            // Invalidate our old position
13457            invalidate(sizeChanged);
13458
13459            mLeft = left;
13460            mTop = top;
13461            mRight = right;
13462            mBottom = bottom;
13463            if (mDisplayList != null) {
13464                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13465            }
13466
13467            mPrivateFlags |= HAS_BOUNDS;
13468
13469
13470            if (sizeChanged) {
13471                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13472                    // A change in dimension means an auto-centered pivot point changes, too
13473                    if (mTransformationInfo != null) {
13474                        mTransformationInfo.mMatrixDirty = true;
13475                    }
13476                }
13477                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13478            }
13479
13480            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13481                // If we are visible, force the DRAWN bit to on so that
13482                // this invalidate will go through (at least to our parent).
13483                // This is because someone may have invalidated this view
13484                // before this call to setFrame came in, thereby clearing
13485                // the DRAWN bit.
13486                mPrivateFlags |= DRAWN;
13487                invalidate(sizeChanged);
13488                // parent display list may need to be recreated based on a change in the bounds
13489                // of any child
13490                invalidateParentCaches();
13491            }
13492
13493            // Reset drawn bit to original value (invalidate turns it off)
13494            mPrivateFlags |= drawn;
13495
13496            mBackgroundSizeChanged = true;
13497        }
13498        return changed;
13499    }
13500
13501    /**
13502     * Finalize inflating a view from XML.  This is called as the last phase
13503     * of inflation, after all child views have been added.
13504     *
13505     * <p>Even if the subclass overrides onFinishInflate, they should always be
13506     * sure to call the super method, so that we get called.
13507     */
13508    protected void onFinishInflate() {
13509    }
13510
13511    /**
13512     * Returns the resources associated with this view.
13513     *
13514     * @return Resources object.
13515     */
13516    public Resources getResources() {
13517        return mResources;
13518    }
13519
13520    /**
13521     * Invalidates the specified Drawable.
13522     *
13523     * @param drawable the drawable to invalidate
13524     */
13525    public void invalidateDrawable(Drawable drawable) {
13526        if (verifyDrawable(drawable)) {
13527            final Rect dirty = drawable.getBounds();
13528            final int scrollX = mScrollX;
13529            final int scrollY = mScrollY;
13530
13531            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13532                    dirty.right + scrollX, dirty.bottom + scrollY);
13533        }
13534    }
13535
13536    /**
13537     * Schedules an action on a drawable to occur at a specified time.
13538     *
13539     * @param who the recipient of the action
13540     * @param what the action to run on the drawable
13541     * @param when the time at which the action must occur. Uses the
13542     *        {@link SystemClock#uptimeMillis} timebase.
13543     */
13544    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13545        if (verifyDrawable(who) && what != null) {
13546            final long delay = when - SystemClock.uptimeMillis();
13547            if (mAttachInfo != null) {
13548                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13549                        Choreographer.CALLBACK_ANIMATION, what, who,
13550                        Choreographer.subtractFrameDelay(delay));
13551            } else {
13552                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13553            }
13554        }
13555    }
13556
13557    /**
13558     * Cancels a scheduled action on a drawable.
13559     *
13560     * @param who the recipient of the action
13561     * @param what the action to cancel
13562     */
13563    public void unscheduleDrawable(Drawable who, Runnable what) {
13564        if (verifyDrawable(who) && what != null) {
13565            if (mAttachInfo != null) {
13566                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13567                        Choreographer.CALLBACK_ANIMATION, what, who);
13568            } else {
13569                ViewRootImpl.getRunQueue().removeCallbacks(what);
13570            }
13571        }
13572    }
13573
13574    /**
13575     * Unschedule any events associated with the given Drawable.  This can be
13576     * used when selecting a new Drawable into a view, so that the previous
13577     * one is completely unscheduled.
13578     *
13579     * @param who The Drawable to unschedule.
13580     *
13581     * @see #drawableStateChanged
13582     */
13583    public void unscheduleDrawable(Drawable who) {
13584        if (mAttachInfo != null && who != null) {
13585            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13586                    Choreographer.CALLBACK_ANIMATION, null, who);
13587        }
13588    }
13589
13590    /**
13591    * Return the layout direction of a given Drawable.
13592    *
13593    * @param who the Drawable to query
13594    * @hide
13595    */
13596    public int getResolvedLayoutDirection(Drawable who) {
13597        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13598    }
13599
13600    /**
13601     * If your view subclass is displaying its own Drawable objects, it should
13602     * override this function and return true for any Drawable it is
13603     * displaying.  This allows animations for those drawables to be
13604     * scheduled.
13605     *
13606     * <p>Be sure to call through to the super class when overriding this
13607     * function.
13608     *
13609     * @param who The Drawable to verify.  Return true if it is one you are
13610     *            displaying, else return the result of calling through to the
13611     *            super class.
13612     *
13613     * @return boolean If true than the Drawable is being displayed in the
13614     *         view; else false and it is not allowed to animate.
13615     *
13616     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13617     * @see #drawableStateChanged()
13618     */
13619    protected boolean verifyDrawable(Drawable who) {
13620        return who == mBackground;
13621    }
13622
13623    /**
13624     * This function is called whenever the state of the view changes in such
13625     * a way that it impacts the state of drawables being shown.
13626     *
13627     * <p>Be sure to call through to the superclass when overriding this
13628     * function.
13629     *
13630     * @see Drawable#setState(int[])
13631     */
13632    protected void drawableStateChanged() {
13633        Drawable d = mBackground;
13634        if (d != null && d.isStateful()) {
13635            d.setState(getDrawableState());
13636        }
13637    }
13638
13639    /**
13640     * Call this to force a view to update its drawable state. This will cause
13641     * drawableStateChanged to be called on this view. Views that are interested
13642     * in the new state should call getDrawableState.
13643     *
13644     * @see #drawableStateChanged
13645     * @see #getDrawableState
13646     */
13647    public void refreshDrawableState() {
13648        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13649        drawableStateChanged();
13650
13651        ViewParent parent = mParent;
13652        if (parent != null) {
13653            parent.childDrawableStateChanged(this);
13654        }
13655    }
13656
13657    /**
13658     * Return an array of resource IDs of the drawable states representing the
13659     * current state of the view.
13660     *
13661     * @return The current drawable state
13662     *
13663     * @see Drawable#setState(int[])
13664     * @see #drawableStateChanged()
13665     * @see #onCreateDrawableState(int)
13666     */
13667    public final int[] getDrawableState() {
13668        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13669            return mDrawableState;
13670        } else {
13671            mDrawableState = onCreateDrawableState(0);
13672            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13673            return mDrawableState;
13674        }
13675    }
13676
13677    /**
13678     * Generate the new {@link android.graphics.drawable.Drawable} state for
13679     * this view. This is called by the view
13680     * system when the cached Drawable state is determined to be invalid.  To
13681     * retrieve the current state, you should use {@link #getDrawableState}.
13682     *
13683     * @param extraSpace if non-zero, this is the number of extra entries you
13684     * would like in the returned array in which you can place your own
13685     * states.
13686     *
13687     * @return Returns an array holding the current {@link Drawable} state of
13688     * the view.
13689     *
13690     * @see #mergeDrawableStates(int[], int[])
13691     */
13692    protected int[] onCreateDrawableState(int extraSpace) {
13693        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13694                mParent instanceof View) {
13695            return ((View) mParent).onCreateDrawableState(extraSpace);
13696        }
13697
13698        int[] drawableState;
13699
13700        int privateFlags = mPrivateFlags;
13701
13702        int viewStateIndex = 0;
13703        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13704        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13705        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13706        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13707        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13708        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13709        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13710                HardwareRenderer.isAvailable()) {
13711            // This is set if HW acceleration is requested, even if the current
13712            // process doesn't allow it.  This is just to allow app preview
13713            // windows to better match their app.
13714            viewStateIndex |= VIEW_STATE_ACCELERATED;
13715        }
13716        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13717
13718        final int privateFlags2 = mPrivateFlags2;
13719        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13720        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13721
13722        drawableState = VIEW_STATE_SETS[viewStateIndex];
13723
13724        //noinspection ConstantIfStatement
13725        if (false) {
13726            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13727            Log.i("View", toString()
13728                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13729                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13730                    + " fo=" + hasFocus()
13731                    + " sl=" + ((privateFlags & SELECTED) != 0)
13732                    + " wf=" + hasWindowFocus()
13733                    + ": " + Arrays.toString(drawableState));
13734        }
13735
13736        if (extraSpace == 0) {
13737            return drawableState;
13738        }
13739
13740        final int[] fullState;
13741        if (drawableState != null) {
13742            fullState = new int[drawableState.length + extraSpace];
13743            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13744        } else {
13745            fullState = new int[extraSpace];
13746        }
13747
13748        return fullState;
13749    }
13750
13751    /**
13752     * Merge your own state values in <var>additionalState</var> into the base
13753     * state values <var>baseState</var> that were returned by
13754     * {@link #onCreateDrawableState(int)}.
13755     *
13756     * @param baseState The base state values returned by
13757     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13758     * own additional state values.
13759     *
13760     * @param additionalState The additional state values you would like
13761     * added to <var>baseState</var>; this array is not modified.
13762     *
13763     * @return As a convenience, the <var>baseState</var> array you originally
13764     * passed into the function is returned.
13765     *
13766     * @see #onCreateDrawableState(int)
13767     */
13768    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13769        final int N = baseState.length;
13770        int i = N - 1;
13771        while (i >= 0 && baseState[i] == 0) {
13772            i--;
13773        }
13774        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13775        return baseState;
13776    }
13777
13778    /**
13779     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13780     * on all Drawable objects associated with this view.
13781     */
13782    public void jumpDrawablesToCurrentState() {
13783        if (mBackground != null) {
13784            mBackground.jumpToCurrentState();
13785        }
13786    }
13787
13788    /**
13789     * Sets the background color for this view.
13790     * @param color the color of the background
13791     */
13792    @RemotableViewMethod
13793    public void setBackgroundColor(int color) {
13794        if (mBackground instanceof ColorDrawable) {
13795            ((ColorDrawable) mBackground).setColor(color);
13796        } else {
13797            setBackground(new ColorDrawable(color));
13798        }
13799    }
13800
13801    /**
13802     * Set the background to a given resource. The resource should refer to
13803     * a Drawable object or 0 to remove the background.
13804     * @param resid The identifier of the resource.
13805     *
13806     * @attr ref android.R.styleable#View_background
13807     */
13808    @RemotableViewMethod
13809    public void setBackgroundResource(int resid) {
13810        if (resid != 0 && resid == mBackgroundResource) {
13811            return;
13812        }
13813
13814        Drawable d= null;
13815        if (resid != 0) {
13816            d = mResources.getDrawable(resid);
13817        }
13818        setBackground(d);
13819
13820        mBackgroundResource = resid;
13821    }
13822
13823    /**
13824     * Set the background to a given Drawable, or remove the background. If the
13825     * background has padding, this View's padding is set to the background's
13826     * padding. However, when a background is removed, this View's padding isn't
13827     * touched. If setting the padding is desired, please use
13828     * {@link #setPadding(int, int, int, int)}.
13829     *
13830     * @param background The Drawable to use as the background, or null to remove the
13831     *        background
13832     */
13833    public void setBackground(Drawable background) {
13834        //noinspection deprecation
13835        setBackgroundDrawable(background);
13836    }
13837
13838    /**
13839     * @deprecated use {@link #setBackground(Drawable)} instead
13840     */
13841    @Deprecated
13842    public void setBackgroundDrawable(Drawable background) {
13843        if (background == mBackground) {
13844            return;
13845        }
13846
13847        boolean requestLayout = false;
13848
13849        mBackgroundResource = 0;
13850
13851        /*
13852         * Regardless of whether we're setting a new background or not, we want
13853         * to clear the previous drawable.
13854         */
13855        if (mBackground != null) {
13856            mBackground.setCallback(null);
13857            unscheduleDrawable(mBackground);
13858        }
13859
13860        if (background != null) {
13861            Rect padding = sThreadLocal.get();
13862            if (padding == null) {
13863                padding = new Rect();
13864                sThreadLocal.set(padding);
13865            }
13866            if (background.getPadding(padding)) {
13867                switch (background.getResolvedLayoutDirectionSelf()) {
13868                    case LAYOUT_DIRECTION_RTL:
13869                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13870                        break;
13871                    case LAYOUT_DIRECTION_LTR:
13872                    default:
13873                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13874                }
13875            }
13876
13877            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13878            // if it has a different minimum size, we should layout again
13879            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13880                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13881                requestLayout = true;
13882            }
13883
13884            background.setCallback(this);
13885            if (background.isStateful()) {
13886                background.setState(getDrawableState());
13887            }
13888            background.setVisible(getVisibility() == VISIBLE, false);
13889            mBackground = background;
13890
13891            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13892                mPrivateFlags &= ~SKIP_DRAW;
13893                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13894                requestLayout = true;
13895            }
13896        } else {
13897            /* Remove the background */
13898            mBackground = null;
13899
13900            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13901                /*
13902                 * This view ONLY drew the background before and we're removing
13903                 * the background, so now it won't draw anything
13904                 * (hence we SKIP_DRAW)
13905                 */
13906                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13907                mPrivateFlags |= SKIP_DRAW;
13908            }
13909
13910            /*
13911             * When the background is set, we try to apply its padding to this
13912             * View. When the background is removed, we don't touch this View's
13913             * padding. This is noted in the Javadocs. Hence, we don't need to
13914             * requestLayout(), the invalidate() below is sufficient.
13915             */
13916
13917            // The old background's minimum size could have affected this
13918            // View's layout, so let's requestLayout
13919            requestLayout = true;
13920        }
13921
13922        computeOpaqueFlags();
13923
13924        if (requestLayout) {
13925            requestLayout();
13926        }
13927
13928        mBackgroundSizeChanged = true;
13929        invalidate(true);
13930    }
13931
13932    /**
13933     * Gets the background drawable
13934     *
13935     * @return The drawable used as the background for this view, if any.
13936     *
13937     * @see #setBackground(Drawable)
13938     *
13939     * @attr ref android.R.styleable#View_background
13940     */
13941    public Drawable getBackground() {
13942        return mBackground;
13943    }
13944
13945    /**
13946     * Sets the padding. The view may add on the space required to display
13947     * the scrollbars, depending on the style and visibility of the scrollbars.
13948     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13949     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13950     * from the values set in this call.
13951     *
13952     * @attr ref android.R.styleable#View_padding
13953     * @attr ref android.R.styleable#View_paddingBottom
13954     * @attr ref android.R.styleable#View_paddingLeft
13955     * @attr ref android.R.styleable#View_paddingRight
13956     * @attr ref android.R.styleable#View_paddingTop
13957     * @param left the left padding in pixels
13958     * @param top the top padding in pixels
13959     * @param right the right padding in pixels
13960     * @param bottom the bottom padding in pixels
13961     */
13962    public void setPadding(int left, int top, int right, int bottom) {
13963        mUserPaddingStart = -1;
13964        mUserPaddingEnd = -1;
13965        mUserPaddingRelative = false;
13966
13967        internalSetPadding(left, top, right, bottom);
13968    }
13969
13970    private void internalSetPadding(int left, int top, int right, int bottom) {
13971        mUserPaddingLeft = left;
13972        mUserPaddingRight = right;
13973        mUserPaddingBottom = bottom;
13974
13975        final int viewFlags = mViewFlags;
13976        boolean changed = false;
13977
13978        // Common case is there are no scroll bars.
13979        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13980            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13981                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13982                        ? 0 : getVerticalScrollbarWidth();
13983                switch (mVerticalScrollbarPosition) {
13984                    case SCROLLBAR_POSITION_DEFAULT:
13985                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13986                            left += offset;
13987                        } else {
13988                            right += offset;
13989                        }
13990                        break;
13991                    case SCROLLBAR_POSITION_RIGHT:
13992                        right += offset;
13993                        break;
13994                    case SCROLLBAR_POSITION_LEFT:
13995                        left += offset;
13996                        break;
13997                }
13998            }
13999            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14000                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14001                        ? 0 : getHorizontalScrollbarHeight();
14002            }
14003        }
14004
14005        if (mPaddingLeft != left) {
14006            changed = true;
14007            mPaddingLeft = left;
14008        }
14009        if (mPaddingTop != top) {
14010            changed = true;
14011            mPaddingTop = top;
14012        }
14013        if (mPaddingRight != right) {
14014            changed = true;
14015            mPaddingRight = right;
14016        }
14017        if (mPaddingBottom != bottom) {
14018            changed = true;
14019            mPaddingBottom = bottom;
14020        }
14021
14022        if (changed) {
14023            requestLayout();
14024        }
14025    }
14026
14027    /**
14028     * Sets the relative padding. The view may add on the space required to display
14029     * the scrollbars, depending on the style and visibility of the scrollbars.
14030     * from the values set in this call.
14031     *
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     * @hide
14037     */
14038    public void setPaddingRelative(int start, int top, int end, int bottom) {
14039        mUserPaddingStart = start;
14040        mUserPaddingEnd = end;
14041        mUserPaddingRelative = true;
14042
14043        switch(getResolvedLayoutDirection()) {
14044            case LAYOUT_DIRECTION_RTL:
14045                internalSetPadding(end, top, start, bottom);
14046                break;
14047            case LAYOUT_DIRECTION_LTR:
14048            default:
14049                internalSetPadding(start, top, end, bottom);
14050        }
14051    }
14052
14053    /**
14054     * Returns the top padding of this view.
14055     *
14056     * @return the top padding in pixels
14057     */
14058    public int getPaddingTop() {
14059        return mPaddingTop;
14060    }
14061
14062    /**
14063     * Returns the bottom padding of this view. If there are inset and enabled
14064     * scrollbars, this value may include the space required to display the
14065     * scrollbars as well.
14066     *
14067     * @return the bottom padding in pixels
14068     */
14069    public int getPaddingBottom() {
14070        return mPaddingBottom;
14071    }
14072
14073    /**
14074     * Returns the left padding of this view. If there are inset and enabled
14075     * scrollbars, this value may include the space required to display the
14076     * scrollbars as well.
14077     *
14078     * @return the left padding in pixels
14079     */
14080    public int getPaddingLeft() {
14081        return mPaddingLeft;
14082    }
14083
14084    /**
14085     * Returns the start padding of this view depending on its resolved layout direction.
14086     * If there are inset and enabled scrollbars, this value may include the space
14087     * required to display the scrollbars as well.
14088     *
14089     * @return the start padding in pixels
14090     * @hide
14091     */
14092    public int getPaddingStart() {
14093        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14094                mPaddingRight : mPaddingLeft;
14095    }
14096
14097    /**
14098     * Returns the right padding of this view. If there are inset and enabled
14099     * scrollbars, this value may include the space required to display the
14100     * scrollbars as well.
14101     *
14102     * @return the right padding in pixels
14103     */
14104    public int getPaddingRight() {
14105        return mPaddingRight;
14106    }
14107
14108    /**
14109     * Returns the end padding of this view depending on its resolved layout direction.
14110     * If there are inset and enabled scrollbars, this value may include the space
14111     * required to display the scrollbars as well.
14112     *
14113     * @return the end padding in pixels
14114     * @hide
14115     */
14116    public int getPaddingEnd() {
14117        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14118                mPaddingLeft : mPaddingRight;
14119    }
14120
14121    /**
14122     * Return if the padding as been set thru relative values
14123     * {@link #setPaddingRelative(int, int, int, int)}
14124     *
14125     * @return true if the padding is relative or false if it is not.
14126     * @hide
14127     */
14128    public boolean isPaddingRelative() {
14129        return mUserPaddingRelative;
14130    }
14131
14132    /**
14133     * @hide
14134     */
14135    public Insets getOpticalInsets() {
14136        if (mLayoutInsets == null) {
14137            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14138        }
14139        return mLayoutInsets;
14140    }
14141
14142    /**
14143     * @hide
14144     */
14145    public void setLayoutInsets(Insets layoutInsets) {
14146        mLayoutInsets = layoutInsets;
14147    }
14148
14149    /**
14150     * Changes the selection state of this view. A view can be selected or not.
14151     * Note that selection is not the same as focus. Views are typically
14152     * selected in the context of an AdapterView like ListView or GridView;
14153     * the selected view is the view that is highlighted.
14154     *
14155     * @param selected true if the view must be selected, false otherwise
14156     */
14157    public void setSelected(boolean selected) {
14158        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14159            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14160            if (!selected) resetPressedState();
14161            invalidate(true);
14162            refreshDrawableState();
14163            dispatchSetSelected(selected);
14164            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14165                notifyAccessibilityStateChanged();
14166            }
14167        }
14168    }
14169
14170    /**
14171     * Dispatch setSelected to all of this View's children.
14172     *
14173     * @see #setSelected(boolean)
14174     *
14175     * @param selected The new selected state
14176     */
14177    protected void dispatchSetSelected(boolean selected) {
14178    }
14179
14180    /**
14181     * Indicates the selection state of this view.
14182     *
14183     * @return true if the view is selected, false otherwise
14184     */
14185    @ViewDebug.ExportedProperty
14186    public boolean isSelected() {
14187        return (mPrivateFlags & SELECTED) != 0;
14188    }
14189
14190    /**
14191     * Changes the activated state of this view. A view can be activated or not.
14192     * Note that activation is not the same as selection.  Selection is
14193     * a transient property, representing the view (hierarchy) the user is
14194     * currently interacting with.  Activation is a longer-term state that the
14195     * user can move views in and out of.  For example, in a list view with
14196     * single or multiple selection enabled, the views in the current selection
14197     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14198     * here.)  The activated state is propagated down to children of the view it
14199     * is set on.
14200     *
14201     * @param activated true if the view must be activated, false otherwise
14202     */
14203    public void setActivated(boolean activated) {
14204        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14205            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14206            invalidate(true);
14207            refreshDrawableState();
14208            dispatchSetActivated(activated);
14209        }
14210    }
14211
14212    /**
14213     * Dispatch setActivated to all of this View's children.
14214     *
14215     * @see #setActivated(boolean)
14216     *
14217     * @param activated The new activated state
14218     */
14219    protected void dispatchSetActivated(boolean activated) {
14220    }
14221
14222    /**
14223     * Indicates the activation state of this view.
14224     *
14225     * @return true if the view is activated, false otherwise
14226     */
14227    @ViewDebug.ExportedProperty
14228    public boolean isActivated() {
14229        return (mPrivateFlags & ACTIVATED) != 0;
14230    }
14231
14232    /**
14233     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14234     * observer can be used to get notifications when global events, like
14235     * layout, happen.
14236     *
14237     * The returned ViewTreeObserver observer is not guaranteed to remain
14238     * valid for the lifetime of this View. If the caller of this method keeps
14239     * a long-lived reference to ViewTreeObserver, it should always check for
14240     * the return value of {@link ViewTreeObserver#isAlive()}.
14241     *
14242     * @return The ViewTreeObserver for this view's hierarchy.
14243     */
14244    public ViewTreeObserver getViewTreeObserver() {
14245        if (mAttachInfo != null) {
14246            return mAttachInfo.mTreeObserver;
14247        }
14248        if (mFloatingTreeObserver == null) {
14249            mFloatingTreeObserver = new ViewTreeObserver();
14250        }
14251        return mFloatingTreeObserver;
14252    }
14253
14254    /**
14255     * <p>Finds the topmost view in the current view hierarchy.</p>
14256     *
14257     * @return the topmost view containing this view
14258     */
14259    public View getRootView() {
14260        if (mAttachInfo != null) {
14261            final View v = mAttachInfo.mRootView;
14262            if (v != null) {
14263                return v;
14264            }
14265        }
14266
14267        View parent = this;
14268
14269        while (parent.mParent != null && parent.mParent instanceof View) {
14270            parent = (View) parent.mParent;
14271        }
14272
14273        return parent;
14274    }
14275
14276    /**
14277     * <p>Computes the coordinates of this view on the screen. The argument
14278     * must be an array of two integers. After the method returns, the array
14279     * contains the x and y location in that order.</p>
14280     *
14281     * @param location an array of two integers in which to hold the coordinates
14282     */
14283    public void getLocationOnScreen(int[] location) {
14284        getLocationInWindow(location);
14285
14286        final AttachInfo info = mAttachInfo;
14287        if (info != null) {
14288            location[0] += info.mWindowLeft;
14289            location[1] += info.mWindowTop;
14290        }
14291    }
14292
14293    /**
14294     * <p>Computes the coordinates of this view in its window. The argument
14295     * must be an array of two integers. After the method returns, the array
14296     * contains the x and y location in that order.</p>
14297     *
14298     * @param location an array of two integers in which to hold the coordinates
14299     */
14300    public void getLocationInWindow(int[] location) {
14301        if (location == null || location.length < 2) {
14302            throw new IllegalArgumentException("location must be an array of two integers");
14303        }
14304
14305        if (mAttachInfo == null) {
14306            // When the view is not attached to a window, this method does not make sense
14307            location[0] = location[1] = 0;
14308            return;
14309        }
14310
14311        float[] position = mAttachInfo.mTmpTransformLocation;
14312        position[0] = position[1] = 0.0f;
14313
14314        if (!hasIdentityMatrix()) {
14315            getMatrix().mapPoints(position);
14316        }
14317
14318        position[0] += mLeft;
14319        position[1] += mTop;
14320
14321        ViewParent viewParent = mParent;
14322        while (viewParent instanceof View) {
14323            final View view = (View) viewParent;
14324
14325            position[0] -= view.mScrollX;
14326            position[1] -= view.mScrollY;
14327
14328            if (!view.hasIdentityMatrix()) {
14329                view.getMatrix().mapPoints(position);
14330            }
14331
14332            position[0] += view.mLeft;
14333            position[1] += view.mTop;
14334
14335            viewParent = view.mParent;
14336         }
14337
14338        if (viewParent instanceof ViewRootImpl) {
14339            // *cough*
14340            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14341            position[1] -= vr.mCurScrollY;
14342        }
14343
14344        location[0] = (int) (position[0] + 0.5f);
14345        location[1] = (int) (position[1] + 0.5f);
14346    }
14347
14348    /**
14349     * {@hide}
14350     * @param id the id of the view to be found
14351     * @return the view of the specified id, null if cannot be found
14352     */
14353    protected View findViewTraversal(int id) {
14354        if (id == mID) {
14355            return this;
14356        }
14357        return null;
14358    }
14359
14360    /**
14361     * {@hide}
14362     * @param tag the tag of the view to be found
14363     * @return the view of specified tag, null if cannot be found
14364     */
14365    protected View findViewWithTagTraversal(Object tag) {
14366        if (tag != null && tag.equals(mTag)) {
14367            return this;
14368        }
14369        return null;
14370    }
14371
14372    /**
14373     * {@hide}
14374     * @param predicate The predicate to evaluate.
14375     * @param childToSkip If not null, ignores this child during the recursive traversal.
14376     * @return The first view that matches the predicate or null.
14377     */
14378    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14379        if (predicate.apply(this)) {
14380            return this;
14381        }
14382        return null;
14383    }
14384
14385    /**
14386     * Look for a child view with the given id.  If this view has the given
14387     * id, return this view.
14388     *
14389     * @param id The id to search for.
14390     * @return The view that has the given id in the hierarchy or null
14391     */
14392    public final View findViewById(int id) {
14393        if (id < 0) {
14394            return null;
14395        }
14396        return findViewTraversal(id);
14397    }
14398
14399    /**
14400     * Finds a view by its unuque and stable accessibility id.
14401     *
14402     * @param accessibilityId The searched accessibility id.
14403     * @return The found view.
14404     */
14405    final View findViewByAccessibilityId(int accessibilityId) {
14406        if (accessibilityId < 0) {
14407            return null;
14408        }
14409        return findViewByAccessibilityIdTraversal(accessibilityId);
14410    }
14411
14412    /**
14413     * Performs the traversal to find a view by its unuque and stable accessibility id.
14414     *
14415     * <strong>Note:</strong>This method does not stop at the root namespace
14416     * boundary since the user can touch the screen at an arbitrary location
14417     * potentially crossing the root namespace bounday which will send an
14418     * accessibility event to accessibility services and they should be able
14419     * to obtain the event source. Also accessibility ids are guaranteed to be
14420     * unique in the window.
14421     *
14422     * @param accessibilityId The accessibility id.
14423     * @return The found view.
14424     */
14425    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14426        if (getAccessibilityViewId() == accessibilityId) {
14427            return this;
14428        }
14429        return null;
14430    }
14431
14432    /**
14433     * Look for a child view with the given tag.  If this view has the given
14434     * tag, return this view.
14435     *
14436     * @param tag The tag to search for, using "tag.equals(getTag())".
14437     * @return The View that has the given tag in the hierarchy or null
14438     */
14439    public final View findViewWithTag(Object tag) {
14440        if (tag == null) {
14441            return null;
14442        }
14443        return findViewWithTagTraversal(tag);
14444    }
14445
14446    /**
14447     * {@hide}
14448     * Look for a child view that matches the specified predicate.
14449     * If this view matches the predicate, return this view.
14450     *
14451     * @param predicate The predicate to evaluate.
14452     * @return The first view that matches the predicate or null.
14453     */
14454    public final View findViewByPredicate(Predicate<View> predicate) {
14455        return findViewByPredicateTraversal(predicate, null);
14456    }
14457
14458    /**
14459     * {@hide}
14460     * Look for a child view that matches the specified predicate,
14461     * starting with the specified view and its descendents and then
14462     * recusively searching the ancestors and siblings of that view
14463     * until this view is reached.
14464     *
14465     * This method is useful in cases where the predicate does not match
14466     * a single unique view (perhaps multiple views use the same id)
14467     * and we are trying to find the view that is "closest" in scope to the
14468     * starting view.
14469     *
14470     * @param start The view to start from.
14471     * @param predicate The predicate to evaluate.
14472     * @return The first view that matches the predicate or null.
14473     */
14474    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14475        View childToSkip = null;
14476        for (;;) {
14477            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14478            if (view != null || start == this) {
14479                return view;
14480            }
14481
14482            ViewParent parent = start.getParent();
14483            if (parent == null || !(parent instanceof View)) {
14484                return null;
14485            }
14486
14487            childToSkip = start;
14488            start = (View) parent;
14489        }
14490    }
14491
14492    /**
14493     * Sets the identifier for this view. The identifier does not have to be
14494     * unique in this view's hierarchy. The identifier should be a positive
14495     * number.
14496     *
14497     * @see #NO_ID
14498     * @see #getId()
14499     * @see #findViewById(int)
14500     *
14501     * @param id a number used to identify the view
14502     *
14503     * @attr ref android.R.styleable#View_id
14504     */
14505    public void setId(int id) {
14506        mID = id;
14507    }
14508
14509    /**
14510     * {@hide}
14511     *
14512     * @param isRoot true if the view belongs to the root namespace, false
14513     *        otherwise
14514     */
14515    public void setIsRootNamespace(boolean isRoot) {
14516        if (isRoot) {
14517            mPrivateFlags |= IS_ROOT_NAMESPACE;
14518        } else {
14519            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14520        }
14521    }
14522
14523    /**
14524     * {@hide}
14525     *
14526     * @return true if the view belongs to the root namespace, false otherwise
14527     */
14528    public boolean isRootNamespace() {
14529        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14530    }
14531
14532    /**
14533     * Returns this view's identifier.
14534     *
14535     * @return a positive integer used to identify the view or {@link #NO_ID}
14536     *         if the view has no ID
14537     *
14538     * @see #setId(int)
14539     * @see #findViewById(int)
14540     * @attr ref android.R.styleable#View_id
14541     */
14542    @ViewDebug.CapturedViewProperty
14543    public int getId() {
14544        return mID;
14545    }
14546
14547    /**
14548     * Returns this view's tag.
14549     *
14550     * @return the Object stored in this view as a tag
14551     *
14552     * @see #setTag(Object)
14553     * @see #getTag(int)
14554     */
14555    @ViewDebug.ExportedProperty
14556    public Object getTag() {
14557        return mTag;
14558    }
14559
14560    /**
14561     * Sets the tag associated with this view. A tag can be used to mark
14562     * a view in its hierarchy and does not have to be unique within the
14563     * hierarchy. Tags can also be used to store data within a view without
14564     * resorting to another data structure.
14565     *
14566     * @param tag an Object to tag the view with
14567     *
14568     * @see #getTag()
14569     * @see #setTag(int, Object)
14570     */
14571    public void setTag(final Object tag) {
14572        mTag = tag;
14573    }
14574
14575    /**
14576     * Returns the tag associated with this view and the specified key.
14577     *
14578     * @param key The key identifying the tag
14579     *
14580     * @return the Object stored in this view as a tag
14581     *
14582     * @see #setTag(int, Object)
14583     * @see #getTag()
14584     */
14585    public Object getTag(int key) {
14586        if (mKeyedTags != null) return mKeyedTags.get(key);
14587        return null;
14588    }
14589
14590    /**
14591     * Sets a tag associated with this view and a key. A tag can be used
14592     * to mark a view in its hierarchy and does not have to be unique within
14593     * the hierarchy. Tags can also be used to store data within a view
14594     * without resorting to another data structure.
14595     *
14596     * The specified key should be an id declared in the resources of the
14597     * application to ensure it is unique (see the <a
14598     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14599     * Keys identified as belonging to
14600     * the Android framework or not associated with any package will cause
14601     * an {@link IllegalArgumentException} to be thrown.
14602     *
14603     * @param key The key identifying the tag
14604     * @param tag An Object to tag the view with
14605     *
14606     * @throws IllegalArgumentException If they specified key is not valid
14607     *
14608     * @see #setTag(Object)
14609     * @see #getTag(int)
14610     */
14611    public void setTag(int key, final Object tag) {
14612        // If the package id is 0x00 or 0x01, it's either an undefined package
14613        // or a framework id
14614        if ((key >>> 24) < 2) {
14615            throw new IllegalArgumentException("The key must be an application-specific "
14616                    + "resource id.");
14617        }
14618
14619        setKeyedTag(key, tag);
14620    }
14621
14622    /**
14623     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14624     * framework id.
14625     *
14626     * @hide
14627     */
14628    public void setTagInternal(int key, Object tag) {
14629        if ((key >>> 24) != 0x1) {
14630            throw new IllegalArgumentException("The key must be a framework-specific "
14631                    + "resource id.");
14632        }
14633
14634        setKeyedTag(key, tag);
14635    }
14636
14637    private void setKeyedTag(int key, Object tag) {
14638        if (mKeyedTags == null) {
14639            mKeyedTags = new SparseArray<Object>();
14640        }
14641
14642        mKeyedTags.put(key, tag);
14643    }
14644
14645    /**
14646     * @param consistency The type of consistency. See ViewDebug for more information.
14647     *
14648     * @hide
14649     */
14650    protected boolean dispatchConsistencyCheck(int consistency) {
14651        return onConsistencyCheck(consistency);
14652    }
14653
14654    /**
14655     * Method that subclasses should implement to check their consistency. The type of
14656     * consistency check is indicated by the bit field passed as a parameter.
14657     *
14658     * @param consistency The type of consistency. See ViewDebug for more information.
14659     *
14660     * @throws IllegalStateException if the view is in an inconsistent state.
14661     *
14662     * @hide
14663     */
14664    protected boolean onConsistencyCheck(int consistency) {
14665        boolean result = true;
14666
14667        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14668        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14669
14670        if (checkLayout) {
14671            if (getParent() == null) {
14672                result = false;
14673                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14674                        "View " + this + " does not have a parent.");
14675            }
14676
14677            if (mAttachInfo == null) {
14678                result = false;
14679                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14680                        "View " + this + " is not attached to a window.");
14681            }
14682        }
14683
14684        if (checkDrawing) {
14685            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14686            // from their draw() method
14687
14688            if ((mPrivateFlags & DRAWN) != DRAWN &&
14689                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14690                result = false;
14691                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14692                        "View " + this + " was invalidated but its drawing cache is valid.");
14693            }
14694        }
14695
14696        return result;
14697    }
14698
14699    /**
14700     * Prints information about this view in the log output, with the tag
14701     * {@link #VIEW_LOG_TAG}.
14702     *
14703     * @hide
14704     */
14705    public void debug() {
14706        debug(0);
14707    }
14708
14709    /**
14710     * Prints information about this view in the log output, with the tag
14711     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14712     * indentation defined by the <code>depth</code>.
14713     *
14714     * @param depth the indentation level
14715     *
14716     * @hide
14717     */
14718    protected void debug(int depth) {
14719        String output = debugIndent(depth - 1);
14720
14721        output += "+ " + this;
14722        int id = getId();
14723        if (id != -1) {
14724            output += " (id=" + id + ")";
14725        }
14726        Object tag = getTag();
14727        if (tag != null) {
14728            output += " (tag=" + tag + ")";
14729        }
14730        Log.d(VIEW_LOG_TAG, output);
14731
14732        if ((mPrivateFlags & FOCUSED) != 0) {
14733            output = debugIndent(depth) + " FOCUSED";
14734            Log.d(VIEW_LOG_TAG, output);
14735        }
14736
14737        output = debugIndent(depth);
14738        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14739                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14740                + "} ";
14741        Log.d(VIEW_LOG_TAG, output);
14742
14743        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14744                || mPaddingBottom != 0) {
14745            output = debugIndent(depth);
14746            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14747                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14748            Log.d(VIEW_LOG_TAG, output);
14749        }
14750
14751        output = debugIndent(depth);
14752        output += "mMeasureWidth=" + mMeasuredWidth +
14753                " mMeasureHeight=" + mMeasuredHeight;
14754        Log.d(VIEW_LOG_TAG, output);
14755
14756        output = debugIndent(depth);
14757        if (mLayoutParams == null) {
14758            output += "BAD! no layout params";
14759        } else {
14760            output = mLayoutParams.debug(output);
14761        }
14762        Log.d(VIEW_LOG_TAG, output);
14763
14764        output = debugIndent(depth);
14765        output += "flags={";
14766        output += View.printFlags(mViewFlags);
14767        output += "}";
14768        Log.d(VIEW_LOG_TAG, output);
14769
14770        output = debugIndent(depth);
14771        output += "privateFlags={";
14772        output += View.printPrivateFlags(mPrivateFlags);
14773        output += "}";
14774        Log.d(VIEW_LOG_TAG, output);
14775    }
14776
14777    /**
14778     * Creates a string of whitespaces used for indentation.
14779     *
14780     * @param depth the indentation level
14781     * @return a String containing (depth * 2 + 3) * 2 white spaces
14782     *
14783     * @hide
14784     */
14785    protected static String debugIndent(int depth) {
14786        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14787        for (int i = 0; i < (depth * 2) + 3; i++) {
14788            spaces.append(' ').append(' ');
14789        }
14790        return spaces.toString();
14791    }
14792
14793    /**
14794     * <p>Return the offset of the widget's text baseline from the widget's top
14795     * boundary. If this widget does not support baseline alignment, this
14796     * method returns -1. </p>
14797     *
14798     * @return the offset of the baseline within the widget's bounds or -1
14799     *         if baseline alignment is not supported
14800     */
14801    @ViewDebug.ExportedProperty(category = "layout")
14802    public int getBaseline() {
14803        return -1;
14804    }
14805
14806    /**
14807     * Call this when something has changed which has invalidated the
14808     * layout of this view. This will schedule a layout pass of the view
14809     * tree.
14810     */
14811    public void requestLayout() {
14812        if (ViewDebug.TRACE_HIERARCHY) {
14813            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14814        }
14815
14816        mPrivateFlags |= FORCE_LAYOUT;
14817        mPrivateFlags |= INVALIDATED;
14818
14819        if (mLayoutParams != null) {
14820            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14821        }
14822
14823        if (mParent != null && !mParent.isLayoutRequested()) {
14824            mParent.requestLayout();
14825        }
14826    }
14827
14828    /**
14829     * Forces this view to be laid out during the next layout pass.
14830     * This method does not call requestLayout() or forceLayout()
14831     * on the parent.
14832     */
14833    public void forceLayout() {
14834        mPrivateFlags |= FORCE_LAYOUT;
14835        mPrivateFlags |= INVALIDATED;
14836    }
14837
14838    /**
14839     * <p>
14840     * This is called to find out how big a view should be. The parent
14841     * supplies constraint information in the width and height parameters.
14842     * </p>
14843     *
14844     * <p>
14845     * The actual measurement work of a view is performed in
14846     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14847     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14848     * </p>
14849     *
14850     *
14851     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14852     *        parent
14853     * @param heightMeasureSpec Vertical space requirements as imposed by the
14854     *        parent
14855     *
14856     * @see #onMeasure(int, int)
14857     */
14858    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14859        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14860                widthMeasureSpec != mOldWidthMeasureSpec ||
14861                heightMeasureSpec != mOldHeightMeasureSpec) {
14862
14863            // first clears the measured dimension flag
14864            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14865
14866            if (ViewDebug.TRACE_HIERARCHY) {
14867                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14868            }
14869
14870            // measure ourselves, this should set the measured dimension flag back
14871            onMeasure(widthMeasureSpec, heightMeasureSpec);
14872
14873            // flag not set, setMeasuredDimension() was not invoked, we raise
14874            // an exception to warn the developer
14875            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14876                throw new IllegalStateException("onMeasure() did not set the"
14877                        + " measured dimension by calling"
14878                        + " setMeasuredDimension()");
14879            }
14880
14881            mPrivateFlags |= LAYOUT_REQUIRED;
14882        }
14883
14884        mOldWidthMeasureSpec = widthMeasureSpec;
14885        mOldHeightMeasureSpec = heightMeasureSpec;
14886    }
14887
14888    /**
14889     * <p>
14890     * Measure the view and its content to determine the measured width and the
14891     * measured height. This method is invoked by {@link #measure(int, int)} and
14892     * should be overriden by subclasses to provide accurate and efficient
14893     * measurement of their contents.
14894     * </p>
14895     *
14896     * <p>
14897     * <strong>CONTRACT:</strong> When overriding this method, you
14898     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14899     * measured width and height of this view. Failure to do so will trigger an
14900     * <code>IllegalStateException</code>, thrown by
14901     * {@link #measure(int, int)}. Calling the superclass'
14902     * {@link #onMeasure(int, int)} is a valid use.
14903     * </p>
14904     *
14905     * <p>
14906     * The base class implementation of measure defaults to the background size,
14907     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14908     * override {@link #onMeasure(int, int)} to provide better measurements of
14909     * their content.
14910     * </p>
14911     *
14912     * <p>
14913     * If this method is overridden, it is the subclass's responsibility to make
14914     * sure the measured height and width are at least the view's minimum height
14915     * and width ({@link #getSuggestedMinimumHeight()} and
14916     * {@link #getSuggestedMinimumWidth()}).
14917     * </p>
14918     *
14919     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14920     *                         The requirements are encoded with
14921     *                         {@link android.view.View.MeasureSpec}.
14922     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14923     *                         The requirements are encoded with
14924     *                         {@link android.view.View.MeasureSpec}.
14925     *
14926     * @see #getMeasuredWidth()
14927     * @see #getMeasuredHeight()
14928     * @see #setMeasuredDimension(int, int)
14929     * @see #getSuggestedMinimumHeight()
14930     * @see #getSuggestedMinimumWidth()
14931     * @see android.view.View.MeasureSpec#getMode(int)
14932     * @see android.view.View.MeasureSpec#getSize(int)
14933     */
14934    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14935        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14936                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14937    }
14938
14939    /**
14940     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14941     * measured width and measured height. Failing to do so will trigger an
14942     * exception at measurement time.</p>
14943     *
14944     * @param measuredWidth The measured width of this view.  May be a complex
14945     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14946     * {@link #MEASURED_STATE_TOO_SMALL}.
14947     * @param measuredHeight The measured height of this view.  May be a complex
14948     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14949     * {@link #MEASURED_STATE_TOO_SMALL}.
14950     */
14951    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14952        mMeasuredWidth = measuredWidth;
14953        mMeasuredHeight = measuredHeight;
14954
14955        mPrivateFlags |= MEASURED_DIMENSION_SET;
14956    }
14957
14958    /**
14959     * Merge two states as returned by {@link #getMeasuredState()}.
14960     * @param curState The current state as returned from a view or the result
14961     * of combining multiple views.
14962     * @param newState The new view state to combine.
14963     * @return Returns a new integer reflecting the combination of the two
14964     * states.
14965     */
14966    public static int combineMeasuredStates(int curState, int newState) {
14967        return curState | newState;
14968    }
14969
14970    /**
14971     * Version of {@link #resolveSizeAndState(int, int, int)}
14972     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14973     */
14974    public static int resolveSize(int size, int measureSpec) {
14975        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14976    }
14977
14978    /**
14979     * Utility to reconcile a desired size and state, with constraints imposed
14980     * by a MeasureSpec.  Will take the desired size, unless a different size
14981     * is imposed by the constraints.  The returned value is a compound integer,
14982     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14983     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14984     * size is smaller than the size the view wants to be.
14985     *
14986     * @param size How big the view wants to be
14987     * @param measureSpec Constraints imposed by the parent
14988     * @return Size information bit mask as defined by
14989     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14990     */
14991    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14992        int result = size;
14993        int specMode = MeasureSpec.getMode(measureSpec);
14994        int specSize =  MeasureSpec.getSize(measureSpec);
14995        switch (specMode) {
14996        case MeasureSpec.UNSPECIFIED:
14997            result = size;
14998            break;
14999        case MeasureSpec.AT_MOST:
15000            if (specSize < size) {
15001                result = specSize | MEASURED_STATE_TOO_SMALL;
15002            } else {
15003                result = size;
15004            }
15005            break;
15006        case MeasureSpec.EXACTLY:
15007            result = specSize;
15008            break;
15009        }
15010        return result | (childMeasuredState&MEASURED_STATE_MASK);
15011    }
15012
15013    /**
15014     * Utility to return a default size. Uses the supplied size if the
15015     * MeasureSpec imposed no constraints. Will get larger if allowed
15016     * by the MeasureSpec.
15017     *
15018     * @param size Default size for this view
15019     * @param measureSpec Constraints imposed by the parent
15020     * @return The size this view should be.
15021     */
15022    public static int getDefaultSize(int size, int measureSpec) {
15023        int result = size;
15024        int specMode = MeasureSpec.getMode(measureSpec);
15025        int specSize = MeasureSpec.getSize(measureSpec);
15026
15027        switch (specMode) {
15028        case MeasureSpec.UNSPECIFIED:
15029            result = size;
15030            break;
15031        case MeasureSpec.AT_MOST:
15032        case MeasureSpec.EXACTLY:
15033            result = specSize;
15034            break;
15035        }
15036        return result;
15037    }
15038
15039    /**
15040     * Returns the suggested minimum height that the view should use. This
15041     * returns the maximum of the view's minimum height
15042     * and the background's minimum height
15043     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15044     * <p>
15045     * When being used in {@link #onMeasure(int, int)}, the caller should still
15046     * ensure the returned height is within the requirements of the parent.
15047     *
15048     * @return The suggested minimum height of the view.
15049     */
15050    protected int getSuggestedMinimumHeight() {
15051        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15052
15053    }
15054
15055    /**
15056     * Returns the suggested minimum width that the view should use. This
15057     * returns the maximum of the view's minimum width)
15058     * and the background's minimum width
15059     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15060     * <p>
15061     * When being used in {@link #onMeasure(int, int)}, the caller should still
15062     * ensure the returned width is within the requirements of the parent.
15063     *
15064     * @return The suggested minimum width of the view.
15065     */
15066    protected int getSuggestedMinimumWidth() {
15067        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15068    }
15069
15070    /**
15071     * Returns the minimum height of the view.
15072     *
15073     * @return the minimum height the view will try to be.
15074     *
15075     * @see #setMinimumHeight(int)
15076     *
15077     * @attr ref android.R.styleable#View_minHeight
15078     */
15079    public int getMinimumHeight() {
15080        return mMinHeight;
15081    }
15082
15083    /**
15084     * Sets the minimum height of the view. It is not guaranteed the view will
15085     * be able to achieve this minimum height (for example, if its parent layout
15086     * constrains it with less available height).
15087     *
15088     * @param minHeight The minimum height the view will try to be.
15089     *
15090     * @see #getMinimumHeight()
15091     *
15092     * @attr ref android.R.styleable#View_minHeight
15093     */
15094    public void setMinimumHeight(int minHeight) {
15095        mMinHeight = minHeight;
15096        requestLayout();
15097    }
15098
15099    /**
15100     * Returns the minimum width of the view.
15101     *
15102     * @return the minimum width the view will try to be.
15103     *
15104     * @see #setMinimumWidth(int)
15105     *
15106     * @attr ref android.R.styleable#View_minWidth
15107     */
15108    public int getMinimumWidth() {
15109        return mMinWidth;
15110    }
15111
15112    /**
15113     * Sets the minimum width of the view. It is not guaranteed the view will
15114     * be able to achieve this minimum width (for example, if its parent layout
15115     * constrains it with less available width).
15116     *
15117     * @param minWidth The minimum width the view will try to be.
15118     *
15119     * @see #getMinimumWidth()
15120     *
15121     * @attr ref android.R.styleable#View_minWidth
15122     */
15123    public void setMinimumWidth(int minWidth) {
15124        mMinWidth = minWidth;
15125        requestLayout();
15126
15127    }
15128
15129    /**
15130     * Get the animation currently associated with this view.
15131     *
15132     * @return The animation that is currently playing or
15133     *         scheduled to play for this view.
15134     */
15135    public Animation getAnimation() {
15136        return mCurrentAnimation;
15137    }
15138
15139    /**
15140     * Start the specified animation now.
15141     *
15142     * @param animation the animation to start now
15143     */
15144    public void startAnimation(Animation animation) {
15145        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15146        setAnimation(animation);
15147        invalidateParentCaches();
15148        invalidate(true);
15149    }
15150
15151    /**
15152     * Cancels any animations for this view.
15153     */
15154    public void clearAnimation() {
15155        if (mCurrentAnimation != null) {
15156            mCurrentAnimation.detach();
15157        }
15158        mCurrentAnimation = null;
15159        invalidateParentIfNeeded();
15160    }
15161
15162    /**
15163     * Sets the next animation to play for this view.
15164     * If you want the animation to play immediately, use
15165     * startAnimation. This method provides allows fine-grained
15166     * control over the start time and invalidation, but you
15167     * must make sure that 1) the animation has a start time set, and
15168     * 2) the view will be invalidated when the animation is supposed to
15169     * start.
15170     *
15171     * @param animation The next animation, or null.
15172     */
15173    public void setAnimation(Animation animation) {
15174        mCurrentAnimation = animation;
15175
15176        if (animation != null) {
15177            // If the screen is off assume the animation start time is now instead of
15178            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15179            // would cause the animation to start when the screen turns back on
15180            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15181                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15182                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15183            }
15184            animation.reset();
15185        }
15186    }
15187
15188    /**
15189     * Invoked by a parent ViewGroup to notify the start of the animation
15190     * currently associated with this view. If you override this method,
15191     * always call super.onAnimationStart();
15192     *
15193     * @see #setAnimation(android.view.animation.Animation)
15194     * @see #getAnimation()
15195     */
15196    protected void onAnimationStart() {
15197        mPrivateFlags |= ANIMATION_STARTED;
15198    }
15199
15200    /**
15201     * Invoked by a parent ViewGroup to notify the end of the animation
15202     * currently associated with this view. If you override this method,
15203     * always call super.onAnimationEnd();
15204     *
15205     * @see #setAnimation(android.view.animation.Animation)
15206     * @see #getAnimation()
15207     */
15208    protected void onAnimationEnd() {
15209        mPrivateFlags &= ~ANIMATION_STARTED;
15210    }
15211
15212    /**
15213     * Invoked if there is a Transform that involves alpha. Subclass that can
15214     * draw themselves with the specified alpha should return true, and then
15215     * respect that alpha when their onDraw() is called. If this returns false
15216     * then the view may be redirected to draw into an offscreen buffer to
15217     * fulfill the request, which will look fine, but may be slower than if the
15218     * subclass handles it internally. The default implementation returns false.
15219     *
15220     * @param alpha The alpha (0..255) to apply to the view's drawing
15221     * @return true if the view can draw with the specified alpha.
15222     */
15223    protected boolean onSetAlpha(int alpha) {
15224        return false;
15225    }
15226
15227    /**
15228     * This is used by the RootView to perform an optimization when
15229     * the view hierarchy contains one or several SurfaceView.
15230     * SurfaceView is always considered transparent, but its children are not,
15231     * therefore all View objects remove themselves from the global transparent
15232     * region (passed as a parameter to this function).
15233     *
15234     * @param region The transparent region for this ViewAncestor (window).
15235     *
15236     * @return Returns true if the effective visibility of the view at this
15237     * point is opaque, regardless of the transparent region; returns false
15238     * if it is possible for underlying windows to be seen behind the view.
15239     *
15240     * {@hide}
15241     */
15242    public boolean gatherTransparentRegion(Region region) {
15243        final AttachInfo attachInfo = mAttachInfo;
15244        if (region != null && attachInfo != null) {
15245            final int pflags = mPrivateFlags;
15246            if ((pflags & SKIP_DRAW) == 0) {
15247                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15248                // remove it from the transparent region.
15249                final int[] location = attachInfo.mTransparentLocation;
15250                getLocationInWindow(location);
15251                region.op(location[0], location[1], location[0] + mRight - mLeft,
15252                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15253            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15254                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15255                // exists, so we remove the background drawable's non-transparent
15256                // parts from this transparent region.
15257                applyDrawableToTransparentRegion(mBackground, region);
15258            }
15259        }
15260        return true;
15261    }
15262
15263    /**
15264     * Play a sound effect for this view.
15265     *
15266     * <p>The framework will play sound effects for some built in actions, such as
15267     * clicking, but you may wish to play these effects in your widget,
15268     * for instance, for internal navigation.
15269     *
15270     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15271     * {@link #isSoundEffectsEnabled()} is true.
15272     *
15273     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15274     */
15275    public void playSoundEffect(int soundConstant) {
15276        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15277            return;
15278        }
15279        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15280    }
15281
15282    /**
15283     * BZZZTT!!1!
15284     *
15285     * <p>Provide haptic feedback to the user for this view.
15286     *
15287     * <p>The framework will provide haptic feedback for some built in actions,
15288     * such as long presses, but you may wish to provide feedback for your
15289     * own widget.
15290     *
15291     * <p>The feedback will only be performed if
15292     * {@link #isHapticFeedbackEnabled()} is true.
15293     *
15294     * @param feedbackConstant One of the constants defined in
15295     * {@link HapticFeedbackConstants}
15296     */
15297    public boolean performHapticFeedback(int feedbackConstant) {
15298        return performHapticFeedback(feedbackConstant, 0);
15299    }
15300
15301    /**
15302     * BZZZTT!!1!
15303     *
15304     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15305     *
15306     * @param feedbackConstant One of the constants defined in
15307     * {@link HapticFeedbackConstants}
15308     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15309     */
15310    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15311        if (mAttachInfo == null) {
15312            return false;
15313        }
15314        //noinspection SimplifiableIfStatement
15315        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15316                && !isHapticFeedbackEnabled()) {
15317            return false;
15318        }
15319        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15320                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15321    }
15322
15323    /**
15324     * Request that the visibility of the status bar or other screen/window
15325     * decorations be changed.
15326     *
15327     * <p>This method is used to put the over device UI into temporary modes
15328     * where the user's attention is focused more on the application content,
15329     * by dimming or hiding surrounding system affordances.  This is typically
15330     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15331     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15332     * to be placed behind the action bar (and with these flags other system
15333     * affordances) so that smooth transitions between hiding and showing them
15334     * can be done.
15335     *
15336     * <p>Two representative examples of the use of system UI visibility is
15337     * implementing a content browsing application (like a magazine reader)
15338     * and a video playing application.
15339     *
15340     * <p>The first code shows a typical implementation of a View in a content
15341     * browsing application.  In this implementation, the application goes
15342     * into a content-oriented mode by hiding the status bar and action bar,
15343     * and putting the navigation elements into lights out mode.  The user can
15344     * then interact with content while in this mode.  Such an application should
15345     * provide an easy way for the user to toggle out of the mode (such as to
15346     * check information in the status bar or access notifications).  In the
15347     * implementation here, this is done simply by tapping on the content.
15348     *
15349     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15350     *      content}
15351     *
15352     * <p>This second code sample shows a typical implementation of a View
15353     * in a video playing application.  In this situation, while the video is
15354     * playing the application would like to go into a complete full-screen mode,
15355     * to use as much of the display as possible for the video.  When in this state
15356     * the user can not interact with the application; the system intercepts
15357     * touching on the screen to pop the UI out of full screen mode.
15358     *
15359     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15360     *      content}
15361     *
15362     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15363     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15364     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15365     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15366     */
15367    public void setSystemUiVisibility(int visibility) {
15368        if (visibility != mSystemUiVisibility) {
15369            mSystemUiVisibility = visibility;
15370            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15371                mParent.recomputeViewAttributes(this);
15372            }
15373        }
15374    }
15375
15376    /**
15377     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15378     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15379     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15380     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15381     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15382     */
15383    public int getSystemUiVisibility() {
15384        return mSystemUiVisibility;
15385    }
15386
15387    /**
15388     * Returns the current system UI visibility that is currently set for
15389     * the entire window.  This is the combination of the
15390     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15391     * views in the window.
15392     */
15393    public int getWindowSystemUiVisibility() {
15394        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15395    }
15396
15397    /**
15398     * Override to find out when the window's requested system UI visibility
15399     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15400     * This is different from the callbacks recieved through
15401     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15402     * in that this is only telling you about the local request of the window,
15403     * not the actual values applied by the system.
15404     */
15405    public void onWindowSystemUiVisibilityChanged(int visible) {
15406    }
15407
15408    /**
15409     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15410     * the view hierarchy.
15411     */
15412    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15413        onWindowSystemUiVisibilityChanged(visible);
15414    }
15415
15416    /**
15417     * Set a listener to receive callbacks when the visibility of the system bar changes.
15418     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15419     */
15420    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15421        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15422        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15423            mParent.recomputeViewAttributes(this);
15424        }
15425    }
15426
15427    /**
15428     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15429     * the view hierarchy.
15430     */
15431    public void dispatchSystemUiVisibilityChanged(int visibility) {
15432        ListenerInfo li = mListenerInfo;
15433        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15434            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15435                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15436        }
15437    }
15438
15439    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15440        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15441        if (val != mSystemUiVisibility) {
15442            setSystemUiVisibility(val);
15443        }
15444    }
15445
15446    /** @hide */
15447    public void setDisabledSystemUiVisibility(int flags) {
15448        if (mAttachInfo != null) {
15449            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15450                mAttachInfo.mDisabledSystemUiVisibility = flags;
15451                if (mParent != null) {
15452                    mParent.recomputeViewAttributes(this);
15453                }
15454            }
15455        }
15456    }
15457
15458    /**
15459     * Creates an image that the system displays during the drag and drop
15460     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15461     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15462     * appearance as the given View. The default also positions the center of the drag shadow
15463     * directly under the touch point. If no View is provided (the constructor with no parameters
15464     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15465     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15466     * default is an invisible drag shadow.
15467     * <p>
15468     * You are not required to use the View you provide to the constructor as the basis of the
15469     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15470     * anything you want as the drag shadow.
15471     * </p>
15472     * <p>
15473     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15474     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15475     *  size and position of the drag shadow. It uses this data to construct a
15476     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15477     *  so that your application can draw the shadow image in the Canvas.
15478     * </p>
15479     *
15480     * <div class="special reference">
15481     * <h3>Developer Guides</h3>
15482     * <p>For a guide to implementing drag and drop features, read the
15483     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15484     * </div>
15485     */
15486    public static class DragShadowBuilder {
15487        private final WeakReference<View> mView;
15488
15489        /**
15490         * Constructs a shadow image builder based on a View. By default, the resulting drag
15491         * shadow will have the same appearance and dimensions as the View, with the touch point
15492         * over the center of the View.
15493         * @param view A View. Any View in scope can be used.
15494         */
15495        public DragShadowBuilder(View view) {
15496            mView = new WeakReference<View>(view);
15497        }
15498
15499        /**
15500         * Construct a shadow builder object with no associated View.  This
15501         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15502         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15503         * to supply the drag shadow's dimensions and appearance without
15504         * reference to any View object. If they are not overridden, then the result is an
15505         * invisible drag shadow.
15506         */
15507        public DragShadowBuilder() {
15508            mView = new WeakReference<View>(null);
15509        }
15510
15511        /**
15512         * Returns the View object that had been passed to the
15513         * {@link #View.DragShadowBuilder(View)}
15514         * constructor.  If that View parameter was {@code null} or if the
15515         * {@link #View.DragShadowBuilder()}
15516         * constructor was used to instantiate the builder object, this method will return
15517         * null.
15518         *
15519         * @return The View object associate with this builder object.
15520         */
15521        @SuppressWarnings({"JavadocReference"})
15522        final public View getView() {
15523            return mView.get();
15524        }
15525
15526        /**
15527         * Provides the metrics for the shadow image. These include the dimensions of
15528         * the shadow image, and the point within that shadow that should
15529         * be centered under the touch location while dragging.
15530         * <p>
15531         * The default implementation sets the dimensions of the shadow to be the
15532         * same as the dimensions of the View itself and centers the shadow under
15533         * the touch point.
15534         * </p>
15535         *
15536         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15537         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15538         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15539         * image.
15540         *
15541         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15542         * shadow image that should be underneath the touch point during the drag and drop
15543         * operation. Your application must set {@link android.graphics.Point#x} to the
15544         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15545         */
15546        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15547            final View view = mView.get();
15548            if (view != null) {
15549                shadowSize.set(view.getWidth(), view.getHeight());
15550                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15551            } else {
15552                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15553            }
15554        }
15555
15556        /**
15557         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15558         * based on the dimensions it received from the
15559         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15560         *
15561         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15562         */
15563        public void onDrawShadow(Canvas canvas) {
15564            final View view = mView.get();
15565            if (view != null) {
15566                view.draw(canvas);
15567            } else {
15568                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15569            }
15570        }
15571    }
15572
15573    /**
15574     * Starts a drag and drop operation. When your application calls this method, it passes a
15575     * {@link android.view.View.DragShadowBuilder} object to the system. The
15576     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15577     * to get metrics for the drag shadow, and then calls the object's
15578     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15579     * <p>
15580     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15581     *  drag events to all the View objects in your application that are currently visible. It does
15582     *  this either by calling the View object's drag listener (an implementation of
15583     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15584     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15585     *  Both are passed a {@link android.view.DragEvent} object that has a
15586     *  {@link android.view.DragEvent#getAction()} value of
15587     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15588     * </p>
15589     * <p>
15590     * Your application can invoke startDrag() on any attached View object. The View object does not
15591     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15592     * be related to the View the user selected for dragging.
15593     * </p>
15594     * @param data A {@link android.content.ClipData} object pointing to the data to be
15595     * transferred by the drag and drop operation.
15596     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15597     * drag shadow.
15598     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15599     * drop operation. This Object is put into every DragEvent object sent by the system during the
15600     * current drag.
15601     * <p>
15602     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15603     * to the target Views. For example, it can contain flags that differentiate between a
15604     * a copy operation and a move operation.
15605     * </p>
15606     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15607     * so the parameter should be set to 0.
15608     * @return {@code true} if the method completes successfully, or
15609     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15610     * do a drag, and so no drag operation is in progress.
15611     */
15612    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15613            Object myLocalState, int flags) {
15614        if (ViewDebug.DEBUG_DRAG) {
15615            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15616        }
15617        boolean okay = false;
15618
15619        Point shadowSize = new Point();
15620        Point shadowTouchPoint = new Point();
15621        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15622
15623        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15624                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15625            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15626        }
15627
15628        if (ViewDebug.DEBUG_DRAG) {
15629            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15630                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15631        }
15632        Surface surface = new Surface();
15633        try {
15634            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15635                    flags, shadowSize.x, shadowSize.y, surface);
15636            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15637                    + " surface=" + surface);
15638            if (token != null) {
15639                Canvas canvas = surface.lockCanvas(null);
15640                try {
15641                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15642                    shadowBuilder.onDrawShadow(canvas);
15643                } finally {
15644                    surface.unlockCanvasAndPost(canvas);
15645                }
15646
15647                final ViewRootImpl root = getViewRootImpl();
15648
15649                // Cache the local state object for delivery with DragEvents
15650                root.setLocalDragState(myLocalState);
15651
15652                // repurpose 'shadowSize' for the last touch point
15653                root.getLastTouchPoint(shadowSize);
15654
15655                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15656                        shadowSize.x, shadowSize.y,
15657                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15658                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15659
15660                // Off and running!  Release our local surface instance; the drag
15661                // shadow surface is now managed by the system process.
15662                surface.release();
15663            }
15664        } catch (Exception e) {
15665            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15666            surface.destroy();
15667        }
15668
15669        return okay;
15670    }
15671
15672    /**
15673     * Handles drag events sent by the system following a call to
15674     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15675     *<p>
15676     * When the system calls this method, it passes a
15677     * {@link android.view.DragEvent} object. A call to
15678     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15679     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15680     * operation.
15681     * @param event The {@link android.view.DragEvent} sent by the system.
15682     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15683     * in DragEvent, indicating the type of drag event represented by this object.
15684     * @return {@code true} if the method was successful, otherwise {@code false}.
15685     * <p>
15686     *  The method should return {@code true} in response to an action type of
15687     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15688     *  operation.
15689     * </p>
15690     * <p>
15691     *  The method should also return {@code true} in response to an action type of
15692     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15693     *  {@code false} if it didn't.
15694     * </p>
15695     */
15696    public boolean onDragEvent(DragEvent event) {
15697        return false;
15698    }
15699
15700    /**
15701     * Detects if this View is enabled and has a drag event listener.
15702     * If both are true, then it calls the drag event listener with the
15703     * {@link android.view.DragEvent} it received. If the drag event listener returns
15704     * {@code true}, then dispatchDragEvent() returns {@code true}.
15705     * <p>
15706     * For all other cases, the method calls the
15707     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15708     * method and returns its result.
15709     * </p>
15710     * <p>
15711     * This ensures that a drag event is always consumed, even if the View does not have a drag
15712     * event listener. However, if the View has a listener and the listener returns true, then
15713     * onDragEvent() is not called.
15714     * </p>
15715     */
15716    public boolean dispatchDragEvent(DragEvent event) {
15717        //noinspection SimplifiableIfStatement
15718        ListenerInfo li = mListenerInfo;
15719        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15720                && li.mOnDragListener.onDrag(this, event)) {
15721            return true;
15722        }
15723        return onDragEvent(event);
15724    }
15725
15726    boolean canAcceptDrag() {
15727        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15728    }
15729
15730    /**
15731     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15732     * it is ever exposed at all.
15733     * @hide
15734     */
15735    public void onCloseSystemDialogs(String reason) {
15736    }
15737
15738    /**
15739     * Given a Drawable whose bounds have been set to draw into this view,
15740     * update a Region being computed for
15741     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15742     * that any non-transparent parts of the Drawable are removed from the
15743     * given transparent region.
15744     *
15745     * @param dr The Drawable whose transparency is to be applied to the region.
15746     * @param region A Region holding the current transparency information,
15747     * where any parts of the region that are set are considered to be
15748     * transparent.  On return, this region will be modified to have the
15749     * transparency information reduced by the corresponding parts of the
15750     * Drawable that are not transparent.
15751     * {@hide}
15752     */
15753    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15754        if (DBG) {
15755            Log.i("View", "Getting transparent region for: " + this);
15756        }
15757        final Region r = dr.getTransparentRegion();
15758        final Rect db = dr.getBounds();
15759        final AttachInfo attachInfo = mAttachInfo;
15760        if (r != null && attachInfo != null) {
15761            final int w = getRight()-getLeft();
15762            final int h = getBottom()-getTop();
15763            if (db.left > 0) {
15764                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15765                r.op(0, 0, db.left, h, Region.Op.UNION);
15766            }
15767            if (db.right < w) {
15768                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15769                r.op(db.right, 0, w, h, Region.Op.UNION);
15770            }
15771            if (db.top > 0) {
15772                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15773                r.op(0, 0, w, db.top, Region.Op.UNION);
15774            }
15775            if (db.bottom < h) {
15776                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15777                r.op(0, db.bottom, w, h, Region.Op.UNION);
15778            }
15779            final int[] location = attachInfo.mTransparentLocation;
15780            getLocationInWindow(location);
15781            r.translate(location[0], location[1]);
15782            region.op(r, Region.Op.INTERSECT);
15783        } else {
15784            region.op(db, Region.Op.DIFFERENCE);
15785        }
15786    }
15787
15788    private void checkForLongClick(int delayOffset) {
15789        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15790            mHasPerformedLongPress = false;
15791
15792            if (mPendingCheckForLongPress == null) {
15793                mPendingCheckForLongPress = new CheckForLongPress();
15794            }
15795            mPendingCheckForLongPress.rememberWindowAttachCount();
15796            postDelayed(mPendingCheckForLongPress,
15797                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15798        }
15799    }
15800
15801    /**
15802     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15803     * LayoutInflater} class, which provides a full range of options for view inflation.
15804     *
15805     * @param context The Context object for your activity or application.
15806     * @param resource The resource ID to inflate
15807     * @param root A view group that will be the parent.  Used to properly inflate the
15808     * layout_* parameters.
15809     * @see LayoutInflater
15810     */
15811    public static View inflate(Context context, int resource, ViewGroup root) {
15812        LayoutInflater factory = LayoutInflater.from(context);
15813        return factory.inflate(resource, root);
15814    }
15815
15816    /**
15817     * Scroll the view with standard behavior for scrolling beyond the normal
15818     * content boundaries. Views that call this method should override
15819     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15820     * results of an over-scroll operation.
15821     *
15822     * Views can use this method to handle any touch or fling-based scrolling.
15823     *
15824     * @param deltaX Change in X in pixels
15825     * @param deltaY Change in Y in pixels
15826     * @param scrollX Current X scroll value in pixels before applying deltaX
15827     * @param scrollY Current Y scroll value in pixels before applying deltaY
15828     * @param scrollRangeX Maximum content scroll range along the X axis
15829     * @param scrollRangeY Maximum content scroll range along the Y axis
15830     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15831     *          along the X axis.
15832     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15833     *          along the Y axis.
15834     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15835     * @return true if scrolling was clamped to an over-scroll boundary along either
15836     *          axis, false otherwise.
15837     */
15838    @SuppressWarnings({"UnusedParameters"})
15839    protected boolean overScrollBy(int deltaX, int deltaY,
15840            int scrollX, int scrollY,
15841            int scrollRangeX, int scrollRangeY,
15842            int maxOverScrollX, int maxOverScrollY,
15843            boolean isTouchEvent) {
15844        final int overScrollMode = mOverScrollMode;
15845        final boolean canScrollHorizontal =
15846                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15847        final boolean canScrollVertical =
15848                computeVerticalScrollRange() > computeVerticalScrollExtent();
15849        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15850                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15851        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15852                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15853
15854        int newScrollX = scrollX + deltaX;
15855        if (!overScrollHorizontal) {
15856            maxOverScrollX = 0;
15857        }
15858
15859        int newScrollY = scrollY + deltaY;
15860        if (!overScrollVertical) {
15861            maxOverScrollY = 0;
15862        }
15863
15864        // Clamp values if at the limits and record
15865        final int left = -maxOverScrollX;
15866        final int right = maxOverScrollX + scrollRangeX;
15867        final int top = -maxOverScrollY;
15868        final int bottom = maxOverScrollY + scrollRangeY;
15869
15870        boolean clampedX = false;
15871        if (newScrollX > right) {
15872            newScrollX = right;
15873            clampedX = true;
15874        } else if (newScrollX < left) {
15875            newScrollX = left;
15876            clampedX = true;
15877        }
15878
15879        boolean clampedY = false;
15880        if (newScrollY > bottom) {
15881            newScrollY = bottom;
15882            clampedY = true;
15883        } else if (newScrollY < top) {
15884            newScrollY = top;
15885            clampedY = true;
15886        }
15887
15888        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15889
15890        return clampedX || clampedY;
15891    }
15892
15893    /**
15894     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15895     * respond to the results of an over-scroll operation.
15896     *
15897     * @param scrollX New X scroll value in pixels
15898     * @param scrollY New Y scroll value in pixels
15899     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15900     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15901     */
15902    protected void onOverScrolled(int scrollX, int scrollY,
15903            boolean clampedX, boolean clampedY) {
15904        // Intentionally empty.
15905    }
15906
15907    /**
15908     * Returns the over-scroll mode for this view. The result will be
15909     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15910     * (allow over-scrolling only if the view content is larger than the container),
15911     * or {@link #OVER_SCROLL_NEVER}.
15912     *
15913     * @return This view's over-scroll mode.
15914     */
15915    public int getOverScrollMode() {
15916        return mOverScrollMode;
15917    }
15918
15919    /**
15920     * Set the over-scroll mode for this view. Valid over-scroll modes are
15921     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15922     * (allow over-scrolling only if the view content is larger than the container),
15923     * or {@link #OVER_SCROLL_NEVER}.
15924     *
15925     * Setting the over-scroll mode of a view will have an effect only if the
15926     * view is capable of scrolling.
15927     *
15928     * @param overScrollMode The new over-scroll mode for this view.
15929     */
15930    public void setOverScrollMode(int overScrollMode) {
15931        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15932                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15933                overScrollMode != OVER_SCROLL_NEVER) {
15934            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15935        }
15936        mOverScrollMode = overScrollMode;
15937    }
15938
15939    /**
15940     * Gets a scale factor that determines the distance the view should scroll
15941     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15942     * @return The vertical scroll scale factor.
15943     * @hide
15944     */
15945    protected float getVerticalScrollFactor() {
15946        if (mVerticalScrollFactor == 0) {
15947            TypedValue outValue = new TypedValue();
15948            if (!mContext.getTheme().resolveAttribute(
15949                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15950                throw new IllegalStateException(
15951                        "Expected theme to define listPreferredItemHeight.");
15952            }
15953            mVerticalScrollFactor = outValue.getDimension(
15954                    mContext.getResources().getDisplayMetrics());
15955        }
15956        return mVerticalScrollFactor;
15957    }
15958
15959    /**
15960     * Gets a scale factor that determines the distance the view should scroll
15961     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15962     * @return The horizontal scroll scale factor.
15963     * @hide
15964     */
15965    protected float getHorizontalScrollFactor() {
15966        // TODO: Should use something else.
15967        return getVerticalScrollFactor();
15968    }
15969
15970    /**
15971     * Return the value specifying the text direction or policy that was set with
15972     * {@link #setTextDirection(int)}.
15973     *
15974     * @return the defined text direction. It can be one of:
15975     *
15976     * {@link #TEXT_DIRECTION_INHERIT},
15977     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15978     * {@link #TEXT_DIRECTION_ANY_RTL},
15979     * {@link #TEXT_DIRECTION_LTR},
15980     * {@link #TEXT_DIRECTION_RTL},
15981     * {@link #TEXT_DIRECTION_LOCALE}
15982     * @hide
15983     */
15984    @ViewDebug.ExportedProperty(category = "text", mapping = {
15985            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15986            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15987            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15988            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15989            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15990            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15991    })
15992    public int getTextDirection() {
15993        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15994    }
15995
15996    /**
15997     * Set the text direction.
15998     *
15999     * @param textDirection the direction to set. Should be one of:
16000     *
16001     * {@link #TEXT_DIRECTION_INHERIT},
16002     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16003     * {@link #TEXT_DIRECTION_ANY_RTL},
16004     * {@link #TEXT_DIRECTION_LTR},
16005     * {@link #TEXT_DIRECTION_RTL},
16006     * {@link #TEXT_DIRECTION_LOCALE}
16007     * @hide
16008     */
16009    public void setTextDirection(int textDirection) {
16010        if (getTextDirection() != textDirection) {
16011            // Reset the current text direction and the resolved one
16012            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16013            resetResolvedTextDirection();
16014            // Set the new text direction
16015            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16016            // Refresh
16017            requestLayout();
16018            invalidate(true);
16019        }
16020    }
16021
16022    /**
16023     * Return the resolved text direction.
16024     *
16025     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16026     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16027     * up the parent chain of the view. if there is no parent, then it will return the default
16028     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16029     *
16030     * @return the resolved text direction. Returns one of:
16031     *
16032     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16033     * {@link #TEXT_DIRECTION_ANY_RTL},
16034     * {@link #TEXT_DIRECTION_LTR},
16035     * {@link #TEXT_DIRECTION_RTL},
16036     * {@link #TEXT_DIRECTION_LOCALE}
16037     * @hide
16038     */
16039    public int getResolvedTextDirection() {
16040        // The text direction will be resolved only if needed
16041        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16042            resolveTextDirection();
16043        }
16044        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16045    }
16046
16047    /**
16048     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16049     * resolution is done.
16050     * @hide
16051     */
16052    public void resolveTextDirection() {
16053        // Reset any previous text direction resolution
16054        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16055
16056        if (hasRtlSupport()) {
16057            // Set resolved text direction flag depending on text direction flag
16058            final int textDirection = getTextDirection();
16059            switch(textDirection) {
16060                case TEXT_DIRECTION_INHERIT:
16061                    if (canResolveTextDirection()) {
16062                        ViewGroup viewGroup = ((ViewGroup) mParent);
16063
16064                        // Set current resolved direction to the same value as the parent's one
16065                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16066                        switch (parentResolvedDirection) {
16067                            case TEXT_DIRECTION_FIRST_STRONG:
16068                            case TEXT_DIRECTION_ANY_RTL:
16069                            case TEXT_DIRECTION_LTR:
16070                            case TEXT_DIRECTION_RTL:
16071                            case TEXT_DIRECTION_LOCALE:
16072                                mPrivateFlags2 |=
16073                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16074                                break;
16075                            default:
16076                                // Default resolved direction is "first strong" heuristic
16077                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16078                        }
16079                    } else {
16080                        // We cannot do the resolution if there is no parent, so use the default one
16081                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16082                    }
16083                    break;
16084                case TEXT_DIRECTION_FIRST_STRONG:
16085                case TEXT_DIRECTION_ANY_RTL:
16086                case TEXT_DIRECTION_LTR:
16087                case TEXT_DIRECTION_RTL:
16088                case TEXT_DIRECTION_LOCALE:
16089                    // Resolved direction is the same as text direction
16090                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16091                    break;
16092                default:
16093                    // Default resolved direction is "first strong" heuristic
16094                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16095            }
16096        } else {
16097            // Default resolved direction is "first strong" heuristic
16098            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16099        }
16100
16101        // Set to resolved
16102        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16103        onResolvedTextDirectionChanged();
16104    }
16105
16106    /**
16107     * Called when text direction has been resolved. Subclasses that care about text direction
16108     * resolution should override this method.
16109     *
16110     * The default implementation does nothing.
16111     * @hide
16112     */
16113    public void onResolvedTextDirectionChanged() {
16114    }
16115
16116    /**
16117     * Check if text direction resolution can be done.
16118     *
16119     * @return true if text direction resolution can be done otherwise return false.
16120     * @hide
16121     */
16122    public boolean canResolveTextDirection() {
16123        switch (getTextDirection()) {
16124            case TEXT_DIRECTION_INHERIT:
16125                return (mParent != null) && (mParent instanceof ViewGroup);
16126            default:
16127                return true;
16128        }
16129    }
16130
16131    /**
16132     * Reset resolved text direction. Text direction can be resolved with a call to
16133     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16134     * reset is done.
16135     * @hide
16136     */
16137    public void resetResolvedTextDirection() {
16138        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16139        onResolvedTextDirectionReset();
16140    }
16141
16142    /**
16143     * Called when text direction is reset. Subclasses that care about text direction reset should
16144     * override this method and do a reset of the text direction of their children. The default
16145     * implementation does nothing.
16146     * @hide
16147     */
16148    public void onResolvedTextDirectionReset() {
16149    }
16150
16151    /**
16152     * Return the value specifying the text alignment or policy that was set with
16153     * {@link #setTextAlignment(int)}.
16154     *
16155     * @return the defined text alignment. It can be one of:
16156     *
16157     * {@link #TEXT_ALIGNMENT_INHERIT},
16158     * {@link #TEXT_ALIGNMENT_GRAVITY},
16159     * {@link #TEXT_ALIGNMENT_CENTER},
16160     * {@link #TEXT_ALIGNMENT_TEXT_START},
16161     * {@link #TEXT_ALIGNMENT_TEXT_END},
16162     * {@link #TEXT_ALIGNMENT_VIEW_START},
16163     * {@link #TEXT_ALIGNMENT_VIEW_END}
16164     * @hide
16165     */
16166    @ViewDebug.ExportedProperty(category = "text", mapping = {
16167            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16168            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16169            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16170            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16171            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16172            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16173            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16174    })
16175    public int getTextAlignment() {
16176        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16177    }
16178
16179    /**
16180     * Set the text alignment.
16181     *
16182     * @param textAlignment The text alignment to set. Should be one of
16183     *
16184     * {@link #TEXT_ALIGNMENT_INHERIT},
16185     * {@link #TEXT_ALIGNMENT_GRAVITY},
16186     * {@link #TEXT_ALIGNMENT_CENTER},
16187     * {@link #TEXT_ALIGNMENT_TEXT_START},
16188     * {@link #TEXT_ALIGNMENT_TEXT_END},
16189     * {@link #TEXT_ALIGNMENT_VIEW_START},
16190     * {@link #TEXT_ALIGNMENT_VIEW_END}
16191     *
16192     * @attr ref android.R.styleable#View_textAlignment
16193     * @hide
16194     */
16195    public void setTextAlignment(int textAlignment) {
16196        if (textAlignment != getTextAlignment()) {
16197            // Reset the current and resolved text alignment
16198            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16199            resetResolvedTextAlignment();
16200            // Set the new text alignment
16201            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16202            // Refresh
16203            requestLayout();
16204            invalidate(true);
16205        }
16206    }
16207
16208    /**
16209     * Return the resolved text alignment.
16210     *
16211     * The resolved text alignment. This needs resolution if the value is
16212     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16213     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16214     *
16215     * @return the resolved text alignment. Returns one of:
16216     *
16217     * {@link #TEXT_ALIGNMENT_GRAVITY},
16218     * {@link #TEXT_ALIGNMENT_CENTER},
16219     * {@link #TEXT_ALIGNMENT_TEXT_START},
16220     * {@link #TEXT_ALIGNMENT_TEXT_END},
16221     * {@link #TEXT_ALIGNMENT_VIEW_START},
16222     * {@link #TEXT_ALIGNMENT_VIEW_END}
16223     * @hide
16224     */
16225    @ViewDebug.ExportedProperty(category = "text", mapping = {
16226            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16227            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16228            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16229            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16230            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16231            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16232            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16233    })
16234    public int getResolvedTextAlignment() {
16235        // If text alignment is not resolved, then resolve it
16236        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16237            resolveTextAlignment();
16238        }
16239        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16240    }
16241
16242    /**
16243     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16244     * resolution is done.
16245     * @hide
16246     */
16247    public void resolveTextAlignment() {
16248        // Reset any previous text alignment resolution
16249        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16250
16251        if (hasRtlSupport()) {
16252            // Set resolved text alignment flag depending on text alignment flag
16253            final int textAlignment = getTextAlignment();
16254            switch (textAlignment) {
16255                case TEXT_ALIGNMENT_INHERIT:
16256                    // Check if we can resolve the text alignment
16257                    if (canResolveLayoutDirection() && mParent instanceof View) {
16258                        View view = (View) mParent;
16259
16260                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16261                        switch (parentResolvedTextAlignment) {
16262                            case TEXT_ALIGNMENT_GRAVITY:
16263                            case TEXT_ALIGNMENT_TEXT_START:
16264                            case TEXT_ALIGNMENT_TEXT_END:
16265                            case TEXT_ALIGNMENT_CENTER:
16266                            case TEXT_ALIGNMENT_VIEW_START:
16267                            case TEXT_ALIGNMENT_VIEW_END:
16268                                // Resolved text alignment is the same as the parent resolved
16269                                // text alignment
16270                                mPrivateFlags2 |=
16271                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16272                                break;
16273                            default:
16274                                // Use default resolved text alignment
16275                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16276                        }
16277                    }
16278                    else {
16279                        // We cannot do the resolution if there is no parent so use the default
16280                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16281                    }
16282                    break;
16283                case TEXT_ALIGNMENT_GRAVITY:
16284                case TEXT_ALIGNMENT_TEXT_START:
16285                case TEXT_ALIGNMENT_TEXT_END:
16286                case TEXT_ALIGNMENT_CENTER:
16287                case TEXT_ALIGNMENT_VIEW_START:
16288                case TEXT_ALIGNMENT_VIEW_END:
16289                    // Resolved text alignment is the same as text alignment
16290                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16291                    break;
16292                default:
16293                    // Use default resolved text alignment
16294                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16295            }
16296        } else {
16297            // Use default resolved text alignment
16298            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16299        }
16300
16301        // Set the resolved
16302        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16303        onResolvedTextAlignmentChanged();
16304    }
16305
16306    /**
16307     * Check if text alignment resolution can be done.
16308     *
16309     * @return true if text alignment resolution can be done otherwise return false.
16310     * @hide
16311     */
16312    public boolean canResolveTextAlignment() {
16313        switch (getTextAlignment()) {
16314            case TEXT_DIRECTION_INHERIT:
16315                return (mParent != null);
16316            default:
16317                return true;
16318        }
16319    }
16320
16321    /**
16322     * Called when text alignment has been resolved. Subclasses that care about text alignment
16323     * resolution should override this method.
16324     *
16325     * The default implementation does nothing.
16326     * @hide
16327     */
16328    public void onResolvedTextAlignmentChanged() {
16329    }
16330
16331    /**
16332     * Reset resolved text alignment. Text alignment can be resolved with a call to
16333     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16334     * reset is done.
16335     * @hide
16336     */
16337    public void resetResolvedTextAlignment() {
16338        // Reset any previous text alignment resolution
16339        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16340        onResolvedTextAlignmentReset();
16341    }
16342
16343    /**
16344     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16345     * override this method and do a reset of the text alignment of their children. The default
16346     * implementation does nothing.
16347     * @hide
16348     */
16349    public void onResolvedTextAlignmentReset() {
16350    }
16351
16352    //
16353    // Properties
16354    //
16355    /**
16356     * A Property wrapper around the <code>alpha</code> functionality handled by the
16357     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16358     */
16359    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16360        @Override
16361        public void setValue(View object, float value) {
16362            object.setAlpha(value);
16363        }
16364
16365        @Override
16366        public Float get(View object) {
16367            return object.getAlpha();
16368        }
16369    };
16370
16371    /**
16372     * A Property wrapper around the <code>translationX</code> functionality handled by the
16373     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16374     */
16375    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16376        @Override
16377        public void setValue(View object, float value) {
16378            object.setTranslationX(value);
16379        }
16380
16381                @Override
16382        public Float get(View object) {
16383            return object.getTranslationX();
16384        }
16385    };
16386
16387    /**
16388     * A Property wrapper around the <code>translationY</code> functionality handled by the
16389     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16390     */
16391    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16392        @Override
16393        public void setValue(View object, float value) {
16394            object.setTranslationY(value);
16395        }
16396
16397        @Override
16398        public Float get(View object) {
16399            return object.getTranslationY();
16400        }
16401    };
16402
16403    /**
16404     * A Property wrapper around the <code>x</code> functionality handled by the
16405     * {@link View#setX(float)} and {@link View#getX()} methods.
16406     */
16407    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16408        @Override
16409        public void setValue(View object, float value) {
16410            object.setX(value);
16411        }
16412
16413        @Override
16414        public Float get(View object) {
16415            return object.getX();
16416        }
16417    };
16418
16419    /**
16420     * A Property wrapper around the <code>y</code> functionality handled by the
16421     * {@link View#setY(float)} and {@link View#getY()} methods.
16422     */
16423    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16424        @Override
16425        public void setValue(View object, float value) {
16426            object.setY(value);
16427        }
16428
16429        @Override
16430        public Float get(View object) {
16431            return object.getY();
16432        }
16433    };
16434
16435    /**
16436     * A Property wrapper around the <code>rotation</code> functionality handled by the
16437     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16438     */
16439    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16440        @Override
16441        public void setValue(View object, float value) {
16442            object.setRotation(value);
16443        }
16444
16445        @Override
16446        public Float get(View object) {
16447            return object.getRotation();
16448        }
16449    };
16450
16451    /**
16452     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16453     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16454     */
16455    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16456        @Override
16457        public void setValue(View object, float value) {
16458            object.setRotationX(value);
16459        }
16460
16461        @Override
16462        public Float get(View object) {
16463            return object.getRotationX();
16464        }
16465    };
16466
16467    /**
16468     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16469     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16470     */
16471    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16472        @Override
16473        public void setValue(View object, float value) {
16474            object.setRotationY(value);
16475        }
16476
16477        @Override
16478        public Float get(View object) {
16479            return object.getRotationY();
16480        }
16481    };
16482
16483    /**
16484     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16485     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16486     */
16487    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16488        @Override
16489        public void setValue(View object, float value) {
16490            object.setScaleX(value);
16491        }
16492
16493        @Override
16494        public Float get(View object) {
16495            return object.getScaleX();
16496        }
16497    };
16498
16499    /**
16500     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16501     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16502     */
16503    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16504        @Override
16505        public void setValue(View object, float value) {
16506            object.setScaleY(value);
16507        }
16508
16509        @Override
16510        public Float get(View object) {
16511            return object.getScaleY();
16512        }
16513    };
16514
16515    /**
16516     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16517     * Each MeasureSpec represents a requirement for either the width or the height.
16518     * A MeasureSpec is comprised of a size and a mode. There are three possible
16519     * modes:
16520     * <dl>
16521     * <dt>UNSPECIFIED</dt>
16522     * <dd>
16523     * The parent has not imposed any constraint on the child. It can be whatever size
16524     * it wants.
16525     * </dd>
16526     *
16527     * <dt>EXACTLY</dt>
16528     * <dd>
16529     * The parent has determined an exact size for the child. The child is going to be
16530     * given those bounds regardless of how big it wants to be.
16531     * </dd>
16532     *
16533     * <dt>AT_MOST</dt>
16534     * <dd>
16535     * The child can be as large as it wants up to the specified size.
16536     * </dd>
16537     * </dl>
16538     *
16539     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16540     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16541     */
16542    public static class MeasureSpec {
16543        private static final int MODE_SHIFT = 30;
16544        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16545
16546        /**
16547         * Measure specification mode: The parent has not imposed any constraint
16548         * on the child. It can be whatever size it wants.
16549         */
16550        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16551
16552        /**
16553         * Measure specification mode: The parent has determined an exact size
16554         * for the child. The child is going to be given those bounds regardless
16555         * of how big it wants to be.
16556         */
16557        public static final int EXACTLY     = 1 << MODE_SHIFT;
16558
16559        /**
16560         * Measure specification mode: The child can be as large as it wants up
16561         * to the specified size.
16562         */
16563        public static final int AT_MOST     = 2 << MODE_SHIFT;
16564
16565        /**
16566         * Creates a measure specification based on the supplied size and mode.
16567         *
16568         * The mode must always be one of the following:
16569         * <ul>
16570         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16571         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16572         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16573         * </ul>
16574         *
16575         * @param size the size of the measure specification
16576         * @param mode the mode of the measure specification
16577         * @return the measure specification based on size and mode
16578         */
16579        public static int makeMeasureSpec(int size, int mode) {
16580            return size + mode;
16581        }
16582
16583        /**
16584         * Extracts the mode from the supplied measure specification.
16585         *
16586         * @param measureSpec the measure specification to extract the mode from
16587         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16588         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16589         *         {@link android.view.View.MeasureSpec#EXACTLY}
16590         */
16591        public static int getMode(int measureSpec) {
16592            return (measureSpec & MODE_MASK);
16593        }
16594
16595        /**
16596         * Extracts the size from the supplied measure specification.
16597         *
16598         * @param measureSpec the measure specification to extract the size from
16599         * @return the size in pixels defined in the supplied measure specification
16600         */
16601        public static int getSize(int measureSpec) {
16602            return (measureSpec & ~MODE_MASK);
16603        }
16604
16605        /**
16606         * Returns a String representation of the specified measure
16607         * specification.
16608         *
16609         * @param measureSpec the measure specification to convert to a String
16610         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16611         */
16612        public static String toString(int measureSpec) {
16613            int mode = getMode(measureSpec);
16614            int size = getSize(measureSpec);
16615
16616            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16617
16618            if (mode == UNSPECIFIED)
16619                sb.append("UNSPECIFIED ");
16620            else if (mode == EXACTLY)
16621                sb.append("EXACTLY ");
16622            else if (mode == AT_MOST)
16623                sb.append("AT_MOST ");
16624            else
16625                sb.append(mode).append(" ");
16626
16627            sb.append(size);
16628            return sb.toString();
16629        }
16630    }
16631
16632    class CheckForLongPress implements Runnable {
16633
16634        private int mOriginalWindowAttachCount;
16635
16636        public void run() {
16637            if (isPressed() && (mParent != null)
16638                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16639                if (performLongClick()) {
16640                    mHasPerformedLongPress = true;
16641                }
16642            }
16643        }
16644
16645        public void rememberWindowAttachCount() {
16646            mOriginalWindowAttachCount = mWindowAttachCount;
16647        }
16648    }
16649
16650    private final class CheckForTap implements Runnable {
16651        public void run() {
16652            mPrivateFlags &= ~PREPRESSED;
16653            setPressed(true);
16654            checkForLongClick(ViewConfiguration.getTapTimeout());
16655        }
16656    }
16657
16658    private final class PerformClick implements Runnable {
16659        public void run() {
16660            performClick();
16661        }
16662    }
16663
16664    /** @hide */
16665    public void hackTurnOffWindowResizeAnim(boolean off) {
16666        mAttachInfo.mTurnOffWindowResizeAnim = off;
16667    }
16668
16669    /**
16670     * This method returns a ViewPropertyAnimator object, which can be used to animate
16671     * specific properties on this View.
16672     *
16673     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16674     */
16675    public ViewPropertyAnimator animate() {
16676        if (mAnimator == null) {
16677            mAnimator = new ViewPropertyAnimator(this);
16678        }
16679        return mAnimator;
16680    }
16681
16682    /**
16683     * Interface definition for a callback to be invoked when a key event is
16684     * dispatched to this view. The callback will be invoked before the key
16685     * event is given to the view.
16686     */
16687    public interface OnKeyListener {
16688        /**
16689         * Called when a key is dispatched to a view. This allows listeners to
16690         * get a chance to respond before the target view.
16691         *
16692         * @param v The view the key has been dispatched to.
16693         * @param keyCode The code for the physical key that was pressed
16694         * @param event The KeyEvent object containing full information about
16695         *        the event.
16696         * @return True if the listener has consumed the event, false otherwise.
16697         */
16698        boolean onKey(View v, int keyCode, KeyEvent event);
16699    }
16700
16701    /**
16702     * Interface definition for a callback to be invoked when a touch event is
16703     * dispatched to this view. The callback will be invoked before the touch
16704     * event is given to the view.
16705     */
16706    public interface OnTouchListener {
16707        /**
16708         * Called when a touch 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 touch 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 onTouch(View v, MotionEvent event);
16717    }
16718
16719    /**
16720     * Interface definition for a callback to be invoked when a hover event is
16721     * dispatched to this view. The callback will be invoked before the hover
16722     * event is given to the view.
16723     */
16724    public interface OnHoverListener {
16725        /**
16726         * Called when a hover 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 hover 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 onHover(View v, MotionEvent event);
16735    }
16736
16737    /**
16738     * Interface definition for a callback to be invoked when a generic motion event is
16739     * dispatched to this view. The callback will be invoked before the generic motion
16740     * event is given to the view.
16741     */
16742    public interface OnGenericMotionListener {
16743        /**
16744         * Called when a generic motion event is dispatched to a view. This allows listeners to
16745         * get a chance to respond before the target view.
16746         *
16747         * @param v The view the generic motion event has been dispatched to.
16748         * @param event The MotionEvent object containing full information about
16749         *        the event.
16750         * @return True if the listener has consumed the event, false otherwise.
16751         */
16752        boolean onGenericMotion(View v, MotionEvent event);
16753    }
16754
16755    /**
16756     * Interface definition for a callback to be invoked when a view has been clicked and held.
16757     */
16758    public interface OnLongClickListener {
16759        /**
16760         * Called when a view has been clicked and held.
16761         *
16762         * @param v The view that was clicked and held.
16763         *
16764         * @return true if the callback consumed the long click, false otherwise.
16765         */
16766        boolean onLongClick(View v);
16767    }
16768
16769    /**
16770     * Interface definition for a callback to be invoked when a drag is being dispatched
16771     * to this view.  The callback will be invoked before the hosting view's own
16772     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16773     * onDrag(event) behavior, it should return 'false' from this callback.
16774     *
16775     * <div class="special reference">
16776     * <h3>Developer Guides</h3>
16777     * <p>For a guide to implementing drag and drop features, read the
16778     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16779     * </div>
16780     */
16781    public interface OnDragListener {
16782        /**
16783         * Called when a drag event is dispatched to a view. This allows listeners
16784         * to get a chance to override base View behavior.
16785         *
16786         * @param v The View that received the drag event.
16787         * @param event The {@link android.view.DragEvent} object for the drag event.
16788         * @return {@code true} if the drag event was handled successfully, or {@code false}
16789         * if the drag event was not handled. Note that {@code false} will trigger the View
16790         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16791         */
16792        boolean onDrag(View v, DragEvent event);
16793    }
16794
16795    /**
16796     * Interface definition for a callback to be invoked when the focus state of
16797     * a view changed.
16798     */
16799    public interface OnFocusChangeListener {
16800        /**
16801         * Called when the focus state of a view has changed.
16802         *
16803         * @param v The view whose state has changed.
16804         * @param hasFocus The new focus state of v.
16805         */
16806        void onFocusChange(View v, boolean hasFocus);
16807    }
16808
16809    /**
16810     * Interface definition for a callback to be invoked when a view is clicked.
16811     */
16812    public interface OnClickListener {
16813        /**
16814         * Called when a view has been clicked.
16815         *
16816         * @param v The view that was clicked.
16817         */
16818        void onClick(View v);
16819    }
16820
16821    /**
16822     * Interface definition for a callback to be invoked when the context menu
16823     * for this view is being built.
16824     */
16825    public interface OnCreateContextMenuListener {
16826        /**
16827         * Called when the context menu for this view is being built. It is not
16828         * safe to hold onto the menu after this method returns.
16829         *
16830         * @param menu The context menu that is being built
16831         * @param v The view for which the context menu is being built
16832         * @param menuInfo Extra information about the item for which the
16833         *            context menu should be shown. This information will vary
16834         *            depending on the class of v.
16835         */
16836        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16837    }
16838
16839    /**
16840     * Interface definition for a callback to be invoked when the status bar changes
16841     * visibility.  This reports <strong>global</strong> changes to the system UI
16842     * state, not just what the application is requesting.
16843     *
16844     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16845     */
16846    public interface OnSystemUiVisibilityChangeListener {
16847        /**
16848         * Called when the status bar changes visibility because of a call to
16849         * {@link View#setSystemUiVisibility(int)}.
16850         *
16851         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16852         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16853         * <strong>global</strong> state of the UI visibility flags, not what your
16854         * app is currently applying.
16855         */
16856        public void onSystemUiVisibilityChange(int visibility);
16857    }
16858
16859    /**
16860     * Interface definition for a callback to be invoked when this view is attached
16861     * or detached from its window.
16862     */
16863    public interface OnAttachStateChangeListener {
16864        /**
16865         * Called when the view is attached to a window.
16866         * @param v The view that was attached
16867         */
16868        public void onViewAttachedToWindow(View v);
16869        /**
16870         * Called when the view is detached from a window.
16871         * @param v The view that was detached
16872         */
16873        public void onViewDetachedFromWindow(View v);
16874    }
16875
16876    private final class UnsetPressedState implements Runnable {
16877        public void run() {
16878            setPressed(false);
16879        }
16880    }
16881
16882    /**
16883     * Base class for derived classes that want to save and restore their own
16884     * state in {@link android.view.View#onSaveInstanceState()}.
16885     */
16886    public static class BaseSavedState extends AbsSavedState {
16887        /**
16888         * Constructor used when reading from a parcel. Reads the state of the superclass.
16889         *
16890         * @param source
16891         */
16892        public BaseSavedState(Parcel source) {
16893            super(source);
16894        }
16895
16896        /**
16897         * Constructor called by derived classes when creating their SavedState objects
16898         *
16899         * @param superState The state of the superclass of this view
16900         */
16901        public BaseSavedState(Parcelable superState) {
16902            super(superState);
16903        }
16904
16905        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16906                new Parcelable.Creator<BaseSavedState>() {
16907            public BaseSavedState createFromParcel(Parcel in) {
16908                return new BaseSavedState(in);
16909            }
16910
16911            public BaseSavedState[] newArray(int size) {
16912                return new BaseSavedState[size];
16913            }
16914        };
16915    }
16916
16917    /**
16918     * A set of information given to a view when it is attached to its parent
16919     * window.
16920     */
16921    static class AttachInfo {
16922        interface Callbacks {
16923            void playSoundEffect(int effectId);
16924            boolean performHapticFeedback(int effectId, boolean always);
16925        }
16926
16927        /**
16928         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16929         * to a Handler. This class contains the target (View) to invalidate and
16930         * the coordinates of the dirty rectangle.
16931         *
16932         * For performance purposes, this class also implements a pool of up to
16933         * POOL_LIMIT objects that get reused. This reduces memory allocations
16934         * whenever possible.
16935         */
16936        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16937            private static final int POOL_LIMIT = 10;
16938            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16939                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16940                        public InvalidateInfo newInstance() {
16941                            return new InvalidateInfo();
16942                        }
16943
16944                        public void onAcquired(InvalidateInfo element) {
16945                        }
16946
16947                        public void onReleased(InvalidateInfo element) {
16948                            element.target = null;
16949                        }
16950                    }, POOL_LIMIT)
16951            );
16952
16953            private InvalidateInfo mNext;
16954            private boolean mIsPooled;
16955
16956            View target;
16957
16958            int left;
16959            int top;
16960            int right;
16961            int bottom;
16962
16963            public void setNextPoolable(InvalidateInfo element) {
16964                mNext = element;
16965            }
16966
16967            public InvalidateInfo getNextPoolable() {
16968                return mNext;
16969            }
16970
16971            static InvalidateInfo acquire() {
16972                return sPool.acquire();
16973            }
16974
16975            void release() {
16976                sPool.release(this);
16977            }
16978
16979            public boolean isPooled() {
16980                return mIsPooled;
16981            }
16982
16983            public void setPooled(boolean isPooled) {
16984                mIsPooled = isPooled;
16985            }
16986        }
16987
16988        final IWindowSession mSession;
16989
16990        final IWindow mWindow;
16991
16992        final IBinder mWindowToken;
16993
16994        final Callbacks mRootCallbacks;
16995
16996        HardwareCanvas mHardwareCanvas;
16997
16998        /**
16999         * The top view of the hierarchy.
17000         */
17001        View mRootView;
17002
17003        IBinder mPanelParentWindowToken;
17004        Surface mSurface;
17005
17006        boolean mHardwareAccelerated;
17007        boolean mHardwareAccelerationRequested;
17008        HardwareRenderer mHardwareRenderer;
17009
17010        boolean mScreenOn;
17011
17012        /**
17013         * Scale factor used by the compatibility mode
17014         */
17015        float mApplicationScale;
17016
17017        /**
17018         * Indicates whether the application is in compatibility mode
17019         */
17020        boolean mScalingRequired;
17021
17022        /**
17023         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17024         */
17025        boolean mTurnOffWindowResizeAnim;
17026
17027        /**
17028         * Left position of this view's window
17029         */
17030        int mWindowLeft;
17031
17032        /**
17033         * Top position of this view's window
17034         */
17035        int mWindowTop;
17036
17037        /**
17038         * Indicates whether views need to use 32-bit drawing caches
17039         */
17040        boolean mUse32BitDrawingCache;
17041
17042        /**
17043         * Describes the parts of the window that are currently completely
17044         * obscured by system UI elements.
17045         */
17046        final Rect mSystemInsets = new Rect();
17047
17048        /**
17049         * For windows that are full-screen but using insets to layout inside
17050         * of the screen decorations, these are the current insets for the
17051         * content of the window.
17052         */
17053        final Rect mContentInsets = new Rect();
17054
17055        /**
17056         * For windows that are full-screen but using insets to layout inside
17057         * of the screen decorations, these are the current insets for the
17058         * actual visible parts of the window.
17059         */
17060        final Rect mVisibleInsets = new Rect();
17061
17062        /**
17063         * The internal insets given by this window.  This value is
17064         * supplied by the client (through
17065         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17066         * be given to the window manager when changed to be used in laying
17067         * out windows behind it.
17068         */
17069        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17070                = new ViewTreeObserver.InternalInsetsInfo();
17071
17072        /**
17073         * All views in the window's hierarchy that serve as scroll containers,
17074         * used to determine if the window can be resized or must be panned
17075         * to adjust for a soft input area.
17076         */
17077        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17078
17079        final KeyEvent.DispatcherState mKeyDispatchState
17080                = new KeyEvent.DispatcherState();
17081
17082        /**
17083         * Indicates whether the view's window currently has the focus.
17084         */
17085        boolean mHasWindowFocus;
17086
17087        /**
17088         * The current visibility of the window.
17089         */
17090        int mWindowVisibility;
17091
17092        /**
17093         * Indicates the time at which drawing started to occur.
17094         */
17095        long mDrawingTime;
17096
17097        /**
17098         * Indicates whether or not ignoring the DIRTY_MASK flags.
17099         */
17100        boolean mIgnoreDirtyState;
17101
17102        /**
17103         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17104         * to avoid clearing that flag prematurely.
17105         */
17106        boolean mSetIgnoreDirtyState = false;
17107
17108        /**
17109         * Indicates whether the view's window is currently in touch mode.
17110         */
17111        boolean mInTouchMode;
17112
17113        /**
17114         * Indicates that ViewAncestor should trigger a global layout change
17115         * the next time it performs a traversal
17116         */
17117        boolean mRecomputeGlobalAttributes;
17118
17119        /**
17120         * Always report new attributes at next traversal.
17121         */
17122        boolean mForceReportNewAttributes;
17123
17124        /**
17125         * Set during a traveral if any views want to keep the screen on.
17126         */
17127        boolean mKeepScreenOn;
17128
17129        /**
17130         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17131         */
17132        int mSystemUiVisibility;
17133
17134        /**
17135         * Hack to force certain system UI visibility flags to be cleared.
17136         */
17137        int mDisabledSystemUiVisibility;
17138
17139        /**
17140         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17141         * attached.
17142         */
17143        boolean mHasSystemUiListeners;
17144
17145        /**
17146         * Set if the visibility of any views has changed.
17147         */
17148        boolean mViewVisibilityChanged;
17149
17150        /**
17151         * Set to true if a view has been scrolled.
17152         */
17153        boolean mViewScrollChanged;
17154
17155        /**
17156         * Global to the view hierarchy used as a temporary for dealing with
17157         * x/y points in the transparent region computations.
17158         */
17159        final int[] mTransparentLocation = new int[2];
17160
17161        /**
17162         * Global to the view hierarchy used as a temporary for dealing with
17163         * x/y points in the ViewGroup.invalidateChild implementation.
17164         */
17165        final int[] mInvalidateChildLocation = new int[2];
17166
17167
17168        /**
17169         * Global to the view hierarchy used as a temporary for dealing with
17170         * x/y location when view is transformed.
17171         */
17172        final float[] mTmpTransformLocation = new float[2];
17173
17174        /**
17175         * The view tree observer used to dispatch global events like
17176         * layout, pre-draw, touch mode change, etc.
17177         */
17178        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17179
17180        /**
17181         * A Canvas used by the view hierarchy to perform bitmap caching.
17182         */
17183        Canvas mCanvas;
17184
17185        /**
17186         * The view root impl.
17187         */
17188        final ViewRootImpl mViewRootImpl;
17189
17190        /**
17191         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17192         * handler can be used to pump events in the UI events queue.
17193         */
17194        final Handler mHandler;
17195
17196        /**
17197         * Temporary for use in computing invalidate rectangles while
17198         * calling up the hierarchy.
17199         */
17200        final Rect mTmpInvalRect = new Rect();
17201
17202        /**
17203         * Temporary for use in computing hit areas with transformed views
17204         */
17205        final RectF mTmpTransformRect = new RectF();
17206
17207        /**
17208         * Temporary list for use in collecting focusable descendents of a view.
17209         */
17210        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17211
17212        /**
17213         * The id of the window for accessibility purposes.
17214         */
17215        int mAccessibilityWindowId = View.NO_ID;
17216
17217        /**
17218         * Whether to ingore not exposed for accessibility Views when
17219         * reporting the view tree to accessibility services.
17220         */
17221        boolean mIncludeNotImportantViews;
17222
17223        /**
17224         * The drawable for highlighting accessibility focus.
17225         */
17226        Drawable mAccessibilityFocusDrawable;
17227
17228        /**
17229         * Show where the margins, bounds and layout bounds are for each view.
17230         */
17231        final boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17232
17233        /**
17234         * Point used to compute visible regions.
17235         */
17236        final Point mPoint = new Point();
17237
17238        /**
17239         * Creates a new set of attachment information with the specified
17240         * events handler and thread.
17241         *
17242         * @param handler the events handler the view must use
17243         */
17244        AttachInfo(IWindowSession session, IWindow window,
17245                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17246            mSession = session;
17247            mWindow = window;
17248            mWindowToken = window.asBinder();
17249            mViewRootImpl = viewRootImpl;
17250            mHandler = handler;
17251            mRootCallbacks = effectPlayer;
17252        }
17253    }
17254
17255    /**
17256     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17257     * is supported. This avoids keeping too many unused fields in most
17258     * instances of View.</p>
17259     */
17260    private static class ScrollabilityCache implements Runnable {
17261
17262        /**
17263         * Scrollbars are not visible
17264         */
17265        public static final int OFF = 0;
17266
17267        /**
17268         * Scrollbars are visible
17269         */
17270        public static final int ON = 1;
17271
17272        /**
17273         * Scrollbars are fading away
17274         */
17275        public static final int FADING = 2;
17276
17277        public boolean fadeScrollBars;
17278
17279        public int fadingEdgeLength;
17280        public int scrollBarDefaultDelayBeforeFade;
17281        public int scrollBarFadeDuration;
17282
17283        public int scrollBarSize;
17284        public ScrollBarDrawable scrollBar;
17285        public float[] interpolatorValues;
17286        public View host;
17287
17288        public final Paint paint;
17289        public final Matrix matrix;
17290        public Shader shader;
17291
17292        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17293
17294        private static final float[] OPAQUE = { 255 };
17295        private static final float[] TRANSPARENT = { 0.0f };
17296
17297        /**
17298         * When fading should start. This time moves into the future every time
17299         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17300         */
17301        public long fadeStartTime;
17302
17303
17304        /**
17305         * The current state of the scrollbars: ON, OFF, or FADING
17306         */
17307        public int state = OFF;
17308
17309        private int mLastColor;
17310
17311        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17312            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17313            scrollBarSize = configuration.getScaledScrollBarSize();
17314            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17315            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17316
17317            paint = new Paint();
17318            matrix = new Matrix();
17319            // use use a height of 1, and then wack the matrix each time we
17320            // actually use it.
17321            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17322
17323            paint.setShader(shader);
17324            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17325            this.host = host;
17326        }
17327
17328        public void setFadeColor(int color) {
17329            if (color != 0 && color != mLastColor) {
17330                mLastColor = color;
17331                color |= 0xFF000000;
17332
17333                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17334                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17335
17336                paint.setShader(shader);
17337                // Restore the default transfer mode (src_over)
17338                paint.setXfermode(null);
17339            }
17340        }
17341
17342        public void run() {
17343            long now = AnimationUtils.currentAnimationTimeMillis();
17344            if (now >= fadeStartTime) {
17345
17346                // the animation fades the scrollbars out by changing
17347                // the opacity (alpha) from fully opaque to fully
17348                // transparent
17349                int nextFrame = (int) now;
17350                int framesCount = 0;
17351
17352                Interpolator interpolator = scrollBarInterpolator;
17353
17354                // Start opaque
17355                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17356
17357                // End transparent
17358                nextFrame += scrollBarFadeDuration;
17359                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17360
17361                state = FADING;
17362
17363                // Kick off the fade animation
17364                host.invalidate(true);
17365            }
17366        }
17367    }
17368
17369    /**
17370     * Resuable callback for sending
17371     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17372     */
17373    private class SendViewScrolledAccessibilityEvent implements Runnable {
17374        public volatile boolean mIsPending;
17375
17376        public void run() {
17377            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17378            mIsPending = false;
17379        }
17380    }
17381
17382    /**
17383     * <p>
17384     * This class represents a delegate that can be registered in a {@link View}
17385     * to enhance accessibility support via composition rather via inheritance.
17386     * It is specifically targeted to widget developers that extend basic View
17387     * classes i.e. classes in package android.view, that would like their
17388     * applications to be backwards compatible.
17389     * </p>
17390     * <div class="special reference">
17391     * <h3>Developer Guides</h3>
17392     * <p>For more information about making applications accessible, read the
17393     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17394     * developer guide.</p>
17395     * </div>
17396     * <p>
17397     * A scenario in which a developer would like to use an accessibility delegate
17398     * is overriding a method introduced in a later API version then the minimal API
17399     * version supported by the application. For example, the method
17400     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17401     * in API version 4 when the accessibility APIs were first introduced. If a
17402     * developer would like his application to run on API version 4 devices (assuming
17403     * all other APIs used by the application are version 4 or lower) and take advantage
17404     * of this method, instead of overriding the method which would break the application's
17405     * backwards compatibility, he can override the corresponding method in this
17406     * delegate and register the delegate in the target View if the API version of
17407     * the system is high enough i.e. the API version is same or higher to the API
17408     * version that introduced
17409     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17410     * </p>
17411     * <p>
17412     * Here is an example implementation:
17413     * </p>
17414     * <code><pre><p>
17415     * if (Build.VERSION.SDK_INT >= 14) {
17416     *     // If the API version is equal of higher than the version in
17417     *     // which onInitializeAccessibilityNodeInfo was introduced we
17418     *     // register a delegate with a customized implementation.
17419     *     View view = findViewById(R.id.view_id);
17420     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17421     *         public void onInitializeAccessibilityNodeInfo(View host,
17422     *                 AccessibilityNodeInfo info) {
17423     *             // Let the default implementation populate the info.
17424     *             super.onInitializeAccessibilityNodeInfo(host, info);
17425     *             // Set some other information.
17426     *             info.setEnabled(host.isEnabled());
17427     *         }
17428     *     });
17429     * }
17430     * </code></pre></p>
17431     * <p>
17432     * This delegate contains methods that correspond to the accessibility methods
17433     * in View. If a delegate has been specified the implementation in View hands
17434     * off handling to the corresponding method in this delegate. The default
17435     * implementation the delegate methods behaves exactly as the corresponding
17436     * method in View for the case of no accessibility delegate been set. Hence,
17437     * to customize the behavior of a View method, clients can override only the
17438     * corresponding delegate method without altering the behavior of the rest
17439     * accessibility related methods of the host view.
17440     * </p>
17441     */
17442    public static class AccessibilityDelegate {
17443
17444        /**
17445         * Sends an accessibility event of the given type. If accessibility is not
17446         * enabled this method has no effect.
17447         * <p>
17448         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17449         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17450         * been set.
17451         * </p>
17452         *
17453         * @param host The View hosting the delegate.
17454         * @param eventType The type of the event to send.
17455         *
17456         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17457         */
17458        public void sendAccessibilityEvent(View host, int eventType) {
17459            host.sendAccessibilityEventInternal(eventType);
17460        }
17461
17462        /**
17463         * Sends an accessibility event. This method behaves exactly as
17464         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17465         * empty {@link AccessibilityEvent} and does not perform a check whether
17466         * accessibility is enabled.
17467         * <p>
17468         * The default implementation behaves as
17469         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17470         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17471         * the case of no accessibility delegate been set.
17472         * </p>
17473         *
17474         * @param host The View hosting the delegate.
17475         * @param event The event to send.
17476         *
17477         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17478         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17479         */
17480        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17481            host.sendAccessibilityEventUncheckedInternal(event);
17482        }
17483
17484        /**
17485         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17486         * to its children for adding their text content to the event.
17487         * <p>
17488         * The default implementation behaves as
17489         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17490         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17491         * the case of no accessibility delegate been set.
17492         * </p>
17493         *
17494         * @param host The View hosting the delegate.
17495         * @param event The event.
17496         * @return True if the event population was completed.
17497         *
17498         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17499         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17500         */
17501        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17502            return host.dispatchPopulateAccessibilityEventInternal(event);
17503        }
17504
17505        /**
17506         * Gives a chance to the host View to populate the accessibility event with its
17507         * text content.
17508         * <p>
17509         * The default implementation behaves as
17510         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17511         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17512         * the case of no accessibility delegate been set.
17513         * </p>
17514         *
17515         * @param host The View hosting the delegate.
17516         * @param event The accessibility event which to populate.
17517         *
17518         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17519         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17520         */
17521        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17522            host.onPopulateAccessibilityEventInternal(event);
17523        }
17524
17525        /**
17526         * Initializes an {@link AccessibilityEvent} with information about the
17527         * the host View which is the event source.
17528         * <p>
17529         * The default implementation behaves as
17530         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17531         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17532         * the case of no accessibility delegate been set.
17533         * </p>
17534         *
17535         * @param host The View hosting the delegate.
17536         * @param event The event to initialize.
17537         *
17538         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17539         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17540         */
17541        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17542            host.onInitializeAccessibilityEventInternal(event);
17543        }
17544
17545        /**
17546         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17547         * <p>
17548         * The default implementation behaves as
17549         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17550         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17551         * the case of no accessibility delegate been set.
17552         * </p>
17553         *
17554         * @param host The View hosting the delegate.
17555         * @param info The instance to initialize.
17556         *
17557         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17558         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17559         */
17560        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17561            host.onInitializeAccessibilityNodeInfoInternal(info);
17562        }
17563
17564        /**
17565         * Called when a child of the host View has requested sending an
17566         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17567         * to augment the event.
17568         * <p>
17569         * The default implementation behaves as
17570         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17571         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17572         * the case of no accessibility delegate been set.
17573         * </p>
17574         *
17575         * @param host The View hosting the delegate.
17576         * @param child The child which requests sending the event.
17577         * @param event The event to be sent.
17578         * @return True if the event should be sent
17579         *
17580         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17581         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17582         */
17583        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17584                AccessibilityEvent event) {
17585            return host.onRequestSendAccessibilityEventInternal(child, event);
17586        }
17587
17588        /**
17589         * Gets the provider for managing a virtual view hierarchy rooted at this View
17590         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17591         * that explore the window content.
17592         * <p>
17593         * The default implementation behaves as
17594         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17595         * the case of no accessibility delegate been set.
17596         * </p>
17597         *
17598         * @return The provider.
17599         *
17600         * @see AccessibilityNodeProvider
17601         */
17602        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17603            return null;
17604        }
17605    }
17606}
17607