View.java revision 5b5cc4d5361c1817938d2db58ad40aab528b3ac3
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    /**
2132     * Flag indicating that view has an animation set on it. This is used to track whether an
2133     * animation is cleared between successive frames, in order to tell the associated
2134     * DisplayList to clear its animation matrix.
2135     */
2136    static final int VIEW_IS_ANIMATING_TRANSFORM = 0x10000000;
2137
2138    /**
2139     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2140     * is used to check whether later changes to the view's transform should invalidate the
2141     * view to force the quickReject test to run again.
2142     */
2143    static final int VIEW_QUICK_REJECTED = 0x20000000;
2144
2145    /* End of masks for mPrivateFlags2 */
2146
2147    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2148
2149    /**
2150     * Always allow a user to over-scroll this view, provided it is a
2151     * view that can scroll.
2152     *
2153     * @see #getOverScrollMode()
2154     * @see #setOverScrollMode(int)
2155     */
2156    public static final int OVER_SCROLL_ALWAYS = 0;
2157
2158    /**
2159     * Allow a user to over-scroll this view only if the content is large
2160     * enough to meaningfully scroll, provided it is a view that can scroll.
2161     *
2162     * @see #getOverScrollMode()
2163     * @see #setOverScrollMode(int)
2164     */
2165    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2166
2167    /**
2168     * Never allow a user to over-scroll this view.
2169     *
2170     * @see #getOverScrollMode()
2171     * @see #setOverScrollMode(int)
2172     */
2173    public static final int OVER_SCROLL_NEVER = 2;
2174
2175    /**
2176     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2177     * requested the system UI (status bar) to be visible (the default).
2178     *
2179     * @see #setSystemUiVisibility(int)
2180     */
2181    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2182
2183    /**
2184     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2185     * system UI to enter an unobtrusive "low profile" mode.
2186     *
2187     * <p>This is for use in games, book readers, video players, or any other
2188     * "immersive" application where the usual system chrome is deemed too distracting.
2189     *
2190     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2191     *
2192     * @see #setSystemUiVisibility(int)
2193     */
2194    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2195
2196    /**
2197     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2198     * system navigation be temporarily hidden.
2199     *
2200     * <p>This is an even less obtrusive state than that called for by
2201     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2202     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2203     * those to disappear. This is useful (in conjunction with the
2204     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2205     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2206     * window flags) for displaying content using every last pixel on the display.
2207     *
2208     * <p>There is a limitation: because navigation controls are so important, the least user
2209     * interaction will cause them to reappear immediately.  When this happens, both
2210     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2211     * so that both elements reappear at the same time.
2212     *
2213     * @see #setSystemUiVisibility(int)
2214     */
2215    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2216
2217    /**
2218     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2219     * into the normal fullscreen mode so that its content can take over the screen
2220     * while still allowing the user to interact with the application.
2221     *
2222     * <p>This has the same visual effect as
2223     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2224     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2225     * meaning that non-critical screen decorations (such as the status bar) will be
2226     * hidden while the user is in the View's window, focusing the experience on
2227     * that content.  Unlike the window flag, if you are using ActionBar in
2228     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2229     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2230     * hide the action bar.
2231     *
2232     * <p>This approach to going fullscreen is best used over the window flag when
2233     * it is a transient state -- that is, the application does this at certain
2234     * points in its user interaction where it wants to allow the user to focus
2235     * on content, but not as a continuous state.  For situations where the application
2236     * would like to simply stay full screen the entire time (such as a game that
2237     * wants to take over the screen), the
2238     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2239     * is usually a better approach.  The state set here will be removed by the system
2240     * in various situations (such as the user moving to another application) like
2241     * the other system UI states.
2242     *
2243     * <p>When using this flag, the application should provide some easy facility
2244     * for the user to go out of it.  A common example would be in an e-book
2245     * reader, where tapping on the screen brings back whatever screen and UI
2246     * decorations that had been hidden while the user was immersed in reading
2247     * the book.
2248     *
2249     * @see #setSystemUiVisibility(int)
2250     */
2251    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2252
2253    /**
2254     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2255     * flags, we would like a stable view of the content insets given to
2256     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2257     * will always represent the worst case that the application can expect
2258     * as a continuous state.  In the stock Android UI this is the space for
2259     * the system bar, nav bar, and status bar, but not more transient elements
2260     * such as an input method.
2261     *
2262     * The stable layout your UI sees is based on the system UI modes you can
2263     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2264     * then you will get a stable layout for changes of the
2265     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2266     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2267     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2268     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2269     * with a stable layout.  (Note that you should avoid using
2270     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2271     *
2272     * If you have set the window flag {@ WindowManager.LayoutParams#FLAG_FULLSCREEN}
2273     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2274     * then a hidden status bar will be considered a "stable" state for purposes
2275     * here.  This allows your UI to continually hide the status bar, while still
2276     * using the system UI flags to hide the action bar while still retaining
2277     * a stable layout.  Note that changing the window fullscreen flag will never
2278     * provide a stable layout for a clean transition.
2279     *
2280     * <p>If you are using ActionBar in
2281     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2282     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2283     * insets it adds to those given to the application.
2284     */
2285    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2286
2287    /**
2288     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2289     * to be layed out as if it has requested
2290     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2291     * allows it to avoid artifacts when switching in and out of that mode, at
2292     * the expense that some of its user interface may be covered by screen
2293     * decorations when they are shown.  You can perform layout of your inner
2294     * UI elements to account for the navagation system UI through the
2295     * {@link #fitSystemWindows(Rect)} method.
2296     */
2297    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2298
2299    /**
2300     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2301     * to be layed out as if it has requested
2302     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2303     * allows it to avoid artifacts when switching in and out of that mode, at
2304     * the expense that some of its user interface may be covered by screen
2305     * decorations when they are shown.  You can perform layout of your inner
2306     * UI elements to account for non-fullscreen system UI through the
2307     * {@link #fitSystemWindows(Rect)} method.
2308     */
2309    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2310
2311    /**
2312     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2313     */
2314    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2315
2316    /**
2317     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2318     */
2319    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
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 make the status bar not expandable.  Unless you also
2328     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2329     */
2330    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2331
2332    /**
2333     * @hide
2334     *
2335     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2336     * out of the public fields to keep the undefined bits out of the developer's way.
2337     *
2338     * Flag to hide notification icons and scrolling ticker text.
2339     */
2340    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2341
2342    /**
2343     * @hide
2344     *
2345     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2346     * out of the public fields to keep the undefined bits out of the developer's way.
2347     *
2348     * Flag to disable incoming notification alerts.  This will not block
2349     * icons, but it will block sound, vibrating and other visual or aural notifications.
2350     */
2351    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2352
2353    /**
2354     * @hide
2355     *
2356     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2357     * out of the public fields to keep the undefined bits out of the developer's way.
2358     *
2359     * Flag to hide only the scrolling ticker.  Note that
2360     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2361     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2362     */
2363    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
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 the center system info area.
2372     */
2373    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2374
2375    /**
2376     * @hide
2377     *
2378     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2379     * out of the public fields to keep the undefined bits out of the developer's way.
2380     *
2381     * Flag to hide only the home button.  Don't use this
2382     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2383     */
2384    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2385
2386    /**
2387     * @hide
2388     *
2389     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2390     * out of the public fields to keep the undefined bits out of the developer's way.
2391     *
2392     * Flag to hide only the back button. Don't use this
2393     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2394     */
2395    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2396
2397    /**
2398     * @hide
2399     *
2400     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2401     * out of the public fields to keep the undefined bits out of the developer's way.
2402     *
2403     * Flag to hide only the clock.  You might use this if your activity has
2404     * its own clock making the status bar's clock redundant.
2405     */
2406    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2407
2408    /**
2409     * @hide
2410     *
2411     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2412     * out of the public fields to keep the undefined bits out of the developer's way.
2413     *
2414     * Flag to hide only the recent apps button. Don't use this
2415     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2416     */
2417    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2418
2419    /**
2420     * @hide
2421     */
2422    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2423
2424    /**
2425     * These are the system UI flags that can be cleared by events outside
2426     * of an application.  Currently this is just the ability to tap on the
2427     * screen while hiding the navigation bar to have it return.
2428     * @hide
2429     */
2430    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2431            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2432            | SYSTEM_UI_FLAG_FULLSCREEN;
2433
2434    /**
2435     * Flags that can impact the layout in relation to system UI.
2436     */
2437    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2438            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2439            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2440
2441    /**
2442     * Find views that render the specified text.
2443     *
2444     * @see #findViewsWithText(ArrayList, CharSequence, int)
2445     */
2446    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2447
2448    /**
2449     * Find find views that contain the specified content description.
2450     *
2451     * @see #findViewsWithText(ArrayList, CharSequence, int)
2452     */
2453    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2454
2455    /**
2456     * Find views that contain {@link AccessibilityNodeProvider}. Such
2457     * a View is a root of virtual view hierarchy and may contain the searched
2458     * text. If this flag is set Views with providers are automatically
2459     * added and it is a responsibility of the client to call the APIs of
2460     * the provider to determine whether the virtual tree rooted at this View
2461     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2462     * represeting the virtual views with this text.
2463     *
2464     * @see #findViewsWithText(ArrayList, CharSequence, int)
2465     *
2466     * @hide
2467     */
2468    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2469
2470    /**
2471     * Indicates that the screen has changed state and is now off.
2472     *
2473     * @see #onScreenStateChanged(int)
2474     */
2475    public static final int SCREEN_STATE_OFF = 0x0;
2476
2477    /**
2478     * Indicates that the screen has changed state and is now on.
2479     *
2480     * @see #onScreenStateChanged(int)
2481     */
2482    public static final int SCREEN_STATE_ON = 0x1;
2483
2484    /**
2485     * Controls the over-scroll mode for this view.
2486     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2487     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2488     * and {@link #OVER_SCROLL_NEVER}.
2489     */
2490    private int mOverScrollMode;
2491
2492    /**
2493     * The parent this view is attached to.
2494     * {@hide}
2495     *
2496     * @see #getParent()
2497     */
2498    protected ViewParent mParent;
2499
2500    /**
2501     * {@hide}
2502     */
2503    AttachInfo mAttachInfo;
2504
2505    /**
2506     * {@hide}
2507     */
2508    @ViewDebug.ExportedProperty(flagMapping = {
2509        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2510                name = "FORCE_LAYOUT"),
2511        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2512                name = "LAYOUT_REQUIRED"),
2513        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2514            name = "DRAWING_CACHE_INVALID", outputIf = false),
2515        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2516        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2517        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2518        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2519    })
2520    int mPrivateFlags;
2521    int mPrivateFlags2;
2522
2523    /**
2524     * This view's request for the visibility of the status bar.
2525     * @hide
2526     */
2527    @ViewDebug.ExportedProperty(flagMapping = {
2528        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2529                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2530                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2531        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2532                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2533                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2534        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2535                                equals = SYSTEM_UI_FLAG_VISIBLE,
2536                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2537    })
2538    int mSystemUiVisibility;
2539
2540    /**
2541     * Reference count for transient state.
2542     * @see #setHasTransientState(boolean)
2543     */
2544    int mTransientStateCount = 0;
2545
2546    /**
2547     * Count of how many windows this view has been attached to.
2548     */
2549    int mWindowAttachCount;
2550
2551    /**
2552     * The layout parameters associated with this view and used by the parent
2553     * {@link android.view.ViewGroup} to determine how this view should be
2554     * laid out.
2555     * {@hide}
2556     */
2557    protected ViewGroup.LayoutParams mLayoutParams;
2558
2559    /**
2560     * The view flags hold various views states.
2561     * {@hide}
2562     */
2563    @ViewDebug.ExportedProperty
2564    int mViewFlags;
2565
2566    static class TransformationInfo {
2567        /**
2568         * The transform matrix for the View. This transform is calculated internally
2569         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2570         * is used by default. Do *not* use this variable directly; instead call
2571         * getMatrix(), which will automatically recalculate the matrix if necessary
2572         * to get the correct matrix based on the latest rotation and scale properties.
2573         */
2574        private final Matrix mMatrix = new Matrix();
2575
2576        /**
2577         * The transform matrix for the View. This transform is calculated internally
2578         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2579         * is used by default. Do *not* use this variable directly; instead call
2580         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2581         * to get the correct matrix based on the latest rotation and scale properties.
2582         */
2583        private Matrix mInverseMatrix;
2584
2585        /**
2586         * An internal variable that tracks whether we need to recalculate the
2587         * transform matrix, based on whether the rotation or scaleX/Y properties
2588         * have changed since the matrix was last calculated.
2589         */
2590        boolean mMatrixDirty = false;
2591
2592        /**
2593         * An internal variable that tracks whether we need to recalculate the
2594         * transform matrix, based on whether the rotation or scaleX/Y properties
2595         * have changed since the matrix was last calculated.
2596         */
2597        private boolean mInverseMatrixDirty = true;
2598
2599        /**
2600         * A variable that tracks whether we need to recalculate the
2601         * transform matrix, based on whether the rotation or scaleX/Y properties
2602         * have changed since the matrix was last calculated. This variable
2603         * is only valid after a call to updateMatrix() or to a function that
2604         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2605         */
2606        private boolean mMatrixIsIdentity = true;
2607
2608        /**
2609         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2610         */
2611        private Camera mCamera = null;
2612
2613        /**
2614         * This matrix is used when computing the matrix for 3D rotations.
2615         */
2616        private Matrix matrix3D = null;
2617
2618        /**
2619         * These prev values are used to recalculate a centered pivot point when necessary. The
2620         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2621         * set), so thes values are only used then as well.
2622         */
2623        private int mPrevWidth = -1;
2624        private int mPrevHeight = -1;
2625
2626        /**
2627         * The degrees rotation around the vertical axis through the pivot point.
2628         */
2629        @ViewDebug.ExportedProperty
2630        float mRotationY = 0f;
2631
2632        /**
2633         * The degrees rotation around the horizontal axis through the pivot point.
2634         */
2635        @ViewDebug.ExportedProperty
2636        float mRotationX = 0f;
2637
2638        /**
2639         * The degrees rotation around the pivot point.
2640         */
2641        @ViewDebug.ExportedProperty
2642        float mRotation = 0f;
2643
2644        /**
2645         * The amount of translation of the object away from its left property (post-layout).
2646         */
2647        @ViewDebug.ExportedProperty
2648        float mTranslationX = 0f;
2649
2650        /**
2651         * The amount of translation of the object away from its top property (post-layout).
2652         */
2653        @ViewDebug.ExportedProperty
2654        float mTranslationY = 0f;
2655
2656        /**
2657         * The amount of scale in the x direction around the pivot point. A
2658         * value of 1 means no scaling is applied.
2659         */
2660        @ViewDebug.ExportedProperty
2661        float mScaleX = 1f;
2662
2663        /**
2664         * The amount of scale in the y direction around the pivot point. A
2665         * value of 1 means no scaling is applied.
2666         */
2667        @ViewDebug.ExportedProperty
2668        float mScaleY = 1f;
2669
2670        /**
2671         * The x location of the point around which the view is rotated and scaled.
2672         */
2673        @ViewDebug.ExportedProperty
2674        float mPivotX = 0f;
2675
2676        /**
2677         * The y location of the point around which the view is rotated and scaled.
2678         */
2679        @ViewDebug.ExportedProperty
2680        float mPivotY = 0f;
2681
2682        /**
2683         * The opacity of the View. This is a value from 0 to 1, where 0 means
2684         * completely transparent and 1 means completely opaque.
2685         */
2686        @ViewDebug.ExportedProperty
2687        float mAlpha = 1f;
2688    }
2689
2690    TransformationInfo mTransformationInfo;
2691
2692    private boolean mLastIsOpaque;
2693
2694    /**
2695     * Convenience value to check for float values that are close enough to zero to be considered
2696     * zero.
2697     */
2698    private static final float NONZERO_EPSILON = .001f;
2699
2700    /**
2701     * The distance in pixels from the left edge of this view's parent
2702     * to the left edge of this view.
2703     * {@hide}
2704     */
2705    @ViewDebug.ExportedProperty(category = "layout")
2706    protected int mLeft;
2707    /**
2708     * The distance in pixels from the left edge of this view's parent
2709     * to the right edge of this view.
2710     * {@hide}
2711     */
2712    @ViewDebug.ExportedProperty(category = "layout")
2713    protected int mRight;
2714    /**
2715     * The distance in pixels from the top edge of this view's parent
2716     * to the top edge of this view.
2717     * {@hide}
2718     */
2719    @ViewDebug.ExportedProperty(category = "layout")
2720    protected int mTop;
2721    /**
2722     * The distance in pixels from the top edge of this view's parent
2723     * to the bottom edge of this view.
2724     * {@hide}
2725     */
2726    @ViewDebug.ExportedProperty(category = "layout")
2727    protected int mBottom;
2728
2729    /**
2730     * The offset, in pixels, by which the content of this view is scrolled
2731     * horizontally.
2732     * {@hide}
2733     */
2734    @ViewDebug.ExportedProperty(category = "scrolling")
2735    protected int mScrollX;
2736    /**
2737     * The offset, in pixels, by which the content of this view is scrolled
2738     * vertically.
2739     * {@hide}
2740     */
2741    @ViewDebug.ExportedProperty(category = "scrolling")
2742    protected int mScrollY;
2743
2744    /**
2745     * The left padding in pixels, that is the distance in pixels between the
2746     * left edge of this view and the left edge of its content.
2747     * {@hide}
2748     */
2749    @ViewDebug.ExportedProperty(category = "padding")
2750    protected int mPaddingLeft;
2751    /**
2752     * The right padding in pixels, that is the distance in pixels between the
2753     * right edge of this view and the right edge of its content.
2754     * {@hide}
2755     */
2756    @ViewDebug.ExportedProperty(category = "padding")
2757    protected int mPaddingRight;
2758    /**
2759     * The top padding in pixels, that is the distance in pixels between the
2760     * top edge of this view and the top edge of its content.
2761     * {@hide}
2762     */
2763    @ViewDebug.ExportedProperty(category = "padding")
2764    protected int mPaddingTop;
2765    /**
2766     * The bottom padding in pixels, that is the distance in pixels between the
2767     * bottom edge of this view and the bottom edge of its content.
2768     * {@hide}
2769     */
2770    @ViewDebug.ExportedProperty(category = "padding")
2771    protected int mPaddingBottom;
2772
2773    /**
2774     * The layout insets in pixels, that is the distance in pixels between the
2775     * visible edges of this view its bounds.
2776     */
2777    private Insets mLayoutInsets;
2778
2779    /**
2780     * Briefly describes the view and is primarily used for accessibility support.
2781     */
2782    private CharSequence mContentDescription;
2783
2784    /**
2785     * Cache the paddingRight set by the user to append to the scrollbar's size.
2786     *
2787     * @hide
2788     */
2789    @ViewDebug.ExportedProperty(category = "padding")
2790    protected int mUserPaddingRight;
2791
2792    /**
2793     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2794     *
2795     * @hide
2796     */
2797    @ViewDebug.ExportedProperty(category = "padding")
2798    protected int mUserPaddingBottom;
2799
2800    /**
2801     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2802     *
2803     * @hide
2804     */
2805    @ViewDebug.ExportedProperty(category = "padding")
2806    protected int mUserPaddingLeft;
2807
2808    /**
2809     * Cache if the user padding is relative.
2810     *
2811     */
2812    @ViewDebug.ExportedProperty(category = "padding")
2813    boolean mUserPaddingRelative;
2814
2815    /**
2816     * Cache the paddingStart set by the user to append to the scrollbar's size.
2817     *
2818     */
2819    @ViewDebug.ExportedProperty(category = "padding")
2820    int mUserPaddingStart;
2821
2822    /**
2823     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2824     *
2825     */
2826    @ViewDebug.ExportedProperty(category = "padding")
2827    int mUserPaddingEnd;
2828
2829    /**
2830     * @hide
2831     */
2832    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2833    /**
2834     * @hide
2835     */
2836    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2837
2838    private Drawable mBackground;
2839
2840    private int mBackgroundResource;
2841    private boolean mBackgroundSizeChanged;
2842
2843    static class ListenerInfo {
2844        /**
2845         * Listener used to dispatch focus change events.
2846         * This field should be made private, so it is hidden from the SDK.
2847         * {@hide}
2848         */
2849        protected OnFocusChangeListener mOnFocusChangeListener;
2850
2851        /**
2852         * Listeners for layout change events.
2853         */
2854        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2855
2856        /**
2857         * Listeners for attach events.
2858         */
2859        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2860
2861        /**
2862         * Listener used to dispatch click events.
2863         * This field should be made private, so it is hidden from the SDK.
2864         * {@hide}
2865         */
2866        public OnClickListener mOnClickListener;
2867
2868        /**
2869         * Listener used to dispatch long click events.
2870         * This field should be made private, so it is hidden from the SDK.
2871         * {@hide}
2872         */
2873        protected OnLongClickListener mOnLongClickListener;
2874
2875        /**
2876         * Listener used to build the context menu.
2877         * This field should be made private, so it is hidden from the SDK.
2878         * {@hide}
2879         */
2880        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2881
2882        private OnKeyListener mOnKeyListener;
2883
2884        private OnTouchListener mOnTouchListener;
2885
2886        private OnHoverListener mOnHoverListener;
2887
2888        private OnGenericMotionListener mOnGenericMotionListener;
2889
2890        private OnDragListener mOnDragListener;
2891
2892        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2893    }
2894
2895    ListenerInfo mListenerInfo;
2896
2897    /**
2898     * The application environment this view lives in.
2899     * This field should be made private, so it is hidden from the SDK.
2900     * {@hide}
2901     */
2902    protected Context mContext;
2903
2904    private final Resources mResources;
2905
2906    private ScrollabilityCache mScrollCache;
2907
2908    private int[] mDrawableState = null;
2909
2910    /**
2911     * Set to true when drawing cache is enabled and cannot be created.
2912     *
2913     * @hide
2914     */
2915    public boolean mCachingFailed;
2916
2917    private Bitmap mDrawingCache;
2918    private Bitmap mUnscaledDrawingCache;
2919    private HardwareLayer mHardwareLayer;
2920    DisplayList mDisplayList;
2921
2922    /**
2923     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2924     * the user may specify which view to go to next.
2925     */
2926    private int mNextFocusLeftId = View.NO_ID;
2927
2928    /**
2929     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2930     * the user may specify which view to go to next.
2931     */
2932    private int mNextFocusRightId = View.NO_ID;
2933
2934    /**
2935     * When this view has focus and the next focus is {@link #FOCUS_UP},
2936     * the user may specify which view to go to next.
2937     */
2938    private int mNextFocusUpId = View.NO_ID;
2939
2940    /**
2941     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2942     * the user may specify which view to go to next.
2943     */
2944    private int mNextFocusDownId = View.NO_ID;
2945
2946    /**
2947     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2948     * the user may specify which view to go to next.
2949     */
2950    int mNextFocusForwardId = View.NO_ID;
2951
2952    private CheckForLongPress mPendingCheckForLongPress;
2953    private CheckForTap mPendingCheckForTap = null;
2954    private PerformClick mPerformClick;
2955    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2956
2957    private UnsetPressedState mUnsetPressedState;
2958
2959    /**
2960     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2961     * up event while a long press is invoked as soon as the long press duration is reached, so
2962     * a long press could be performed before the tap is checked, in which case the tap's action
2963     * should not be invoked.
2964     */
2965    private boolean mHasPerformedLongPress;
2966
2967    /**
2968     * The minimum height of the view. We'll try our best to have the height
2969     * of this view to at least this amount.
2970     */
2971    @ViewDebug.ExportedProperty(category = "measurement")
2972    private int mMinHeight;
2973
2974    /**
2975     * The minimum width of the view. We'll try our best to have the width
2976     * of this view to at least this amount.
2977     */
2978    @ViewDebug.ExportedProperty(category = "measurement")
2979    private int mMinWidth;
2980
2981    /**
2982     * The delegate to handle touch events that are physically in this view
2983     * but should be handled by another view.
2984     */
2985    private TouchDelegate mTouchDelegate = null;
2986
2987    /**
2988     * Solid color to use as a background when creating the drawing cache. Enables
2989     * the cache to use 16 bit bitmaps instead of 32 bit.
2990     */
2991    private int mDrawingCacheBackgroundColor = 0;
2992
2993    /**
2994     * Special tree observer used when mAttachInfo is null.
2995     */
2996    private ViewTreeObserver mFloatingTreeObserver;
2997
2998    /**
2999     * Cache the touch slop from the context that created the view.
3000     */
3001    private int mTouchSlop;
3002
3003    /**
3004     * Object that handles automatic animation of view properties.
3005     */
3006    private ViewPropertyAnimator mAnimator = null;
3007
3008    /**
3009     * Flag indicating that a drag can cross window boundaries.  When
3010     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3011     * with this flag set, all visible applications will be able to participate
3012     * in the drag operation and receive the dragged content.
3013     *
3014     * @hide
3015     */
3016    public static final int DRAG_FLAG_GLOBAL = 1;
3017
3018    /**
3019     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3020     */
3021    private float mVerticalScrollFactor;
3022
3023    /**
3024     * Position of the vertical scroll bar.
3025     */
3026    private int mVerticalScrollbarPosition;
3027
3028    /**
3029     * Position the scroll bar at the default position as determined by the system.
3030     */
3031    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3032
3033    /**
3034     * Position the scroll bar along the left edge.
3035     */
3036    public static final int SCROLLBAR_POSITION_LEFT = 1;
3037
3038    /**
3039     * Position the scroll bar along the right edge.
3040     */
3041    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3042
3043    /**
3044     * Indicates that the view does not have a layer.
3045     *
3046     * @see #getLayerType()
3047     * @see #setLayerType(int, android.graphics.Paint)
3048     * @see #LAYER_TYPE_SOFTWARE
3049     * @see #LAYER_TYPE_HARDWARE
3050     */
3051    public static final int LAYER_TYPE_NONE = 0;
3052
3053    /**
3054     * <p>Indicates that the view has a software layer. A software layer is backed
3055     * by a bitmap and causes the view to be rendered using Android's software
3056     * rendering pipeline, even if hardware acceleration is enabled.</p>
3057     *
3058     * <p>Software layers have various usages:</p>
3059     * <p>When the application is not using hardware acceleration, a software layer
3060     * is useful to apply a specific color filter and/or blending mode and/or
3061     * translucency to a view and all its children.</p>
3062     * <p>When the application is using hardware acceleration, a software layer
3063     * is useful to render drawing primitives not supported by the hardware
3064     * accelerated pipeline. It can also be used to cache a complex view tree
3065     * into a texture and reduce the complexity of drawing operations. For instance,
3066     * when animating a complex view tree with a translation, a software layer can
3067     * be used to render the view tree only once.</p>
3068     * <p>Software layers should be avoided when the affected view tree updates
3069     * often. Every update will require to re-render the software layer, which can
3070     * potentially be slow (particularly when hardware acceleration is turned on
3071     * since the layer will have to be uploaded into a hardware texture after every
3072     * update.)</p>
3073     *
3074     * @see #getLayerType()
3075     * @see #setLayerType(int, android.graphics.Paint)
3076     * @see #LAYER_TYPE_NONE
3077     * @see #LAYER_TYPE_HARDWARE
3078     */
3079    public static final int LAYER_TYPE_SOFTWARE = 1;
3080
3081    /**
3082     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3083     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3084     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3085     * rendering pipeline, but only if hardware acceleration is turned on for the
3086     * view hierarchy. When hardware acceleration is turned off, hardware layers
3087     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3088     *
3089     * <p>A hardware layer is useful to apply a specific color filter and/or
3090     * blending mode and/or translucency to a view and all its children.</p>
3091     * <p>A hardware layer can be used to cache a complex view tree into a
3092     * texture and reduce the complexity of drawing operations. For instance,
3093     * when animating a complex view tree with a translation, a hardware layer can
3094     * be used to render the view tree only once.</p>
3095     * <p>A hardware layer can also be used to increase the rendering quality when
3096     * rotation transformations are applied on a view. It can also be used to
3097     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3098     *
3099     * @see #getLayerType()
3100     * @see #setLayerType(int, android.graphics.Paint)
3101     * @see #LAYER_TYPE_NONE
3102     * @see #LAYER_TYPE_SOFTWARE
3103     */
3104    public static final int LAYER_TYPE_HARDWARE = 2;
3105
3106    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3107            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3108            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3109            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3110    })
3111    int mLayerType = LAYER_TYPE_NONE;
3112    Paint mLayerPaint;
3113    Rect mLocalDirtyRect;
3114
3115    /**
3116     * Set to true when the view is sending hover accessibility events because it
3117     * is the innermost hovered view.
3118     */
3119    private boolean mSendingHoverAccessibilityEvents;
3120
3121    /**
3122     * Simple constructor to use when creating a view from code.
3123     *
3124     * @param context The Context the view is running in, through which it can
3125     *        access the current theme, resources, etc.
3126     */
3127    public View(Context context) {
3128        mContext = context;
3129        mResources = context != null ? context.getResources() : null;
3130        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3131        // Set layout and text direction defaults
3132        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3133                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3134                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3135                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3136        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3137        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3138        mUserPaddingStart = -1;
3139        mUserPaddingEnd = -1;
3140        mUserPaddingRelative = false;
3141    }
3142
3143    /**
3144     * Delegate for injecting accessiblity functionality.
3145     */
3146    AccessibilityDelegate mAccessibilityDelegate;
3147
3148    /**
3149     * Consistency verifier for debugging purposes.
3150     * @hide
3151     */
3152    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3153            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3154                    new InputEventConsistencyVerifier(this, 0) : null;
3155
3156    /**
3157     * Constructor that is called when inflating a view from XML. This is called
3158     * when a view is being constructed from an XML file, supplying attributes
3159     * that were specified in the XML file. This version uses a default style of
3160     * 0, so the only attribute values applied are those in the Context's Theme
3161     * and the given AttributeSet.
3162     *
3163     * <p>
3164     * The method onFinishInflate() will be called after all children have been
3165     * added.
3166     *
3167     * @param context The Context the view is running in, through which it can
3168     *        access the current theme, resources, etc.
3169     * @param attrs The attributes of the XML tag that is inflating the view.
3170     * @see #View(Context, AttributeSet, int)
3171     */
3172    public View(Context context, AttributeSet attrs) {
3173        this(context, attrs, 0);
3174    }
3175
3176    /**
3177     * Perform inflation from XML and apply a class-specific base style. This
3178     * constructor of View allows subclasses to use their own base style when
3179     * they are inflating. For example, a Button class's constructor would call
3180     * this version of the super class constructor and supply
3181     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3182     * the theme's button style to modify all of the base view attributes (in
3183     * particular its background) as well as the Button class's attributes.
3184     *
3185     * @param context The Context the view is running in, through which it can
3186     *        access the current theme, resources, etc.
3187     * @param attrs The attributes of the XML tag that is inflating the view.
3188     * @param defStyle The default style to apply to this view. If 0, no style
3189     *        will be applied (beyond what is included in the theme). This may
3190     *        either be an attribute resource, whose value will be retrieved
3191     *        from the current theme, or an explicit style resource.
3192     * @see #View(Context, AttributeSet)
3193     */
3194    public View(Context context, AttributeSet attrs, int defStyle) {
3195        this(context);
3196
3197        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3198                defStyle, 0);
3199
3200        Drawable background = null;
3201
3202        int leftPadding = -1;
3203        int topPadding = -1;
3204        int rightPadding = -1;
3205        int bottomPadding = -1;
3206        int startPadding = -1;
3207        int endPadding = -1;
3208
3209        int padding = -1;
3210
3211        int viewFlagValues = 0;
3212        int viewFlagMasks = 0;
3213
3214        boolean setScrollContainer = false;
3215
3216        int x = 0;
3217        int y = 0;
3218
3219        float tx = 0;
3220        float ty = 0;
3221        float rotation = 0;
3222        float rotationX = 0;
3223        float rotationY = 0;
3224        float sx = 1f;
3225        float sy = 1f;
3226        boolean transformSet = false;
3227
3228        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3229
3230        int overScrollMode = mOverScrollMode;
3231        final int N = a.getIndexCount();
3232        for (int i = 0; i < N; i++) {
3233            int attr = a.getIndex(i);
3234            switch (attr) {
3235                case com.android.internal.R.styleable.View_background:
3236                    background = a.getDrawable(attr);
3237                    break;
3238                case com.android.internal.R.styleable.View_padding:
3239                    padding = a.getDimensionPixelSize(attr, -1);
3240                    break;
3241                 case com.android.internal.R.styleable.View_paddingLeft:
3242                    leftPadding = a.getDimensionPixelSize(attr, -1);
3243                    break;
3244                case com.android.internal.R.styleable.View_paddingTop:
3245                    topPadding = a.getDimensionPixelSize(attr, -1);
3246                    break;
3247                case com.android.internal.R.styleable.View_paddingRight:
3248                    rightPadding = a.getDimensionPixelSize(attr, -1);
3249                    break;
3250                case com.android.internal.R.styleable.View_paddingBottom:
3251                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3252                    break;
3253                case com.android.internal.R.styleable.View_paddingStart:
3254                    startPadding = a.getDimensionPixelSize(attr, -1);
3255                    break;
3256                case com.android.internal.R.styleable.View_paddingEnd:
3257                    endPadding = a.getDimensionPixelSize(attr, -1);
3258                    break;
3259                case com.android.internal.R.styleable.View_scrollX:
3260                    x = a.getDimensionPixelOffset(attr, 0);
3261                    break;
3262                case com.android.internal.R.styleable.View_scrollY:
3263                    y = a.getDimensionPixelOffset(attr, 0);
3264                    break;
3265                case com.android.internal.R.styleable.View_alpha:
3266                    setAlpha(a.getFloat(attr, 1f));
3267                    break;
3268                case com.android.internal.R.styleable.View_transformPivotX:
3269                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3270                    break;
3271                case com.android.internal.R.styleable.View_transformPivotY:
3272                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3273                    break;
3274                case com.android.internal.R.styleable.View_translationX:
3275                    tx = a.getDimensionPixelOffset(attr, 0);
3276                    transformSet = true;
3277                    break;
3278                case com.android.internal.R.styleable.View_translationY:
3279                    ty = a.getDimensionPixelOffset(attr, 0);
3280                    transformSet = true;
3281                    break;
3282                case com.android.internal.R.styleable.View_rotation:
3283                    rotation = a.getFloat(attr, 0);
3284                    transformSet = true;
3285                    break;
3286                case com.android.internal.R.styleable.View_rotationX:
3287                    rotationX = a.getFloat(attr, 0);
3288                    transformSet = true;
3289                    break;
3290                case com.android.internal.R.styleable.View_rotationY:
3291                    rotationY = a.getFloat(attr, 0);
3292                    transformSet = true;
3293                    break;
3294                case com.android.internal.R.styleable.View_scaleX:
3295                    sx = a.getFloat(attr, 1f);
3296                    transformSet = true;
3297                    break;
3298                case com.android.internal.R.styleable.View_scaleY:
3299                    sy = a.getFloat(attr, 1f);
3300                    transformSet = true;
3301                    break;
3302                case com.android.internal.R.styleable.View_id:
3303                    mID = a.getResourceId(attr, NO_ID);
3304                    break;
3305                case com.android.internal.R.styleable.View_tag:
3306                    mTag = a.getText(attr);
3307                    break;
3308                case com.android.internal.R.styleable.View_fitsSystemWindows:
3309                    if (a.getBoolean(attr, false)) {
3310                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3311                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3312                    }
3313                    break;
3314                case com.android.internal.R.styleable.View_focusable:
3315                    if (a.getBoolean(attr, false)) {
3316                        viewFlagValues |= FOCUSABLE;
3317                        viewFlagMasks |= FOCUSABLE_MASK;
3318                    }
3319                    break;
3320                case com.android.internal.R.styleable.View_focusableInTouchMode:
3321                    if (a.getBoolean(attr, false)) {
3322                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3323                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3324                    }
3325                    break;
3326                case com.android.internal.R.styleable.View_clickable:
3327                    if (a.getBoolean(attr, false)) {
3328                        viewFlagValues |= CLICKABLE;
3329                        viewFlagMasks |= CLICKABLE;
3330                    }
3331                    break;
3332                case com.android.internal.R.styleable.View_longClickable:
3333                    if (a.getBoolean(attr, false)) {
3334                        viewFlagValues |= LONG_CLICKABLE;
3335                        viewFlagMasks |= LONG_CLICKABLE;
3336                    }
3337                    break;
3338                case com.android.internal.R.styleable.View_saveEnabled:
3339                    if (!a.getBoolean(attr, true)) {
3340                        viewFlagValues |= SAVE_DISABLED;
3341                        viewFlagMasks |= SAVE_DISABLED_MASK;
3342                    }
3343                    break;
3344                case com.android.internal.R.styleable.View_duplicateParentState:
3345                    if (a.getBoolean(attr, false)) {
3346                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3347                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3348                    }
3349                    break;
3350                case com.android.internal.R.styleable.View_visibility:
3351                    final int visibility = a.getInt(attr, 0);
3352                    if (visibility != 0) {
3353                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3354                        viewFlagMasks |= VISIBILITY_MASK;
3355                    }
3356                    break;
3357                case com.android.internal.R.styleable.View_layoutDirection:
3358                    // Clear any layout direction flags (included resolved bits) already set
3359                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3360                    // Set the layout direction flags depending on the value of the attribute
3361                    final int layoutDirection = a.getInt(attr, -1);
3362                    final int value = (layoutDirection != -1) ?
3363                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3364                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3365                    break;
3366                case com.android.internal.R.styleable.View_drawingCacheQuality:
3367                    final int cacheQuality = a.getInt(attr, 0);
3368                    if (cacheQuality != 0) {
3369                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3370                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3371                    }
3372                    break;
3373                case com.android.internal.R.styleable.View_contentDescription:
3374                    mContentDescription = a.getString(attr);
3375                    break;
3376                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3377                    if (!a.getBoolean(attr, true)) {
3378                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3379                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3380                    }
3381                    break;
3382                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3383                    if (!a.getBoolean(attr, true)) {
3384                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3385                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3386                    }
3387                    break;
3388                case R.styleable.View_scrollbars:
3389                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3390                    if (scrollbars != SCROLLBARS_NONE) {
3391                        viewFlagValues |= scrollbars;
3392                        viewFlagMasks |= SCROLLBARS_MASK;
3393                        initializeScrollbars(a);
3394                    }
3395                    break;
3396                //noinspection deprecation
3397                case R.styleable.View_fadingEdge:
3398                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3399                        // Ignore the attribute starting with ICS
3400                        break;
3401                    }
3402                    // With builds < ICS, fall through and apply fading edges
3403                case R.styleable.View_requiresFadingEdge:
3404                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3405                    if (fadingEdge != FADING_EDGE_NONE) {
3406                        viewFlagValues |= fadingEdge;
3407                        viewFlagMasks |= FADING_EDGE_MASK;
3408                        initializeFadingEdge(a);
3409                    }
3410                    break;
3411                case R.styleable.View_scrollbarStyle:
3412                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3413                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3414                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3415                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3416                    }
3417                    break;
3418                case R.styleable.View_isScrollContainer:
3419                    setScrollContainer = true;
3420                    if (a.getBoolean(attr, false)) {
3421                        setScrollContainer(true);
3422                    }
3423                    break;
3424                case com.android.internal.R.styleable.View_keepScreenOn:
3425                    if (a.getBoolean(attr, false)) {
3426                        viewFlagValues |= KEEP_SCREEN_ON;
3427                        viewFlagMasks |= KEEP_SCREEN_ON;
3428                    }
3429                    break;
3430                case R.styleable.View_filterTouchesWhenObscured:
3431                    if (a.getBoolean(attr, false)) {
3432                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3433                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3434                    }
3435                    break;
3436                case R.styleable.View_nextFocusLeft:
3437                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3438                    break;
3439                case R.styleable.View_nextFocusRight:
3440                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3441                    break;
3442                case R.styleable.View_nextFocusUp:
3443                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3444                    break;
3445                case R.styleable.View_nextFocusDown:
3446                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3447                    break;
3448                case R.styleable.View_nextFocusForward:
3449                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3450                    break;
3451                case R.styleable.View_minWidth:
3452                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3453                    break;
3454                case R.styleable.View_minHeight:
3455                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3456                    break;
3457                case R.styleable.View_onClick:
3458                    if (context.isRestricted()) {
3459                        throw new IllegalStateException("The android:onClick attribute cannot "
3460                                + "be used within a restricted context");
3461                    }
3462
3463                    final String handlerName = a.getString(attr);
3464                    if (handlerName != null) {
3465                        setOnClickListener(new OnClickListener() {
3466                            private Method mHandler;
3467
3468                            public void onClick(View v) {
3469                                if (mHandler == null) {
3470                                    try {
3471                                        mHandler = getContext().getClass().getMethod(handlerName,
3472                                                View.class);
3473                                    } catch (NoSuchMethodException e) {
3474                                        int id = getId();
3475                                        String idText = id == NO_ID ? "" : " with id '"
3476                                                + getContext().getResources().getResourceEntryName(
3477                                                    id) + "'";
3478                                        throw new IllegalStateException("Could not find a method " +
3479                                                handlerName + "(View) in the activity "
3480                                                + getContext().getClass() + " for onClick handler"
3481                                                + " on view " + View.this.getClass() + idText, e);
3482                                    }
3483                                }
3484
3485                                try {
3486                                    mHandler.invoke(getContext(), View.this);
3487                                } catch (IllegalAccessException e) {
3488                                    throw new IllegalStateException("Could not execute non "
3489                                            + "public method of the activity", e);
3490                                } catch (InvocationTargetException e) {
3491                                    throw new IllegalStateException("Could not execute "
3492                                            + "method of the activity", e);
3493                                }
3494                            }
3495                        });
3496                    }
3497                    break;
3498                case R.styleable.View_overScrollMode:
3499                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3500                    break;
3501                case R.styleable.View_verticalScrollbarPosition:
3502                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3503                    break;
3504                case R.styleable.View_layerType:
3505                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3506                    break;
3507                case R.styleable.View_textDirection:
3508                    // Clear any text direction flag already set
3509                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3510                    // Set the text direction flags depending on the value of the attribute
3511                    final int textDirection = a.getInt(attr, -1);
3512                    if (textDirection != -1) {
3513                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3514                    }
3515                    break;
3516                case R.styleable.View_textAlignment:
3517                    // Clear any text alignment flag already set
3518                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3519                    // Set the text alignment flag depending on the value of the attribute
3520                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3521                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3522                    break;
3523                case R.styleable.View_importantForAccessibility:
3524                    setImportantForAccessibility(a.getInt(attr,
3525                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3526            }
3527        }
3528
3529        a.recycle();
3530
3531        setOverScrollMode(overScrollMode);
3532
3533        if (background != null) {
3534            setBackground(background);
3535        }
3536
3537        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3538        // layout direction). Those cached values will be used later during padding resolution.
3539        mUserPaddingStart = startPadding;
3540        mUserPaddingEnd = endPadding;
3541
3542        updateUserPaddingRelative();
3543
3544        if (padding >= 0) {
3545            leftPadding = padding;
3546            topPadding = padding;
3547            rightPadding = padding;
3548            bottomPadding = padding;
3549        }
3550
3551        // If the user specified the padding (either with android:padding or
3552        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3553        // use the default padding or the padding from the background drawable
3554        // (stored at this point in mPadding*)
3555        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3556                topPadding >= 0 ? topPadding : mPaddingTop,
3557                rightPadding >= 0 ? rightPadding : mPaddingRight,
3558                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3559
3560        if (viewFlagMasks != 0) {
3561            setFlags(viewFlagValues, viewFlagMasks);
3562        }
3563
3564        // Needs to be called after mViewFlags is set
3565        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3566            recomputePadding();
3567        }
3568
3569        if (x != 0 || y != 0) {
3570            scrollTo(x, y);
3571        }
3572
3573        if (transformSet) {
3574            setTranslationX(tx);
3575            setTranslationY(ty);
3576            setRotation(rotation);
3577            setRotationX(rotationX);
3578            setRotationY(rotationY);
3579            setScaleX(sx);
3580            setScaleY(sy);
3581        }
3582
3583        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3584            setScrollContainer(true);
3585        }
3586
3587        computeOpaqueFlags();
3588    }
3589
3590    private void updateUserPaddingRelative() {
3591        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3592    }
3593
3594    /**
3595     * Non-public constructor for use in testing
3596     */
3597    View() {
3598        mResources = null;
3599    }
3600
3601    /**
3602     * <p>
3603     * Initializes the fading edges from a given set of styled attributes. This
3604     * method should be called by subclasses that need fading edges and when an
3605     * instance of these subclasses is created programmatically rather than
3606     * being inflated from XML. This method is automatically called when the XML
3607     * is inflated.
3608     * </p>
3609     *
3610     * @param a the styled attributes set to initialize the fading edges from
3611     */
3612    protected void initializeFadingEdge(TypedArray a) {
3613        initScrollCache();
3614
3615        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3616                R.styleable.View_fadingEdgeLength,
3617                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3618    }
3619
3620    /**
3621     * Returns the size of the vertical faded edges used to indicate that more
3622     * content in this view is visible.
3623     *
3624     * @return The size in pixels of the vertical faded edge or 0 if vertical
3625     *         faded edges are not enabled for this view.
3626     * @attr ref android.R.styleable#View_fadingEdgeLength
3627     */
3628    public int getVerticalFadingEdgeLength() {
3629        if (isVerticalFadingEdgeEnabled()) {
3630            ScrollabilityCache cache = mScrollCache;
3631            if (cache != null) {
3632                return cache.fadingEdgeLength;
3633            }
3634        }
3635        return 0;
3636    }
3637
3638    /**
3639     * Set the size of the faded edge used to indicate that more content in this
3640     * view is available.  Will not change whether the fading edge is enabled; use
3641     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3642     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3643     * for the vertical or horizontal fading edges.
3644     *
3645     * @param length The size in pixels of the faded edge used to indicate that more
3646     *        content in this view is visible.
3647     */
3648    public void setFadingEdgeLength(int length) {
3649        initScrollCache();
3650        mScrollCache.fadingEdgeLength = length;
3651    }
3652
3653    /**
3654     * Returns the size of the horizontal faded edges used to indicate that more
3655     * content in this view is visible.
3656     *
3657     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3658     *         faded edges are not enabled for this view.
3659     * @attr ref android.R.styleable#View_fadingEdgeLength
3660     */
3661    public int getHorizontalFadingEdgeLength() {
3662        if (isHorizontalFadingEdgeEnabled()) {
3663            ScrollabilityCache cache = mScrollCache;
3664            if (cache != null) {
3665                return cache.fadingEdgeLength;
3666            }
3667        }
3668        return 0;
3669    }
3670
3671    /**
3672     * Returns the width of the vertical scrollbar.
3673     *
3674     * @return The width in pixels of the vertical scrollbar or 0 if there
3675     *         is no vertical scrollbar.
3676     */
3677    public int getVerticalScrollbarWidth() {
3678        ScrollabilityCache cache = mScrollCache;
3679        if (cache != null) {
3680            ScrollBarDrawable scrollBar = cache.scrollBar;
3681            if (scrollBar != null) {
3682                int size = scrollBar.getSize(true);
3683                if (size <= 0) {
3684                    size = cache.scrollBarSize;
3685                }
3686                return size;
3687            }
3688            return 0;
3689        }
3690        return 0;
3691    }
3692
3693    /**
3694     * Returns the height of the horizontal scrollbar.
3695     *
3696     * @return The height in pixels of the horizontal scrollbar or 0 if
3697     *         there is no horizontal scrollbar.
3698     */
3699    protected int getHorizontalScrollbarHeight() {
3700        ScrollabilityCache cache = mScrollCache;
3701        if (cache != null) {
3702            ScrollBarDrawable scrollBar = cache.scrollBar;
3703            if (scrollBar != null) {
3704                int size = scrollBar.getSize(false);
3705                if (size <= 0) {
3706                    size = cache.scrollBarSize;
3707                }
3708                return size;
3709            }
3710            return 0;
3711        }
3712        return 0;
3713    }
3714
3715    /**
3716     * <p>
3717     * Initializes the scrollbars from a given set of styled attributes. This
3718     * method should be called by subclasses that need scrollbars and when an
3719     * instance of these subclasses is created programmatically rather than
3720     * being inflated from XML. This method is automatically called when the XML
3721     * is inflated.
3722     * </p>
3723     *
3724     * @param a the styled attributes set to initialize the scrollbars from
3725     */
3726    protected void initializeScrollbars(TypedArray a) {
3727        initScrollCache();
3728
3729        final ScrollabilityCache scrollabilityCache = mScrollCache;
3730
3731        if (scrollabilityCache.scrollBar == null) {
3732            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3733        }
3734
3735        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3736
3737        if (!fadeScrollbars) {
3738            scrollabilityCache.state = ScrollabilityCache.ON;
3739        }
3740        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3741
3742
3743        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3744                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3745                        .getScrollBarFadeDuration());
3746        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3747                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3748                ViewConfiguration.getScrollDefaultDelay());
3749
3750
3751        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3752                com.android.internal.R.styleable.View_scrollbarSize,
3753                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3754
3755        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3756        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3757
3758        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3759        if (thumb != null) {
3760            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3761        }
3762
3763        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3764                false);
3765        if (alwaysDraw) {
3766            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3767        }
3768
3769        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3770        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3771
3772        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3773        if (thumb != null) {
3774            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3775        }
3776
3777        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3778                false);
3779        if (alwaysDraw) {
3780            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3781        }
3782
3783        // Re-apply user/background padding so that scrollbar(s) get added
3784        resolvePadding();
3785    }
3786
3787    /**
3788     * <p>
3789     * Initalizes the scrollability cache if necessary.
3790     * </p>
3791     */
3792    private void initScrollCache() {
3793        if (mScrollCache == null) {
3794            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3795        }
3796    }
3797
3798    private ScrollabilityCache getScrollCache() {
3799        initScrollCache();
3800        return mScrollCache;
3801    }
3802
3803    /**
3804     * Set the position of the vertical scroll bar. Should be one of
3805     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3806     * {@link #SCROLLBAR_POSITION_RIGHT}.
3807     *
3808     * @param position Where the vertical scroll bar should be positioned.
3809     */
3810    public void setVerticalScrollbarPosition(int position) {
3811        if (mVerticalScrollbarPosition != position) {
3812            mVerticalScrollbarPosition = position;
3813            computeOpaqueFlags();
3814            resolvePadding();
3815        }
3816    }
3817
3818    /**
3819     * @return The position where the vertical scroll bar will show, if applicable.
3820     * @see #setVerticalScrollbarPosition(int)
3821     */
3822    public int getVerticalScrollbarPosition() {
3823        return mVerticalScrollbarPosition;
3824    }
3825
3826    ListenerInfo getListenerInfo() {
3827        if (mListenerInfo != null) {
3828            return mListenerInfo;
3829        }
3830        mListenerInfo = new ListenerInfo();
3831        return mListenerInfo;
3832    }
3833
3834    /**
3835     * Register a callback to be invoked when focus of this view changed.
3836     *
3837     * @param l The callback that will run.
3838     */
3839    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3840        getListenerInfo().mOnFocusChangeListener = l;
3841    }
3842
3843    /**
3844     * Add a listener that will be called when the bounds of the view change due to
3845     * layout processing.
3846     *
3847     * @param listener The listener that will be called when layout bounds change.
3848     */
3849    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3850        ListenerInfo li = getListenerInfo();
3851        if (li.mOnLayoutChangeListeners == null) {
3852            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3853        }
3854        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3855            li.mOnLayoutChangeListeners.add(listener);
3856        }
3857    }
3858
3859    /**
3860     * Remove a listener for layout changes.
3861     *
3862     * @param listener The listener for layout bounds change.
3863     */
3864    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3865        ListenerInfo li = mListenerInfo;
3866        if (li == null || li.mOnLayoutChangeListeners == null) {
3867            return;
3868        }
3869        li.mOnLayoutChangeListeners.remove(listener);
3870    }
3871
3872    /**
3873     * Add a listener for attach state changes.
3874     *
3875     * This listener will be called whenever this view is attached or detached
3876     * from a window. Remove the listener using
3877     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3878     *
3879     * @param listener Listener to attach
3880     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3881     */
3882    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3883        ListenerInfo li = getListenerInfo();
3884        if (li.mOnAttachStateChangeListeners == null) {
3885            li.mOnAttachStateChangeListeners
3886                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3887        }
3888        li.mOnAttachStateChangeListeners.add(listener);
3889    }
3890
3891    /**
3892     * Remove a listener for attach state changes. The listener will receive no further
3893     * notification of window attach/detach events.
3894     *
3895     * @param listener Listener to remove
3896     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3897     */
3898    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3899        ListenerInfo li = mListenerInfo;
3900        if (li == null || li.mOnAttachStateChangeListeners == null) {
3901            return;
3902        }
3903        li.mOnAttachStateChangeListeners.remove(listener);
3904    }
3905
3906    /**
3907     * Returns the focus-change callback registered for this view.
3908     *
3909     * @return The callback, or null if one is not registered.
3910     */
3911    public OnFocusChangeListener getOnFocusChangeListener() {
3912        ListenerInfo li = mListenerInfo;
3913        return li != null ? li.mOnFocusChangeListener : null;
3914    }
3915
3916    /**
3917     * Register a callback to be invoked when this view is clicked. If this view is not
3918     * clickable, it becomes clickable.
3919     *
3920     * @param l The callback that will run
3921     *
3922     * @see #setClickable(boolean)
3923     */
3924    public void setOnClickListener(OnClickListener l) {
3925        if (!isClickable()) {
3926            setClickable(true);
3927        }
3928        getListenerInfo().mOnClickListener = l;
3929    }
3930
3931    /**
3932     * Return whether this view has an attached OnClickListener.  Returns
3933     * true if there is a listener, false if there is none.
3934     */
3935    public boolean hasOnClickListeners() {
3936        ListenerInfo li = mListenerInfo;
3937        return (li != null && li.mOnClickListener != null);
3938    }
3939
3940    /**
3941     * Register a callback to be invoked when this view is clicked and held. If this view is not
3942     * long clickable, it becomes long clickable.
3943     *
3944     * @param l The callback that will run
3945     *
3946     * @see #setLongClickable(boolean)
3947     */
3948    public void setOnLongClickListener(OnLongClickListener l) {
3949        if (!isLongClickable()) {
3950            setLongClickable(true);
3951        }
3952        getListenerInfo().mOnLongClickListener = l;
3953    }
3954
3955    /**
3956     * Register a callback to be invoked when the context menu for this view is
3957     * being built. If this view is not long clickable, it becomes long clickable.
3958     *
3959     * @param l The callback that will run
3960     *
3961     */
3962    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3963        if (!isLongClickable()) {
3964            setLongClickable(true);
3965        }
3966        getListenerInfo().mOnCreateContextMenuListener = l;
3967    }
3968
3969    /**
3970     * Call this view's OnClickListener, if it is defined.  Performs all normal
3971     * actions associated with clicking: reporting accessibility event, playing
3972     * a sound, etc.
3973     *
3974     * @return True there was an assigned OnClickListener that was called, false
3975     *         otherwise is returned.
3976     */
3977    public boolean performClick() {
3978        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3979
3980        ListenerInfo li = mListenerInfo;
3981        if (li != null && li.mOnClickListener != null) {
3982            playSoundEffect(SoundEffectConstants.CLICK);
3983            li.mOnClickListener.onClick(this);
3984            return true;
3985        }
3986
3987        return false;
3988    }
3989
3990    /**
3991     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3992     * this only calls the listener, and does not do any associated clicking
3993     * actions like reporting an accessibility event.
3994     *
3995     * @return True there was an assigned OnClickListener that was called, false
3996     *         otherwise is returned.
3997     */
3998    public boolean callOnClick() {
3999        ListenerInfo li = mListenerInfo;
4000        if (li != null && li.mOnClickListener != null) {
4001            li.mOnClickListener.onClick(this);
4002            return true;
4003        }
4004        return false;
4005    }
4006
4007    /**
4008     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4009     * OnLongClickListener did not consume the event.
4010     *
4011     * @return True if one of the above receivers consumed the event, false otherwise.
4012     */
4013    public boolean performLongClick() {
4014        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4015
4016        boolean handled = false;
4017        ListenerInfo li = mListenerInfo;
4018        if (li != null && li.mOnLongClickListener != null) {
4019            handled = li.mOnLongClickListener.onLongClick(View.this);
4020        }
4021        if (!handled) {
4022            handled = showContextMenu();
4023        }
4024        if (handled) {
4025            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4026        }
4027        return handled;
4028    }
4029
4030    /**
4031     * Performs button-related actions during a touch down event.
4032     *
4033     * @param event The event.
4034     * @return True if the down was consumed.
4035     *
4036     * @hide
4037     */
4038    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4039        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4040            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4041                return true;
4042            }
4043        }
4044        return false;
4045    }
4046
4047    /**
4048     * Bring up the context menu for this view.
4049     *
4050     * @return Whether a context menu was displayed.
4051     */
4052    public boolean showContextMenu() {
4053        return getParent().showContextMenuForChild(this);
4054    }
4055
4056    /**
4057     * Bring up the context menu for this view, referring to the item under the specified point.
4058     *
4059     * @param x The referenced x coordinate.
4060     * @param y The referenced y coordinate.
4061     * @param metaState The keyboard modifiers that were pressed.
4062     * @return Whether a context menu was displayed.
4063     *
4064     * @hide
4065     */
4066    public boolean showContextMenu(float x, float y, int metaState) {
4067        return showContextMenu();
4068    }
4069
4070    /**
4071     * Start an action mode.
4072     *
4073     * @param callback Callback that will control the lifecycle of the action mode
4074     * @return The new action mode if it is started, null otherwise
4075     *
4076     * @see ActionMode
4077     */
4078    public ActionMode startActionMode(ActionMode.Callback callback) {
4079        ViewParent parent = getParent();
4080        if (parent == null) return null;
4081        return parent.startActionModeForChild(this, callback);
4082    }
4083
4084    /**
4085     * Register a callback to be invoked when a key is pressed in this view.
4086     * @param l the key listener to attach to this view
4087     */
4088    public void setOnKeyListener(OnKeyListener l) {
4089        getListenerInfo().mOnKeyListener = l;
4090    }
4091
4092    /**
4093     * Register a callback to be invoked when a touch event is sent to this view.
4094     * @param l the touch listener to attach to this view
4095     */
4096    public void setOnTouchListener(OnTouchListener l) {
4097        getListenerInfo().mOnTouchListener = l;
4098    }
4099
4100    /**
4101     * Register a callback to be invoked when a generic motion event is sent to this view.
4102     * @param l the generic motion listener to attach to this view
4103     */
4104    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4105        getListenerInfo().mOnGenericMotionListener = l;
4106    }
4107
4108    /**
4109     * Register a callback to be invoked when a hover event is sent to this view.
4110     * @param l the hover listener to attach to this view
4111     */
4112    public void setOnHoverListener(OnHoverListener l) {
4113        getListenerInfo().mOnHoverListener = l;
4114    }
4115
4116    /**
4117     * Register a drag event listener callback object for this View. The parameter is
4118     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4119     * View, the system calls the
4120     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4121     * @param l An implementation of {@link android.view.View.OnDragListener}.
4122     */
4123    public void setOnDragListener(OnDragListener l) {
4124        getListenerInfo().mOnDragListener = l;
4125    }
4126
4127    /**
4128     * Give this view focus. This will cause
4129     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4130     *
4131     * Note: this does not check whether this {@link View} should get focus, it just
4132     * gives it focus no matter what.  It should only be called internally by framework
4133     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4134     *
4135     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4136     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4137     *        focus moved when requestFocus() is called. It may not always
4138     *        apply, in which case use the default View.FOCUS_DOWN.
4139     * @param previouslyFocusedRect The rectangle of the view that had focus
4140     *        prior in this View's coordinate system.
4141     */
4142    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4143        if (DBG) {
4144            System.out.println(this + " requestFocus()");
4145        }
4146
4147        if ((mPrivateFlags & FOCUSED) == 0) {
4148            mPrivateFlags |= FOCUSED;
4149
4150            if (mParent != null) {
4151                mParent.requestChildFocus(this, this);
4152            }
4153
4154            onFocusChanged(true, direction, previouslyFocusedRect);
4155            refreshDrawableState();
4156
4157            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4158                notifyAccessibilityStateChanged();
4159            }
4160        }
4161    }
4162
4163    /**
4164     * Request that a rectangle of this view be visible on the screen,
4165     * scrolling if necessary just enough.
4166     *
4167     * <p>A View should call this if it maintains some notion of which part
4168     * of its content is interesting.  For example, a text editing view
4169     * should call this when its cursor moves.
4170     *
4171     * @param rectangle The rectangle.
4172     * @return Whether any parent scrolled.
4173     */
4174    public boolean requestRectangleOnScreen(Rect rectangle) {
4175        return requestRectangleOnScreen(rectangle, false);
4176    }
4177
4178    /**
4179     * Request that a rectangle of this view be visible on the screen,
4180     * scrolling if necessary just enough.
4181     *
4182     * <p>A View should call this if it maintains some notion of which part
4183     * of its content is interesting.  For example, a text editing view
4184     * should call this when its cursor moves.
4185     *
4186     * <p>When <code>immediate</code> is set to true, scrolling will not be
4187     * animated.
4188     *
4189     * @param rectangle The rectangle.
4190     * @param immediate True to forbid animated scrolling, false otherwise
4191     * @return Whether any parent scrolled.
4192     */
4193    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4194        View child = this;
4195        ViewParent parent = mParent;
4196        boolean scrolled = false;
4197        while (parent != null) {
4198            scrolled |= parent.requestChildRectangleOnScreen(child,
4199                    rectangle, immediate);
4200
4201            // offset rect so next call has the rectangle in the
4202            // coordinate system of its direct child.
4203            rectangle.offset(child.getLeft(), child.getTop());
4204            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4205
4206            if (!(parent instanceof View)) {
4207                break;
4208            }
4209
4210            child = (View) parent;
4211            parent = child.getParent();
4212        }
4213        return scrolled;
4214    }
4215
4216    /**
4217     * Called when this view wants to give up focus. If focus is cleared
4218     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4219     * <p>
4220     * <strong>Note:</strong> When a View clears focus the framework is trying
4221     * to give focus to the first focusable View from the top. Hence, if this
4222     * View is the first from the top that can take focus, then all callbacks
4223     * related to clearing focus will be invoked after wich the framework will
4224     * give focus to this view.
4225     * </p>
4226     */
4227    public void clearFocus() {
4228        if (DBG) {
4229            System.out.println(this + " clearFocus()");
4230        }
4231
4232        if ((mPrivateFlags & FOCUSED) != 0) {
4233            mPrivateFlags &= ~FOCUSED;
4234
4235            if (mParent != null) {
4236                mParent.clearChildFocus(this);
4237            }
4238
4239            onFocusChanged(false, 0, null);
4240
4241            refreshDrawableState();
4242
4243            ensureInputFocusOnFirstFocusable();
4244
4245            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4246                notifyAccessibilityStateChanged();
4247            }
4248        }
4249    }
4250
4251    void ensureInputFocusOnFirstFocusable() {
4252        View root = getRootView();
4253        if (root != null) {
4254            root.requestFocus();
4255        }
4256    }
4257
4258    /**
4259     * Called internally by the view system when a new view is getting focus.
4260     * This is what clears the old focus.
4261     */
4262    void unFocus() {
4263        if (DBG) {
4264            System.out.println(this + " unFocus()");
4265        }
4266
4267        if ((mPrivateFlags & FOCUSED) != 0) {
4268            mPrivateFlags &= ~FOCUSED;
4269
4270            onFocusChanged(false, 0, null);
4271            refreshDrawableState();
4272
4273            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4274                notifyAccessibilityStateChanged();
4275            }
4276        }
4277    }
4278
4279    /**
4280     * Returns true if this view has focus iteself, or is the ancestor of the
4281     * view that has focus.
4282     *
4283     * @return True if this view has or contains focus, false otherwise.
4284     */
4285    @ViewDebug.ExportedProperty(category = "focus")
4286    public boolean hasFocus() {
4287        return (mPrivateFlags & FOCUSED) != 0;
4288    }
4289
4290    /**
4291     * Returns true if this view is focusable or if it contains a reachable View
4292     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4293     * is a View whose parents do not block descendants focus.
4294     *
4295     * Only {@link #VISIBLE} views are considered focusable.
4296     *
4297     * @return True if the view is focusable or if the view contains a focusable
4298     *         View, false otherwise.
4299     *
4300     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4301     */
4302    public boolean hasFocusable() {
4303        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4304    }
4305
4306    /**
4307     * Called by the view system when the focus state of this view changes.
4308     * When the focus change event is caused by directional navigation, direction
4309     * and previouslyFocusedRect provide insight into where the focus is coming from.
4310     * When overriding, be sure to call up through to the super class so that
4311     * the standard focus handling will occur.
4312     *
4313     * @param gainFocus True if the View has focus; false otherwise.
4314     * @param direction The direction focus has moved when requestFocus()
4315     *                  is called to give this view focus. Values are
4316     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4317     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4318     *                  It may not always apply, in which case use the default.
4319     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4320     *        system, of the previously focused view.  If applicable, this will be
4321     *        passed in as finer grained information about where the focus is coming
4322     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4323     */
4324    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4325        if (gainFocus) {
4326            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4327                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4328                requestAccessibilityFocus();
4329            }
4330        }
4331
4332        InputMethodManager imm = InputMethodManager.peekInstance();
4333        if (!gainFocus) {
4334            if (isPressed()) {
4335                setPressed(false);
4336            }
4337            if (imm != null && mAttachInfo != null
4338                    && mAttachInfo.mHasWindowFocus) {
4339                imm.focusOut(this);
4340            }
4341            onFocusLost();
4342        } else if (imm != null && mAttachInfo != null
4343                && mAttachInfo.mHasWindowFocus) {
4344            imm.focusIn(this);
4345        }
4346
4347        invalidate(true);
4348        ListenerInfo li = mListenerInfo;
4349        if (li != null && li.mOnFocusChangeListener != null) {
4350            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4351        }
4352
4353        if (mAttachInfo != null) {
4354            mAttachInfo.mKeyDispatchState.reset(this);
4355        }
4356    }
4357
4358    /**
4359     * Sends an accessibility event of the given type. If accessiiblity is
4360     * not enabled this method has no effect. The default implementation calls
4361     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4362     * to populate information about the event source (this View), then calls
4363     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4364     * populate the text content of the event source including its descendants,
4365     * and last calls
4366     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4367     * on its parent to resuest sending of the event to interested parties.
4368     * <p>
4369     * If an {@link AccessibilityDelegate} has been specified via calling
4370     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4371     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4372     * responsible for handling this call.
4373     * </p>
4374     *
4375     * @param eventType The type of the event to send, as defined by several types from
4376     * {@link android.view.accessibility.AccessibilityEvent}, such as
4377     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4378     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4379     *
4380     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4381     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4382     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4383     * @see AccessibilityDelegate
4384     */
4385    public void sendAccessibilityEvent(int eventType) {
4386        if (mAccessibilityDelegate != null) {
4387            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4388        } else {
4389            sendAccessibilityEventInternal(eventType);
4390        }
4391    }
4392
4393    /**
4394     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4395     * {@link AccessibilityEvent} to make an announcement which is related to some
4396     * sort of a context change for which none of the events representing UI transitions
4397     * is a good fit. For example, announcing a new page in a book. If accessibility
4398     * is not enabled this method does nothing.
4399     *
4400     * @param text The announcement text.
4401     */
4402    public void announceForAccessibility(CharSequence text) {
4403        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4404            AccessibilityEvent event = AccessibilityEvent.obtain(
4405                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4406            event.getText().add(text);
4407            sendAccessibilityEventUnchecked(event);
4408        }
4409    }
4410
4411    /**
4412     * @see #sendAccessibilityEvent(int)
4413     *
4414     * Note: Called from the default {@link AccessibilityDelegate}.
4415     */
4416    void sendAccessibilityEventInternal(int eventType) {
4417        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4418            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4419        }
4420    }
4421
4422    /**
4423     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4424     * takes as an argument an empty {@link AccessibilityEvent} and does not
4425     * perform a check whether accessibility is enabled.
4426     * <p>
4427     * If an {@link AccessibilityDelegate} has been specified via calling
4428     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4429     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4430     * is responsible for handling this call.
4431     * </p>
4432     *
4433     * @param event The event to send.
4434     *
4435     * @see #sendAccessibilityEvent(int)
4436     */
4437    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4438        if (mAccessibilityDelegate != null) {
4439            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4440        } else {
4441            sendAccessibilityEventUncheckedInternal(event);
4442        }
4443    }
4444
4445    /**
4446     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4447     *
4448     * Note: Called from the default {@link AccessibilityDelegate}.
4449     */
4450    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4451        if (!isShown()) {
4452            return;
4453        }
4454        onInitializeAccessibilityEvent(event);
4455        // Only a subset of accessibility events populates text content.
4456        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4457            dispatchPopulateAccessibilityEvent(event);
4458        }
4459        // Intercept accessibility focus events fired by virtual nodes to keep
4460        // track of accessibility focus position in such nodes.
4461        final int eventType = event.getEventType();
4462        switch (eventType) {
4463            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4464                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4465                        event.getSourceNodeId());
4466                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4467                    ViewRootImpl viewRootImpl = getViewRootImpl();
4468                    if (viewRootImpl != null) {
4469                        viewRootImpl.setAccessibilityFocusedHost(this);
4470                    }
4471                }
4472            } break;
4473            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4474                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4475                        event.getSourceNodeId());
4476                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4477                    ViewRootImpl viewRootImpl = getViewRootImpl();
4478                    if (viewRootImpl != null) {
4479                        viewRootImpl.setAccessibilityFocusedHost(null);
4480                    }
4481                }
4482            } break;
4483        }
4484        // In the beginning we called #isShown(), so we know that getParent() is not null.
4485        getParent().requestSendAccessibilityEvent(this, event);
4486    }
4487
4488    /**
4489     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4490     * to its children for adding their text content to the event. Note that the
4491     * event text is populated in a separate dispatch path since we add to the
4492     * event not only the text of the source but also the text of all its descendants.
4493     * A typical implementation will call
4494     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4495     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4496     * on each child. Override this method if custom population of the event text
4497     * content is required.
4498     * <p>
4499     * If an {@link AccessibilityDelegate} has been specified via calling
4500     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4501     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4502     * is responsible for handling this call.
4503     * </p>
4504     * <p>
4505     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4506     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4507     * </p>
4508     *
4509     * @param event The event.
4510     *
4511     * @return True if the event population was completed.
4512     */
4513    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4514        if (mAccessibilityDelegate != null) {
4515            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4516        } else {
4517            return dispatchPopulateAccessibilityEventInternal(event);
4518        }
4519    }
4520
4521    /**
4522     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4523     *
4524     * Note: Called from the default {@link AccessibilityDelegate}.
4525     */
4526    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4527        onPopulateAccessibilityEvent(event);
4528        return false;
4529    }
4530
4531    /**
4532     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4533     * giving a chance to this View to populate the accessibility event with its
4534     * text content. While this method is free to modify event
4535     * attributes other than text content, doing so should normally be performed in
4536     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4537     * <p>
4538     * Example: Adding formatted date string to an accessibility event in addition
4539     *          to the text added by the super implementation:
4540     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4541     *     super.onPopulateAccessibilityEvent(event);
4542     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4543     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4544     *         mCurrentDate.getTimeInMillis(), flags);
4545     *     event.getText().add(selectedDateUtterance);
4546     * }</pre>
4547     * <p>
4548     * If an {@link AccessibilityDelegate} has been specified via calling
4549     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4550     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4551     * is responsible for handling this call.
4552     * </p>
4553     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4554     * information to the event, in case the default implementation has basic information to add.
4555     * </p>
4556     *
4557     * @param event The accessibility event which to populate.
4558     *
4559     * @see #sendAccessibilityEvent(int)
4560     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4561     */
4562    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4563        if (mAccessibilityDelegate != null) {
4564            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4565        } else {
4566            onPopulateAccessibilityEventInternal(event);
4567        }
4568    }
4569
4570    /**
4571     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4572     *
4573     * Note: Called from the default {@link AccessibilityDelegate}.
4574     */
4575    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4576
4577    }
4578
4579    /**
4580     * Initializes an {@link AccessibilityEvent} with information about
4581     * this View which is the event source. In other words, the source of
4582     * an accessibility event is the view whose state change triggered firing
4583     * the event.
4584     * <p>
4585     * Example: Setting the password property of an event in addition
4586     *          to properties set by the super implementation:
4587     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4588     *     super.onInitializeAccessibilityEvent(event);
4589     *     event.setPassword(true);
4590     * }</pre>
4591     * <p>
4592     * If an {@link AccessibilityDelegate} has been specified via calling
4593     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4594     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4595     * is responsible for handling this call.
4596     * </p>
4597     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4598     * information to the event, in case the default implementation has basic information to add.
4599     * </p>
4600     * @param event The event to initialize.
4601     *
4602     * @see #sendAccessibilityEvent(int)
4603     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4604     */
4605    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4606        if (mAccessibilityDelegate != null) {
4607            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4608        } else {
4609            onInitializeAccessibilityEventInternal(event);
4610        }
4611    }
4612
4613    /**
4614     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4615     *
4616     * Note: Called from the default {@link AccessibilityDelegate}.
4617     */
4618    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4619        event.setSource(this);
4620        event.setClassName(View.class.getName());
4621        event.setPackageName(getContext().getPackageName());
4622        event.setEnabled(isEnabled());
4623        event.setContentDescription(mContentDescription);
4624
4625        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4626            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4627            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4628                    FOCUSABLES_ALL);
4629            event.setItemCount(focusablesTempList.size());
4630            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4631            focusablesTempList.clear();
4632        }
4633    }
4634
4635    /**
4636     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4637     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4638     * This method is responsible for obtaining an accessibility node info from a
4639     * pool of reusable instances and calling
4640     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4641     * initialize the former.
4642     * <p>
4643     * Note: The client is responsible for recycling the obtained instance by calling
4644     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4645     * </p>
4646     *
4647     * @return A populated {@link AccessibilityNodeInfo}.
4648     *
4649     * @see AccessibilityNodeInfo
4650     */
4651    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4652        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4653        if (provider != null) {
4654            return provider.createAccessibilityNodeInfo(View.NO_ID);
4655        } else {
4656            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4657            onInitializeAccessibilityNodeInfo(info);
4658            return info;
4659        }
4660    }
4661
4662    /**
4663     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4664     * The base implementation sets:
4665     * <ul>
4666     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4667     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4668     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4669     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4670     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4671     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4672     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4673     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4674     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4675     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4676     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4677     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4678     * </ul>
4679     * <p>
4680     * Subclasses should override this method, call the super implementation,
4681     * and set additional attributes.
4682     * </p>
4683     * <p>
4684     * If an {@link AccessibilityDelegate} has been specified via calling
4685     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4686     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4687     * is responsible for handling this call.
4688     * </p>
4689     *
4690     * @param info The instance to initialize.
4691     */
4692    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4693        if (mAccessibilityDelegate != null) {
4694            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4695        } else {
4696            onInitializeAccessibilityNodeInfoInternal(info);
4697        }
4698    }
4699
4700    /**
4701     * Gets the location of this view in screen coordintates.
4702     *
4703     * @param outRect The output location
4704     */
4705    private void getBoundsOnScreen(Rect outRect) {
4706        if (mAttachInfo == null) {
4707            return;
4708        }
4709
4710        RectF position = mAttachInfo.mTmpTransformRect;
4711        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4712
4713        if (!hasIdentityMatrix()) {
4714            getMatrix().mapRect(position);
4715        }
4716
4717        position.offset(mLeft, mTop);
4718
4719        ViewParent parent = mParent;
4720        while (parent instanceof View) {
4721            View parentView = (View) parent;
4722
4723            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4724
4725            if (!parentView.hasIdentityMatrix()) {
4726                parentView.getMatrix().mapRect(position);
4727            }
4728
4729            position.offset(parentView.mLeft, parentView.mTop);
4730
4731            parent = parentView.mParent;
4732        }
4733
4734        if (parent instanceof ViewRootImpl) {
4735            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4736            position.offset(0, -viewRootImpl.mCurScrollY);
4737        }
4738
4739        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4740
4741        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4742                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4743    }
4744
4745    /**
4746     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4747     *
4748     * Note: Called from the default {@link AccessibilityDelegate}.
4749     */
4750    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4751        Rect bounds = mAttachInfo.mTmpInvalRect;
4752        getDrawingRect(bounds);
4753        info.setBoundsInParent(bounds);
4754
4755        getBoundsOnScreen(bounds);
4756        info.setBoundsInScreen(bounds);
4757
4758        ViewParent parent = getParentForAccessibility();
4759        if (parent instanceof View) {
4760            info.setParent((View) parent);
4761        }
4762
4763        info.setVisibleToUser(isVisibleToUser());
4764
4765        info.setPackageName(mContext.getPackageName());
4766        info.setClassName(View.class.getName());
4767        info.setContentDescription(getContentDescription());
4768
4769        info.setEnabled(isEnabled());
4770        info.setClickable(isClickable());
4771        info.setFocusable(isFocusable());
4772        info.setFocused(isFocused());
4773        info.setAccessibilityFocused(isAccessibilityFocused());
4774        info.setSelected(isSelected());
4775        info.setLongClickable(isLongClickable());
4776
4777        // TODO: These make sense only if we are in an AdapterView but all
4778        // views can be selected. Maybe from accessiiblity perspective
4779        // we should report as selectable view in an AdapterView.
4780        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4781        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4782
4783        if (isFocusable()) {
4784            if (isFocused()) {
4785                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4786            } else {
4787                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4788            }
4789        }
4790
4791        if (!isAccessibilityFocused()) {
4792            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4793        } else {
4794            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4795        }
4796
4797        if (isClickable()) {
4798            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4799        }
4800
4801        if (isLongClickable()) {
4802            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4803        }
4804
4805        if (mContentDescription != null && mContentDescription.length() > 0) {
4806            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4807            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4808            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4809                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4810                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4811        }
4812    }
4813
4814    /**
4815     * Computes whether this view is visible to the user. Such a view is
4816     * attached, visible, all its predecessors are visible, it is not clipped
4817     * entirely by its predecessors, and has an alpha greater than zero.
4818     *
4819     * @return Whether the view is visible on the screen.
4820     *
4821     * @hide
4822     */
4823    protected boolean isVisibleToUser() {
4824        return isVisibleToUser(null);
4825    }
4826
4827    /**
4828     * Computes whether the given portion of this view is visible to the user. Such a view is
4829     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4830     * the specified portion is not clipped entirely by its predecessors.
4831     *
4832     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4833     *                    <code>null</code>, and the entire view will be tested in this case.
4834     *                    When <code>true</code> is returned by the function, the actual visible
4835     *                    region will be stored in this parameter; that is, if boundInView is fully
4836     *                    contained within the view, no modification will be made, otherwise regions
4837     *                    outside of the visible area of the view will be clipped.
4838     *
4839     * @return Whether the specified portion of the view is visible on the screen.
4840     *
4841     * @hide
4842     */
4843    protected boolean isVisibleToUser(Rect boundInView) {
4844        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4845        Point offset = mAttachInfo.mPoint;
4846        // The first two checks are made also made by isShown() which
4847        // however traverses the tree up to the parent to catch that.
4848        // Therefore, we do some fail fast check to minimize the up
4849        // tree traversal.
4850        boolean isVisible = mAttachInfo != null
4851            && mAttachInfo.mWindowVisibility == View.VISIBLE
4852            && getAlpha() > 0
4853            && isShown()
4854            && getGlobalVisibleRect(visibleRect, offset);
4855            if (isVisible && boundInView != null) {
4856                visibleRect.offset(-offset.x, -offset.y);
4857                isVisible &= boundInView.intersect(visibleRect);
4858            }
4859            return isVisible;
4860    }
4861
4862    /**
4863     * Sets a delegate for implementing accessibility support via compositon as
4864     * opposed to inheritance. The delegate's primary use is for implementing
4865     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4866     *
4867     * @param delegate The delegate instance.
4868     *
4869     * @see AccessibilityDelegate
4870     */
4871    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4872        mAccessibilityDelegate = delegate;
4873    }
4874
4875    /**
4876     * Gets the provider for managing a virtual view hierarchy rooted at this View
4877     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4878     * that explore the window content.
4879     * <p>
4880     * If this method returns an instance, this instance is responsible for managing
4881     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4882     * View including the one representing the View itself. Similarly the returned
4883     * instance is responsible for performing accessibility actions on any virtual
4884     * view or the root view itself.
4885     * </p>
4886     * <p>
4887     * If an {@link AccessibilityDelegate} has been specified via calling
4888     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4889     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4890     * is responsible for handling this call.
4891     * </p>
4892     *
4893     * @return The provider.
4894     *
4895     * @see AccessibilityNodeProvider
4896     */
4897    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4898        if (mAccessibilityDelegate != null) {
4899            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4900        } else {
4901            return null;
4902        }
4903    }
4904
4905    /**
4906     * Gets the unique identifier of this view on the screen for accessibility purposes.
4907     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4908     *
4909     * @return The view accessibility id.
4910     *
4911     * @hide
4912     */
4913    public int getAccessibilityViewId() {
4914        if (mAccessibilityViewId == NO_ID) {
4915            mAccessibilityViewId = sNextAccessibilityViewId++;
4916        }
4917        return mAccessibilityViewId;
4918    }
4919
4920    /**
4921     * Gets the unique identifier of the window in which this View reseides.
4922     *
4923     * @return The window accessibility id.
4924     *
4925     * @hide
4926     */
4927    public int getAccessibilityWindowId() {
4928        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4929    }
4930
4931    /**
4932     * Gets the {@link View} description. It briefly describes the view and is
4933     * primarily used for accessibility support. Set this property to enable
4934     * better accessibility support for your application. This is especially
4935     * true for views that do not have textual representation (For example,
4936     * ImageButton).
4937     *
4938     * @return The content description.
4939     *
4940     * @attr ref android.R.styleable#View_contentDescription
4941     */
4942    @ViewDebug.ExportedProperty(category = "accessibility")
4943    public CharSequence getContentDescription() {
4944        return mContentDescription;
4945    }
4946
4947    /**
4948     * Sets the {@link View} description. It briefly describes the view and is
4949     * primarily used for accessibility support. Set this property to enable
4950     * better accessibility support for your application. This is especially
4951     * true for views that do not have textual representation (For example,
4952     * ImageButton).
4953     *
4954     * @param contentDescription The content description.
4955     *
4956     * @attr ref android.R.styleable#View_contentDescription
4957     */
4958    @RemotableViewMethod
4959    public void setContentDescription(CharSequence contentDescription) {
4960        mContentDescription = contentDescription;
4961    }
4962
4963    /**
4964     * Invoked whenever this view loses focus, either by losing window focus or by losing
4965     * focus within its window. This method can be used to clear any state tied to the
4966     * focus. For instance, if a button is held pressed with the trackball and the window
4967     * loses focus, this method can be used to cancel the press.
4968     *
4969     * Subclasses of View overriding this method should always call super.onFocusLost().
4970     *
4971     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4972     * @see #onWindowFocusChanged(boolean)
4973     *
4974     * @hide pending API council approval
4975     */
4976    protected void onFocusLost() {
4977        resetPressedState();
4978    }
4979
4980    private void resetPressedState() {
4981        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4982            return;
4983        }
4984
4985        if (isPressed()) {
4986            setPressed(false);
4987
4988            if (!mHasPerformedLongPress) {
4989                removeLongPressCallback();
4990            }
4991        }
4992    }
4993
4994    /**
4995     * Returns true if this view has focus
4996     *
4997     * @return True if this view has focus, false otherwise.
4998     */
4999    @ViewDebug.ExportedProperty(category = "focus")
5000    public boolean isFocused() {
5001        return (mPrivateFlags & FOCUSED) != 0;
5002    }
5003
5004    /**
5005     * Find the view in the hierarchy rooted at this view that currently has
5006     * focus.
5007     *
5008     * @return The view that currently has focus, or null if no focused view can
5009     *         be found.
5010     */
5011    public View findFocus() {
5012        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
5013    }
5014
5015    /**
5016     * Indicates whether this view is one of the set of scrollable containers in
5017     * its window.
5018     *
5019     * @return whether this view is one of the set of scrollable containers in
5020     * its window
5021     *
5022     * @attr ref android.R.styleable#View_isScrollContainer
5023     */
5024    public boolean isScrollContainer() {
5025        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5026    }
5027
5028    /**
5029     * Change whether this view is one of the set of scrollable containers in
5030     * its window.  This will be used to determine whether the window can
5031     * resize or must pan when a soft input area is open -- scrollable
5032     * containers allow the window to use resize mode since the container
5033     * will appropriately shrink.
5034     *
5035     * @attr ref android.R.styleable#View_isScrollContainer
5036     */
5037    public void setScrollContainer(boolean isScrollContainer) {
5038        if (isScrollContainer) {
5039            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5040                mAttachInfo.mScrollContainers.add(this);
5041                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5042            }
5043            mPrivateFlags |= SCROLL_CONTAINER;
5044        } else {
5045            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5046                mAttachInfo.mScrollContainers.remove(this);
5047            }
5048            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5049        }
5050    }
5051
5052    /**
5053     * Returns the quality of the drawing cache.
5054     *
5055     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5056     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5057     *
5058     * @see #setDrawingCacheQuality(int)
5059     * @see #setDrawingCacheEnabled(boolean)
5060     * @see #isDrawingCacheEnabled()
5061     *
5062     * @attr ref android.R.styleable#View_drawingCacheQuality
5063     */
5064    public int getDrawingCacheQuality() {
5065        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5066    }
5067
5068    /**
5069     * Set the drawing cache quality of this view. This value is used only when the
5070     * drawing cache is enabled
5071     *
5072     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5073     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5074     *
5075     * @see #getDrawingCacheQuality()
5076     * @see #setDrawingCacheEnabled(boolean)
5077     * @see #isDrawingCacheEnabled()
5078     *
5079     * @attr ref android.R.styleable#View_drawingCacheQuality
5080     */
5081    public void setDrawingCacheQuality(int quality) {
5082        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5083    }
5084
5085    /**
5086     * Returns whether the screen should remain on, corresponding to the current
5087     * value of {@link #KEEP_SCREEN_ON}.
5088     *
5089     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5090     *
5091     * @see #setKeepScreenOn(boolean)
5092     *
5093     * @attr ref android.R.styleable#View_keepScreenOn
5094     */
5095    public boolean getKeepScreenOn() {
5096        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5097    }
5098
5099    /**
5100     * Controls whether the screen should remain on, modifying the
5101     * value of {@link #KEEP_SCREEN_ON}.
5102     *
5103     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5104     *
5105     * @see #getKeepScreenOn()
5106     *
5107     * @attr ref android.R.styleable#View_keepScreenOn
5108     */
5109    public void setKeepScreenOn(boolean keepScreenOn) {
5110        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5111    }
5112
5113    /**
5114     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5115     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5116     *
5117     * @attr ref android.R.styleable#View_nextFocusLeft
5118     */
5119    public int getNextFocusLeftId() {
5120        return mNextFocusLeftId;
5121    }
5122
5123    /**
5124     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5125     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5126     * decide automatically.
5127     *
5128     * @attr ref android.R.styleable#View_nextFocusLeft
5129     */
5130    public void setNextFocusLeftId(int nextFocusLeftId) {
5131        mNextFocusLeftId = nextFocusLeftId;
5132    }
5133
5134    /**
5135     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5136     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5137     *
5138     * @attr ref android.R.styleable#View_nextFocusRight
5139     */
5140    public int getNextFocusRightId() {
5141        return mNextFocusRightId;
5142    }
5143
5144    /**
5145     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5146     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5147     * decide automatically.
5148     *
5149     * @attr ref android.R.styleable#View_nextFocusRight
5150     */
5151    public void setNextFocusRightId(int nextFocusRightId) {
5152        mNextFocusRightId = nextFocusRightId;
5153    }
5154
5155    /**
5156     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5157     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5158     *
5159     * @attr ref android.R.styleable#View_nextFocusUp
5160     */
5161    public int getNextFocusUpId() {
5162        return mNextFocusUpId;
5163    }
5164
5165    /**
5166     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5167     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5168     * decide automatically.
5169     *
5170     * @attr ref android.R.styleable#View_nextFocusUp
5171     */
5172    public void setNextFocusUpId(int nextFocusUpId) {
5173        mNextFocusUpId = nextFocusUpId;
5174    }
5175
5176    /**
5177     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5178     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5179     *
5180     * @attr ref android.R.styleable#View_nextFocusDown
5181     */
5182    public int getNextFocusDownId() {
5183        return mNextFocusDownId;
5184    }
5185
5186    /**
5187     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5188     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5189     * decide automatically.
5190     *
5191     * @attr ref android.R.styleable#View_nextFocusDown
5192     */
5193    public void setNextFocusDownId(int nextFocusDownId) {
5194        mNextFocusDownId = nextFocusDownId;
5195    }
5196
5197    /**
5198     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5199     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5200     *
5201     * @attr ref android.R.styleable#View_nextFocusForward
5202     */
5203    public int getNextFocusForwardId() {
5204        return mNextFocusForwardId;
5205    }
5206
5207    /**
5208     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5209     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5210     * decide automatically.
5211     *
5212     * @attr ref android.R.styleable#View_nextFocusForward
5213     */
5214    public void setNextFocusForwardId(int nextFocusForwardId) {
5215        mNextFocusForwardId = nextFocusForwardId;
5216    }
5217
5218    /**
5219     * Returns the visibility of this view and all of its ancestors
5220     *
5221     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5222     */
5223    public boolean isShown() {
5224        View current = this;
5225        //noinspection ConstantConditions
5226        do {
5227            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5228                return false;
5229            }
5230            ViewParent parent = current.mParent;
5231            if (parent == null) {
5232                return false; // We are not attached to the view root
5233            }
5234            if (!(parent instanceof View)) {
5235                return true;
5236            }
5237            current = (View) parent;
5238        } while (current != null);
5239
5240        return false;
5241    }
5242
5243    /**
5244     * Called by the view hierarchy when the content insets for a window have
5245     * changed, to allow it to adjust its content to fit within those windows.
5246     * The content insets tell you the space that the status bar, input method,
5247     * and other system windows infringe on the application's window.
5248     *
5249     * <p>You do not normally need to deal with this function, since the default
5250     * window decoration given to applications takes care of applying it to the
5251     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5252     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5253     * and your content can be placed under those system elements.  You can then
5254     * use this method within your view hierarchy if you have parts of your UI
5255     * which you would like to ensure are not being covered.
5256     *
5257     * <p>The default implementation of this method simply applies the content
5258     * inset's to the view's padding.  This can be enabled through
5259     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5260     * the method and handle the insets however you would like.  Note that the
5261     * insets provided by the framework are always relative to the far edges
5262     * of the window, not accounting for the location of the called view within
5263     * that window.  (In fact when this method is called you do not yet know
5264     * where the layout will place the view, as it is done before layout happens.)
5265     *
5266     * <p>Note: unlike many View methods, there is no dispatch phase to this
5267     * call.  If you are overriding it in a ViewGroup and want to allow the
5268     * call to continue to your children, you must be sure to call the super
5269     * implementation.
5270     *
5271     * <p>Here is a sample layout that makes use of fitting system windows
5272     * to have controls for a video view placed inside of the window decorations
5273     * that it hides and shows.  This can be used with code like the second
5274     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5275     *
5276     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5277     *
5278     * @param insets Current content insets of the window.  Prior to
5279     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5280     * the insets or else you and Android will be unhappy.
5281     *
5282     * @return Return true if this view applied the insets and it should not
5283     * continue propagating further down the hierarchy, false otherwise.
5284     */
5285    protected boolean fitSystemWindows(Rect insets) {
5286        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5287            mUserPaddingStart = -1;
5288            mUserPaddingEnd = -1;
5289            mUserPaddingRelative = false;
5290            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5291                    || mAttachInfo == null
5292                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5293                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5294                return true;
5295            } else {
5296                internalSetPadding(0, 0, 0, 0);
5297                return false;
5298            }
5299        }
5300        return false;
5301    }
5302
5303    /**
5304     * Set whether or not this view should account for system screen decorations
5305     * such as the status bar and inset its content. This allows this view to be
5306     * positioned in absolute screen coordinates and remain visible to the user.
5307     *
5308     * <p>This should only be used by top-level window decor views.
5309     *
5310     * @param fitSystemWindows true to inset content for system screen decorations, false for
5311     *                         default behavior.
5312     *
5313     * @attr ref android.R.styleable#View_fitsSystemWindows
5314     */
5315    public void setFitsSystemWindows(boolean fitSystemWindows) {
5316        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5317    }
5318
5319    /**
5320     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5321     * returns true, this view
5322     * will account for system screen decorations such as the status bar and inset its
5323     * content. This allows the view to be positioned in absolute screen coordinates
5324     * and remain visible to the user.
5325     *
5326     * @return true if this view will adjust its content bounds for system screen decorations.
5327     *
5328     * @attr ref android.R.styleable#View_fitsSystemWindows
5329     */
5330    public boolean getFitsSystemWindows() {
5331        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5332    }
5333
5334    /** @hide */
5335    public boolean fitsSystemWindows() {
5336        return getFitsSystemWindows();
5337    }
5338
5339    /**
5340     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5341     */
5342    public void requestFitSystemWindows() {
5343        if (mParent != null) {
5344            mParent.requestFitSystemWindows();
5345        }
5346    }
5347
5348    /**
5349     * For use by PhoneWindow to make its own system window fitting optional.
5350     * @hide
5351     */
5352    public void makeOptionalFitsSystemWindows() {
5353        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5354    }
5355
5356    /**
5357     * Returns the visibility status for this view.
5358     *
5359     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5360     * @attr ref android.R.styleable#View_visibility
5361     */
5362    @ViewDebug.ExportedProperty(mapping = {
5363        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5364        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5365        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5366    })
5367    public int getVisibility() {
5368        return mViewFlags & VISIBILITY_MASK;
5369    }
5370
5371    /**
5372     * Set the enabled state of this view.
5373     *
5374     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5375     * @attr ref android.R.styleable#View_visibility
5376     */
5377    @RemotableViewMethod
5378    public void setVisibility(int visibility) {
5379        setFlags(visibility, VISIBILITY_MASK);
5380        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5381    }
5382
5383    /**
5384     * Returns the enabled status for this view. The interpretation of the
5385     * enabled state varies by subclass.
5386     *
5387     * @return True if this view is enabled, false otherwise.
5388     */
5389    @ViewDebug.ExportedProperty
5390    public boolean isEnabled() {
5391        return (mViewFlags & ENABLED_MASK) == ENABLED;
5392    }
5393
5394    /**
5395     * Set the enabled state of this view. The interpretation of the enabled
5396     * state varies by subclass.
5397     *
5398     * @param enabled True if this view is enabled, false otherwise.
5399     */
5400    @RemotableViewMethod
5401    public void setEnabled(boolean enabled) {
5402        if (enabled == isEnabled()) return;
5403
5404        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5405
5406        /*
5407         * The View most likely has to change its appearance, so refresh
5408         * the drawable state.
5409         */
5410        refreshDrawableState();
5411
5412        // Invalidate too, since the default behavior for views is to be
5413        // be drawn at 50% alpha rather than to change the drawable.
5414        invalidate(true);
5415    }
5416
5417    /**
5418     * Set whether this view can receive the focus.
5419     *
5420     * Setting this to false will also ensure that this view is not focusable
5421     * in touch mode.
5422     *
5423     * @param focusable If true, this view can receive the focus.
5424     *
5425     * @see #setFocusableInTouchMode(boolean)
5426     * @attr ref android.R.styleable#View_focusable
5427     */
5428    public void setFocusable(boolean focusable) {
5429        if (!focusable) {
5430            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5431        }
5432        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5433    }
5434
5435    /**
5436     * Set whether this view can receive focus while in touch mode.
5437     *
5438     * Setting this to true will also ensure that this view is focusable.
5439     *
5440     * @param focusableInTouchMode If true, this view can receive the focus while
5441     *   in touch mode.
5442     *
5443     * @see #setFocusable(boolean)
5444     * @attr ref android.R.styleable#View_focusableInTouchMode
5445     */
5446    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5447        // Focusable in touch mode should always be set before the focusable flag
5448        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5449        // which, in touch mode, will not successfully request focus on this view
5450        // because the focusable in touch mode flag is not set
5451        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5452        if (focusableInTouchMode) {
5453            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5454        }
5455    }
5456
5457    /**
5458     * Set whether this view should have sound effects enabled for events such as
5459     * clicking and touching.
5460     *
5461     * <p>You may wish to disable sound effects for a view if you already play sounds,
5462     * for instance, a dial key that plays dtmf tones.
5463     *
5464     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5465     * @see #isSoundEffectsEnabled()
5466     * @see #playSoundEffect(int)
5467     * @attr ref android.R.styleable#View_soundEffectsEnabled
5468     */
5469    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5470        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5471    }
5472
5473    /**
5474     * @return whether this view should have sound effects enabled for events such as
5475     *     clicking and touching.
5476     *
5477     * @see #setSoundEffectsEnabled(boolean)
5478     * @see #playSoundEffect(int)
5479     * @attr ref android.R.styleable#View_soundEffectsEnabled
5480     */
5481    @ViewDebug.ExportedProperty
5482    public boolean isSoundEffectsEnabled() {
5483        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5484    }
5485
5486    /**
5487     * Set whether this view should have haptic feedback for events such as
5488     * long presses.
5489     *
5490     * <p>You may wish to disable haptic feedback if your view already controls
5491     * its own haptic feedback.
5492     *
5493     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5494     * @see #isHapticFeedbackEnabled()
5495     * @see #performHapticFeedback(int)
5496     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5497     */
5498    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5499        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5500    }
5501
5502    /**
5503     * @return whether this view should have haptic feedback enabled for events
5504     * long presses.
5505     *
5506     * @see #setHapticFeedbackEnabled(boolean)
5507     * @see #performHapticFeedback(int)
5508     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5509     */
5510    @ViewDebug.ExportedProperty
5511    public boolean isHapticFeedbackEnabled() {
5512        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5513    }
5514
5515    /**
5516     * Returns the layout direction for this view.
5517     *
5518     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5519     *   {@link #LAYOUT_DIRECTION_RTL},
5520     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5521     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5522     *
5523     * @attr ref android.R.styleable#View_layoutDirection
5524     * @hide
5525     */
5526    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5527        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5528        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5529        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5530        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5531    })
5532    public int getLayoutDirection() {
5533        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5534    }
5535
5536    /**
5537     * Set the layout direction for this view. This will propagate a reset of layout direction
5538     * resolution to the view's children and resolve layout direction for this view.
5539     *
5540     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5541     *   {@link #LAYOUT_DIRECTION_RTL},
5542     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5543     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5544     *
5545     * @attr ref android.R.styleable#View_layoutDirection
5546     * @hide
5547     */
5548    @RemotableViewMethod
5549    public void setLayoutDirection(int layoutDirection) {
5550        if (getLayoutDirection() != layoutDirection) {
5551            // Reset the current layout direction and the resolved one
5552            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5553            resetResolvedLayoutDirection();
5554            // Set the new layout direction (filtered) and ask for a layout pass
5555            mPrivateFlags2 |=
5556                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5557            requestLayout();
5558        }
5559    }
5560
5561    /**
5562     * Returns the resolved layout direction for this view.
5563     *
5564     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5565     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5566     * @hide
5567     */
5568    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5569        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5570        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5571    })
5572    public int getResolvedLayoutDirection() {
5573        // The layout diretion will be resolved only if needed
5574        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5575            resolveLayoutDirection();
5576        }
5577        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5578                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5579    }
5580
5581    /**
5582     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5583     * layout attribute and/or the inherited value from the parent
5584     *
5585     * @return true if the layout is right-to-left.
5586     * @hide
5587     */
5588    @ViewDebug.ExportedProperty(category = "layout")
5589    public boolean isLayoutRtl() {
5590        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5591    }
5592
5593    /**
5594     * Indicates whether the view is currently tracking transient state that the
5595     * app should not need to concern itself with saving and restoring, but that
5596     * the framework should take special note to preserve when possible.
5597     *
5598     * <p>A view with transient state cannot be trivially rebound from an external
5599     * data source, such as an adapter binding item views in a list. This may be
5600     * because the view is performing an animation, tracking user selection
5601     * of content, or similar.</p>
5602     *
5603     * @return true if the view has transient state
5604     */
5605    @ViewDebug.ExportedProperty(category = "layout")
5606    public boolean hasTransientState() {
5607        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5608    }
5609
5610    /**
5611     * Set whether this view is currently tracking transient state that the
5612     * framework should attempt to preserve when possible. This flag is reference counted,
5613     * so every call to setHasTransientState(true) should be paired with a later call
5614     * to setHasTransientState(false).
5615     *
5616     * <p>A view with transient state cannot be trivially rebound from an external
5617     * data source, such as an adapter binding item views in a list. This may be
5618     * because the view is performing an animation, tracking user selection
5619     * of content, or similar.</p>
5620     *
5621     * @param hasTransientState true if this view has transient state
5622     */
5623    public void setHasTransientState(boolean hasTransientState) {
5624        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5625                mTransientStateCount - 1;
5626        if (mTransientStateCount < 0) {
5627            mTransientStateCount = 0;
5628            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5629                    "unmatched pair of setHasTransientState calls");
5630        }
5631        if ((hasTransientState && mTransientStateCount == 1) ||
5632                (!hasTransientState && mTransientStateCount == 0)) {
5633            // update flag if we've just incremented up from 0 or decremented down to 0
5634            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5635                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5636            if (mParent != null) {
5637                try {
5638                    mParent.childHasTransientStateChanged(this, hasTransientState);
5639                } catch (AbstractMethodError e) {
5640                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5641                            " does not fully implement ViewParent", e);
5642                }
5643            }
5644        }
5645    }
5646
5647    /**
5648     * If this view doesn't do any drawing on its own, set this flag to
5649     * allow further optimizations. By default, this flag is not set on
5650     * View, but could be set on some View subclasses such as ViewGroup.
5651     *
5652     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5653     * you should clear this flag.
5654     *
5655     * @param willNotDraw whether or not this View draw on its own
5656     */
5657    public void setWillNotDraw(boolean willNotDraw) {
5658        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5659    }
5660
5661    /**
5662     * Returns whether or not this View draws on its own.
5663     *
5664     * @return true if this view has nothing to draw, false otherwise
5665     */
5666    @ViewDebug.ExportedProperty(category = "drawing")
5667    public boolean willNotDraw() {
5668        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5669    }
5670
5671    /**
5672     * When a View's drawing cache is enabled, drawing is redirected to an
5673     * offscreen bitmap. Some views, like an ImageView, must be able to
5674     * bypass this mechanism if they already draw a single bitmap, to avoid
5675     * unnecessary usage of the memory.
5676     *
5677     * @param willNotCacheDrawing true if this view does not cache its
5678     *        drawing, false otherwise
5679     */
5680    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5681        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5682    }
5683
5684    /**
5685     * Returns whether or not this View can cache its drawing or not.
5686     *
5687     * @return true if this view does not cache its drawing, false otherwise
5688     */
5689    @ViewDebug.ExportedProperty(category = "drawing")
5690    public boolean willNotCacheDrawing() {
5691        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5692    }
5693
5694    /**
5695     * Indicates whether this view reacts to click events or not.
5696     *
5697     * @return true if the view is clickable, false otherwise
5698     *
5699     * @see #setClickable(boolean)
5700     * @attr ref android.R.styleable#View_clickable
5701     */
5702    @ViewDebug.ExportedProperty
5703    public boolean isClickable() {
5704        return (mViewFlags & CLICKABLE) == CLICKABLE;
5705    }
5706
5707    /**
5708     * Enables or disables click events for this view. When a view
5709     * is clickable it will change its state to "pressed" on every click.
5710     * Subclasses should set the view clickable to visually react to
5711     * user's clicks.
5712     *
5713     * @param clickable true to make the view clickable, false otherwise
5714     *
5715     * @see #isClickable()
5716     * @attr ref android.R.styleable#View_clickable
5717     */
5718    public void setClickable(boolean clickable) {
5719        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5720    }
5721
5722    /**
5723     * Indicates whether this view reacts to long click events or not.
5724     *
5725     * @return true if the view is long clickable, false otherwise
5726     *
5727     * @see #setLongClickable(boolean)
5728     * @attr ref android.R.styleable#View_longClickable
5729     */
5730    public boolean isLongClickable() {
5731        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5732    }
5733
5734    /**
5735     * Enables or disables long click events for this view. When a view is long
5736     * clickable it reacts to the user holding down the button for a longer
5737     * duration than a tap. This event can either launch the listener or a
5738     * context menu.
5739     *
5740     * @param longClickable true to make the view long clickable, false otherwise
5741     * @see #isLongClickable()
5742     * @attr ref android.R.styleable#View_longClickable
5743     */
5744    public void setLongClickable(boolean longClickable) {
5745        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5746    }
5747
5748    /**
5749     * Sets the pressed state for this view.
5750     *
5751     * @see #isClickable()
5752     * @see #setClickable(boolean)
5753     *
5754     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5755     *        the View's internal state from a previously set "pressed" state.
5756     */
5757    public void setPressed(boolean pressed) {
5758        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5759
5760        if (pressed) {
5761            mPrivateFlags |= PRESSED;
5762        } else {
5763            mPrivateFlags &= ~PRESSED;
5764        }
5765
5766        if (needsRefresh) {
5767            refreshDrawableState();
5768        }
5769        dispatchSetPressed(pressed);
5770    }
5771
5772    /**
5773     * Dispatch setPressed to all of this View's children.
5774     *
5775     * @see #setPressed(boolean)
5776     *
5777     * @param pressed The new pressed state
5778     */
5779    protected void dispatchSetPressed(boolean pressed) {
5780    }
5781
5782    /**
5783     * Indicates whether the view is currently in pressed state. Unless
5784     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5785     * the pressed state.
5786     *
5787     * @see #setPressed(boolean)
5788     * @see #isClickable()
5789     * @see #setClickable(boolean)
5790     *
5791     * @return true if the view is currently pressed, false otherwise
5792     */
5793    public boolean isPressed() {
5794        return (mPrivateFlags & PRESSED) == PRESSED;
5795    }
5796
5797    /**
5798     * Indicates whether this view will save its state (that is,
5799     * whether its {@link #onSaveInstanceState} method will be called).
5800     *
5801     * @return Returns true if the view state saving is enabled, else false.
5802     *
5803     * @see #setSaveEnabled(boolean)
5804     * @attr ref android.R.styleable#View_saveEnabled
5805     */
5806    public boolean isSaveEnabled() {
5807        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5808    }
5809
5810    /**
5811     * Controls whether the saving of this view's state is
5812     * enabled (that is, whether its {@link #onSaveInstanceState} method
5813     * will be called).  Note that even if freezing is enabled, the
5814     * view still must have an id assigned to it (via {@link #setId(int)})
5815     * for its state to be saved.  This flag can only disable the
5816     * saving of this view; any child views may still have their state saved.
5817     *
5818     * @param enabled Set to false to <em>disable</em> state saving, or true
5819     * (the default) to allow it.
5820     *
5821     * @see #isSaveEnabled()
5822     * @see #setId(int)
5823     * @see #onSaveInstanceState()
5824     * @attr ref android.R.styleable#View_saveEnabled
5825     */
5826    public void setSaveEnabled(boolean enabled) {
5827        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5828    }
5829
5830    /**
5831     * Gets whether the framework should discard touches when the view's
5832     * window is obscured by another visible window.
5833     * Refer to the {@link View} security documentation for more details.
5834     *
5835     * @return True if touch filtering is enabled.
5836     *
5837     * @see #setFilterTouchesWhenObscured(boolean)
5838     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5839     */
5840    @ViewDebug.ExportedProperty
5841    public boolean getFilterTouchesWhenObscured() {
5842        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5843    }
5844
5845    /**
5846     * Sets whether the framework should discard touches when the view's
5847     * window is obscured by another visible window.
5848     * Refer to the {@link View} security documentation for more details.
5849     *
5850     * @param enabled True if touch filtering should be enabled.
5851     *
5852     * @see #getFilterTouchesWhenObscured
5853     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5854     */
5855    public void setFilterTouchesWhenObscured(boolean enabled) {
5856        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5857                FILTER_TOUCHES_WHEN_OBSCURED);
5858    }
5859
5860    /**
5861     * Indicates whether the entire hierarchy under this view will save its
5862     * state when a state saving traversal occurs from its parent.  The default
5863     * is true; if false, these views will not be saved unless
5864     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5865     *
5866     * @return Returns true if the view state saving from parent is enabled, else false.
5867     *
5868     * @see #setSaveFromParentEnabled(boolean)
5869     */
5870    public boolean isSaveFromParentEnabled() {
5871        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5872    }
5873
5874    /**
5875     * Controls whether the entire hierarchy under this view will save its
5876     * state when a state saving traversal occurs from its parent.  The default
5877     * is true; if false, these views will not be saved unless
5878     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5879     *
5880     * @param enabled Set to false to <em>disable</em> state saving, or true
5881     * (the default) to allow it.
5882     *
5883     * @see #isSaveFromParentEnabled()
5884     * @see #setId(int)
5885     * @see #onSaveInstanceState()
5886     */
5887    public void setSaveFromParentEnabled(boolean enabled) {
5888        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5889    }
5890
5891
5892    /**
5893     * Returns whether this View is able to take focus.
5894     *
5895     * @return True if this view can take focus, or false otherwise.
5896     * @attr ref android.R.styleable#View_focusable
5897     */
5898    @ViewDebug.ExportedProperty(category = "focus")
5899    public final boolean isFocusable() {
5900        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5901    }
5902
5903    /**
5904     * When a view is focusable, it may not want to take focus when in touch mode.
5905     * For example, a button would like focus when the user is navigating via a D-pad
5906     * so that the user can click on it, but once the user starts touching the screen,
5907     * the button shouldn't take focus
5908     * @return Whether the view is focusable in touch mode.
5909     * @attr ref android.R.styleable#View_focusableInTouchMode
5910     */
5911    @ViewDebug.ExportedProperty
5912    public final boolean isFocusableInTouchMode() {
5913        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5914    }
5915
5916    /**
5917     * Find the nearest view in the specified direction that can take focus.
5918     * This does not actually give focus to that view.
5919     *
5920     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5921     *
5922     * @return The nearest focusable in the specified direction, or null if none
5923     *         can be found.
5924     */
5925    public View focusSearch(int direction) {
5926        if (mParent != null) {
5927            return mParent.focusSearch(this, direction);
5928        } else {
5929            return null;
5930        }
5931    }
5932
5933    /**
5934     * This method is the last chance for the focused view and its ancestors to
5935     * respond to an arrow key. This is called when the focused view did not
5936     * consume the key internally, nor could the view system find a new view in
5937     * the requested direction to give focus to.
5938     *
5939     * @param focused The currently focused view.
5940     * @param direction The direction focus wants to move. One of FOCUS_UP,
5941     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5942     * @return True if the this view consumed this unhandled move.
5943     */
5944    public boolean dispatchUnhandledMove(View focused, int direction) {
5945        return false;
5946    }
5947
5948    /**
5949     * If a user manually specified the next view id for a particular direction,
5950     * use the root to look up the view.
5951     * @param root The root view of the hierarchy containing this view.
5952     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5953     * or FOCUS_BACKWARD.
5954     * @return The user specified next view, or null if there is none.
5955     */
5956    View findUserSetNextFocus(View root, int direction) {
5957        switch (direction) {
5958            case FOCUS_LEFT:
5959                if (mNextFocusLeftId == View.NO_ID) return null;
5960                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5961            case FOCUS_RIGHT:
5962                if (mNextFocusRightId == View.NO_ID) return null;
5963                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5964            case FOCUS_UP:
5965                if (mNextFocusUpId == View.NO_ID) return null;
5966                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5967            case FOCUS_DOWN:
5968                if (mNextFocusDownId == View.NO_ID) return null;
5969                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5970            case FOCUS_FORWARD:
5971                if (mNextFocusForwardId == View.NO_ID) return null;
5972                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5973            case FOCUS_BACKWARD: {
5974                if (mID == View.NO_ID) return null;
5975                final int id = mID;
5976                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5977                    @Override
5978                    public boolean apply(View t) {
5979                        return t.mNextFocusForwardId == id;
5980                    }
5981                });
5982            }
5983        }
5984        return null;
5985    }
5986
5987    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5988        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5989            @Override
5990            public boolean apply(View t) {
5991                return t.mID == childViewId;
5992            }
5993        });
5994
5995        if (result == null) {
5996            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5997                    + "by user for id " + childViewId);
5998        }
5999        return result;
6000    }
6001
6002    /**
6003     * Find and return all focusable views that are descendants of this view,
6004     * possibly including this view if it is focusable itself.
6005     *
6006     * @param direction The direction of the focus
6007     * @return A list of focusable views
6008     */
6009    public ArrayList<View> getFocusables(int direction) {
6010        ArrayList<View> result = new ArrayList<View>(24);
6011        addFocusables(result, direction);
6012        return result;
6013    }
6014
6015    /**
6016     * Add any focusable views that are descendants of this view (possibly
6017     * including this view if it is focusable itself) to views.  If we are in touch mode,
6018     * only add views that are also focusable in touch mode.
6019     *
6020     * @param views Focusable views found so far
6021     * @param direction The direction of the focus
6022     */
6023    public void addFocusables(ArrayList<View> views, int direction) {
6024        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6025    }
6026
6027    /**
6028     * Adds any focusable views that are descendants of this view (possibly
6029     * including this view if it is focusable itself) to views. This method
6030     * adds all focusable views regardless if we are in touch mode or
6031     * only views focusable in touch mode if we are in touch mode or
6032     * only views that can take accessibility focus if accessibility is enabeld
6033     * depending on the focusable mode paramater.
6034     *
6035     * @param views Focusable views found so far or null if all we are interested is
6036     *        the number of focusables.
6037     * @param direction The direction of the focus.
6038     * @param focusableMode The type of focusables to be added.
6039     *
6040     * @see #FOCUSABLES_ALL
6041     * @see #FOCUSABLES_TOUCH_MODE
6042     */
6043    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6044        if (views == null) {
6045            return;
6046        }
6047        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
6048            if (canTakeAccessibilityFocusFromHover() || getAccessibilityNodeProvider() != null) {
6049                views.add(this);
6050                return;
6051            }
6052        }
6053        if (!isFocusable()) {
6054            return;
6055        }
6056        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6057                && isInTouchMode() && !isFocusableInTouchMode()) {
6058            return;
6059        }
6060        views.add(this);
6061    }
6062
6063    /**
6064     * Finds the Views that contain given text. The containment is case insensitive.
6065     * The search is performed by either the text that the View renders or the content
6066     * description that describes the view for accessibility purposes and the view does
6067     * not render or both. Clients can specify how the search is to be performed via
6068     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6069     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6070     *
6071     * @param outViews The output list of matching Views.
6072     * @param searched The text to match against.
6073     *
6074     * @see #FIND_VIEWS_WITH_TEXT
6075     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6076     * @see #setContentDescription(CharSequence)
6077     */
6078    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6079        if (getAccessibilityNodeProvider() != null) {
6080            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6081                outViews.add(this);
6082            }
6083        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6084                && (searched != null && searched.length() > 0)
6085                && (mContentDescription != null && mContentDescription.length() > 0)) {
6086            String searchedLowerCase = searched.toString().toLowerCase();
6087            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6088            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6089                outViews.add(this);
6090            }
6091        }
6092    }
6093
6094    /**
6095     * Find and return all touchable views that are descendants of this view,
6096     * possibly including this view if it is touchable itself.
6097     *
6098     * @return A list of touchable views
6099     */
6100    public ArrayList<View> getTouchables() {
6101        ArrayList<View> result = new ArrayList<View>();
6102        addTouchables(result);
6103        return result;
6104    }
6105
6106    /**
6107     * Add any touchable views that are descendants of this view (possibly
6108     * including this view if it is touchable itself) to views.
6109     *
6110     * @param views Touchable views found so far
6111     */
6112    public void addTouchables(ArrayList<View> views) {
6113        final int viewFlags = mViewFlags;
6114
6115        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6116                && (viewFlags & ENABLED_MASK) == ENABLED) {
6117            views.add(this);
6118        }
6119    }
6120
6121    /**
6122     * Returns whether this View is accessibility focused.
6123     *
6124     * @return True if this View is accessibility focused.
6125     */
6126    boolean isAccessibilityFocused() {
6127        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6128    }
6129
6130    /**
6131     * Call this to try to give accessibility focus to this view.
6132     *
6133     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6134     * returns false or the view is no visible or the view already has accessibility
6135     * focus.
6136     *
6137     * See also {@link #focusSearch(int)}, which is what you call to say that you
6138     * have focus, and you want your parent to look for the next one.
6139     *
6140     * @return Whether this view actually took accessibility focus.
6141     *
6142     * @hide
6143     */
6144    public boolean requestAccessibilityFocus() {
6145        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6146        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6147            return false;
6148        }
6149        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6150            return false;
6151        }
6152        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6153            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6154            ViewRootImpl viewRootImpl = getViewRootImpl();
6155            if (viewRootImpl != null) {
6156                viewRootImpl.setAccessibilityFocusedHost(this);
6157            }
6158            invalidate();
6159            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6160            notifyAccessibilityStateChanged();
6161            // Try to give input focus to this view - not a descendant.
6162            requestFocusNoSearch(View.FOCUS_DOWN, null);
6163            return true;
6164        }
6165        return false;
6166    }
6167
6168    /**
6169     * Call this to try to clear accessibility focus of this view.
6170     *
6171     * See also {@link #focusSearch(int)}, which is what you call to say that you
6172     * have focus, and you want your parent to look for the next one.
6173     *
6174     * @hide
6175     */
6176    public void clearAccessibilityFocus() {
6177        ViewRootImpl viewRootImpl = getViewRootImpl();
6178        if (viewRootImpl != null) {
6179            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6180            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6181                viewRootImpl.setAccessibilityFocusedHost(null);
6182            }
6183        }
6184        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6185            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6186            invalidate();
6187            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6188            notifyAccessibilityStateChanged();
6189
6190            // Clear the text navigation state.
6191            setAccessibilityCursorPosition(-1);
6192
6193            // Try to move accessibility focus to the input focus.
6194            View rootView = getRootView();
6195            if (rootView != null) {
6196                View inputFocus = rootView.findFocus();
6197                if (inputFocus != null) {
6198                    inputFocus.requestAccessibilityFocus();
6199                }
6200            }
6201        }
6202    }
6203
6204    private void requestAccessibilityFocusFromHover() {
6205        if (includeForAccessibility() && isActionableForAccessibility()) {
6206            requestAccessibilityFocus();
6207        } else {
6208            if (mParent != null) {
6209                View nextFocus = mParent.findViewToTakeAccessibilityFocusFromHover(this, this);
6210                if (nextFocus != null) {
6211                    nextFocus.requestAccessibilityFocus();
6212                }
6213            }
6214        }
6215    }
6216
6217    /**
6218     * @hide
6219     */
6220    public boolean canTakeAccessibilityFocusFromHover() {
6221        if (includeForAccessibility() && isActionableForAccessibility()) {
6222            return true;
6223        }
6224        if (mParent != null) {
6225            return (mParent.findViewToTakeAccessibilityFocusFromHover(this, this) == this);
6226        }
6227        return false;
6228    }
6229
6230    /**
6231     * Clears accessibility focus without calling any callback methods
6232     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6233     * is used for clearing accessibility focus when giving this focus to
6234     * another view.
6235     */
6236    void clearAccessibilityFocusNoCallbacks() {
6237        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6238            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6239            invalidate();
6240        }
6241    }
6242
6243    /**
6244     * Call this to try to give focus to a specific view or to one of its
6245     * descendants.
6246     *
6247     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6248     * false), or if it is focusable and it is not focusable in touch mode
6249     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6250     *
6251     * See also {@link #focusSearch(int)}, which is what you call to say that you
6252     * have focus, and you want your parent to look for the next one.
6253     *
6254     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6255     * {@link #FOCUS_DOWN} and <code>null</code>.
6256     *
6257     * @return Whether this view or one of its descendants actually took focus.
6258     */
6259    public final boolean requestFocus() {
6260        return requestFocus(View.FOCUS_DOWN);
6261    }
6262
6263    /**
6264     * Call this to try to give focus to a specific view or to one of its
6265     * descendants and give it a hint about what direction focus is heading.
6266     *
6267     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6268     * false), or if it is focusable and it is not focusable in touch mode
6269     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6270     *
6271     * See also {@link #focusSearch(int)}, which is what you call to say that you
6272     * have focus, and you want your parent to look for the next one.
6273     *
6274     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6275     * <code>null</code> set for the previously focused rectangle.
6276     *
6277     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6278     * @return Whether this view or one of its descendants actually took focus.
6279     */
6280    public final boolean requestFocus(int direction) {
6281        return requestFocus(direction, null);
6282    }
6283
6284    /**
6285     * Call this to try to give focus to a specific view or to one of its descendants
6286     * and give it hints about the direction and a specific rectangle that the focus
6287     * is coming from.  The rectangle can help give larger views a finer grained hint
6288     * about where focus is coming from, and therefore, where to show selection, or
6289     * forward focus change internally.
6290     *
6291     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6292     * false), or if it is focusable and it is not focusable in touch mode
6293     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6294     *
6295     * A View will not take focus if it is not visible.
6296     *
6297     * A View will not take focus if one of its parents has
6298     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6299     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6300     *
6301     * See also {@link #focusSearch(int)}, which is what you call to say that you
6302     * have focus, and you want your parent to look for the next one.
6303     *
6304     * You may wish to override this method if your custom {@link View} has an internal
6305     * {@link View} that it wishes to forward the request to.
6306     *
6307     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6308     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6309     *        to give a finer grained hint about where focus is coming from.  May be null
6310     *        if there is no hint.
6311     * @return Whether this view or one of its descendants actually took focus.
6312     */
6313    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6314        return requestFocusNoSearch(direction, previouslyFocusedRect);
6315    }
6316
6317    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6318        // need to be focusable
6319        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6320                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6321            return false;
6322        }
6323
6324        // need to be focusable in touch mode if in touch mode
6325        if (isInTouchMode() &&
6326            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6327               return false;
6328        }
6329
6330        // need to not have any parents blocking us
6331        if (hasAncestorThatBlocksDescendantFocus()) {
6332            return false;
6333        }
6334
6335        handleFocusGainInternal(direction, previouslyFocusedRect);
6336        return true;
6337    }
6338
6339    /**
6340     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6341     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6342     * touch mode to request focus when they are touched.
6343     *
6344     * @return Whether this view or one of its descendants actually took focus.
6345     *
6346     * @see #isInTouchMode()
6347     *
6348     */
6349    public final boolean requestFocusFromTouch() {
6350        // Leave touch mode if we need to
6351        if (isInTouchMode()) {
6352            ViewRootImpl viewRoot = getViewRootImpl();
6353            if (viewRoot != null) {
6354                viewRoot.ensureTouchMode(false);
6355            }
6356        }
6357        return requestFocus(View.FOCUS_DOWN);
6358    }
6359
6360    /**
6361     * @return Whether any ancestor of this view blocks descendant focus.
6362     */
6363    private boolean hasAncestorThatBlocksDescendantFocus() {
6364        ViewParent ancestor = mParent;
6365        while (ancestor instanceof ViewGroup) {
6366            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6367            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6368                return true;
6369            } else {
6370                ancestor = vgAncestor.getParent();
6371            }
6372        }
6373        return false;
6374    }
6375
6376    /**
6377     * Gets the mode for determining whether this View is important for accessibility
6378     * which is if it fires accessibility events and if it is reported to
6379     * accessibility services that query the screen.
6380     *
6381     * @return The mode for determining whether a View is important for accessibility.
6382     *
6383     * @attr ref android.R.styleable#View_importantForAccessibility
6384     *
6385     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6386     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6387     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6388     */
6389    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6390            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6391                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6392            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6393                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6394            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6395                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6396        })
6397    public int getImportantForAccessibility() {
6398        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6399                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6400    }
6401
6402    /**
6403     * Sets how to determine whether this view is important for accessibility
6404     * which is if it fires accessibility events and if it is reported to
6405     * accessibility services that query the screen.
6406     *
6407     * @param mode How to determine whether this view is important for accessibility.
6408     *
6409     * @attr ref android.R.styleable#View_importantForAccessibility
6410     *
6411     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6412     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6413     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6414     */
6415    public void setImportantForAccessibility(int mode) {
6416        if (mode != getImportantForAccessibility()) {
6417            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6418            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6419                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6420            notifyAccessibilityStateChanged();
6421        }
6422    }
6423
6424    /**
6425     * Gets whether this view should be exposed for accessibility.
6426     *
6427     * @return Whether the view is exposed for accessibility.
6428     *
6429     * @hide
6430     */
6431    public boolean isImportantForAccessibility() {
6432        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6433                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6434        switch (mode) {
6435            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6436                return true;
6437            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6438                return false;
6439            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6440                return isActionableForAccessibility() || hasListenersForAccessibility();
6441            default:
6442                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6443                        + mode);
6444        }
6445    }
6446
6447    /**
6448     * Gets the parent for accessibility purposes. Note that the parent for
6449     * accessibility is not necessary the immediate parent. It is the first
6450     * predecessor that is important for accessibility.
6451     *
6452     * @return The parent for accessibility purposes.
6453     */
6454    public ViewParent getParentForAccessibility() {
6455        if (mParent instanceof View) {
6456            View parentView = (View) mParent;
6457            if (parentView.includeForAccessibility()) {
6458                return mParent;
6459            } else {
6460                return mParent.getParentForAccessibility();
6461            }
6462        }
6463        return null;
6464    }
6465
6466    /**
6467     * Adds the children of a given View for accessibility. Since some Views are
6468     * not important for accessibility the children for accessibility are not
6469     * necessarily direct children of the riew, rather they are the first level of
6470     * descendants important for accessibility.
6471     *
6472     * @param children The list of children for accessibility.
6473     */
6474    public void addChildrenForAccessibility(ArrayList<View> children) {
6475        if (includeForAccessibility()) {
6476            children.add(this);
6477        }
6478    }
6479
6480    /**
6481     * Whether to regard this view for accessibility. A view is regarded for
6482     * accessibility if it is important for accessibility or the querying
6483     * accessibility service has explicitly requested that view not
6484     * important for accessibility are regarded.
6485     *
6486     * @return Whether to regard the view for accessibility.
6487     *
6488     * @hide
6489     */
6490    public boolean includeForAccessibility() {
6491        if (mAttachInfo != null) {
6492            if (!mAttachInfo.mIncludeNotImportantViews) {
6493                return isImportantForAccessibility();
6494            }
6495            return true;
6496        }
6497        return false;
6498    }
6499
6500    /**
6501     * Returns whether the View is considered actionable from
6502     * accessibility perspective. Such view are important for
6503     * accessiiblity.
6504     *
6505     * @return True if the view is actionable for accessibility.
6506     *
6507     * @hide
6508     */
6509    public boolean isActionableForAccessibility() {
6510        return (isClickable() || isLongClickable() || isFocusable());
6511    }
6512
6513    /**
6514     * Returns whether the View has registered callbacks wich makes it
6515     * important for accessiiblity.
6516     *
6517     * @return True if the view is actionable for accessibility.
6518     */
6519    private boolean hasListenersForAccessibility() {
6520        ListenerInfo info = getListenerInfo();
6521        return mTouchDelegate != null || info.mOnKeyListener != null
6522                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6523                || info.mOnHoverListener != null || info.mOnDragListener != null;
6524    }
6525
6526    /**
6527     * Notifies accessibility services that some view's important for
6528     * accessibility state has changed. Note that such notifications
6529     * are made at most once every
6530     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6531     * to avoid unnecessary load to the system. Also once a view has
6532     * made a notifucation this method is a NOP until the notification has
6533     * been sent to clients.
6534     *
6535     * @hide
6536     *
6537     * TODO: Makse sure this method is called for any view state change
6538     *       that is interesting for accessilility purposes.
6539     */
6540    public void notifyAccessibilityStateChanged() {
6541        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6542            return;
6543        }
6544        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6545            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6546            if (mParent != null) {
6547                mParent.childAccessibilityStateChanged(this);
6548            }
6549        }
6550    }
6551
6552    /**
6553     * Reset the state indicating the this view has requested clients
6554     * interested in its accessiblity state to be notified.
6555     *
6556     * @hide
6557     */
6558    public void resetAccessibilityStateChanged() {
6559        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6560    }
6561
6562    /**
6563     * Performs the specified accessibility action on the view. For
6564     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6565    * <p>
6566    * If an {@link AccessibilityDelegate} has been specified via calling
6567    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6568    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6569    * is responsible for handling this call.
6570    * </p>
6571     *
6572     * @param action The action to perform.
6573     * @param arguments Optional action arguments.
6574     * @return Whether the action was performed.
6575     */
6576    public boolean performAccessibilityAction(int action, Bundle arguments) {
6577      if (mAccessibilityDelegate != null) {
6578          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6579      } else {
6580          return performAccessibilityActionInternal(action, arguments);
6581      }
6582    }
6583
6584   /**
6585    * @see #performAccessibilityAction(int, Bundle)
6586    *
6587    * Note: Called from the default {@link AccessibilityDelegate}.
6588    */
6589    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6590        switch (action) {
6591            case AccessibilityNodeInfo.ACTION_CLICK: {
6592                if (isClickable()) {
6593                    return performClick();
6594                }
6595            } break;
6596            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6597                if (isLongClickable()) {
6598                    return performLongClick();
6599                }
6600            } break;
6601            case AccessibilityNodeInfo.ACTION_FOCUS: {
6602                if (!hasFocus()) {
6603                    // Get out of touch mode since accessibility
6604                    // wants to move focus around.
6605                    getViewRootImpl().ensureTouchMode(false);
6606                    return requestFocus();
6607                }
6608            } break;
6609            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6610                if (hasFocus()) {
6611                    clearFocus();
6612                    return !isFocused();
6613                }
6614            } break;
6615            case AccessibilityNodeInfo.ACTION_SELECT: {
6616                if (!isSelected()) {
6617                    setSelected(true);
6618                    return isSelected();
6619                }
6620            } break;
6621            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6622                if (isSelected()) {
6623                    setSelected(false);
6624                    return !isSelected();
6625                }
6626            } break;
6627            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6628                if (!isAccessibilityFocused()) {
6629                    return requestAccessibilityFocus();
6630                }
6631            } break;
6632            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6633                if (isAccessibilityFocused()) {
6634                    clearAccessibilityFocus();
6635                    return true;
6636                }
6637            } break;
6638            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6639                if (arguments != null) {
6640                    final int granularity = arguments.getInt(
6641                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6642                    return nextAtGranularity(granularity);
6643                }
6644            } break;
6645            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6646                if (arguments != null) {
6647                    final int granularity = arguments.getInt(
6648                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6649                    return previousAtGranularity(granularity);
6650                }
6651            } break;
6652        }
6653        return false;
6654    }
6655
6656    private boolean nextAtGranularity(int granularity) {
6657        CharSequence text = getIterableTextForAccessibility();
6658        if (text != null && text.length() > 0) {
6659            return false;
6660        }
6661        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6662        if (iterator == null) {
6663            return false;
6664        }
6665        final int current = getAccessibilityCursorPosition();
6666        final int[] range = iterator.following(current);
6667        if (range == null) {
6668            setAccessibilityCursorPosition(-1);
6669            return false;
6670        }
6671        final int start = range[0];
6672        final int end = range[1];
6673        setAccessibilityCursorPosition(start);
6674        sendViewTextTraversedAtGranularityEvent(
6675                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6676                granularity, start, end);
6677        return true;
6678    }
6679
6680    private boolean previousAtGranularity(int granularity) {
6681        CharSequence text = getIterableTextForAccessibility();
6682        if (text != null && text.length() > 0) {
6683            return false;
6684        }
6685        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6686        if (iterator == null) {
6687            return false;
6688        }
6689        final int selectionStart = getAccessibilityCursorPosition();
6690        final int current = selectionStart >= 0 ? selectionStart : text.length() + 1;
6691        final int[] range = iterator.preceding(current);
6692        if (range == null) {
6693            setAccessibilityCursorPosition(-1);
6694            return false;
6695        }
6696        final int start = range[0];
6697        final int end = range[1];
6698        setAccessibilityCursorPosition(end);
6699        sendViewTextTraversedAtGranularityEvent(
6700                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6701                granularity, start, end);
6702        return true;
6703    }
6704
6705    /**
6706     * Gets the text reported for accessibility purposes.
6707     *
6708     * @return The accessibility text.
6709     *
6710     * @hide
6711     */
6712    public CharSequence getIterableTextForAccessibility() {
6713        return mContentDescription;
6714    }
6715
6716    /**
6717     * @hide
6718     */
6719    public int getAccessibilityCursorPosition() {
6720        return mAccessibilityCursorPosition;
6721    }
6722
6723    /**
6724     * @hide
6725     */
6726    public void setAccessibilityCursorPosition(int position) {
6727        mAccessibilityCursorPosition = position;
6728    }
6729
6730    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6731            int fromIndex, int toIndex) {
6732        if (mParent == null) {
6733            return;
6734        }
6735        AccessibilityEvent event = AccessibilityEvent.obtain(
6736                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6737        onInitializeAccessibilityEvent(event);
6738        onPopulateAccessibilityEvent(event);
6739        event.setFromIndex(fromIndex);
6740        event.setToIndex(toIndex);
6741        event.setAction(action);
6742        event.setMovementGranularity(granularity);
6743        mParent.requestSendAccessibilityEvent(this, event);
6744    }
6745
6746    /**
6747     * @hide
6748     */
6749    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6750        switch (granularity) {
6751            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6752                CharSequence text = getIterableTextForAccessibility();
6753                if (text != null && text.length() > 0) {
6754                    CharacterTextSegmentIterator iterator =
6755                        CharacterTextSegmentIterator.getInstance(mContext);
6756                    iterator.initialize(text.toString());
6757                    return iterator;
6758                }
6759            } break;
6760            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6761                CharSequence text = getIterableTextForAccessibility();
6762                if (text != null && text.length() > 0) {
6763                    WordTextSegmentIterator iterator =
6764                        WordTextSegmentIterator.getInstance(mContext);
6765                    iterator.initialize(text.toString());
6766                    return iterator;
6767                }
6768            } break;
6769            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6770                CharSequence text = getIterableTextForAccessibility();
6771                if (text != null && text.length() > 0) {
6772                    ParagraphTextSegmentIterator iterator =
6773                        ParagraphTextSegmentIterator.getInstance();
6774                    iterator.initialize(text.toString());
6775                    return iterator;
6776                }
6777            } break;
6778        }
6779        return null;
6780    }
6781
6782    /**
6783     * @hide
6784     */
6785    public void dispatchStartTemporaryDetach() {
6786        clearAccessibilityFocus();
6787        onStartTemporaryDetach();
6788    }
6789
6790    /**
6791     * This is called when a container is going to temporarily detach a child, with
6792     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6793     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6794     * {@link #onDetachedFromWindow()} when the container is done.
6795     */
6796    public void onStartTemporaryDetach() {
6797        removeUnsetPressCallback();
6798        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6799    }
6800
6801    /**
6802     * @hide
6803     */
6804    public void dispatchFinishTemporaryDetach() {
6805        onFinishTemporaryDetach();
6806    }
6807
6808    /**
6809     * Called after {@link #onStartTemporaryDetach} when the container is done
6810     * changing the view.
6811     */
6812    public void onFinishTemporaryDetach() {
6813    }
6814
6815    /**
6816     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6817     * for this view's window.  Returns null if the view is not currently attached
6818     * to the window.  Normally you will not need to use this directly, but
6819     * just use the standard high-level event callbacks like
6820     * {@link #onKeyDown(int, KeyEvent)}.
6821     */
6822    public KeyEvent.DispatcherState getKeyDispatcherState() {
6823        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6824    }
6825
6826    /**
6827     * Dispatch a key event before it is processed by any input method
6828     * associated with the view hierarchy.  This can be used to intercept
6829     * key events in special situations before the IME consumes them; a
6830     * typical example would be handling the BACK key to update the application's
6831     * UI instead of allowing the IME to see it and close itself.
6832     *
6833     * @param event The key event to be dispatched.
6834     * @return True if the event was handled, false otherwise.
6835     */
6836    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6837        return onKeyPreIme(event.getKeyCode(), event);
6838    }
6839
6840    /**
6841     * Dispatch a key event to the next view on the focus path. This path runs
6842     * from the top of the view tree down to the currently focused view. If this
6843     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6844     * the next node down the focus path. This method also fires any key
6845     * listeners.
6846     *
6847     * @param event The key event to be dispatched.
6848     * @return True if the event was handled, false otherwise.
6849     */
6850    public boolean dispatchKeyEvent(KeyEvent event) {
6851        if (mInputEventConsistencyVerifier != null) {
6852            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6853        }
6854
6855        // Give any attached key listener a first crack at the event.
6856        //noinspection SimplifiableIfStatement
6857        ListenerInfo li = mListenerInfo;
6858        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6859                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6860            return true;
6861        }
6862
6863        if (event.dispatch(this, mAttachInfo != null
6864                ? mAttachInfo.mKeyDispatchState : null, this)) {
6865            return true;
6866        }
6867
6868        if (mInputEventConsistencyVerifier != null) {
6869            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6870        }
6871        return false;
6872    }
6873
6874    /**
6875     * Dispatches a key shortcut event.
6876     *
6877     * @param event The key event to be dispatched.
6878     * @return True if the event was handled by the view, false otherwise.
6879     */
6880    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6881        return onKeyShortcut(event.getKeyCode(), event);
6882    }
6883
6884    /**
6885     * Pass the touch screen motion event down to the target view, or this
6886     * view if it is the target.
6887     *
6888     * @param event The motion event to be dispatched.
6889     * @return True if the event was handled by the view, false otherwise.
6890     */
6891    public boolean dispatchTouchEvent(MotionEvent event) {
6892        if (mInputEventConsistencyVerifier != null) {
6893            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6894        }
6895
6896        if (onFilterTouchEventForSecurity(event)) {
6897            //noinspection SimplifiableIfStatement
6898            ListenerInfo li = mListenerInfo;
6899            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6900                    && li.mOnTouchListener.onTouch(this, event)) {
6901                return true;
6902            }
6903
6904            if (onTouchEvent(event)) {
6905                return true;
6906            }
6907        }
6908
6909        if (mInputEventConsistencyVerifier != null) {
6910            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6911        }
6912        return false;
6913    }
6914
6915    /**
6916     * Filter the touch event to apply security policies.
6917     *
6918     * @param event The motion event to be filtered.
6919     * @return True if the event should be dispatched, false if the event should be dropped.
6920     *
6921     * @see #getFilterTouchesWhenObscured
6922     */
6923    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6924        //noinspection RedundantIfStatement
6925        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6926                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6927            // Window is obscured, drop this touch.
6928            return false;
6929        }
6930        return true;
6931    }
6932
6933    /**
6934     * Pass a trackball motion event down to the focused view.
6935     *
6936     * @param event The motion event to be dispatched.
6937     * @return True if the event was handled by the view, false otherwise.
6938     */
6939    public boolean dispatchTrackballEvent(MotionEvent event) {
6940        if (mInputEventConsistencyVerifier != null) {
6941            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6942        }
6943
6944        return onTrackballEvent(event);
6945    }
6946
6947    /**
6948     * Dispatch a generic motion event.
6949     * <p>
6950     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6951     * are delivered to the view under the pointer.  All other generic motion events are
6952     * delivered to the focused view.  Hover events are handled specially and are delivered
6953     * to {@link #onHoverEvent(MotionEvent)}.
6954     * </p>
6955     *
6956     * @param event The motion event to be dispatched.
6957     * @return True if the event was handled by the view, false otherwise.
6958     */
6959    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6960        if (mInputEventConsistencyVerifier != null) {
6961            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6962        }
6963
6964        final int source = event.getSource();
6965        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6966            final int action = event.getAction();
6967            if (action == MotionEvent.ACTION_HOVER_ENTER
6968                    || action == MotionEvent.ACTION_HOVER_MOVE
6969                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6970                if (dispatchHoverEvent(event)) {
6971                    return true;
6972                }
6973            } else if (dispatchGenericPointerEvent(event)) {
6974                return true;
6975            }
6976        } else if (dispatchGenericFocusedEvent(event)) {
6977            return true;
6978        }
6979
6980        if (dispatchGenericMotionEventInternal(event)) {
6981            return true;
6982        }
6983
6984        if (mInputEventConsistencyVerifier != null) {
6985            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6986        }
6987        return false;
6988    }
6989
6990    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6991        //noinspection SimplifiableIfStatement
6992        ListenerInfo li = mListenerInfo;
6993        if (li != null && li.mOnGenericMotionListener != null
6994                && (mViewFlags & ENABLED_MASK) == ENABLED
6995                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6996            return true;
6997        }
6998
6999        if (onGenericMotionEvent(event)) {
7000            return true;
7001        }
7002
7003        if (mInputEventConsistencyVerifier != null) {
7004            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7005        }
7006        return false;
7007    }
7008
7009    /**
7010     * Dispatch a hover event.
7011     * <p>
7012     * Do not call this method directly.
7013     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7014     * </p>
7015     *
7016     * @param event The motion event to be dispatched.
7017     * @return True if the event was handled by the view, false otherwise.
7018     */
7019    protected boolean dispatchHoverEvent(MotionEvent event) {
7020        //noinspection SimplifiableIfStatement
7021        ListenerInfo li = mListenerInfo;
7022        if (li != null && li.mOnHoverListener != null
7023                && (mViewFlags & ENABLED_MASK) == ENABLED
7024                && li.mOnHoverListener.onHover(this, event)) {
7025            return true;
7026        }
7027
7028        return onHoverEvent(event);
7029    }
7030
7031    /**
7032     * Returns true if the view has a child to which it has recently sent
7033     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7034     * it does not have a hovered child, then it must be the innermost hovered view.
7035     * @hide
7036     */
7037    protected boolean hasHoveredChild() {
7038        return false;
7039    }
7040
7041    /**
7042     * Dispatch a generic motion event to the view under the first pointer.
7043     * <p>
7044     * Do not call this method directly.
7045     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7046     * </p>
7047     *
7048     * @param event The motion event to be dispatched.
7049     * @return True if the event was handled by the view, false otherwise.
7050     */
7051    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7052        return false;
7053    }
7054
7055    /**
7056     * Dispatch a generic motion event to the currently focused view.
7057     * <p>
7058     * Do not call this method directly.
7059     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7060     * </p>
7061     *
7062     * @param event The motion event to be dispatched.
7063     * @return True if the event was handled by the view, false otherwise.
7064     */
7065    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7066        return false;
7067    }
7068
7069    /**
7070     * Dispatch a pointer event.
7071     * <p>
7072     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7073     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7074     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7075     * and should not be expected to handle other pointing device features.
7076     * </p>
7077     *
7078     * @param event The motion event to be dispatched.
7079     * @return True if the event was handled by the view, false otherwise.
7080     * @hide
7081     */
7082    public final boolean dispatchPointerEvent(MotionEvent event) {
7083        if (event.isTouchEvent()) {
7084            return dispatchTouchEvent(event);
7085        } else {
7086            return dispatchGenericMotionEvent(event);
7087        }
7088    }
7089
7090    /**
7091     * Called when the window containing this view gains or loses window focus.
7092     * ViewGroups should override to route to their children.
7093     *
7094     * @param hasFocus True if the window containing this view now has focus,
7095     *        false otherwise.
7096     */
7097    public void dispatchWindowFocusChanged(boolean hasFocus) {
7098        onWindowFocusChanged(hasFocus);
7099    }
7100
7101    /**
7102     * Called when the window containing this view gains or loses focus.  Note
7103     * that this is separate from view focus: to receive key events, both
7104     * your view and its window must have focus.  If a window is displayed
7105     * on top of yours that takes input focus, then your own window will lose
7106     * focus but the view focus will remain unchanged.
7107     *
7108     * @param hasWindowFocus True if the window containing this view now has
7109     *        focus, false otherwise.
7110     */
7111    public void onWindowFocusChanged(boolean hasWindowFocus) {
7112        InputMethodManager imm = InputMethodManager.peekInstance();
7113        if (!hasWindowFocus) {
7114            if (isPressed()) {
7115                setPressed(false);
7116            }
7117            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7118                imm.focusOut(this);
7119            }
7120            removeLongPressCallback();
7121            removeTapCallback();
7122            onFocusLost();
7123        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7124            imm.focusIn(this);
7125        }
7126        refreshDrawableState();
7127    }
7128
7129    /**
7130     * Returns true if this view is in a window that currently has window focus.
7131     * Note that this is not the same as the view itself having focus.
7132     *
7133     * @return True if this view is in a window that currently has window focus.
7134     */
7135    public boolean hasWindowFocus() {
7136        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7137    }
7138
7139    /**
7140     * Dispatch a view visibility change down the view hierarchy.
7141     * ViewGroups should override to route to their children.
7142     * @param changedView The view whose visibility changed. Could be 'this' or
7143     * an ancestor view.
7144     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7145     * {@link #INVISIBLE} or {@link #GONE}.
7146     */
7147    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7148        onVisibilityChanged(changedView, visibility);
7149    }
7150
7151    /**
7152     * Called when the visibility of the view or an ancestor of the view is changed.
7153     * @param changedView The view whose visibility changed. Could be 'this' or
7154     * an ancestor view.
7155     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7156     * {@link #INVISIBLE} or {@link #GONE}.
7157     */
7158    protected void onVisibilityChanged(View changedView, int visibility) {
7159        if (visibility == VISIBLE) {
7160            if (mAttachInfo != null) {
7161                initialAwakenScrollBars();
7162            } else {
7163                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7164            }
7165        }
7166    }
7167
7168    /**
7169     * Dispatch a hint about whether this view is displayed. For instance, when
7170     * a View moves out of the screen, it might receives a display hint indicating
7171     * the view is not displayed. Applications should not <em>rely</em> on this hint
7172     * as there is no guarantee that they will receive one.
7173     *
7174     * @param hint A hint about whether or not this view is displayed:
7175     * {@link #VISIBLE} or {@link #INVISIBLE}.
7176     */
7177    public void dispatchDisplayHint(int hint) {
7178        onDisplayHint(hint);
7179    }
7180
7181    /**
7182     * Gives this view a hint about whether is displayed or not. For instance, when
7183     * a View moves out of the screen, it might receives a display hint indicating
7184     * the view is not displayed. Applications should not <em>rely</em> on this hint
7185     * as there is no guarantee that they will receive one.
7186     *
7187     * @param hint A hint about whether or not this view is displayed:
7188     * {@link #VISIBLE} or {@link #INVISIBLE}.
7189     */
7190    protected void onDisplayHint(int hint) {
7191    }
7192
7193    /**
7194     * Dispatch a window visibility change down the view hierarchy.
7195     * ViewGroups should override to route to their children.
7196     *
7197     * @param visibility The new visibility of the window.
7198     *
7199     * @see #onWindowVisibilityChanged(int)
7200     */
7201    public void dispatchWindowVisibilityChanged(int visibility) {
7202        onWindowVisibilityChanged(visibility);
7203    }
7204
7205    /**
7206     * Called when the window containing has change its visibility
7207     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7208     * that this tells you whether or not your window is being made visible
7209     * to the window manager; this does <em>not</em> tell you whether or not
7210     * your window is obscured by other windows on the screen, even if it
7211     * is itself visible.
7212     *
7213     * @param visibility The new visibility of the window.
7214     */
7215    protected void onWindowVisibilityChanged(int visibility) {
7216        if (visibility == VISIBLE) {
7217            initialAwakenScrollBars();
7218        }
7219    }
7220
7221    /**
7222     * Returns the current visibility of the window this view is attached to
7223     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7224     *
7225     * @return Returns the current visibility of the view's window.
7226     */
7227    public int getWindowVisibility() {
7228        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7229    }
7230
7231    /**
7232     * Retrieve the overall visible display size in which the window this view is
7233     * attached to has been positioned in.  This takes into account screen
7234     * decorations above the window, for both cases where the window itself
7235     * is being position inside of them or the window is being placed under
7236     * then and covered insets are used for the window to position its content
7237     * inside.  In effect, this tells you the available area where content can
7238     * be placed and remain visible to users.
7239     *
7240     * <p>This function requires an IPC back to the window manager to retrieve
7241     * the requested information, so should not be used in performance critical
7242     * code like drawing.
7243     *
7244     * @param outRect Filled in with the visible display frame.  If the view
7245     * is not attached to a window, this is simply the raw display size.
7246     */
7247    public void getWindowVisibleDisplayFrame(Rect outRect) {
7248        if (mAttachInfo != null) {
7249            try {
7250                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7251            } catch (RemoteException e) {
7252                return;
7253            }
7254            // XXX This is really broken, and probably all needs to be done
7255            // in the window manager, and we need to know more about whether
7256            // we want the area behind or in front of the IME.
7257            final Rect insets = mAttachInfo.mVisibleInsets;
7258            outRect.left += insets.left;
7259            outRect.top += insets.top;
7260            outRect.right -= insets.right;
7261            outRect.bottom -= insets.bottom;
7262            return;
7263        }
7264        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7265        d.getRectSize(outRect);
7266    }
7267
7268    /**
7269     * Dispatch a notification about a resource configuration change down
7270     * the view hierarchy.
7271     * ViewGroups should override to route to their children.
7272     *
7273     * @param newConfig The new resource configuration.
7274     *
7275     * @see #onConfigurationChanged(android.content.res.Configuration)
7276     */
7277    public void dispatchConfigurationChanged(Configuration newConfig) {
7278        onConfigurationChanged(newConfig);
7279    }
7280
7281    /**
7282     * Called when the current configuration of the resources being used
7283     * by the application have changed.  You can use this to decide when
7284     * to reload resources that can changed based on orientation and other
7285     * configuration characterstics.  You only need to use this if you are
7286     * not relying on the normal {@link android.app.Activity} mechanism of
7287     * recreating the activity instance upon a configuration change.
7288     *
7289     * @param newConfig The new resource configuration.
7290     */
7291    protected void onConfigurationChanged(Configuration newConfig) {
7292    }
7293
7294    /**
7295     * Private function to aggregate all per-view attributes in to the view
7296     * root.
7297     */
7298    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7299        performCollectViewAttributes(attachInfo, visibility);
7300    }
7301
7302    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7303        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7304            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7305                attachInfo.mKeepScreenOn = true;
7306            }
7307            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7308            ListenerInfo li = mListenerInfo;
7309            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7310                attachInfo.mHasSystemUiListeners = true;
7311            }
7312        }
7313    }
7314
7315    void needGlobalAttributesUpdate(boolean force) {
7316        final AttachInfo ai = mAttachInfo;
7317        if (ai != null) {
7318            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7319                    || ai.mHasSystemUiListeners) {
7320                ai.mRecomputeGlobalAttributes = true;
7321            }
7322        }
7323    }
7324
7325    /**
7326     * Returns whether the device is currently in touch mode.  Touch mode is entered
7327     * once the user begins interacting with the device by touch, and affects various
7328     * things like whether focus is always visible to the user.
7329     *
7330     * @return Whether the device is in touch mode.
7331     */
7332    @ViewDebug.ExportedProperty
7333    public boolean isInTouchMode() {
7334        if (mAttachInfo != null) {
7335            return mAttachInfo.mInTouchMode;
7336        } else {
7337            return ViewRootImpl.isInTouchMode();
7338        }
7339    }
7340
7341    /**
7342     * Returns the context the view is running in, through which it can
7343     * access the current theme, resources, etc.
7344     *
7345     * @return The view's Context.
7346     */
7347    @ViewDebug.CapturedViewProperty
7348    public final Context getContext() {
7349        return mContext;
7350    }
7351
7352    /**
7353     * Handle a key event before it is processed by any input method
7354     * associated with the view hierarchy.  This can be used to intercept
7355     * key events in special situations before the IME consumes them; a
7356     * typical example would be handling the BACK key to update the application's
7357     * UI instead of allowing the IME to see it and close itself.
7358     *
7359     * @param keyCode The value in event.getKeyCode().
7360     * @param event Description of the key event.
7361     * @return If you handled the event, return true. If you want to allow the
7362     *         event to be handled by the next receiver, return false.
7363     */
7364    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7365        return false;
7366    }
7367
7368    /**
7369     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7370     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7371     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7372     * is released, if the view is enabled and clickable.
7373     *
7374     * @param keyCode A key code that represents the button pressed, from
7375     *                {@link android.view.KeyEvent}.
7376     * @param event   The KeyEvent object that defines the button action.
7377     */
7378    public boolean onKeyDown(int keyCode, KeyEvent event) {
7379        boolean result = false;
7380
7381        switch (keyCode) {
7382            case KeyEvent.KEYCODE_DPAD_CENTER:
7383            case KeyEvent.KEYCODE_ENTER: {
7384                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7385                    return true;
7386                }
7387                // Long clickable items don't necessarily have to be clickable
7388                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7389                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7390                        (event.getRepeatCount() == 0)) {
7391                    setPressed(true);
7392                    checkForLongClick(0);
7393                    return true;
7394                }
7395                break;
7396            }
7397        }
7398        return result;
7399    }
7400
7401    /**
7402     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7403     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7404     * the event).
7405     */
7406    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7407        return false;
7408    }
7409
7410    /**
7411     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7412     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7413     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7414     * {@link KeyEvent#KEYCODE_ENTER} is released.
7415     *
7416     * @param keyCode A key code that represents the button pressed, from
7417     *                {@link android.view.KeyEvent}.
7418     * @param event   The KeyEvent object that defines the button action.
7419     */
7420    public boolean onKeyUp(int keyCode, KeyEvent event) {
7421        boolean result = false;
7422
7423        switch (keyCode) {
7424            case KeyEvent.KEYCODE_DPAD_CENTER:
7425            case KeyEvent.KEYCODE_ENTER: {
7426                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7427                    return true;
7428                }
7429                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7430                    setPressed(false);
7431
7432                    if (!mHasPerformedLongPress) {
7433                        // This is a tap, so remove the longpress check
7434                        removeLongPressCallback();
7435
7436                        result = performClick();
7437                    }
7438                }
7439                break;
7440            }
7441        }
7442        return result;
7443    }
7444
7445    /**
7446     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7447     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7448     * the event).
7449     *
7450     * @param keyCode     A key code that represents the button pressed, from
7451     *                    {@link android.view.KeyEvent}.
7452     * @param repeatCount The number of times the action was made.
7453     * @param event       The KeyEvent object that defines the button action.
7454     */
7455    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7456        return false;
7457    }
7458
7459    /**
7460     * Called on the focused view when a key shortcut event is not handled.
7461     * Override this method to implement local key shortcuts for the View.
7462     * Key shortcuts can also be implemented by setting the
7463     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7464     *
7465     * @param keyCode The value in event.getKeyCode().
7466     * @param event Description of the key event.
7467     * @return If you handled the event, return true. If you want to allow the
7468     *         event to be handled by the next receiver, return false.
7469     */
7470    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7471        return false;
7472    }
7473
7474    /**
7475     * Check whether the called view is a text editor, in which case it
7476     * would make sense to automatically display a soft input window for
7477     * it.  Subclasses should override this if they implement
7478     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7479     * a call on that method would return a non-null InputConnection, and
7480     * they are really a first-class editor that the user would normally
7481     * start typing on when the go into a window containing your view.
7482     *
7483     * <p>The default implementation always returns false.  This does
7484     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7485     * will not be called or the user can not otherwise perform edits on your
7486     * view; it is just a hint to the system that this is not the primary
7487     * purpose of this view.
7488     *
7489     * @return Returns true if this view is a text editor, else false.
7490     */
7491    public boolean onCheckIsTextEditor() {
7492        return false;
7493    }
7494
7495    /**
7496     * Create a new InputConnection for an InputMethod to interact
7497     * with the view.  The default implementation returns null, since it doesn't
7498     * support input methods.  You can override this to implement such support.
7499     * This is only needed for views that take focus and text input.
7500     *
7501     * <p>When implementing this, you probably also want to implement
7502     * {@link #onCheckIsTextEditor()} to indicate you will return a
7503     * non-null InputConnection.
7504     *
7505     * @param outAttrs Fill in with attribute information about the connection.
7506     */
7507    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7508        return null;
7509    }
7510
7511    /**
7512     * Called by the {@link android.view.inputmethod.InputMethodManager}
7513     * when a view who is not the current
7514     * input connection target is trying to make a call on the manager.  The
7515     * default implementation returns false; you can override this to return
7516     * true for certain views if you are performing InputConnection proxying
7517     * to them.
7518     * @param view The View that is making the InputMethodManager call.
7519     * @return Return true to allow the call, false to reject.
7520     */
7521    public boolean checkInputConnectionProxy(View view) {
7522        return false;
7523    }
7524
7525    /**
7526     * Show the context menu for this view. It is not safe to hold on to the
7527     * menu after returning from this method.
7528     *
7529     * You should normally not overload this method. Overload
7530     * {@link #onCreateContextMenu(ContextMenu)} or define an
7531     * {@link OnCreateContextMenuListener} to add items to the context menu.
7532     *
7533     * @param menu The context menu to populate
7534     */
7535    public void createContextMenu(ContextMenu menu) {
7536        ContextMenuInfo menuInfo = getContextMenuInfo();
7537
7538        // Sets the current menu info so all items added to menu will have
7539        // my extra info set.
7540        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7541
7542        onCreateContextMenu(menu);
7543        ListenerInfo li = mListenerInfo;
7544        if (li != null && li.mOnCreateContextMenuListener != null) {
7545            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7546        }
7547
7548        // Clear the extra information so subsequent items that aren't mine don't
7549        // have my extra info.
7550        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7551
7552        if (mParent != null) {
7553            mParent.createContextMenu(menu);
7554        }
7555    }
7556
7557    /**
7558     * Views should implement this if they have extra information to associate
7559     * with the context menu. The return result is supplied as a parameter to
7560     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7561     * callback.
7562     *
7563     * @return Extra information about the item for which the context menu
7564     *         should be shown. This information will vary across different
7565     *         subclasses of View.
7566     */
7567    protected ContextMenuInfo getContextMenuInfo() {
7568        return null;
7569    }
7570
7571    /**
7572     * Views should implement this if the view itself is going to add items to
7573     * the context menu.
7574     *
7575     * @param menu the context menu to populate
7576     */
7577    protected void onCreateContextMenu(ContextMenu menu) {
7578    }
7579
7580    /**
7581     * Implement this method to handle trackball motion events.  The
7582     * <em>relative</em> movement of the trackball since the last event
7583     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7584     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7585     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7586     * they will often be fractional values, representing the more fine-grained
7587     * movement information available from a trackball).
7588     *
7589     * @param event The motion event.
7590     * @return True if the event was handled, false otherwise.
7591     */
7592    public boolean onTrackballEvent(MotionEvent event) {
7593        return false;
7594    }
7595
7596    /**
7597     * Implement this method to handle generic motion events.
7598     * <p>
7599     * Generic motion events describe joystick movements, mouse hovers, track pad
7600     * touches, scroll wheel movements and other input events.  The
7601     * {@link MotionEvent#getSource() source} of the motion event specifies
7602     * the class of input that was received.  Implementations of this method
7603     * must examine the bits in the source before processing the event.
7604     * The following code example shows how this is done.
7605     * </p><p>
7606     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7607     * are delivered to the view under the pointer.  All other generic motion events are
7608     * delivered to the focused view.
7609     * </p>
7610     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7611     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7612     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7613     *             // process the joystick movement...
7614     *             return true;
7615     *         }
7616     *     }
7617     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7618     *         switch (event.getAction()) {
7619     *             case MotionEvent.ACTION_HOVER_MOVE:
7620     *                 // process the mouse hover movement...
7621     *                 return true;
7622     *             case MotionEvent.ACTION_SCROLL:
7623     *                 // process the scroll wheel movement...
7624     *                 return true;
7625     *         }
7626     *     }
7627     *     return super.onGenericMotionEvent(event);
7628     * }</pre>
7629     *
7630     * @param event The generic motion event being processed.
7631     * @return True if the event was handled, false otherwise.
7632     */
7633    public boolean onGenericMotionEvent(MotionEvent event) {
7634        return false;
7635    }
7636
7637    /**
7638     * Implement this method to handle hover events.
7639     * <p>
7640     * This method is called whenever a pointer is hovering into, over, or out of the
7641     * bounds of a view and the view is not currently being touched.
7642     * Hover events are represented as pointer events with action
7643     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7644     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7645     * </p>
7646     * <ul>
7647     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7648     * when the pointer enters the bounds of the view.</li>
7649     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7650     * when the pointer has already entered the bounds of the view and has moved.</li>
7651     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7652     * when the pointer has exited the bounds of the view or when the pointer is
7653     * about to go down due to a button click, tap, or similar user action that
7654     * causes the view to be touched.</li>
7655     * </ul>
7656     * <p>
7657     * The view should implement this method to return true to indicate that it is
7658     * handling the hover event, such as by changing its drawable state.
7659     * </p><p>
7660     * The default implementation calls {@link #setHovered} to update the hovered state
7661     * of the view when a hover enter or hover exit event is received, if the view
7662     * is enabled and is clickable.  The default implementation also sends hover
7663     * accessibility events.
7664     * </p>
7665     *
7666     * @param event The motion event that describes the hover.
7667     * @return True if the view handled the hover event.
7668     *
7669     * @see #isHovered
7670     * @see #setHovered
7671     * @see #onHoverChanged
7672     */
7673    public boolean onHoverEvent(MotionEvent event) {
7674        // The root view may receive hover (or touch) events that are outside the bounds of
7675        // the window.  This code ensures that we only send accessibility events for
7676        // hovers that are actually within the bounds of the root view.
7677        final int action = event.getActionMasked();
7678        if (!mSendingHoverAccessibilityEvents) {
7679            if ((action == MotionEvent.ACTION_HOVER_ENTER
7680                    || action == MotionEvent.ACTION_HOVER_MOVE)
7681                    && !hasHoveredChild()
7682                    && pointInView(event.getX(), event.getY())) {
7683                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7684                mSendingHoverAccessibilityEvents = true;
7685                requestAccessibilityFocusFromHover();
7686            }
7687        } else {
7688            if (action == MotionEvent.ACTION_HOVER_EXIT
7689                    || (action == MotionEvent.ACTION_MOVE
7690                            && !pointInView(event.getX(), event.getY()))) {
7691                mSendingHoverAccessibilityEvents = false;
7692                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7693                // If the window does not have input focus we take away accessibility
7694                // focus as soon as the user stop hovering over the view.
7695                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7696                    getViewRootImpl().setAccessibilityFocusedHost(null);
7697                }
7698            }
7699        }
7700
7701        if (isHoverable()) {
7702            switch (action) {
7703                case MotionEvent.ACTION_HOVER_ENTER:
7704                    setHovered(true);
7705                    break;
7706                case MotionEvent.ACTION_HOVER_EXIT:
7707                    setHovered(false);
7708                    break;
7709            }
7710
7711            // Dispatch the event to onGenericMotionEvent before returning true.
7712            // This is to provide compatibility with existing applications that
7713            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7714            // break because of the new default handling for hoverable views
7715            // in onHoverEvent.
7716            // Note that onGenericMotionEvent will be called by default when
7717            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7718            dispatchGenericMotionEventInternal(event);
7719            return true;
7720        }
7721
7722        return false;
7723    }
7724
7725    /**
7726     * Returns true if the view should handle {@link #onHoverEvent}
7727     * by calling {@link #setHovered} to change its hovered state.
7728     *
7729     * @return True if the view is hoverable.
7730     */
7731    private boolean isHoverable() {
7732        final int viewFlags = mViewFlags;
7733        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7734            return false;
7735        }
7736
7737        return (viewFlags & CLICKABLE) == CLICKABLE
7738                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7739    }
7740
7741    /**
7742     * Returns true if the view is currently hovered.
7743     *
7744     * @return True if the view is currently hovered.
7745     *
7746     * @see #setHovered
7747     * @see #onHoverChanged
7748     */
7749    @ViewDebug.ExportedProperty
7750    public boolean isHovered() {
7751        return (mPrivateFlags & HOVERED) != 0;
7752    }
7753
7754    /**
7755     * Sets whether the view is currently hovered.
7756     * <p>
7757     * Calling this method also changes the drawable state of the view.  This
7758     * enables the view to react to hover by using different drawable resources
7759     * to change its appearance.
7760     * </p><p>
7761     * The {@link #onHoverChanged} method is called when the hovered state changes.
7762     * </p>
7763     *
7764     * @param hovered True if the view is hovered.
7765     *
7766     * @see #isHovered
7767     * @see #onHoverChanged
7768     */
7769    public void setHovered(boolean hovered) {
7770        if (hovered) {
7771            if ((mPrivateFlags & HOVERED) == 0) {
7772                mPrivateFlags |= HOVERED;
7773                refreshDrawableState();
7774                onHoverChanged(true);
7775            }
7776        } else {
7777            if ((mPrivateFlags & HOVERED) != 0) {
7778                mPrivateFlags &= ~HOVERED;
7779                refreshDrawableState();
7780                onHoverChanged(false);
7781            }
7782        }
7783    }
7784
7785    /**
7786     * Implement this method to handle hover state changes.
7787     * <p>
7788     * This method is called whenever the hover state changes as a result of a
7789     * call to {@link #setHovered}.
7790     * </p>
7791     *
7792     * @param hovered The current hover state, as returned by {@link #isHovered}.
7793     *
7794     * @see #isHovered
7795     * @see #setHovered
7796     */
7797    public void onHoverChanged(boolean hovered) {
7798    }
7799
7800    /**
7801     * Implement this method to handle touch screen motion events.
7802     *
7803     * @param event The motion event.
7804     * @return True if the event was handled, false otherwise.
7805     */
7806    public boolean onTouchEvent(MotionEvent event) {
7807        final int viewFlags = mViewFlags;
7808
7809        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7810            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7811                setPressed(false);
7812            }
7813            // A disabled view that is clickable still consumes the touch
7814            // events, it just doesn't respond to them.
7815            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7816                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7817        }
7818
7819        if (mTouchDelegate != null) {
7820            if (mTouchDelegate.onTouchEvent(event)) {
7821                return true;
7822            }
7823        }
7824
7825        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7826                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7827            switch (event.getAction()) {
7828                case MotionEvent.ACTION_UP:
7829                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7830                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7831                        // take focus if we don't have it already and we should in
7832                        // touch mode.
7833                        boolean focusTaken = false;
7834                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7835                            focusTaken = requestFocus();
7836                        }
7837
7838                        if (prepressed) {
7839                            // The button is being released before we actually
7840                            // showed it as pressed.  Make it show the pressed
7841                            // state now (before scheduling the click) to ensure
7842                            // the user sees it.
7843                            setPressed(true);
7844                       }
7845
7846                        if (!mHasPerformedLongPress) {
7847                            // This is a tap, so remove the longpress check
7848                            removeLongPressCallback();
7849
7850                            // Only perform take click actions if we were in the pressed state
7851                            if (!focusTaken) {
7852                                // Use a Runnable and post this rather than calling
7853                                // performClick directly. This lets other visual state
7854                                // of the view update before click actions start.
7855                                if (mPerformClick == null) {
7856                                    mPerformClick = new PerformClick();
7857                                }
7858                                if (!post(mPerformClick)) {
7859                                    performClick();
7860                                }
7861                            }
7862                        }
7863
7864                        if (mUnsetPressedState == null) {
7865                            mUnsetPressedState = new UnsetPressedState();
7866                        }
7867
7868                        if (prepressed) {
7869                            postDelayed(mUnsetPressedState,
7870                                    ViewConfiguration.getPressedStateDuration());
7871                        } else if (!post(mUnsetPressedState)) {
7872                            // If the post failed, unpress right now
7873                            mUnsetPressedState.run();
7874                        }
7875                        removeTapCallback();
7876                    }
7877                    break;
7878
7879                case MotionEvent.ACTION_DOWN:
7880                    mHasPerformedLongPress = false;
7881
7882                    if (performButtonActionOnTouchDown(event)) {
7883                        break;
7884                    }
7885
7886                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7887                    boolean isInScrollingContainer = isInScrollingContainer();
7888
7889                    // For views inside a scrolling container, delay the pressed feedback for
7890                    // a short period in case this is a scroll.
7891                    if (isInScrollingContainer) {
7892                        mPrivateFlags |= PREPRESSED;
7893                        if (mPendingCheckForTap == null) {
7894                            mPendingCheckForTap = new CheckForTap();
7895                        }
7896                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7897                    } else {
7898                        // Not inside a scrolling container, so show the feedback right away
7899                        setPressed(true);
7900                        checkForLongClick(0);
7901                    }
7902                    break;
7903
7904                case MotionEvent.ACTION_CANCEL:
7905                    setPressed(false);
7906                    removeTapCallback();
7907                    break;
7908
7909                case MotionEvent.ACTION_MOVE:
7910                    final int x = (int) event.getX();
7911                    final int y = (int) event.getY();
7912
7913                    // Be lenient about moving outside of buttons
7914                    if (!pointInView(x, y, mTouchSlop)) {
7915                        // Outside button
7916                        removeTapCallback();
7917                        if ((mPrivateFlags & PRESSED) != 0) {
7918                            // Remove any future long press/tap checks
7919                            removeLongPressCallback();
7920
7921                            setPressed(false);
7922                        }
7923                    }
7924                    break;
7925            }
7926            return true;
7927        }
7928
7929        return false;
7930    }
7931
7932    /**
7933     * @hide
7934     */
7935    public boolean isInScrollingContainer() {
7936        ViewParent p = getParent();
7937        while (p != null && p instanceof ViewGroup) {
7938            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7939                return true;
7940            }
7941            p = p.getParent();
7942        }
7943        return false;
7944    }
7945
7946    /**
7947     * Remove the longpress detection timer.
7948     */
7949    private void removeLongPressCallback() {
7950        if (mPendingCheckForLongPress != null) {
7951          removeCallbacks(mPendingCheckForLongPress);
7952        }
7953    }
7954
7955    /**
7956     * Remove the pending click action
7957     */
7958    private void removePerformClickCallback() {
7959        if (mPerformClick != null) {
7960            removeCallbacks(mPerformClick);
7961        }
7962    }
7963
7964    /**
7965     * Remove the prepress detection timer.
7966     */
7967    private void removeUnsetPressCallback() {
7968        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7969            setPressed(false);
7970            removeCallbacks(mUnsetPressedState);
7971        }
7972    }
7973
7974    /**
7975     * Remove the tap detection timer.
7976     */
7977    private void removeTapCallback() {
7978        if (mPendingCheckForTap != null) {
7979            mPrivateFlags &= ~PREPRESSED;
7980            removeCallbacks(mPendingCheckForTap);
7981        }
7982    }
7983
7984    /**
7985     * Cancels a pending long press.  Your subclass can use this if you
7986     * want the context menu to come up if the user presses and holds
7987     * at the same place, but you don't want it to come up if they press
7988     * and then move around enough to cause scrolling.
7989     */
7990    public void cancelLongPress() {
7991        removeLongPressCallback();
7992
7993        /*
7994         * The prepressed state handled by the tap callback is a display
7995         * construct, but the tap callback will post a long press callback
7996         * less its own timeout. Remove it here.
7997         */
7998        removeTapCallback();
7999    }
8000
8001    /**
8002     * Remove the pending callback for sending a
8003     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8004     */
8005    private void removeSendViewScrolledAccessibilityEventCallback() {
8006        if (mSendViewScrolledAccessibilityEvent != null) {
8007            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8008        }
8009    }
8010
8011    /**
8012     * Sets the TouchDelegate for this View.
8013     */
8014    public void setTouchDelegate(TouchDelegate delegate) {
8015        mTouchDelegate = delegate;
8016    }
8017
8018    /**
8019     * Gets the TouchDelegate for this View.
8020     */
8021    public TouchDelegate getTouchDelegate() {
8022        return mTouchDelegate;
8023    }
8024
8025    /**
8026     * Set flags controlling behavior of this view.
8027     *
8028     * @param flags Constant indicating the value which should be set
8029     * @param mask Constant indicating the bit range that should be changed
8030     */
8031    void setFlags(int flags, int mask) {
8032        int old = mViewFlags;
8033        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8034
8035        int changed = mViewFlags ^ old;
8036        if (changed == 0) {
8037            return;
8038        }
8039        int privateFlags = mPrivateFlags;
8040
8041        /* Check if the FOCUSABLE bit has changed */
8042        if (((changed & FOCUSABLE_MASK) != 0) &&
8043                ((privateFlags & HAS_BOUNDS) !=0)) {
8044            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8045                    && ((privateFlags & FOCUSED) != 0)) {
8046                /* Give up focus if we are no longer focusable */
8047                clearFocus();
8048            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8049                    && ((privateFlags & FOCUSED) == 0)) {
8050                /*
8051                 * Tell the view system that we are now available to take focus
8052                 * if no one else already has it.
8053                 */
8054                if (mParent != null) mParent.focusableViewAvailable(this);
8055            }
8056            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8057                notifyAccessibilityStateChanged();
8058            }
8059        }
8060
8061        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8062            if ((changed & VISIBILITY_MASK) != 0) {
8063                /*
8064                 * If this view is becoming visible, invalidate it in case it changed while
8065                 * it was not visible. Marking it drawn ensures that the invalidation will
8066                 * go through.
8067                 */
8068                mPrivateFlags |= DRAWN;
8069                invalidate(true);
8070
8071                needGlobalAttributesUpdate(true);
8072
8073                // a view becoming visible is worth notifying the parent
8074                // about in case nothing has focus.  even if this specific view
8075                // isn't focusable, it may contain something that is, so let
8076                // the root view try to give this focus if nothing else does.
8077                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8078                    mParent.focusableViewAvailable(this);
8079                }
8080            }
8081        }
8082
8083        /* Check if the GONE bit has changed */
8084        if ((changed & GONE) != 0) {
8085            needGlobalAttributesUpdate(false);
8086            requestLayout();
8087
8088            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8089                if (hasFocus()) clearFocus();
8090                clearAccessibilityFocus();
8091                destroyDrawingCache();
8092                if (mParent instanceof View) {
8093                    // GONE views noop invalidation, so invalidate the parent
8094                    ((View) mParent).invalidate(true);
8095                }
8096                // Mark the view drawn to ensure that it gets invalidated properly the next
8097                // time it is visible and gets invalidated
8098                mPrivateFlags |= DRAWN;
8099            }
8100            if (mAttachInfo != null) {
8101                mAttachInfo.mViewVisibilityChanged = true;
8102            }
8103        }
8104
8105        /* Check if the VISIBLE bit has changed */
8106        if ((changed & INVISIBLE) != 0) {
8107            needGlobalAttributesUpdate(false);
8108            /*
8109             * If this view is becoming invisible, set the DRAWN flag so that
8110             * the next invalidate() will not be skipped.
8111             */
8112            mPrivateFlags |= DRAWN;
8113
8114            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8115                // root view becoming invisible shouldn't clear focus and accessibility focus
8116                if (getRootView() != this) {
8117                    clearFocus();
8118                    clearAccessibilityFocus();
8119                }
8120            }
8121            if (mAttachInfo != null) {
8122                mAttachInfo.mViewVisibilityChanged = true;
8123            }
8124        }
8125
8126        if ((changed & VISIBILITY_MASK) != 0) {
8127            if (mParent instanceof ViewGroup) {
8128                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8129                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8130                ((View) mParent).invalidate(true);
8131            } else if (mParent != null) {
8132                mParent.invalidateChild(this, null);
8133            }
8134            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8135        }
8136
8137        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8138            destroyDrawingCache();
8139        }
8140
8141        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8142            destroyDrawingCache();
8143            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8144            invalidateParentCaches();
8145        }
8146
8147        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8148            destroyDrawingCache();
8149            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8150        }
8151
8152        if ((changed & DRAW_MASK) != 0) {
8153            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8154                if (mBackground != null) {
8155                    mPrivateFlags &= ~SKIP_DRAW;
8156                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8157                } else {
8158                    mPrivateFlags |= SKIP_DRAW;
8159                }
8160            } else {
8161                mPrivateFlags &= ~SKIP_DRAW;
8162            }
8163            requestLayout();
8164            invalidate(true);
8165        }
8166
8167        if ((changed & KEEP_SCREEN_ON) != 0) {
8168            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8169                mParent.recomputeViewAttributes(this);
8170            }
8171        }
8172
8173        if (AccessibilityManager.getInstance(mContext).isEnabled()
8174                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8175                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8176            notifyAccessibilityStateChanged();
8177        }
8178    }
8179
8180    /**
8181     * Change the view's z order in the tree, so it's on top of other sibling
8182     * views
8183     */
8184    public void bringToFront() {
8185        if (mParent != null) {
8186            mParent.bringChildToFront(this);
8187        }
8188    }
8189
8190    /**
8191     * This is called in response to an internal scroll in this view (i.e., the
8192     * view scrolled its own contents). This is typically as a result of
8193     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8194     * called.
8195     *
8196     * @param l Current horizontal scroll origin.
8197     * @param t Current vertical scroll origin.
8198     * @param oldl Previous horizontal scroll origin.
8199     * @param oldt Previous vertical scroll origin.
8200     */
8201    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8202        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8203            postSendViewScrolledAccessibilityEventCallback();
8204        }
8205
8206        mBackgroundSizeChanged = true;
8207
8208        final AttachInfo ai = mAttachInfo;
8209        if (ai != null) {
8210            ai.mViewScrollChanged = true;
8211        }
8212    }
8213
8214    /**
8215     * Interface definition for a callback to be invoked when the layout bounds of a view
8216     * changes due to layout processing.
8217     */
8218    public interface OnLayoutChangeListener {
8219        /**
8220         * Called when the focus state of a view has changed.
8221         *
8222         * @param v The view whose state has changed.
8223         * @param left The new value of the view's left property.
8224         * @param top The new value of the view's top property.
8225         * @param right The new value of the view's right property.
8226         * @param bottom The new value of the view's bottom property.
8227         * @param oldLeft The previous value of the view's left property.
8228         * @param oldTop The previous value of the view's top property.
8229         * @param oldRight The previous value of the view's right property.
8230         * @param oldBottom The previous value of the view's bottom property.
8231         */
8232        void onLayoutChange(View v, int left, int top, int right, int bottom,
8233            int oldLeft, int oldTop, int oldRight, int oldBottom);
8234    }
8235
8236    /**
8237     * This is called during layout when the size of this view has changed. If
8238     * you were just added to the view hierarchy, you're called with the old
8239     * values of 0.
8240     *
8241     * @param w Current width of this view.
8242     * @param h Current height of this view.
8243     * @param oldw Old width of this view.
8244     * @param oldh Old height of this view.
8245     */
8246    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8247    }
8248
8249    /**
8250     * Called by draw to draw the child views. This may be overridden
8251     * by derived classes to gain control just before its children are drawn
8252     * (but after its own view has been drawn).
8253     * @param canvas the canvas on which to draw the view
8254     */
8255    protected void dispatchDraw(Canvas canvas) {
8256
8257    }
8258
8259    /**
8260     * Gets the parent of this view. Note that the parent is a
8261     * ViewParent and not necessarily a View.
8262     *
8263     * @return Parent of this view.
8264     */
8265    public final ViewParent getParent() {
8266        return mParent;
8267    }
8268
8269    /**
8270     * Set the horizontal scrolled position of your view. This will cause a call to
8271     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8272     * invalidated.
8273     * @param value the x position to scroll to
8274     */
8275    public void setScrollX(int value) {
8276        scrollTo(value, mScrollY);
8277    }
8278
8279    /**
8280     * Set the vertical scrolled position of your view. This will cause a call to
8281     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8282     * invalidated.
8283     * @param value the y position to scroll to
8284     */
8285    public void setScrollY(int value) {
8286        scrollTo(mScrollX, value);
8287    }
8288
8289    /**
8290     * Return the scrolled left position of this view. This is the left edge of
8291     * the displayed part of your view. You do not need to draw any pixels
8292     * farther left, since those are outside of the frame of your view on
8293     * screen.
8294     *
8295     * @return The left edge of the displayed part of your view, in pixels.
8296     */
8297    public final int getScrollX() {
8298        return mScrollX;
8299    }
8300
8301    /**
8302     * Return the scrolled top position of this view. This is the top edge of
8303     * the displayed part of your view. You do not need to draw any pixels above
8304     * it, since those are outside of the frame of your view on screen.
8305     *
8306     * @return The top edge of the displayed part of your view, in pixels.
8307     */
8308    public final int getScrollY() {
8309        return mScrollY;
8310    }
8311
8312    /**
8313     * Return the width of the your view.
8314     *
8315     * @return The width of your view, in pixels.
8316     */
8317    @ViewDebug.ExportedProperty(category = "layout")
8318    public final int getWidth() {
8319        return mRight - mLeft;
8320    }
8321
8322    /**
8323     * Return the height of your view.
8324     *
8325     * @return The height of your view, in pixels.
8326     */
8327    @ViewDebug.ExportedProperty(category = "layout")
8328    public final int getHeight() {
8329        return mBottom - mTop;
8330    }
8331
8332    /**
8333     * Return the visible drawing bounds of your view. Fills in the output
8334     * rectangle with the values from getScrollX(), getScrollY(),
8335     * getWidth(), and getHeight().
8336     *
8337     * @param outRect The (scrolled) drawing bounds of the view.
8338     */
8339    public void getDrawingRect(Rect outRect) {
8340        outRect.left = mScrollX;
8341        outRect.top = mScrollY;
8342        outRect.right = mScrollX + (mRight - mLeft);
8343        outRect.bottom = mScrollY + (mBottom - mTop);
8344    }
8345
8346    /**
8347     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8348     * raw width component (that is the result is masked by
8349     * {@link #MEASURED_SIZE_MASK}).
8350     *
8351     * @return The raw measured width of this view.
8352     */
8353    public final int getMeasuredWidth() {
8354        return mMeasuredWidth & MEASURED_SIZE_MASK;
8355    }
8356
8357    /**
8358     * Return the full width measurement information for this view as computed
8359     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8360     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8361     * This should be used during measurement and layout calculations only. Use
8362     * {@link #getWidth()} to see how wide a view is after layout.
8363     *
8364     * @return The measured width of this view as a bit mask.
8365     */
8366    public final int getMeasuredWidthAndState() {
8367        return mMeasuredWidth;
8368    }
8369
8370    /**
8371     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8372     * raw width component (that is the result is masked by
8373     * {@link #MEASURED_SIZE_MASK}).
8374     *
8375     * @return The raw measured height of this view.
8376     */
8377    public final int getMeasuredHeight() {
8378        return mMeasuredHeight & MEASURED_SIZE_MASK;
8379    }
8380
8381    /**
8382     * Return the full height measurement information for this view as computed
8383     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8384     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8385     * This should be used during measurement and layout calculations only. Use
8386     * {@link #getHeight()} to see how wide a view is after layout.
8387     *
8388     * @return The measured width of this view as a bit mask.
8389     */
8390    public final int getMeasuredHeightAndState() {
8391        return mMeasuredHeight;
8392    }
8393
8394    /**
8395     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8396     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8397     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8398     * and the height component is at the shifted bits
8399     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8400     */
8401    public final int getMeasuredState() {
8402        return (mMeasuredWidth&MEASURED_STATE_MASK)
8403                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8404                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8405    }
8406
8407    /**
8408     * The transform matrix of this view, which is calculated based on the current
8409     * roation, scale, and pivot properties.
8410     *
8411     * @see #getRotation()
8412     * @see #getScaleX()
8413     * @see #getScaleY()
8414     * @see #getPivotX()
8415     * @see #getPivotY()
8416     * @return The current transform matrix for the view
8417     */
8418    public Matrix getMatrix() {
8419        if (mTransformationInfo != null) {
8420            updateMatrix();
8421            return mTransformationInfo.mMatrix;
8422        }
8423        return Matrix.IDENTITY_MATRIX;
8424    }
8425
8426    /**
8427     * Utility function to determine if the value is far enough away from zero to be
8428     * considered non-zero.
8429     * @param value A floating point value to check for zero-ness
8430     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8431     */
8432    private static boolean nonzero(float value) {
8433        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8434    }
8435
8436    /**
8437     * Returns true if the transform matrix is the identity matrix.
8438     * Recomputes the matrix if necessary.
8439     *
8440     * @return True if the transform matrix is the identity matrix, false otherwise.
8441     */
8442    final boolean hasIdentityMatrix() {
8443        if (mTransformationInfo != null) {
8444            updateMatrix();
8445            return mTransformationInfo.mMatrixIsIdentity;
8446        }
8447        return true;
8448    }
8449
8450    void ensureTransformationInfo() {
8451        if (mTransformationInfo == null) {
8452            mTransformationInfo = new TransformationInfo();
8453        }
8454    }
8455
8456    /**
8457     * Recomputes the transform matrix if necessary.
8458     */
8459    private void updateMatrix() {
8460        final TransformationInfo info = mTransformationInfo;
8461        if (info == null) {
8462            return;
8463        }
8464        if (info.mMatrixDirty) {
8465            // transform-related properties have changed since the last time someone
8466            // asked for the matrix; recalculate it with the current values
8467
8468            // Figure out if we need to update the pivot point
8469            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8470                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8471                    info.mPrevWidth = mRight - mLeft;
8472                    info.mPrevHeight = mBottom - mTop;
8473                    info.mPivotX = info.mPrevWidth / 2f;
8474                    info.mPivotY = info.mPrevHeight / 2f;
8475                }
8476            }
8477            info.mMatrix.reset();
8478            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8479                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8480                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8481                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8482            } else {
8483                if (info.mCamera == null) {
8484                    info.mCamera = new Camera();
8485                    info.matrix3D = new Matrix();
8486                }
8487                info.mCamera.save();
8488                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8489                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8490                info.mCamera.getMatrix(info.matrix3D);
8491                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8492                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8493                        info.mPivotY + info.mTranslationY);
8494                info.mMatrix.postConcat(info.matrix3D);
8495                info.mCamera.restore();
8496            }
8497            info.mMatrixDirty = false;
8498            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8499            info.mInverseMatrixDirty = true;
8500        }
8501    }
8502
8503    /**
8504     * Utility method to retrieve the inverse of the current mMatrix property.
8505     * We cache the matrix to avoid recalculating it when transform properties
8506     * have not changed.
8507     *
8508     * @return The inverse of the current matrix of this view.
8509     */
8510    final Matrix getInverseMatrix() {
8511        final TransformationInfo info = mTransformationInfo;
8512        if (info != null) {
8513            updateMatrix();
8514            if (info.mInverseMatrixDirty) {
8515                if (info.mInverseMatrix == null) {
8516                    info.mInverseMatrix = new Matrix();
8517                }
8518                info.mMatrix.invert(info.mInverseMatrix);
8519                info.mInverseMatrixDirty = false;
8520            }
8521            return info.mInverseMatrix;
8522        }
8523        return Matrix.IDENTITY_MATRIX;
8524    }
8525
8526    /**
8527     * Gets the distance along the Z axis from the camera to this view.
8528     *
8529     * @see #setCameraDistance(float)
8530     *
8531     * @return The distance along the Z axis.
8532     */
8533    public float getCameraDistance() {
8534        ensureTransformationInfo();
8535        final float dpi = mResources.getDisplayMetrics().densityDpi;
8536        final TransformationInfo info = mTransformationInfo;
8537        if (info.mCamera == null) {
8538            info.mCamera = new Camera();
8539            info.matrix3D = new Matrix();
8540        }
8541        return -(info.mCamera.getLocationZ() * dpi);
8542    }
8543
8544    /**
8545     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8546     * views are drawn) from the camera to this view. The camera's distance
8547     * affects 3D transformations, for instance rotations around the X and Y
8548     * axis. If the rotationX or rotationY properties are changed and this view is
8549     * large (more than half the size of the screen), it is recommended to always
8550     * use a camera distance that's greater than the height (X axis rotation) or
8551     * the width (Y axis rotation) of this view.</p>
8552     *
8553     * <p>The distance of the camera from the view plane can have an affect on the
8554     * perspective distortion of the view when it is rotated around the x or y axis.
8555     * For example, a large distance will result in a large viewing angle, and there
8556     * will not be much perspective distortion of the view as it rotates. A short
8557     * distance may cause much more perspective distortion upon rotation, and can
8558     * also result in some drawing artifacts if the rotated view ends up partially
8559     * behind the camera (which is why the recommendation is to use a distance at
8560     * least as far as the size of the view, if the view is to be rotated.)</p>
8561     *
8562     * <p>The distance is expressed in "depth pixels." The default distance depends
8563     * on the screen density. For instance, on a medium density display, the
8564     * default distance is 1280. On a high density display, the default distance
8565     * is 1920.</p>
8566     *
8567     * <p>If you want to specify a distance that leads to visually consistent
8568     * results across various densities, use the following formula:</p>
8569     * <pre>
8570     * float scale = context.getResources().getDisplayMetrics().density;
8571     * view.setCameraDistance(distance * scale);
8572     * </pre>
8573     *
8574     * <p>The density scale factor of a high density display is 1.5,
8575     * and 1920 = 1280 * 1.5.</p>
8576     *
8577     * @param distance The distance in "depth pixels", if negative the opposite
8578     *        value is used
8579     *
8580     * @see #setRotationX(float)
8581     * @see #setRotationY(float)
8582     */
8583    public void setCameraDistance(float distance) {
8584        invalidateViewProperty(true, false);
8585
8586        ensureTransformationInfo();
8587        final float dpi = mResources.getDisplayMetrics().densityDpi;
8588        final TransformationInfo info = mTransformationInfo;
8589        if (info.mCamera == null) {
8590            info.mCamera = new Camera();
8591            info.matrix3D = new Matrix();
8592        }
8593
8594        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8595        info.mMatrixDirty = true;
8596
8597        invalidateViewProperty(false, false);
8598        if (mDisplayList != null) {
8599            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8600        }
8601        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8602            // View was rejected last time it was drawn by its parent; this may have changed
8603            invalidateParentIfNeeded();
8604        }
8605    }
8606
8607    /**
8608     * The degrees that the view is rotated around the pivot point.
8609     *
8610     * @see #setRotation(float)
8611     * @see #getPivotX()
8612     * @see #getPivotY()
8613     *
8614     * @return The degrees of rotation.
8615     */
8616    @ViewDebug.ExportedProperty(category = "drawing")
8617    public float getRotation() {
8618        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8619    }
8620
8621    /**
8622     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8623     * result in clockwise rotation.
8624     *
8625     * @param rotation The degrees of rotation.
8626     *
8627     * @see #getRotation()
8628     * @see #getPivotX()
8629     * @see #getPivotY()
8630     * @see #setRotationX(float)
8631     * @see #setRotationY(float)
8632     *
8633     * @attr ref android.R.styleable#View_rotation
8634     */
8635    public void setRotation(float rotation) {
8636        ensureTransformationInfo();
8637        final TransformationInfo info = mTransformationInfo;
8638        if (info.mRotation != rotation) {
8639            // Double-invalidation is necessary to capture view's old and new areas
8640            invalidateViewProperty(true, false);
8641            info.mRotation = rotation;
8642            info.mMatrixDirty = true;
8643            invalidateViewProperty(false, true);
8644            if (mDisplayList != null) {
8645                mDisplayList.setRotation(rotation);
8646            }
8647            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8648                // View was rejected last time it was drawn by its parent; this may have changed
8649                invalidateParentIfNeeded();
8650            }
8651        }
8652    }
8653
8654    /**
8655     * The degrees that the view is rotated around the vertical axis through the pivot point.
8656     *
8657     * @see #getPivotX()
8658     * @see #getPivotY()
8659     * @see #setRotationY(float)
8660     *
8661     * @return The degrees of Y rotation.
8662     */
8663    @ViewDebug.ExportedProperty(category = "drawing")
8664    public float getRotationY() {
8665        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8666    }
8667
8668    /**
8669     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8670     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8671     * down the y axis.
8672     *
8673     * When rotating large views, it is recommended to adjust the camera distance
8674     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8675     *
8676     * @param rotationY The degrees of Y rotation.
8677     *
8678     * @see #getRotationY()
8679     * @see #getPivotX()
8680     * @see #getPivotY()
8681     * @see #setRotation(float)
8682     * @see #setRotationX(float)
8683     * @see #setCameraDistance(float)
8684     *
8685     * @attr ref android.R.styleable#View_rotationY
8686     */
8687    public void setRotationY(float rotationY) {
8688        ensureTransformationInfo();
8689        final TransformationInfo info = mTransformationInfo;
8690        if (info.mRotationY != rotationY) {
8691            invalidateViewProperty(true, false);
8692            info.mRotationY = rotationY;
8693            info.mMatrixDirty = true;
8694            invalidateViewProperty(false, true);
8695            if (mDisplayList != null) {
8696                mDisplayList.setRotationY(rotationY);
8697            }
8698            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8699                // View was rejected last time it was drawn by its parent; this may have changed
8700                invalidateParentIfNeeded();
8701            }
8702        }
8703    }
8704
8705    /**
8706     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8707     *
8708     * @see #getPivotX()
8709     * @see #getPivotY()
8710     * @see #setRotationX(float)
8711     *
8712     * @return The degrees of X rotation.
8713     */
8714    @ViewDebug.ExportedProperty(category = "drawing")
8715    public float getRotationX() {
8716        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8717    }
8718
8719    /**
8720     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8721     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8722     * x axis.
8723     *
8724     * When rotating large views, it is recommended to adjust the camera distance
8725     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8726     *
8727     * @param rotationX The degrees of X rotation.
8728     *
8729     * @see #getRotationX()
8730     * @see #getPivotX()
8731     * @see #getPivotY()
8732     * @see #setRotation(float)
8733     * @see #setRotationY(float)
8734     * @see #setCameraDistance(float)
8735     *
8736     * @attr ref android.R.styleable#View_rotationX
8737     */
8738    public void setRotationX(float rotationX) {
8739        ensureTransformationInfo();
8740        final TransformationInfo info = mTransformationInfo;
8741        if (info.mRotationX != rotationX) {
8742            invalidateViewProperty(true, false);
8743            info.mRotationX = rotationX;
8744            info.mMatrixDirty = true;
8745            invalidateViewProperty(false, true);
8746            if (mDisplayList != null) {
8747                mDisplayList.setRotationX(rotationX);
8748            }
8749            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8750                // View was rejected last time it was drawn by its parent; this may have changed
8751                invalidateParentIfNeeded();
8752            }
8753        }
8754    }
8755
8756    /**
8757     * The amount that the view is scaled in x around the pivot point, as a proportion of
8758     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8759     *
8760     * <p>By default, this is 1.0f.
8761     *
8762     * @see #getPivotX()
8763     * @see #getPivotY()
8764     * @return The scaling factor.
8765     */
8766    @ViewDebug.ExportedProperty(category = "drawing")
8767    public float getScaleX() {
8768        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8769    }
8770
8771    /**
8772     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8773     * the view's unscaled width. A value of 1 means that no scaling is applied.
8774     *
8775     * @param scaleX The scaling factor.
8776     * @see #getPivotX()
8777     * @see #getPivotY()
8778     *
8779     * @attr ref android.R.styleable#View_scaleX
8780     */
8781    public void setScaleX(float scaleX) {
8782        ensureTransformationInfo();
8783        final TransformationInfo info = mTransformationInfo;
8784        if (info.mScaleX != scaleX) {
8785            invalidateViewProperty(true, false);
8786            info.mScaleX = scaleX;
8787            info.mMatrixDirty = true;
8788            invalidateViewProperty(false, true);
8789            if (mDisplayList != null) {
8790                mDisplayList.setScaleX(scaleX);
8791            }
8792            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8793                // View was rejected last time it was drawn by its parent; this may have changed
8794                invalidateParentIfNeeded();
8795            }
8796        }
8797    }
8798
8799    /**
8800     * The amount that the view is scaled in y around the pivot point, as a proportion of
8801     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8802     *
8803     * <p>By default, this is 1.0f.
8804     *
8805     * @see #getPivotX()
8806     * @see #getPivotY()
8807     * @return The scaling factor.
8808     */
8809    @ViewDebug.ExportedProperty(category = "drawing")
8810    public float getScaleY() {
8811        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8812    }
8813
8814    /**
8815     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8816     * the view's unscaled width. A value of 1 means that no scaling is applied.
8817     *
8818     * @param scaleY The scaling factor.
8819     * @see #getPivotX()
8820     * @see #getPivotY()
8821     *
8822     * @attr ref android.R.styleable#View_scaleY
8823     */
8824    public void setScaleY(float scaleY) {
8825        ensureTransformationInfo();
8826        final TransformationInfo info = mTransformationInfo;
8827        if (info.mScaleY != scaleY) {
8828            invalidateViewProperty(true, false);
8829            info.mScaleY = scaleY;
8830            info.mMatrixDirty = true;
8831            invalidateViewProperty(false, true);
8832            if (mDisplayList != null) {
8833                mDisplayList.setScaleY(scaleY);
8834            }
8835            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8836                // View was rejected last time it was drawn by its parent; this may have changed
8837                invalidateParentIfNeeded();
8838            }
8839        }
8840    }
8841
8842    /**
8843     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8844     * and {@link #setScaleX(float) scaled}.
8845     *
8846     * @see #getRotation()
8847     * @see #getScaleX()
8848     * @see #getScaleY()
8849     * @see #getPivotY()
8850     * @return The x location of the pivot point.
8851     *
8852     * @attr ref android.R.styleable#View_transformPivotX
8853     */
8854    @ViewDebug.ExportedProperty(category = "drawing")
8855    public float getPivotX() {
8856        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8857    }
8858
8859    /**
8860     * Sets the x location of the point around which the view is
8861     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8862     * By default, the pivot point is centered on the object.
8863     * Setting this property disables this behavior and causes the view to use only the
8864     * explicitly set pivotX and pivotY values.
8865     *
8866     * @param pivotX The x location of the pivot point.
8867     * @see #getRotation()
8868     * @see #getScaleX()
8869     * @see #getScaleY()
8870     * @see #getPivotY()
8871     *
8872     * @attr ref android.R.styleable#View_transformPivotX
8873     */
8874    public void setPivotX(float pivotX) {
8875        ensureTransformationInfo();
8876        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8877        final TransformationInfo info = mTransformationInfo;
8878        if (info.mPivotX != pivotX) {
8879            invalidateViewProperty(true, false);
8880            info.mPivotX = pivotX;
8881            info.mMatrixDirty = true;
8882            invalidateViewProperty(false, true);
8883            if (mDisplayList != null) {
8884                mDisplayList.setPivotX(pivotX);
8885            }
8886            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8887                // View was rejected last time it was drawn by its parent; this may have changed
8888                invalidateParentIfNeeded();
8889            }
8890        }
8891    }
8892
8893    /**
8894     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8895     * and {@link #setScaleY(float) scaled}.
8896     *
8897     * @see #getRotation()
8898     * @see #getScaleX()
8899     * @see #getScaleY()
8900     * @see #getPivotY()
8901     * @return The y location of the pivot point.
8902     *
8903     * @attr ref android.R.styleable#View_transformPivotY
8904     */
8905    @ViewDebug.ExportedProperty(category = "drawing")
8906    public float getPivotY() {
8907        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8908    }
8909
8910    /**
8911     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8912     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8913     * Setting this property disables this behavior and causes the view to use only the
8914     * explicitly set pivotX and pivotY values.
8915     *
8916     * @param pivotY The y location of the pivot point.
8917     * @see #getRotation()
8918     * @see #getScaleX()
8919     * @see #getScaleY()
8920     * @see #getPivotY()
8921     *
8922     * @attr ref android.R.styleable#View_transformPivotY
8923     */
8924    public void setPivotY(float pivotY) {
8925        ensureTransformationInfo();
8926        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8927        final TransformationInfo info = mTransformationInfo;
8928        if (info.mPivotY != pivotY) {
8929            invalidateViewProperty(true, false);
8930            info.mPivotY = pivotY;
8931            info.mMatrixDirty = true;
8932            invalidateViewProperty(false, true);
8933            if (mDisplayList != null) {
8934                mDisplayList.setPivotY(pivotY);
8935            }
8936            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8937                // View was rejected last time it was drawn by its parent; this may have changed
8938                invalidateParentIfNeeded();
8939            }
8940        }
8941    }
8942
8943    /**
8944     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8945     * completely transparent and 1 means the view is completely opaque.
8946     *
8947     * <p>By default this is 1.0f.
8948     * @return The opacity of the view.
8949     */
8950    @ViewDebug.ExportedProperty(category = "drawing")
8951    public float getAlpha() {
8952        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8953    }
8954
8955    /**
8956     * Returns whether this View has content which overlaps. This function, intended to be
8957     * overridden by specific View types, is an optimization when alpha is set on a view. If
8958     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8959     * and then composited it into place, which can be expensive. If the view has no overlapping
8960     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8961     * An example of overlapping rendering is a TextView with a background image, such as a
8962     * Button. An example of non-overlapping rendering is a TextView with no background, or
8963     * an ImageView with only the foreground image. The default implementation returns true;
8964     * subclasses should override if they have cases which can be optimized.
8965     *
8966     * @return true if the content in this view might overlap, false otherwise.
8967     */
8968    public boolean hasOverlappingRendering() {
8969        return true;
8970    }
8971
8972    /**
8973     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8974     * completely transparent and 1 means the view is completely opaque.</p>
8975     *
8976     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8977     * responsible for applying the opacity itself. Otherwise, calling this method is
8978     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8979     * setting a hardware layer.</p>
8980     *
8981     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8982     * performance implications. It is generally best to use the alpha property sparingly and
8983     * transiently, as in the case of fading animations.</p>
8984     *
8985     * @param alpha The opacity of the view.
8986     *
8987     * @see #setLayerType(int, android.graphics.Paint)
8988     *
8989     * @attr ref android.R.styleable#View_alpha
8990     */
8991    public void setAlpha(float alpha) {
8992        ensureTransformationInfo();
8993        if (mTransformationInfo.mAlpha != alpha) {
8994            mTransformationInfo.mAlpha = alpha;
8995            if (onSetAlpha((int) (alpha * 255))) {
8996                mPrivateFlags |= ALPHA_SET;
8997                // subclass is handling alpha - don't optimize rendering cache invalidation
8998                invalidateParentCaches();
8999                invalidate(true);
9000            } else {
9001                mPrivateFlags &= ~ALPHA_SET;
9002                invalidateViewProperty(true, false);
9003                if (mDisplayList != null) {
9004                    mDisplayList.setAlpha(alpha);
9005                }
9006            }
9007        }
9008    }
9009
9010    /**
9011     * Faster version of setAlpha() which performs the same steps except there are
9012     * no calls to invalidate(). The caller of this function should perform proper invalidation
9013     * on the parent and this object. The return value indicates whether the subclass handles
9014     * alpha (the return value for onSetAlpha()).
9015     *
9016     * @param alpha The new value for the alpha property
9017     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9018     *         the new value for the alpha property is different from the old value
9019     */
9020    boolean setAlphaNoInvalidation(float alpha) {
9021        ensureTransformationInfo();
9022        if (mTransformationInfo.mAlpha != alpha) {
9023            mTransformationInfo.mAlpha = alpha;
9024            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9025            if (subclassHandlesAlpha) {
9026                mPrivateFlags |= ALPHA_SET;
9027                return true;
9028            } else {
9029                mPrivateFlags &= ~ALPHA_SET;
9030                if (mDisplayList != null) {
9031                    mDisplayList.setAlpha(alpha);
9032                }
9033            }
9034        }
9035        return false;
9036    }
9037
9038    /**
9039     * Top position of this view relative to its parent.
9040     *
9041     * @return The top of this view, in pixels.
9042     */
9043    @ViewDebug.CapturedViewProperty
9044    public final int getTop() {
9045        return mTop;
9046    }
9047
9048    /**
9049     * Sets the top position of this view relative to its parent. This method is meant to be called
9050     * by the layout system and should not generally be called otherwise, because the property
9051     * may be changed at any time by the layout.
9052     *
9053     * @param top The top of this view, in pixels.
9054     */
9055    public final void setTop(int top) {
9056        if (top != mTop) {
9057            updateMatrix();
9058            final boolean matrixIsIdentity = mTransformationInfo == null
9059                    || mTransformationInfo.mMatrixIsIdentity;
9060            if (matrixIsIdentity) {
9061                if (mAttachInfo != null) {
9062                    int minTop;
9063                    int yLoc;
9064                    if (top < mTop) {
9065                        minTop = top;
9066                        yLoc = top - mTop;
9067                    } else {
9068                        minTop = mTop;
9069                        yLoc = 0;
9070                    }
9071                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9072                }
9073            } else {
9074                // Double-invalidation is necessary to capture view's old and new areas
9075                invalidate(true);
9076            }
9077
9078            int width = mRight - mLeft;
9079            int oldHeight = mBottom - mTop;
9080
9081            mTop = top;
9082            if (mDisplayList != null) {
9083                mDisplayList.setTop(mTop);
9084            }
9085
9086            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9087
9088            if (!matrixIsIdentity) {
9089                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9090                    // A change in dimension means an auto-centered pivot point changes, too
9091                    mTransformationInfo.mMatrixDirty = true;
9092                }
9093                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9094                invalidate(true);
9095            }
9096            mBackgroundSizeChanged = true;
9097            invalidateParentIfNeeded();
9098            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9099                // View was rejected last time it was drawn by its parent; this may have changed
9100                invalidateParentIfNeeded();
9101            }
9102        }
9103    }
9104
9105    /**
9106     * Bottom position of this view relative to its parent.
9107     *
9108     * @return The bottom of this view, in pixels.
9109     */
9110    @ViewDebug.CapturedViewProperty
9111    public final int getBottom() {
9112        return mBottom;
9113    }
9114
9115    /**
9116     * True if this view has changed since the last time being drawn.
9117     *
9118     * @return The dirty state of this view.
9119     */
9120    public boolean isDirty() {
9121        return (mPrivateFlags & DIRTY_MASK) != 0;
9122    }
9123
9124    /**
9125     * Sets the bottom position of this view relative to its parent. This method is meant to be
9126     * called by the layout system and should not generally be called otherwise, because the
9127     * property may be changed at any time by the layout.
9128     *
9129     * @param bottom The bottom of this view, in pixels.
9130     */
9131    public final void setBottom(int bottom) {
9132        if (bottom != mBottom) {
9133            updateMatrix();
9134            final boolean matrixIsIdentity = mTransformationInfo == null
9135                    || mTransformationInfo.mMatrixIsIdentity;
9136            if (matrixIsIdentity) {
9137                if (mAttachInfo != null) {
9138                    int maxBottom;
9139                    if (bottom < mBottom) {
9140                        maxBottom = mBottom;
9141                    } else {
9142                        maxBottom = bottom;
9143                    }
9144                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9145                }
9146            } else {
9147                // Double-invalidation is necessary to capture view's old and new areas
9148                invalidate(true);
9149            }
9150
9151            int width = mRight - mLeft;
9152            int oldHeight = mBottom - mTop;
9153
9154            mBottom = bottom;
9155            if (mDisplayList != null) {
9156                mDisplayList.setBottom(mBottom);
9157            }
9158
9159            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9160
9161            if (!matrixIsIdentity) {
9162                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9163                    // A change in dimension means an auto-centered pivot point changes, too
9164                    mTransformationInfo.mMatrixDirty = true;
9165                }
9166                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9167                invalidate(true);
9168            }
9169            mBackgroundSizeChanged = true;
9170            invalidateParentIfNeeded();
9171            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9172                // View was rejected last time it was drawn by its parent; this may have changed
9173                invalidateParentIfNeeded();
9174            }
9175        }
9176    }
9177
9178    /**
9179     * Left position of this view relative to its parent.
9180     *
9181     * @return The left edge of this view, in pixels.
9182     */
9183    @ViewDebug.CapturedViewProperty
9184    public final int getLeft() {
9185        return mLeft;
9186    }
9187
9188    /**
9189     * Sets the left position of this view relative to its parent. This method is meant to be called
9190     * by the layout system and should not generally be called otherwise, because the property
9191     * may be changed at any time by the layout.
9192     *
9193     * @param left The bottom of this view, in pixels.
9194     */
9195    public final void setLeft(int left) {
9196        if (left != mLeft) {
9197            updateMatrix();
9198            final boolean matrixIsIdentity = mTransformationInfo == null
9199                    || mTransformationInfo.mMatrixIsIdentity;
9200            if (matrixIsIdentity) {
9201                if (mAttachInfo != null) {
9202                    int minLeft;
9203                    int xLoc;
9204                    if (left < mLeft) {
9205                        minLeft = left;
9206                        xLoc = left - mLeft;
9207                    } else {
9208                        minLeft = mLeft;
9209                        xLoc = 0;
9210                    }
9211                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9212                }
9213            } else {
9214                // Double-invalidation is necessary to capture view's old and new areas
9215                invalidate(true);
9216            }
9217
9218            int oldWidth = mRight - mLeft;
9219            int height = mBottom - mTop;
9220
9221            mLeft = left;
9222            if (mDisplayList != null) {
9223                mDisplayList.setLeft(left);
9224            }
9225
9226            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9227
9228            if (!matrixIsIdentity) {
9229                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9230                    // A change in dimension means an auto-centered pivot point changes, too
9231                    mTransformationInfo.mMatrixDirty = true;
9232                }
9233                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9234                invalidate(true);
9235            }
9236            mBackgroundSizeChanged = true;
9237            invalidateParentIfNeeded();
9238            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9239                // View was rejected last time it was drawn by its parent; this may have changed
9240                invalidateParentIfNeeded();
9241            }
9242        }
9243    }
9244
9245    /**
9246     * Right position of this view relative to its parent.
9247     *
9248     * @return The right edge of this view, in pixels.
9249     */
9250    @ViewDebug.CapturedViewProperty
9251    public final int getRight() {
9252        return mRight;
9253    }
9254
9255    /**
9256     * Sets the right position of this view relative to its parent. This method is meant to be called
9257     * by the layout system and should not generally be called otherwise, because the property
9258     * may be changed at any time by the layout.
9259     *
9260     * @param right The bottom of this view, in pixels.
9261     */
9262    public final void setRight(int right) {
9263        if (right != mRight) {
9264            updateMatrix();
9265            final boolean matrixIsIdentity = mTransformationInfo == null
9266                    || mTransformationInfo.mMatrixIsIdentity;
9267            if (matrixIsIdentity) {
9268                if (mAttachInfo != null) {
9269                    int maxRight;
9270                    if (right < mRight) {
9271                        maxRight = mRight;
9272                    } else {
9273                        maxRight = right;
9274                    }
9275                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9276                }
9277            } else {
9278                // Double-invalidation is necessary to capture view's old and new areas
9279                invalidate(true);
9280            }
9281
9282            int oldWidth = mRight - mLeft;
9283            int height = mBottom - mTop;
9284
9285            mRight = right;
9286            if (mDisplayList != null) {
9287                mDisplayList.setRight(mRight);
9288            }
9289
9290            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9291
9292            if (!matrixIsIdentity) {
9293                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9294                    // A change in dimension means an auto-centered pivot point changes, too
9295                    mTransformationInfo.mMatrixDirty = true;
9296                }
9297                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9298                invalidate(true);
9299            }
9300            mBackgroundSizeChanged = true;
9301            invalidateParentIfNeeded();
9302            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9303                // View was rejected last time it was drawn by its parent; this may have changed
9304                invalidateParentIfNeeded();
9305            }
9306        }
9307    }
9308
9309    /**
9310     * The visual x position of this view, in pixels. This is equivalent to the
9311     * {@link #setTranslationX(float) translationX} property plus the current
9312     * {@link #getLeft() left} property.
9313     *
9314     * @return The visual x position of this view, in pixels.
9315     */
9316    @ViewDebug.ExportedProperty(category = "drawing")
9317    public float getX() {
9318        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9319    }
9320
9321    /**
9322     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9323     * {@link #setTranslationX(float) translationX} property to be the difference between
9324     * the x value passed in and the current {@link #getLeft() left} property.
9325     *
9326     * @param x The visual x position of this view, in pixels.
9327     */
9328    public void setX(float x) {
9329        setTranslationX(x - mLeft);
9330    }
9331
9332    /**
9333     * The visual y position of this view, in pixels. This is equivalent to the
9334     * {@link #setTranslationY(float) translationY} property plus the current
9335     * {@link #getTop() top} property.
9336     *
9337     * @return The visual y position of this view, in pixels.
9338     */
9339    @ViewDebug.ExportedProperty(category = "drawing")
9340    public float getY() {
9341        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9342    }
9343
9344    /**
9345     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9346     * {@link #setTranslationY(float) translationY} property to be the difference between
9347     * the y value passed in and the current {@link #getTop() top} property.
9348     *
9349     * @param y The visual y position of this view, in pixels.
9350     */
9351    public void setY(float y) {
9352        setTranslationY(y - mTop);
9353    }
9354
9355
9356    /**
9357     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9358     * This position is post-layout, in addition to wherever the object's
9359     * layout placed it.
9360     *
9361     * @return The horizontal position of this view relative to its left position, in pixels.
9362     */
9363    @ViewDebug.ExportedProperty(category = "drawing")
9364    public float getTranslationX() {
9365        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9366    }
9367
9368    /**
9369     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9370     * This effectively positions the object post-layout, in addition to wherever the object's
9371     * layout placed it.
9372     *
9373     * @param translationX The horizontal position of this view relative to its left position,
9374     * in pixels.
9375     *
9376     * @attr ref android.R.styleable#View_translationX
9377     */
9378    public void setTranslationX(float translationX) {
9379        ensureTransformationInfo();
9380        final TransformationInfo info = mTransformationInfo;
9381        if (info.mTranslationX != translationX) {
9382            // Double-invalidation is necessary to capture view's old and new areas
9383            invalidateViewProperty(true, false);
9384            info.mTranslationX = translationX;
9385            info.mMatrixDirty = true;
9386            invalidateViewProperty(false, true);
9387            if (mDisplayList != null) {
9388                mDisplayList.setTranslationX(translationX);
9389            }
9390            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9391                // View was rejected last time it was drawn by its parent; this may have changed
9392                invalidateParentIfNeeded();
9393            }
9394        }
9395    }
9396
9397    /**
9398     * The horizontal location of this view relative to its {@link #getTop() top} position.
9399     * This position is post-layout, in addition to wherever the object's
9400     * layout placed it.
9401     *
9402     * @return The vertical position of this view relative to its top position,
9403     * in pixels.
9404     */
9405    @ViewDebug.ExportedProperty(category = "drawing")
9406    public float getTranslationY() {
9407        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9408    }
9409
9410    /**
9411     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9412     * This effectively positions the object post-layout, in addition to wherever the object's
9413     * layout placed it.
9414     *
9415     * @param translationY The vertical position of this view relative to its top position,
9416     * in pixels.
9417     *
9418     * @attr ref android.R.styleable#View_translationY
9419     */
9420    public void setTranslationY(float translationY) {
9421        ensureTransformationInfo();
9422        final TransformationInfo info = mTransformationInfo;
9423        if (info.mTranslationY != translationY) {
9424            invalidateViewProperty(true, false);
9425            info.mTranslationY = translationY;
9426            info.mMatrixDirty = true;
9427            invalidateViewProperty(false, true);
9428            if (mDisplayList != null) {
9429                mDisplayList.setTranslationY(translationY);
9430            }
9431            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9432                // View was rejected last time it was drawn by its parent; this may have changed
9433                invalidateParentIfNeeded();
9434            }
9435        }
9436    }
9437
9438    /**
9439     * Hit rectangle in parent's coordinates
9440     *
9441     * @param outRect The hit rectangle of the view.
9442     */
9443    public void getHitRect(Rect outRect) {
9444        updateMatrix();
9445        final TransformationInfo info = mTransformationInfo;
9446        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9447            outRect.set(mLeft, mTop, mRight, mBottom);
9448        } else {
9449            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9450            tmpRect.set(-info.mPivotX, -info.mPivotY,
9451                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9452            info.mMatrix.mapRect(tmpRect);
9453            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9454                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9455        }
9456    }
9457
9458    /**
9459     * Determines whether the given point, in local coordinates is inside the view.
9460     */
9461    /*package*/ final boolean pointInView(float localX, float localY) {
9462        return localX >= 0 && localX < (mRight - mLeft)
9463                && localY >= 0 && localY < (mBottom - mTop);
9464    }
9465
9466    /**
9467     * Utility method to determine whether the given point, in local coordinates,
9468     * is inside the view, where the area of the view is expanded by the slop factor.
9469     * This method is called while processing touch-move events to determine if the event
9470     * is still within the view.
9471     */
9472    private boolean pointInView(float localX, float localY, float slop) {
9473        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9474                localY < ((mBottom - mTop) + slop);
9475    }
9476
9477    /**
9478     * When a view has focus and the user navigates away from it, the next view is searched for
9479     * starting from the rectangle filled in by this method.
9480     *
9481     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9482     * of the view.  However, if your view maintains some idea of internal selection,
9483     * such as a cursor, or a selected row or column, you should override this method and
9484     * fill in a more specific rectangle.
9485     *
9486     * @param r The rectangle to fill in, in this view's coordinates.
9487     */
9488    public void getFocusedRect(Rect r) {
9489        getDrawingRect(r);
9490    }
9491
9492    /**
9493     * If some part of this view is not clipped by any of its parents, then
9494     * return that area in r in global (root) coordinates. To convert r to local
9495     * coordinates (without taking possible View rotations into account), offset
9496     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9497     * If the view is completely clipped or translated out, return false.
9498     *
9499     * @param r If true is returned, r holds the global coordinates of the
9500     *        visible portion of this view.
9501     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9502     *        between this view and its root. globalOffet may be null.
9503     * @return true if r is non-empty (i.e. part of the view is visible at the
9504     *         root level.
9505     */
9506    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9507        int width = mRight - mLeft;
9508        int height = mBottom - mTop;
9509        if (width > 0 && height > 0) {
9510            r.set(0, 0, width, height);
9511            if (globalOffset != null) {
9512                globalOffset.set(-mScrollX, -mScrollY);
9513            }
9514            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9515        }
9516        return false;
9517    }
9518
9519    public final boolean getGlobalVisibleRect(Rect r) {
9520        return getGlobalVisibleRect(r, null);
9521    }
9522
9523    public final boolean getLocalVisibleRect(Rect r) {
9524        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9525        if (getGlobalVisibleRect(r, offset)) {
9526            r.offset(-offset.x, -offset.y); // make r local
9527            return true;
9528        }
9529        return false;
9530    }
9531
9532    /**
9533     * Offset this view's vertical location by the specified number of pixels.
9534     *
9535     * @param offset the number of pixels to offset the view by
9536     */
9537    public void offsetTopAndBottom(int offset) {
9538        if (offset != 0) {
9539            updateMatrix();
9540            final boolean matrixIsIdentity = mTransformationInfo == null
9541                    || mTransformationInfo.mMatrixIsIdentity;
9542            if (matrixIsIdentity) {
9543                if (mDisplayList != null) {
9544                    invalidateViewProperty(false, false);
9545                } else {
9546                    final ViewParent p = mParent;
9547                    if (p != null && mAttachInfo != null) {
9548                        final Rect r = mAttachInfo.mTmpInvalRect;
9549                        int minTop;
9550                        int maxBottom;
9551                        int yLoc;
9552                        if (offset < 0) {
9553                            minTop = mTop + offset;
9554                            maxBottom = mBottom;
9555                            yLoc = offset;
9556                        } else {
9557                            minTop = mTop;
9558                            maxBottom = mBottom + offset;
9559                            yLoc = 0;
9560                        }
9561                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9562                        p.invalidateChild(this, r);
9563                    }
9564                }
9565            } else {
9566                invalidateViewProperty(false, false);
9567            }
9568
9569            mTop += offset;
9570            mBottom += offset;
9571            if (mDisplayList != null) {
9572                mDisplayList.offsetTopBottom(offset);
9573                invalidateViewProperty(false, false);
9574            } else {
9575                if (!matrixIsIdentity) {
9576                    invalidateViewProperty(false, true);
9577                }
9578                invalidateParentIfNeeded();
9579            }
9580        }
9581    }
9582
9583    /**
9584     * Offset this view's horizontal location by the specified amount of pixels.
9585     *
9586     * @param offset the numer of pixels to offset the view by
9587     */
9588    public void offsetLeftAndRight(int offset) {
9589        if (offset != 0) {
9590            updateMatrix();
9591            final boolean matrixIsIdentity = mTransformationInfo == null
9592                    || mTransformationInfo.mMatrixIsIdentity;
9593            if (matrixIsIdentity) {
9594                if (mDisplayList != null) {
9595                    invalidateViewProperty(false, false);
9596                } else {
9597                    final ViewParent p = mParent;
9598                    if (p != null && mAttachInfo != null) {
9599                        final Rect r = mAttachInfo.mTmpInvalRect;
9600                        int minLeft;
9601                        int maxRight;
9602                        if (offset < 0) {
9603                            minLeft = mLeft + offset;
9604                            maxRight = mRight;
9605                        } else {
9606                            minLeft = mLeft;
9607                            maxRight = mRight + offset;
9608                        }
9609                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9610                        p.invalidateChild(this, r);
9611                    }
9612                }
9613            } else {
9614                invalidateViewProperty(false, false);
9615            }
9616
9617            mLeft += offset;
9618            mRight += offset;
9619            if (mDisplayList != null) {
9620                mDisplayList.offsetLeftRight(offset);
9621                invalidateViewProperty(false, false);
9622            } else {
9623                if (!matrixIsIdentity) {
9624                    invalidateViewProperty(false, true);
9625                }
9626                invalidateParentIfNeeded();
9627            }
9628        }
9629    }
9630
9631    /**
9632     * Get the LayoutParams associated with this view. All views should have
9633     * layout parameters. These supply parameters to the <i>parent</i> of this
9634     * view specifying how it should be arranged. There are many subclasses of
9635     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9636     * of ViewGroup that are responsible for arranging their children.
9637     *
9638     * This method may return null if this View is not attached to a parent
9639     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9640     * was not invoked successfully. When a View is attached to a parent
9641     * ViewGroup, this method must not return null.
9642     *
9643     * @return The LayoutParams associated with this view, or null if no
9644     *         parameters have been set yet
9645     */
9646    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9647    public ViewGroup.LayoutParams getLayoutParams() {
9648        return mLayoutParams;
9649    }
9650
9651    /**
9652     * Set the layout parameters associated with this view. These supply
9653     * parameters to the <i>parent</i> of this view specifying how it should be
9654     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9655     * correspond to the different subclasses of ViewGroup that are responsible
9656     * for arranging their children.
9657     *
9658     * @param params The layout parameters for this view, cannot be null
9659     */
9660    public void setLayoutParams(ViewGroup.LayoutParams params) {
9661        if (params == null) {
9662            throw new NullPointerException("Layout parameters cannot be null");
9663        }
9664        mLayoutParams = params;
9665        if (mParent instanceof ViewGroup) {
9666            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9667        }
9668        requestLayout();
9669    }
9670
9671    /**
9672     * Set the scrolled position of your view. This will cause a call to
9673     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9674     * invalidated.
9675     * @param x the x position to scroll to
9676     * @param y the y position to scroll to
9677     */
9678    public void scrollTo(int x, int y) {
9679        if (mScrollX != x || mScrollY != y) {
9680            int oldX = mScrollX;
9681            int oldY = mScrollY;
9682            mScrollX = x;
9683            mScrollY = y;
9684            invalidateParentCaches();
9685            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9686            if (!awakenScrollBars()) {
9687                postInvalidateOnAnimation();
9688            }
9689        }
9690    }
9691
9692    /**
9693     * Move the scrolled position of your view. This will cause a call to
9694     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9695     * invalidated.
9696     * @param x the amount of pixels to scroll by horizontally
9697     * @param y the amount of pixels to scroll by vertically
9698     */
9699    public void scrollBy(int x, int y) {
9700        scrollTo(mScrollX + x, mScrollY + y);
9701    }
9702
9703    /**
9704     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9705     * animation to fade the scrollbars out after a default delay. If a subclass
9706     * provides animated scrolling, the start delay should equal the duration
9707     * of the scrolling animation.</p>
9708     *
9709     * <p>The animation starts only if at least one of the scrollbars is
9710     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9711     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9712     * this method returns true, and false otherwise. If the animation is
9713     * started, this method calls {@link #invalidate()}; in that case the
9714     * caller should not call {@link #invalidate()}.</p>
9715     *
9716     * <p>This method should be invoked every time a subclass directly updates
9717     * the scroll parameters.</p>
9718     *
9719     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9720     * and {@link #scrollTo(int, int)}.</p>
9721     *
9722     * @return true if the animation is played, false otherwise
9723     *
9724     * @see #awakenScrollBars(int)
9725     * @see #scrollBy(int, int)
9726     * @see #scrollTo(int, int)
9727     * @see #isHorizontalScrollBarEnabled()
9728     * @see #isVerticalScrollBarEnabled()
9729     * @see #setHorizontalScrollBarEnabled(boolean)
9730     * @see #setVerticalScrollBarEnabled(boolean)
9731     */
9732    protected boolean awakenScrollBars() {
9733        return mScrollCache != null &&
9734                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9735    }
9736
9737    /**
9738     * Trigger the scrollbars to draw.
9739     * This method differs from awakenScrollBars() only in its default duration.
9740     * initialAwakenScrollBars() will show the scroll bars for longer than
9741     * usual to give the user more of a chance to notice them.
9742     *
9743     * @return true if the animation is played, false otherwise.
9744     */
9745    private boolean initialAwakenScrollBars() {
9746        return mScrollCache != null &&
9747                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9748    }
9749
9750    /**
9751     * <p>
9752     * Trigger the scrollbars to draw. When invoked this method starts an
9753     * animation to fade the scrollbars out after a fixed delay. If a subclass
9754     * provides animated scrolling, the start delay should equal the duration of
9755     * the scrolling animation.
9756     * </p>
9757     *
9758     * <p>
9759     * The animation starts only if at least one of the scrollbars is enabled,
9760     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9761     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9762     * this method returns true, and false otherwise. If the animation is
9763     * started, this method calls {@link #invalidate()}; in that case the caller
9764     * should not call {@link #invalidate()}.
9765     * </p>
9766     *
9767     * <p>
9768     * This method should be invoked everytime a subclass directly updates the
9769     * scroll parameters.
9770     * </p>
9771     *
9772     * @param startDelay the delay, in milliseconds, after which the animation
9773     *        should start; when the delay is 0, the animation starts
9774     *        immediately
9775     * @return true if the animation is played, false otherwise
9776     *
9777     * @see #scrollBy(int, int)
9778     * @see #scrollTo(int, int)
9779     * @see #isHorizontalScrollBarEnabled()
9780     * @see #isVerticalScrollBarEnabled()
9781     * @see #setHorizontalScrollBarEnabled(boolean)
9782     * @see #setVerticalScrollBarEnabled(boolean)
9783     */
9784    protected boolean awakenScrollBars(int startDelay) {
9785        return awakenScrollBars(startDelay, true);
9786    }
9787
9788    /**
9789     * <p>
9790     * Trigger the scrollbars to draw. When invoked this method starts an
9791     * animation to fade the scrollbars out after a fixed delay. If a subclass
9792     * provides animated scrolling, the start delay should equal the duration of
9793     * the scrolling animation.
9794     * </p>
9795     *
9796     * <p>
9797     * The animation starts only if at least one of the scrollbars is enabled,
9798     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9799     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9800     * this method returns true, and false otherwise. If the animation is
9801     * started, this method calls {@link #invalidate()} if the invalidate parameter
9802     * is set to true; in that case the caller
9803     * should not call {@link #invalidate()}.
9804     * </p>
9805     *
9806     * <p>
9807     * This method should be invoked everytime a subclass directly updates the
9808     * scroll parameters.
9809     * </p>
9810     *
9811     * @param startDelay the delay, in milliseconds, after which the animation
9812     *        should start; when the delay is 0, the animation starts
9813     *        immediately
9814     *
9815     * @param invalidate Wheter this method should call invalidate
9816     *
9817     * @return true if the animation is played, false otherwise
9818     *
9819     * @see #scrollBy(int, int)
9820     * @see #scrollTo(int, int)
9821     * @see #isHorizontalScrollBarEnabled()
9822     * @see #isVerticalScrollBarEnabled()
9823     * @see #setHorizontalScrollBarEnabled(boolean)
9824     * @see #setVerticalScrollBarEnabled(boolean)
9825     */
9826    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9827        final ScrollabilityCache scrollCache = mScrollCache;
9828
9829        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9830            return false;
9831        }
9832
9833        if (scrollCache.scrollBar == null) {
9834            scrollCache.scrollBar = new ScrollBarDrawable();
9835        }
9836
9837        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9838
9839            if (invalidate) {
9840                // Invalidate to show the scrollbars
9841                postInvalidateOnAnimation();
9842            }
9843
9844            if (scrollCache.state == ScrollabilityCache.OFF) {
9845                // FIXME: this is copied from WindowManagerService.
9846                // We should get this value from the system when it
9847                // is possible to do so.
9848                final int KEY_REPEAT_FIRST_DELAY = 750;
9849                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9850            }
9851
9852            // Tell mScrollCache when we should start fading. This may
9853            // extend the fade start time if one was already scheduled
9854            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9855            scrollCache.fadeStartTime = fadeStartTime;
9856            scrollCache.state = ScrollabilityCache.ON;
9857
9858            // Schedule our fader to run, unscheduling any old ones first
9859            if (mAttachInfo != null) {
9860                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9861                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9862            }
9863
9864            return true;
9865        }
9866
9867        return false;
9868    }
9869
9870    /**
9871     * Do not invalidate views which are not visible and which are not running an animation. They
9872     * will not get drawn and they should not set dirty flags as if they will be drawn
9873     */
9874    private boolean skipInvalidate() {
9875        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9876                (!(mParent instanceof ViewGroup) ||
9877                        !((ViewGroup) mParent).isViewTransitioning(this));
9878    }
9879    /**
9880     * Mark the area defined by dirty as needing to be drawn. If the view is
9881     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9882     * in the future. This must be called from a UI thread. To call from a non-UI
9883     * thread, call {@link #postInvalidate()}.
9884     *
9885     * WARNING: This method is destructive to dirty.
9886     * @param dirty the rectangle representing the bounds of the dirty region
9887     */
9888    public void invalidate(Rect dirty) {
9889        if (ViewDebug.TRACE_HIERARCHY) {
9890            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9891        }
9892
9893        if (skipInvalidate()) {
9894            return;
9895        }
9896        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9897                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9898                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9899            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9900            mPrivateFlags |= INVALIDATED;
9901            mPrivateFlags |= DIRTY;
9902            final ViewParent p = mParent;
9903            final AttachInfo ai = mAttachInfo;
9904            //noinspection PointlessBooleanExpression,ConstantConditions
9905            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9906                if (p != null && ai != null && ai.mHardwareAccelerated) {
9907                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9908                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9909                    p.invalidateChild(this, null);
9910                    return;
9911                }
9912            }
9913            if (p != null && ai != null) {
9914                final int scrollX = mScrollX;
9915                final int scrollY = mScrollY;
9916                final Rect r = ai.mTmpInvalRect;
9917                r.set(dirty.left - scrollX, dirty.top - scrollY,
9918                        dirty.right - scrollX, dirty.bottom - scrollY);
9919                mParent.invalidateChild(this, r);
9920            }
9921        }
9922    }
9923
9924    /**
9925     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9926     * The coordinates of the dirty rect are relative to the view.
9927     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9928     * will be called at some point in the future. This must be called from
9929     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9930     * @param l the left position of the dirty region
9931     * @param t the top position of the dirty region
9932     * @param r the right position of the dirty region
9933     * @param b the bottom position of the dirty region
9934     */
9935    public void invalidate(int l, int t, int r, int b) {
9936        if (ViewDebug.TRACE_HIERARCHY) {
9937            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9938        }
9939
9940        if (skipInvalidate()) {
9941            return;
9942        }
9943        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9944                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9945                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9946            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9947            mPrivateFlags |= INVALIDATED;
9948            mPrivateFlags |= DIRTY;
9949            final ViewParent p = mParent;
9950            final AttachInfo ai = mAttachInfo;
9951            //noinspection PointlessBooleanExpression,ConstantConditions
9952            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9953                if (p != null && ai != null && ai.mHardwareAccelerated) {
9954                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9955                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9956                    p.invalidateChild(this, null);
9957                    return;
9958                }
9959            }
9960            if (p != null && ai != null && l < r && t < b) {
9961                final int scrollX = mScrollX;
9962                final int scrollY = mScrollY;
9963                final Rect tmpr = ai.mTmpInvalRect;
9964                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9965                p.invalidateChild(this, tmpr);
9966            }
9967        }
9968    }
9969
9970    /**
9971     * Invalidate the whole view. If the view is visible,
9972     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9973     * the future. This must be called from a UI thread. To call from a non-UI thread,
9974     * call {@link #postInvalidate()}.
9975     */
9976    public void invalidate() {
9977        invalidate(true);
9978    }
9979
9980    /**
9981     * This is where the invalidate() work actually happens. A full invalidate()
9982     * causes the drawing cache to be invalidated, but this function can be called with
9983     * invalidateCache set to false to skip that invalidation step for cases that do not
9984     * need it (for example, a component that remains at the same dimensions with the same
9985     * content).
9986     *
9987     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9988     * well. This is usually true for a full invalidate, but may be set to false if the
9989     * View's contents or dimensions have not changed.
9990     */
9991    void invalidate(boolean invalidateCache) {
9992        if (ViewDebug.TRACE_HIERARCHY) {
9993            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9994        }
9995
9996        if (skipInvalidate()) {
9997            return;
9998        }
9999        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10000                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
10001                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
10002            mLastIsOpaque = isOpaque();
10003            mPrivateFlags &= ~DRAWN;
10004            mPrivateFlags |= DIRTY;
10005            if (invalidateCache) {
10006                mPrivateFlags |= INVALIDATED;
10007                mPrivateFlags &= ~DRAWING_CACHE_VALID;
10008            }
10009            final AttachInfo ai = mAttachInfo;
10010            final ViewParent p = mParent;
10011            //noinspection PointlessBooleanExpression,ConstantConditions
10012            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10013                if (p != null && ai != null && ai.mHardwareAccelerated) {
10014                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10015                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10016                    p.invalidateChild(this, null);
10017                    return;
10018                }
10019            }
10020
10021            if (p != null && ai != null) {
10022                final Rect r = ai.mTmpInvalRect;
10023                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10024                // Don't call invalidate -- we don't want to internally scroll
10025                // our own bounds
10026                p.invalidateChild(this, r);
10027            }
10028        }
10029    }
10030
10031    /**
10032     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10033     * set any flags or handle all of the cases handled by the default invalidation methods.
10034     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10035     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10036     * walk up the hierarchy, transforming the dirty rect as necessary.
10037     *
10038     * The method also handles normal invalidation logic if display list properties are not
10039     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10040     * backup approach, to handle these cases used in the various property-setting methods.
10041     *
10042     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10043     * are not being used in this view
10044     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10045     * list properties are not being used in this view
10046     */
10047    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10048        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10049            if (invalidateParent) {
10050                invalidateParentCaches();
10051            }
10052            if (forceRedraw) {
10053                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10054            }
10055            invalidate(false);
10056        } else {
10057            final AttachInfo ai = mAttachInfo;
10058            final ViewParent p = mParent;
10059            if (p != null && ai != null) {
10060                final Rect r = ai.mTmpInvalRect;
10061                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10062                if (mParent instanceof ViewGroup) {
10063                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10064                } else {
10065                    mParent.invalidateChild(this, r);
10066                }
10067            }
10068        }
10069    }
10070
10071    /**
10072     * Utility method to transform a given Rect by the current matrix of this view.
10073     */
10074    void transformRect(final Rect rect) {
10075        if (!getMatrix().isIdentity()) {
10076            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10077            boundingRect.set(rect);
10078            getMatrix().mapRect(boundingRect);
10079            rect.set((int) (boundingRect.left - 0.5f),
10080                    (int) (boundingRect.top - 0.5f),
10081                    (int) (boundingRect.right + 0.5f),
10082                    (int) (boundingRect.bottom + 0.5f));
10083        }
10084    }
10085
10086    /**
10087     * Used to indicate that the parent of this view should clear its caches. This functionality
10088     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10089     * which is necessary when various parent-managed properties of the view change, such as
10090     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10091     * clears the parent caches and does not causes an invalidate event.
10092     *
10093     * @hide
10094     */
10095    protected void invalidateParentCaches() {
10096        if (mParent instanceof View) {
10097            ((View) mParent).mPrivateFlags |= INVALIDATED;
10098        }
10099    }
10100
10101    /**
10102     * Used to indicate that the parent of this view should be invalidated. This functionality
10103     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10104     * which is necessary when various parent-managed properties of the view change, such as
10105     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10106     * an invalidation event to the parent.
10107     *
10108     * @hide
10109     */
10110    protected void invalidateParentIfNeeded() {
10111        if (isHardwareAccelerated() && mParent instanceof View) {
10112            ((View) mParent).invalidate(true);
10113        }
10114    }
10115
10116    /**
10117     * Indicates whether this View is opaque. An opaque View guarantees that it will
10118     * draw all the pixels overlapping its bounds using a fully opaque color.
10119     *
10120     * Subclasses of View should override this method whenever possible to indicate
10121     * whether an instance is opaque. Opaque Views are treated in a special way by
10122     * the View hierarchy, possibly allowing it to perform optimizations during
10123     * invalidate/draw passes.
10124     *
10125     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10126     */
10127    @ViewDebug.ExportedProperty(category = "drawing")
10128    public boolean isOpaque() {
10129        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10130                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10131                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10132    }
10133
10134    /**
10135     * @hide
10136     */
10137    protected void computeOpaqueFlags() {
10138        // Opaque if:
10139        //   - Has a background
10140        //   - Background is opaque
10141        //   - Doesn't have scrollbars or scrollbars are inside overlay
10142
10143        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10144            mPrivateFlags |= OPAQUE_BACKGROUND;
10145        } else {
10146            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10147        }
10148
10149        final int flags = mViewFlags;
10150        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10151                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10152            mPrivateFlags |= OPAQUE_SCROLLBARS;
10153        } else {
10154            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10155        }
10156    }
10157
10158    /**
10159     * @hide
10160     */
10161    protected boolean hasOpaqueScrollbars() {
10162        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10163    }
10164
10165    /**
10166     * @return A handler associated with the thread running the View. This
10167     * handler can be used to pump events in the UI events queue.
10168     */
10169    public Handler getHandler() {
10170        if (mAttachInfo != null) {
10171            return mAttachInfo.mHandler;
10172        }
10173        return null;
10174    }
10175
10176    /**
10177     * Gets the view root associated with the View.
10178     * @return The view root, or null if none.
10179     * @hide
10180     */
10181    public ViewRootImpl getViewRootImpl() {
10182        if (mAttachInfo != null) {
10183            return mAttachInfo.mViewRootImpl;
10184        }
10185        return null;
10186    }
10187
10188    /**
10189     * <p>Causes the Runnable to be added to the message queue.
10190     * The runnable will be run on the user interface thread.</p>
10191     *
10192     * <p>This method can be invoked from outside of the UI thread
10193     * only when this View is attached to a window.</p>
10194     *
10195     * @param action The Runnable that will be executed.
10196     *
10197     * @return Returns true if the Runnable was successfully placed in to the
10198     *         message queue.  Returns false on failure, usually because the
10199     *         looper processing the message queue is exiting.
10200     *
10201     * @see #postDelayed
10202     * @see #removeCallbacks
10203     */
10204    public boolean post(Runnable action) {
10205        final AttachInfo attachInfo = mAttachInfo;
10206        if (attachInfo != null) {
10207            return attachInfo.mHandler.post(action);
10208        }
10209        // Assume that post will succeed later
10210        ViewRootImpl.getRunQueue().post(action);
10211        return true;
10212    }
10213
10214    /**
10215     * <p>Causes the Runnable to be added to the message queue, to be run
10216     * after the specified amount of time elapses.
10217     * The runnable will be run on the user interface thread.</p>
10218     *
10219     * <p>This method can be invoked from outside of the UI thread
10220     * only when this View is attached to a window.</p>
10221     *
10222     * @param action The Runnable that will be executed.
10223     * @param delayMillis The delay (in milliseconds) until the Runnable
10224     *        will be executed.
10225     *
10226     * @return true if the Runnable was successfully placed in to the
10227     *         message queue.  Returns false on failure, usually because the
10228     *         looper processing the message queue is exiting.  Note that a
10229     *         result of true does not mean the Runnable will be processed --
10230     *         if the looper is quit before the delivery time of the message
10231     *         occurs then the message will be dropped.
10232     *
10233     * @see #post
10234     * @see #removeCallbacks
10235     */
10236    public boolean postDelayed(Runnable action, long delayMillis) {
10237        final AttachInfo attachInfo = mAttachInfo;
10238        if (attachInfo != null) {
10239            return attachInfo.mHandler.postDelayed(action, delayMillis);
10240        }
10241        // Assume that post will succeed later
10242        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10243        return true;
10244    }
10245
10246    /**
10247     * <p>Causes the Runnable to execute on the next animation time step.
10248     * The runnable will be run on the user interface thread.</p>
10249     *
10250     * <p>This method can be invoked from outside of the UI thread
10251     * only when this View is attached to a window.</p>
10252     *
10253     * @param action The Runnable that will be executed.
10254     *
10255     * @see #postOnAnimationDelayed
10256     * @see #removeCallbacks
10257     */
10258    public void postOnAnimation(Runnable action) {
10259        final AttachInfo attachInfo = mAttachInfo;
10260        if (attachInfo != null) {
10261            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10262                    Choreographer.CALLBACK_ANIMATION, action, null);
10263        } else {
10264            // Assume that post will succeed later
10265            ViewRootImpl.getRunQueue().post(action);
10266        }
10267    }
10268
10269    /**
10270     * <p>Causes the Runnable to execute on the next animation time step,
10271     * after the specified amount of time elapses.
10272     * The runnable will be run on the user interface thread.</p>
10273     *
10274     * <p>This method can be invoked from outside of the UI thread
10275     * only when this View is attached to a window.</p>
10276     *
10277     * @param action The Runnable that will be executed.
10278     * @param delayMillis The delay (in milliseconds) until the Runnable
10279     *        will be executed.
10280     *
10281     * @see #postOnAnimation
10282     * @see #removeCallbacks
10283     */
10284    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10285        final AttachInfo attachInfo = mAttachInfo;
10286        if (attachInfo != null) {
10287            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10288                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10289        } else {
10290            // Assume that post will succeed later
10291            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10292        }
10293    }
10294
10295    /**
10296     * <p>Removes the specified Runnable from the message queue.</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     * @param action The Runnable to remove from the message handling queue
10302     *
10303     * @return true if this view could ask the Handler to remove the Runnable,
10304     *         false otherwise. When the returned value is true, the Runnable
10305     *         may or may not have been actually removed from the message queue
10306     *         (for instance, if the Runnable was not in the queue already.)
10307     *
10308     * @see #post
10309     * @see #postDelayed
10310     * @see #postOnAnimation
10311     * @see #postOnAnimationDelayed
10312     */
10313    public boolean removeCallbacks(Runnable action) {
10314        if (action != null) {
10315            final AttachInfo attachInfo = mAttachInfo;
10316            if (attachInfo != null) {
10317                attachInfo.mHandler.removeCallbacks(action);
10318                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10319                        Choreographer.CALLBACK_ANIMATION, action, null);
10320            } else {
10321                // Assume that post will succeed later
10322                ViewRootImpl.getRunQueue().removeCallbacks(action);
10323            }
10324        }
10325        return true;
10326    }
10327
10328    /**
10329     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10330     * Use this to invalidate the View from a non-UI thread.</p>
10331     *
10332     * <p>This method can be invoked from outside of the UI thread
10333     * only when this View is attached to a window.</p>
10334     *
10335     * @see #invalidate()
10336     * @see #postInvalidateDelayed(long)
10337     */
10338    public void postInvalidate() {
10339        postInvalidateDelayed(0);
10340    }
10341
10342    /**
10343     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10344     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10345     *
10346     * <p>This method can be invoked from outside of the UI thread
10347     * only when this View is attached to a window.</p>
10348     *
10349     * @param left The left coordinate of the rectangle to invalidate.
10350     * @param top The top coordinate of the rectangle to invalidate.
10351     * @param right The right coordinate of the rectangle to invalidate.
10352     * @param bottom The bottom coordinate of the rectangle to invalidate.
10353     *
10354     * @see #invalidate(int, int, int, int)
10355     * @see #invalidate(Rect)
10356     * @see #postInvalidateDelayed(long, int, int, int, int)
10357     */
10358    public void postInvalidate(int left, int top, int right, int bottom) {
10359        postInvalidateDelayed(0, left, top, right, bottom);
10360    }
10361
10362    /**
10363     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10364     * loop. Waits for the specified amount of time.</p>
10365     *
10366     * <p>This method can be invoked from outside of the UI thread
10367     * only when this View is attached to a window.</p>
10368     *
10369     * @param delayMilliseconds the duration in milliseconds to delay the
10370     *         invalidation by
10371     *
10372     * @see #invalidate()
10373     * @see #postInvalidate()
10374     */
10375    public void postInvalidateDelayed(long delayMilliseconds) {
10376        // We try only with the AttachInfo because there's no point in invalidating
10377        // if we are not attached to our window
10378        final AttachInfo attachInfo = mAttachInfo;
10379        if (attachInfo != null) {
10380            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10381        }
10382    }
10383
10384    /**
10385     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10386     * through the event loop. Waits for the specified amount of time.</p>
10387     *
10388     * <p>This method can be invoked from outside of the UI thread
10389     * only when this View is attached to a window.</p>
10390     *
10391     * @param delayMilliseconds the duration in milliseconds to delay the
10392     *         invalidation by
10393     * @param left The left coordinate of the rectangle to invalidate.
10394     * @param top The top coordinate of the rectangle to invalidate.
10395     * @param right The right coordinate of the rectangle to invalidate.
10396     * @param bottom The bottom coordinate of the rectangle to invalidate.
10397     *
10398     * @see #invalidate(int, int, int, int)
10399     * @see #invalidate(Rect)
10400     * @see #postInvalidate(int, int, int, int)
10401     */
10402    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10403            int right, int bottom) {
10404
10405        // We try only with the AttachInfo because there's no point in invalidating
10406        // if we are not attached to our window
10407        final AttachInfo attachInfo = mAttachInfo;
10408        if (attachInfo != null) {
10409            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10410            info.target = this;
10411            info.left = left;
10412            info.top = top;
10413            info.right = right;
10414            info.bottom = bottom;
10415
10416            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10417        }
10418    }
10419
10420    /**
10421     * <p>Cause an invalidate to happen on the next animation time step, typically the
10422     * next display frame.</p>
10423     *
10424     * <p>This method can be invoked from outside of the UI thread
10425     * only when this View is attached to a window.</p>
10426     *
10427     * @see #invalidate()
10428     */
10429    public void postInvalidateOnAnimation() {
10430        // We try only with the AttachInfo because there's no point in invalidating
10431        // if we are not attached to our window
10432        final AttachInfo attachInfo = mAttachInfo;
10433        if (attachInfo != null) {
10434            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10435        }
10436    }
10437
10438    /**
10439     * <p>Cause an invalidate of the specified area to happen on the next animation
10440     * time step, typically the next display frame.</p>
10441     *
10442     * <p>This method can be invoked from outside of the UI thread
10443     * only when this View is attached to a window.</p>
10444     *
10445     * @param left The left coordinate of the rectangle to invalidate.
10446     * @param top The top coordinate of the rectangle to invalidate.
10447     * @param right The right coordinate of the rectangle to invalidate.
10448     * @param bottom The bottom coordinate of the rectangle to invalidate.
10449     *
10450     * @see #invalidate(int, int, int, int)
10451     * @see #invalidate(Rect)
10452     */
10453    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10454        // We try only with the AttachInfo because there's no point in invalidating
10455        // if we are not attached to our window
10456        final AttachInfo attachInfo = mAttachInfo;
10457        if (attachInfo != null) {
10458            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10459            info.target = this;
10460            info.left = left;
10461            info.top = top;
10462            info.right = right;
10463            info.bottom = bottom;
10464
10465            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10466        }
10467    }
10468
10469    /**
10470     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10471     * This event is sent at most once every
10472     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10473     */
10474    private void postSendViewScrolledAccessibilityEventCallback() {
10475        if (mSendViewScrolledAccessibilityEvent == null) {
10476            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10477        }
10478        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10479            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10480            postDelayed(mSendViewScrolledAccessibilityEvent,
10481                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10482        }
10483    }
10484
10485    /**
10486     * Called by a parent to request that a child update its values for mScrollX
10487     * and mScrollY if necessary. This will typically be done if the child is
10488     * animating a scroll using a {@link android.widget.Scroller Scroller}
10489     * object.
10490     */
10491    public void computeScroll() {
10492    }
10493
10494    /**
10495     * <p>Indicate whether the horizontal edges are faded when the view is
10496     * scrolled horizontally.</p>
10497     *
10498     * @return true if the horizontal edges should are faded on scroll, false
10499     *         otherwise
10500     *
10501     * @see #setHorizontalFadingEdgeEnabled(boolean)
10502     *
10503     * @attr ref android.R.styleable#View_requiresFadingEdge
10504     */
10505    public boolean isHorizontalFadingEdgeEnabled() {
10506        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10507    }
10508
10509    /**
10510     * <p>Define whether the horizontal edges should be faded when this view
10511     * is scrolled horizontally.</p>
10512     *
10513     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10514     *                                    be faded when the view is scrolled
10515     *                                    horizontally
10516     *
10517     * @see #isHorizontalFadingEdgeEnabled()
10518     *
10519     * @attr ref android.R.styleable#View_requiresFadingEdge
10520     */
10521    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10522        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10523            if (horizontalFadingEdgeEnabled) {
10524                initScrollCache();
10525            }
10526
10527            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10528        }
10529    }
10530
10531    /**
10532     * <p>Indicate whether the vertical edges are faded when the view is
10533     * scrolled horizontally.</p>
10534     *
10535     * @return true if the vertical edges should are faded on scroll, false
10536     *         otherwise
10537     *
10538     * @see #setVerticalFadingEdgeEnabled(boolean)
10539     *
10540     * @attr ref android.R.styleable#View_requiresFadingEdge
10541     */
10542    public boolean isVerticalFadingEdgeEnabled() {
10543        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10544    }
10545
10546    /**
10547     * <p>Define whether the vertical edges should be faded when this view
10548     * is scrolled vertically.</p>
10549     *
10550     * @param verticalFadingEdgeEnabled true if the vertical edges should
10551     *                                  be faded when the view is scrolled
10552     *                                  vertically
10553     *
10554     * @see #isVerticalFadingEdgeEnabled()
10555     *
10556     * @attr ref android.R.styleable#View_requiresFadingEdge
10557     */
10558    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10559        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10560            if (verticalFadingEdgeEnabled) {
10561                initScrollCache();
10562            }
10563
10564            mViewFlags ^= FADING_EDGE_VERTICAL;
10565        }
10566    }
10567
10568    /**
10569     * Returns the strength, or intensity, of the top faded edge. The strength is
10570     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10571     * returns 0.0 or 1.0 but no value in between.
10572     *
10573     * Subclasses should override this method to provide a smoother fade transition
10574     * when scrolling occurs.
10575     *
10576     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10577     */
10578    protected float getTopFadingEdgeStrength() {
10579        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10580    }
10581
10582    /**
10583     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10584     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10585     * returns 0.0 or 1.0 but no value in between.
10586     *
10587     * Subclasses should override this method to provide a smoother fade transition
10588     * when scrolling occurs.
10589     *
10590     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10591     */
10592    protected float getBottomFadingEdgeStrength() {
10593        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10594                computeVerticalScrollRange() ? 1.0f : 0.0f;
10595    }
10596
10597    /**
10598     * Returns the strength, or intensity, of the left faded edge. The strength is
10599     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10600     * returns 0.0 or 1.0 but no value in between.
10601     *
10602     * Subclasses should override this method to provide a smoother fade transition
10603     * when scrolling occurs.
10604     *
10605     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10606     */
10607    protected float getLeftFadingEdgeStrength() {
10608        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10609    }
10610
10611    /**
10612     * Returns the strength, or intensity, of the right faded edge. The strength is
10613     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10614     * returns 0.0 or 1.0 but no value in between.
10615     *
10616     * Subclasses should override this method to provide a smoother fade transition
10617     * when scrolling occurs.
10618     *
10619     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10620     */
10621    protected float getRightFadingEdgeStrength() {
10622        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10623                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10624    }
10625
10626    /**
10627     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10628     * scrollbar is not drawn by default.</p>
10629     *
10630     * @return true if the horizontal scrollbar should be painted, false
10631     *         otherwise
10632     *
10633     * @see #setHorizontalScrollBarEnabled(boolean)
10634     */
10635    public boolean isHorizontalScrollBarEnabled() {
10636        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10637    }
10638
10639    /**
10640     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10641     * scrollbar is not drawn by default.</p>
10642     *
10643     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10644     *                                   be painted
10645     *
10646     * @see #isHorizontalScrollBarEnabled()
10647     */
10648    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10649        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10650            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10651            computeOpaqueFlags();
10652            resolvePadding();
10653        }
10654    }
10655
10656    /**
10657     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10658     * scrollbar is not drawn by default.</p>
10659     *
10660     * @return true if the vertical scrollbar should be painted, false
10661     *         otherwise
10662     *
10663     * @see #setVerticalScrollBarEnabled(boolean)
10664     */
10665    public boolean isVerticalScrollBarEnabled() {
10666        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10667    }
10668
10669    /**
10670     * <p>Define whether the vertical scrollbar should be drawn or not. The
10671     * scrollbar is not drawn by default.</p>
10672     *
10673     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10674     *                                 be painted
10675     *
10676     * @see #isVerticalScrollBarEnabled()
10677     */
10678    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10679        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10680            mViewFlags ^= SCROLLBARS_VERTICAL;
10681            computeOpaqueFlags();
10682            resolvePadding();
10683        }
10684    }
10685
10686    /**
10687     * @hide
10688     */
10689    protected void recomputePadding() {
10690        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10691    }
10692
10693    /**
10694     * Define whether scrollbars will fade when the view is not scrolling.
10695     *
10696     * @param fadeScrollbars wheter to enable fading
10697     *
10698     * @attr ref android.R.styleable#View_fadeScrollbars
10699     */
10700    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10701        initScrollCache();
10702        final ScrollabilityCache scrollabilityCache = mScrollCache;
10703        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10704        if (fadeScrollbars) {
10705            scrollabilityCache.state = ScrollabilityCache.OFF;
10706        } else {
10707            scrollabilityCache.state = ScrollabilityCache.ON;
10708        }
10709    }
10710
10711    /**
10712     *
10713     * Returns true if scrollbars will fade when this view is not scrolling
10714     *
10715     * @return true if scrollbar fading is enabled
10716     *
10717     * @attr ref android.R.styleable#View_fadeScrollbars
10718     */
10719    public boolean isScrollbarFadingEnabled() {
10720        return mScrollCache != null && mScrollCache.fadeScrollBars;
10721    }
10722
10723    /**
10724     *
10725     * Returns the delay before scrollbars fade.
10726     *
10727     * @return the delay before scrollbars fade
10728     *
10729     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10730     */
10731    public int getScrollBarDefaultDelayBeforeFade() {
10732        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10733                mScrollCache.scrollBarDefaultDelayBeforeFade;
10734    }
10735
10736    /**
10737     * Define the delay before scrollbars fade.
10738     *
10739     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10740     *
10741     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10742     */
10743    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10744        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10745    }
10746
10747    /**
10748     *
10749     * Returns the scrollbar fade duration.
10750     *
10751     * @return the scrollbar fade duration
10752     *
10753     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10754     */
10755    public int getScrollBarFadeDuration() {
10756        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10757                mScrollCache.scrollBarFadeDuration;
10758    }
10759
10760    /**
10761     * Define the scrollbar fade duration.
10762     *
10763     * @param scrollBarFadeDuration - the scrollbar fade duration
10764     *
10765     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10766     */
10767    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10768        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10769    }
10770
10771    /**
10772     *
10773     * Returns the scrollbar size.
10774     *
10775     * @return the scrollbar size
10776     *
10777     * @attr ref android.R.styleable#View_scrollbarSize
10778     */
10779    public int getScrollBarSize() {
10780        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10781                mScrollCache.scrollBarSize;
10782    }
10783
10784    /**
10785     * Define the scrollbar size.
10786     *
10787     * @param scrollBarSize - the scrollbar size
10788     *
10789     * @attr ref android.R.styleable#View_scrollbarSize
10790     */
10791    public void setScrollBarSize(int scrollBarSize) {
10792        getScrollCache().scrollBarSize = scrollBarSize;
10793    }
10794
10795    /**
10796     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10797     * inset. When inset, they add to the padding of the view. And the scrollbars
10798     * can be drawn inside the padding area or on the edge of the view. For example,
10799     * if a view has a background drawable and you want to draw the scrollbars
10800     * inside the padding specified by the drawable, you can use
10801     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10802     * appear at the edge of the view, ignoring the padding, then you can use
10803     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10804     * @param style the style of the scrollbars. Should be one of
10805     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10806     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10807     * @see #SCROLLBARS_INSIDE_OVERLAY
10808     * @see #SCROLLBARS_INSIDE_INSET
10809     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10810     * @see #SCROLLBARS_OUTSIDE_INSET
10811     *
10812     * @attr ref android.R.styleable#View_scrollbarStyle
10813     */
10814    public void setScrollBarStyle(int style) {
10815        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10816            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10817            computeOpaqueFlags();
10818            resolvePadding();
10819        }
10820    }
10821
10822    /**
10823     * <p>Returns the current scrollbar style.</p>
10824     * @return the current scrollbar style
10825     * @see #SCROLLBARS_INSIDE_OVERLAY
10826     * @see #SCROLLBARS_INSIDE_INSET
10827     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10828     * @see #SCROLLBARS_OUTSIDE_INSET
10829     *
10830     * @attr ref android.R.styleable#View_scrollbarStyle
10831     */
10832    @ViewDebug.ExportedProperty(mapping = {
10833            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10834            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10835            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10836            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10837    })
10838    public int getScrollBarStyle() {
10839        return mViewFlags & SCROLLBARS_STYLE_MASK;
10840    }
10841
10842    /**
10843     * <p>Compute the horizontal range that the horizontal scrollbar
10844     * represents.</p>
10845     *
10846     * <p>The range is expressed in arbitrary units that must be the same as the
10847     * units used by {@link #computeHorizontalScrollExtent()} and
10848     * {@link #computeHorizontalScrollOffset()}.</p>
10849     *
10850     * <p>The default range is the drawing width of this view.</p>
10851     *
10852     * @return the total horizontal range represented by the horizontal
10853     *         scrollbar
10854     *
10855     * @see #computeHorizontalScrollExtent()
10856     * @see #computeHorizontalScrollOffset()
10857     * @see android.widget.ScrollBarDrawable
10858     */
10859    protected int computeHorizontalScrollRange() {
10860        return getWidth();
10861    }
10862
10863    /**
10864     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10865     * within the horizontal range. This value is used to compute the position
10866     * of the thumb within the scrollbar's track.</p>
10867     *
10868     * <p>The range is expressed in arbitrary units that must be the same as the
10869     * units used by {@link #computeHorizontalScrollRange()} and
10870     * {@link #computeHorizontalScrollExtent()}.</p>
10871     *
10872     * <p>The default offset is the scroll offset of this view.</p>
10873     *
10874     * @return the horizontal offset of the scrollbar's thumb
10875     *
10876     * @see #computeHorizontalScrollRange()
10877     * @see #computeHorizontalScrollExtent()
10878     * @see android.widget.ScrollBarDrawable
10879     */
10880    protected int computeHorizontalScrollOffset() {
10881        return mScrollX;
10882    }
10883
10884    /**
10885     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10886     * within the horizontal range. This value is used to compute the length
10887     * of the thumb within the scrollbar's track.</p>
10888     *
10889     * <p>The range is expressed in arbitrary units that must be the same as the
10890     * units used by {@link #computeHorizontalScrollRange()} and
10891     * {@link #computeHorizontalScrollOffset()}.</p>
10892     *
10893     * <p>The default extent is the drawing width of this view.</p>
10894     *
10895     * @return the horizontal extent of the scrollbar's thumb
10896     *
10897     * @see #computeHorizontalScrollRange()
10898     * @see #computeHorizontalScrollOffset()
10899     * @see android.widget.ScrollBarDrawable
10900     */
10901    protected int computeHorizontalScrollExtent() {
10902        return getWidth();
10903    }
10904
10905    /**
10906     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10907     *
10908     * <p>The range is expressed in arbitrary units that must be the same as the
10909     * units used by {@link #computeVerticalScrollExtent()} and
10910     * {@link #computeVerticalScrollOffset()}.</p>
10911     *
10912     * @return the total vertical range represented by the vertical scrollbar
10913     *
10914     * <p>The default range is the drawing height of this view.</p>
10915     *
10916     * @see #computeVerticalScrollExtent()
10917     * @see #computeVerticalScrollOffset()
10918     * @see android.widget.ScrollBarDrawable
10919     */
10920    protected int computeVerticalScrollRange() {
10921        return getHeight();
10922    }
10923
10924    /**
10925     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10926     * within the horizontal range. This value is used to compute the position
10927     * of the thumb within the scrollbar's track.</p>
10928     *
10929     * <p>The range is expressed in arbitrary units that must be the same as the
10930     * units used by {@link #computeVerticalScrollRange()} and
10931     * {@link #computeVerticalScrollExtent()}.</p>
10932     *
10933     * <p>The default offset is the scroll offset of this view.</p>
10934     *
10935     * @return the vertical offset of the scrollbar's thumb
10936     *
10937     * @see #computeVerticalScrollRange()
10938     * @see #computeVerticalScrollExtent()
10939     * @see android.widget.ScrollBarDrawable
10940     */
10941    protected int computeVerticalScrollOffset() {
10942        return mScrollY;
10943    }
10944
10945    /**
10946     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10947     * within the vertical range. This value is used to compute the length
10948     * of the thumb within the scrollbar's track.</p>
10949     *
10950     * <p>The range is expressed in arbitrary units that must be the same as the
10951     * units used by {@link #computeVerticalScrollRange()} and
10952     * {@link #computeVerticalScrollOffset()}.</p>
10953     *
10954     * <p>The default extent is the drawing height of this view.</p>
10955     *
10956     * @return the vertical extent of the scrollbar's thumb
10957     *
10958     * @see #computeVerticalScrollRange()
10959     * @see #computeVerticalScrollOffset()
10960     * @see android.widget.ScrollBarDrawable
10961     */
10962    protected int computeVerticalScrollExtent() {
10963        return getHeight();
10964    }
10965
10966    /**
10967     * Check if this view can be scrolled horizontally in a certain direction.
10968     *
10969     * @param direction Negative to check scrolling left, positive to check scrolling right.
10970     * @return true if this view can be scrolled in the specified direction, false otherwise.
10971     */
10972    public boolean canScrollHorizontally(int direction) {
10973        final int offset = computeHorizontalScrollOffset();
10974        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10975        if (range == 0) return false;
10976        if (direction < 0) {
10977            return offset > 0;
10978        } else {
10979            return offset < range - 1;
10980        }
10981    }
10982
10983    /**
10984     * Check if this view can be scrolled vertically in a certain direction.
10985     *
10986     * @param direction Negative to check scrolling up, positive to check scrolling down.
10987     * @return true if this view can be scrolled in the specified direction, false otherwise.
10988     */
10989    public boolean canScrollVertically(int direction) {
10990        final int offset = computeVerticalScrollOffset();
10991        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10992        if (range == 0) return false;
10993        if (direction < 0) {
10994            return offset > 0;
10995        } else {
10996            return offset < range - 1;
10997        }
10998    }
10999
11000    /**
11001     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11002     * scrollbars are painted only if they have been awakened first.</p>
11003     *
11004     * @param canvas the canvas on which to draw the scrollbars
11005     *
11006     * @see #awakenScrollBars(int)
11007     */
11008    protected final void onDrawScrollBars(Canvas canvas) {
11009        // scrollbars are drawn only when the animation is running
11010        final ScrollabilityCache cache = mScrollCache;
11011        if (cache != null) {
11012
11013            int state = cache.state;
11014
11015            if (state == ScrollabilityCache.OFF) {
11016                return;
11017            }
11018
11019            boolean invalidate = false;
11020
11021            if (state == ScrollabilityCache.FADING) {
11022                // We're fading -- get our fade interpolation
11023                if (cache.interpolatorValues == null) {
11024                    cache.interpolatorValues = new float[1];
11025                }
11026
11027                float[] values = cache.interpolatorValues;
11028
11029                // Stops the animation if we're done
11030                if (cache.scrollBarInterpolator.timeToValues(values) ==
11031                        Interpolator.Result.FREEZE_END) {
11032                    cache.state = ScrollabilityCache.OFF;
11033                } else {
11034                    cache.scrollBar.setAlpha(Math.round(values[0]));
11035                }
11036
11037                // This will make the scroll bars inval themselves after
11038                // drawing. We only want this when we're fading so that
11039                // we prevent excessive redraws
11040                invalidate = true;
11041            } else {
11042                // We're just on -- but we may have been fading before so
11043                // reset alpha
11044                cache.scrollBar.setAlpha(255);
11045            }
11046
11047
11048            final int viewFlags = mViewFlags;
11049
11050            final boolean drawHorizontalScrollBar =
11051                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11052            final boolean drawVerticalScrollBar =
11053                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11054                && !isVerticalScrollBarHidden();
11055
11056            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11057                final int width = mRight - mLeft;
11058                final int height = mBottom - mTop;
11059
11060                final ScrollBarDrawable scrollBar = cache.scrollBar;
11061
11062                final int scrollX = mScrollX;
11063                final int scrollY = mScrollY;
11064                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11065
11066                int left, top, right, bottom;
11067
11068                if (drawHorizontalScrollBar) {
11069                    int size = scrollBar.getSize(false);
11070                    if (size <= 0) {
11071                        size = cache.scrollBarSize;
11072                    }
11073
11074                    scrollBar.setParameters(computeHorizontalScrollRange(),
11075                                            computeHorizontalScrollOffset(),
11076                                            computeHorizontalScrollExtent(), false);
11077                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11078                            getVerticalScrollbarWidth() : 0;
11079                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11080                    left = scrollX + (mPaddingLeft & inside);
11081                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11082                    bottom = top + size;
11083                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11084                    if (invalidate) {
11085                        invalidate(left, top, right, bottom);
11086                    }
11087                }
11088
11089                if (drawVerticalScrollBar) {
11090                    int size = scrollBar.getSize(true);
11091                    if (size <= 0) {
11092                        size = cache.scrollBarSize;
11093                    }
11094
11095                    scrollBar.setParameters(computeVerticalScrollRange(),
11096                                            computeVerticalScrollOffset(),
11097                                            computeVerticalScrollExtent(), true);
11098                    switch (mVerticalScrollbarPosition) {
11099                        default:
11100                        case SCROLLBAR_POSITION_DEFAULT:
11101                        case SCROLLBAR_POSITION_RIGHT:
11102                            left = scrollX + width - size - (mUserPaddingRight & inside);
11103                            break;
11104                        case SCROLLBAR_POSITION_LEFT:
11105                            left = scrollX + (mUserPaddingLeft & inside);
11106                            break;
11107                    }
11108                    top = scrollY + (mPaddingTop & inside);
11109                    right = left + size;
11110                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11111                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11112                    if (invalidate) {
11113                        invalidate(left, top, right, bottom);
11114                    }
11115                }
11116            }
11117        }
11118    }
11119
11120    /**
11121     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11122     * FastScroller is visible.
11123     * @return whether to temporarily hide the vertical scrollbar
11124     * @hide
11125     */
11126    protected boolean isVerticalScrollBarHidden() {
11127        return false;
11128    }
11129
11130    /**
11131     * <p>Draw the horizontal scrollbar if
11132     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11133     *
11134     * @param canvas the canvas on which to draw the scrollbar
11135     * @param scrollBar the scrollbar's drawable
11136     *
11137     * @see #isHorizontalScrollBarEnabled()
11138     * @see #computeHorizontalScrollRange()
11139     * @see #computeHorizontalScrollExtent()
11140     * @see #computeHorizontalScrollOffset()
11141     * @see android.widget.ScrollBarDrawable
11142     * @hide
11143     */
11144    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11145            int l, int t, int r, int b) {
11146        scrollBar.setBounds(l, t, r, b);
11147        scrollBar.draw(canvas);
11148    }
11149
11150    /**
11151     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11152     * returns true.</p>
11153     *
11154     * @param canvas the canvas on which to draw the scrollbar
11155     * @param scrollBar the scrollbar's drawable
11156     *
11157     * @see #isVerticalScrollBarEnabled()
11158     * @see #computeVerticalScrollRange()
11159     * @see #computeVerticalScrollExtent()
11160     * @see #computeVerticalScrollOffset()
11161     * @see android.widget.ScrollBarDrawable
11162     * @hide
11163     */
11164    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11165            int l, int t, int r, int b) {
11166        scrollBar.setBounds(l, t, r, b);
11167        scrollBar.draw(canvas);
11168    }
11169
11170    /**
11171     * Implement this to do your drawing.
11172     *
11173     * @param canvas the canvas on which the background will be drawn
11174     */
11175    protected void onDraw(Canvas canvas) {
11176    }
11177
11178    /*
11179     * Caller is responsible for calling requestLayout if necessary.
11180     * (This allows addViewInLayout to not request a new layout.)
11181     */
11182    void assignParent(ViewParent parent) {
11183        if (mParent == null) {
11184            mParent = parent;
11185        } else if (parent == null) {
11186            mParent = null;
11187        } else {
11188            throw new RuntimeException("view " + this + " being added, but"
11189                    + " it already has a parent");
11190        }
11191    }
11192
11193    /**
11194     * This is called when the view is attached to a window.  At this point it
11195     * has a Surface and will start drawing.  Note that this function is
11196     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11197     * however it may be called any time before the first onDraw -- including
11198     * before or after {@link #onMeasure(int, int)}.
11199     *
11200     * @see #onDetachedFromWindow()
11201     */
11202    protected void onAttachedToWindow() {
11203        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11204            mParent.requestTransparentRegion(this);
11205        }
11206
11207        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11208            initialAwakenScrollBars();
11209            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11210        }
11211
11212        jumpDrawablesToCurrentState();
11213
11214        // Order is important here: LayoutDirection MUST be resolved before Padding
11215        // and TextDirection
11216        resolveLayoutDirection();
11217        resolvePadding();
11218        resolveTextDirection();
11219        resolveTextAlignment();
11220
11221        clearAccessibilityFocus();
11222        if (isFocused()) {
11223            InputMethodManager imm = InputMethodManager.peekInstance();
11224            imm.focusIn(this);
11225        }
11226
11227        if (mAttachInfo != null && mDisplayList != null) {
11228            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11229        }
11230    }
11231
11232    /**
11233     * @see #onScreenStateChanged(int)
11234     */
11235    void dispatchScreenStateChanged(int screenState) {
11236        onScreenStateChanged(screenState);
11237    }
11238
11239    /**
11240     * This method is called whenever the state of the screen this view is
11241     * attached to changes. A state change will usually occurs when the screen
11242     * turns on or off (whether it happens automatically or the user does it
11243     * manually.)
11244     *
11245     * @param screenState The new state of the screen. Can be either
11246     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11247     */
11248    public void onScreenStateChanged(int screenState) {
11249    }
11250
11251    /**
11252     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11253     */
11254    private boolean hasRtlSupport() {
11255        return mContext.getApplicationInfo().hasRtlSupport();
11256    }
11257
11258    /**
11259     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11260     * that the parent directionality can and will be resolved before its children.
11261     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11262     * @hide
11263     */
11264    public void resolveLayoutDirection() {
11265        // Clear any previous layout direction resolution
11266        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11267
11268        if (hasRtlSupport()) {
11269            // Set resolved depending on layout direction
11270            switch (getLayoutDirection()) {
11271                case LAYOUT_DIRECTION_INHERIT:
11272                    // If this is root view, no need to look at parent's layout dir.
11273                    if (canResolveLayoutDirection()) {
11274                        ViewGroup viewGroup = ((ViewGroup) mParent);
11275
11276                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11277                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11278                        }
11279                    } else {
11280                        // Nothing to do, LTR by default
11281                    }
11282                    break;
11283                case LAYOUT_DIRECTION_RTL:
11284                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11285                    break;
11286                case LAYOUT_DIRECTION_LOCALE:
11287                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11288                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11289                    }
11290                    break;
11291                default:
11292                    // Nothing to do, LTR by default
11293            }
11294        }
11295
11296        // Set to resolved
11297        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11298        onResolvedLayoutDirectionChanged();
11299        // Resolve padding
11300        resolvePadding();
11301    }
11302
11303    /**
11304     * Called when layout direction has been resolved.
11305     *
11306     * The default implementation does nothing.
11307     * @hide
11308     */
11309    public void onResolvedLayoutDirectionChanged() {
11310    }
11311
11312    /**
11313     * Resolve padding depending on layout direction.
11314     * @hide
11315     */
11316    public void resolvePadding() {
11317        // If the user specified the absolute padding (either with android:padding or
11318        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11319        // use the default padding or the padding from the background drawable
11320        // (stored at this point in mPadding*)
11321        int resolvedLayoutDirection = getResolvedLayoutDirection();
11322        switch (resolvedLayoutDirection) {
11323            case LAYOUT_DIRECTION_RTL:
11324                // Start user padding override Right user padding. Otherwise, if Right user
11325                // padding is not defined, use the default Right padding. If Right user padding
11326                // is defined, just use it.
11327                if (mUserPaddingStart >= 0) {
11328                    mUserPaddingRight = mUserPaddingStart;
11329                } else if (mUserPaddingRight < 0) {
11330                    mUserPaddingRight = mPaddingRight;
11331                }
11332                if (mUserPaddingEnd >= 0) {
11333                    mUserPaddingLeft = mUserPaddingEnd;
11334                } else if (mUserPaddingLeft < 0) {
11335                    mUserPaddingLeft = mPaddingLeft;
11336                }
11337                break;
11338            case LAYOUT_DIRECTION_LTR:
11339            default:
11340                // Start user padding override Left user padding. Otherwise, if Left user
11341                // padding is not defined, use the default left padding. If Left user padding
11342                // is defined, just use it.
11343                if (mUserPaddingStart >= 0) {
11344                    mUserPaddingLeft = mUserPaddingStart;
11345                } else if (mUserPaddingLeft < 0) {
11346                    mUserPaddingLeft = mPaddingLeft;
11347                }
11348                if (mUserPaddingEnd >= 0) {
11349                    mUserPaddingRight = mUserPaddingEnd;
11350                } else if (mUserPaddingRight < 0) {
11351                    mUserPaddingRight = mPaddingRight;
11352                }
11353        }
11354
11355        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11356
11357        if(isPaddingRelative()) {
11358            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11359        } else {
11360            recomputePadding();
11361        }
11362        onPaddingChanged(resolvedLayoutDirection);
11363    }
11364
11365    /**
11366     * Resolve padding depending on the layout direction. Subclasses that care about
11367     * padding resolution should override this method. The default implementation does
11368     * nothing.
11369     *
11370     * @param layoutDirection the direction of the layout
11371     *
11372     * @see {@link #LAYOUT_DIRECTION_LTR}
11373     * @see {@link #LAYOUT_DIRECTION_RTL}
11374     * @hide
11375     */
11376    public void onPaddingChanged(int layoutDirection) {
11377    }
11378
11379    /**
11380     * Check if layout direction resolution can be done.
11381     *
11382     * @return true if layout direction resolution can be done otherwise return false.
11383     * @hide
11384     */
11385    public boolean canResolveLayoutDirection() {
11386        switch (getLayoutDirection()) {
11387            case LAYOUT_DIRECTION_INHERIT:
11388                return (mParent != null) && (mParent instanceof ViewGroup);
11389            default:
11390                return true;
11391        }
11392    }
11393
11394    /**
11395     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11396     * when reset is done.
11397     * @hide
11398     */
11399    public void resetResolvedLayoutDirection() {
11400        // Reset the current resolved bits
11401        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11402        onResolvedLayoutDirectionReset();
11403        // Reset also the text direction
11404        resetResolvedTextDirection();
11405    }
11406
11407    /**
11408     * Called during reset of resolved layout direction.
11409     *
11410     * Subclasses need to override this method to clear cached information that depends on the
11411     * resolved layout direction, or to inform child views that inherit their layout direction.
11412     *
11413     * The default implementation does nothing.
11414     * @hide
11415     */
11416    public void onResolvedLayoutDirectionReset() {
11417    }
11418
11419    /**
11420     * Check if a Locale uses an RTL script.
11421     *
11422     * @param locale Locale to check
11423     * @return true if the Locale uses an RTL script.
11424     * @hide
11425     */
11426    protected static boolean isLayoutDirectionRtl(Locale locale) {
11427        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11428    }
11429
11430    /**
11431     * This is called when the view is detached from a window.  At this point it
11432     * no longer has a surface for drawing.
11433     *
11434     * @see #onAttachedToWindow()
11435     */
11436    protected void onDetachedFromWindow() {
11437        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11438
11439        removeUnsetPressCallback();
11440        removeLongPressCallback();
11441        removePerformClickCallback();
11442        removeSendViewScrolledAccessibilityEventCallback();
11443
11444        destroyDrawingCache();
11445
11446        destroyLayer(false);
11447
11448        if (mAttachInfo != null) {
11449            if (mDisplayList != null) {
11450                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11451            }
11452            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11453        } else {
11454            if (mDisplayList != null) {
11455                // Should never happen
11456                mDisplayList.invalidate();
11457            }
11458        }
11459
11460        mCurrentAnimation = null;
11461
11462        resetResolvedLayoutDirection();
11463        resetResolvedTextAlignment();
11464        resetAccessibilityStateChanged();
11465    }
11466
11467    /**
11468     * @return The number of times this view has been attached to a window
11469     */
11470    protected int getWindowAttachCount() {
11471        return mWindowAttachCount;
11472    }
11473
11474    /**
11475     * Retrieve a unique token identifying the window this view is attached to.
11476     * @return Return the window's token for use in
11477     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11478     */
11479    public IBinder getWindowToken() {
11480        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11481    }
11482
11483    /**
11484     * Retrieve a unique token identifying the top-level "real" window of
11485     * the window that this view is attached to.  That is, this is like
11486     * {@link #getWindowToken}, except if the window this view in is a panel
11487     * window (attached to another containing window), then the token of
11488     * the containing window is returned instead.
11489     *
11490     * @return Returns the associated window token, either
11491     * {@link #getWindowToken()} or the containing window's token.
11492     */
11493    public IBinder getApplicationWindowToken() {
11494        AttachInfo ai = mAttachInfo;
11495        if (ai != null) {
11496            IBinder appWindowToken = ai.mPanelParentWindowToken;
11497            if (appWindowToken == null) {
11498                appWindowToken = ai.mWindowToken;
11499            }
11500            return appWindowToken;
11501        }
11502        return null;
11503    }
11504
11505    /**
11506     * Retrieve private session object this view hierarchy is using to
11507     * communicate with the window manager.
11508     * @return the session object to communicate with the window manager
11509     */
11510    /*package*/ IWindowSession getWindowSession() {
11511        return mAttachInfo != null ? mAttachInfo.mSession : null;
11512    }
11513
11514    /**
11515     * @param info the {@link android.view.View.AttachInfo} to associated with
11516     *        this view
11517     */
11518    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11519        //System.out.println("Attached! " + this);
11520        mAttachInfo = info;
11521        mWindowAttachCount++;
11522        // We will need to evaluate the drawable state at least once.
11523        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11524        if (mFloatingTreeObserver != null) {
11525            info.mTreeObserver.merge(mFloatingTreeObserver);
11526            mFloatingTreeObserver = null;
11527        }
11528        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11529            mAttachInfo.mScrollContainers.add(this);
11530            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11531        }
11532        performCollectViewAttributes(mAttachInfo, visibility);
11533        onAttachedToWindow();
11534
11535        ListenerInfo li = mListenerInfo;
11536        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11537                li != null ? li.mOnAttachStateChangeListeners : null;
11538        if (listeners != null && listeners.size() > 0) {
11539            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11540            // perform the dispatching. The iterator is a safe guard against listeners that
11541            // could mutate the list by calling the various add/remove methods. This prevents
11542            // the array from being modified while we iterate it.
11543            for (OnAttachStateChangeListener listener : listeners) {
11544                listener.onViewAttachedToWindow(this);
11545            }
11546        }
11547
11548        int vis = info.mWindowVisibility;
11549        if (vis != GONE) {
11550            onWindowVisibilityChanged(vis);
11551        }
11552        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11553            // If nobody has evaluated the drawable state yet, then do it now.
11554            refreshDrawableState();
11555        }
11556    }
11557
11558    void dispatchDetachedFromWindow() {
11559        AttachInfo info = mAttachInfo;
11560        if (info != null) {
11561            int vis = info.mWindowVisibility;
11562            if (vis != GONE) {
11563                onWindowVisibilityChanged(GONE);
11564            }
11565        }
11566
11567        onDetachedFromWindow();
11568
11569        ListenerInfo li = mListenerInfo;
11570        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11571                li != null ? li.mOnAttachStateChangeListeners : null;
11572        if (listeners != null && listeners.size() > 0) {
11573            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11574            // perform the dispatching. The iterator is a safe guard against listeners that
11575            // could mutate the list by calling the various add/remove methods. This prevents
11576            // the array from being modified while we iterate it.
11577            for (OnAttachStateChangeListener listener : listeners) {
11578                listener.onViewDetachedFromWindow(this);
11579            }
11580        }
11581
11582        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11583            mAttachInfo.mScrollContainers.remove(this);
11584            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11585        }
11586
11587        mAttachInfo = null;
11588    }
11589
11590    /**
11591     * Store this view hierarchy's frozen state into the given container.
11592     *
11593     * @param container The SparseArray in which to save the view's state.
11594     *
11595     * @see #restoreHierarchyState(android.util.SparseArray)
11596     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11597     * @see #onSaveInstanceState()
11598     */
11599    public void saveHierarchyState(SparseArray<Parcelable> container) {
11600        dispatchSaveInstanceState(container);
11601    }
11602
11603    /**
11604     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11605     * this view and its children. May be overridden to modify how freezing happens to a
11606     * view's children; for example, some views may want to not store state for their children.
11607     *
11608     * @param container The SparseArray in which to save the view's state.
11609     *
11610     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11611     * @see #saveHierarchyState(android.util.SparseArray)
11612     * @see #onSaveInstanceState()
11613     */
11614    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11615        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11616            mPrivateFlags &= ~SAVE_STATE_CALLED;
11617            Parcelable state = onSaveInstanceState();
11618            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11619                throw new IllegalStateException(
11620                        "Derived class did not call super.onSaveInstanceState()");
11621            }
11622            if (state != null) {
11623                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11624                // + ": " + state);
11625                container.put(mID, state);
11626            }
11627        }
11628    }
11629
11630    /**
11631     * Hook allowing a view to generate a representation of its internal state
11632     * that can later be used to create a new instance with that same state.
11633     * This state should only contain information that is not persistent or can
11634     * not be reconstructed later. For example, you will never store your
11635     * current position on screen because that will be computed again when a
11636     * new instance of the view is placed in its view hierarchy.
11637     * <p>
11638     * Some examples of things you may store here: the current cursor position
11639     * in a text view (but usually not the text itself since that is stored in a
11640     * content provider or other persistent storage), the currently selected
11641     * item in a list view.
11642     *
11643     * @return Returns a Parcelable object containing the view's current dynamic
11644     *         state, or null if there is nothing interesting to save. The
11645     *         default implementation returns null.
11646     * @see #onRestoreInstanceState(android.os.Parcelable)
11647     * @see #saveHierarchyState(android.util.SparseArray)
11648     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11649     * @see #setSaveEnabled(boolean)
11650     */
11651    protected Parcelable onSaveInstanceState() {
11652        mPrivateFlags |= SAVE_STATE_CALLED;
11653        return BaseSavedState.EMPTY_STATE;
11654    }
11655
11656    /**
11657     * Restore this view hierarchy's frozen state from the given container.
11658     *
11659     * @param container The SparseArray which holds previously frozen states.
11660     *
11661     * @see #saveHierarchyState(android.util.SparseArray)
11662     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11663     * @see #onRestoreInstanceState(android.os.Parcelable)
11664     */
11665    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11666        dispatchRestoreInstanceState(container);
11667    }
11668
11669    /**
11670     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11671     * state for this view and its children. May be overridden to modify how restoring
11672     * happens to a view's children; for example, some views may want to not store state
11673     * for their children.
11674     *
11675     * @param container The SparseArray which holds previously saved state.
11676     *
11677     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11678     * @see #restoreHierarchyState(android.util.SparseArray)
11679     * @see #onRestoreInstanceState(android.os.Parcelable)
11680     */
11681    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11682        if (mID != NO_ID) {
11683            Parcelable state = container.get(mID);
11684            if (state != null) {
11685                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11686                // + ": " + state);
11687                mPrivateFlags &= ~SAVE_STATE_CALLED;
11688                onRestoreInstanceState(state);
11689                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11690                    throw new IllegalStateException(
11691                            "Derived class did not call super.onRestoreInstanceState()");
11692                }
11693            }
11694        }
11695    }
11696
11697    /**
11698     * Hook allowing a view to re-apply a representation of its internal state that had previously
11699     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11700     * null state.
11701     *
11702     * @param state The frozen state that had previously been returned by
11703     *        {@link #onSaveInstanceState}.
11704     *
11705     * @see #onSaveInstanceState()
11706     * @see #restoreHierarchyState(android.util.SparseArray)
11707     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11708     */
11709    protected void onRestoreInstanceState(Parcelable state) {
11710        mPrivateFlags |= SAVE_STATE_CALLED;
11711        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11712            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11713                    + "received " + state.getClass().toString() + " instead. This usually happens "
11714                    + "when two views of different type have the same id in the same hierarchy. "
11715                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11716                    + "other views do not use the same id.");
11717        }
11718    }
11719
11720    /**
11721     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11722     *
11723     * @return the drawing start time in milliseconds
11724     */
11725    public long getDrawingTime() {
11726        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11727    }
11728
11729    /**
11730     * <p>Enables or disables the duplication of the parent's state into this view. When
11731     * duplication is enabled, this view gets its drawable state from its parent rather
11732     * than from its own internal properties.</p>
11733     *
11734     * <p>Note: in the current implementation, setting this property to true after the
11735     * view was added to a ViewGroup might have no effect at all. This property should
11736     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11737     *
11738     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11739     * property is enabled, an exception will be thrown.</p>
11740     *
11741     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11742     * parent, these states should not be affected by this method.</p>
11743     *
11744     * @param enabled True to enable duplication of the parent's drawable state, false
11745     *                to disable it.
11746     *
11747     * @see #getDrawableState()
11748     * @see #isDuplicateParentStateEnabled()
11749     */
11750    public void setDuplicateParentStateEnabled(boolean enabled) {
11751        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11752    }
11753
11754    /**
11755     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11756     *
11757     * @return True if this view's drawable state is duplicated from the parent,
11758     *         false otherwise
11759     *
11760     * @see #getDrawableState()
11761     * @see #setDuplicateParentStateEnabled(boolean)
11762     */
11763    public boolean isDuplicateParentStateEnabled() {
11764        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11765    }
11766
11767    /**
11768     * <p>Specifies the type of layer backing this view. The layer can be
11769     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11770     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11771     *
11772     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11773     * instance that controls how the layer is composed on screen. The following
11774     * properties of the paint are taken into account when composing the layer:</p>
11775     * <ul>
11776     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11777     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11778     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11779     * </ul>
11780     *
11781     * <p>If this view has an alpha value set to < 1.0 by calling
11782     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11783     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11784     * equivalent to setting a hardware layer on this view and providing a paint with
11785     * the desired alpha value.<p>
11786     *
11787     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11788     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11789     * for more information on when and how to use layers.</p>
11790     *
11791     * @param layerType The ype of layer to use with this view, must be one of
11792     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11793     *        {@link #LAYER_TYPE_HARDWARE}
11794     * @param paint The paint used to compose the layer. This argument is optional
11795     *        and can be null. It is ignored when the layer type is
11796     *        {@link #LAYER_TYPE_NONE}
11797     *
11798     * @see #getLayerType()
11799     * @see #LAYER_TYPE_NONE
11800     * @see #LAYER_TYPE_SOFTWARE
11801     * @see #LAYER_TYPE_HARDWARE
11802     * @see #setAlpha(float)
11803     *
11804     * @attr ref android.R.styleable#View_layerType
11805     */
11806    public void setLayerType(int layerType, Paint paint) {
11807        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11808            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11809                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11810        }
11811
11812        if (layerType == mLayerType) {
11813            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11814                mLayerPaint = paint == null ? new Paint() : paint;
11815                invalidateParentCaches();
11816                invalidate(true);
11817            }
11818            return;
11819        }
11820
11821        // Destroy any previous software drawing cache if needed
11822        switch (mLayerType) {
11823            case LAYER_TYPE_HARDWARE:
11824                destroyLayer(false);
11825                // fall through - non-accelerated views may use software layer mechanism instead
11826            case LAYER_TYPE_SOFTWARE:
11827                destroyDrawingCache();
11828                break;
11829            default:
11830                break;
11831        }
11832
11833        mLayerType = layerType;
11834        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11835        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11836        mLocalDirtyRect = layerDisabled ? null : new Rect();
11837
11838        invalidateParentCaches();
11839        invalidate(true);
11840    }
11841
11842    /**
11843     * Indicates whether this view has a static layer. A view with layer type
11844     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11845     * dynamic.
11846     */
11847    boolean hasStaticLayer() {
11848        return true;
11849    }
11850
11851    /**
11852     * Indicates what type of layer is currently associated with this view. By default
11853     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11854     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11855     * for more information on the different types of layers.
11856     *
11857     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11858     *         {@link #LAYER_TYPE_HARDWARE}
11859     *
11860     * @see #setLayerType(int, android.graphics.Paint)
11861     * @see #buildLayer()
11862     * @see #LAYER_TYPE_NONE
11863     * @see #LAYER_TYPE_SOFTWARE
11864     * @see #LAYER_TYPE_HARDWARE
11865     */
11866    public int getLayerType() {
11867        return mLayerType;
11868    }
11869
11870    /**
11871     * Forces this view's layer to be created and this view to be rendered
11872     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11873     * invoking this method will have no effect.
11874     *
11875     * This method can for instance be used to render a view into its layer before
11876     * starting an animation. If this view is complex, rendering into the layer
11877     * before starting the animation will avoid skipping frames.
11878     *
11879     * @throws IllegalStateException If this view is not attached to a window
11880     *
11881     * @see #setLayerType(int, android.graphics.Paint)
11882     */
11883    public void buildLayer() {
11884        if (mLayerType == LAYER_TYPE_NONE) return;
11885
11886        if (mAttachInfo == null) {
11887            throw new IllegalStateException("This view must be attached to a window first");
11888        }
11889
11890        switch (mLayerType) {
11891            case LAYER_TYPE_HARDWARE:
11892                if (mAttachInfo.mHardwareRenderer != null &&
11893                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11894                        mAttachInfo.mHardwareRenderer.validate()) {
11895                    getHardwareLayer();
11896                }
11897                break;
11898            case LAYER_TYPE_SOFTWARE:
11899                buildDrawingCache(true);
11900                break;
11901        }
11902    }
11903
11904    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11905    void flushLayer() {
11906        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11907            mHardwareLayer.flush();
11908        }
11909    }
11910
11911    /**
11912     * <p>Returns a hardware layer that can be used to draw this view again
11913     * without executing its draw method.</p>
11914     *
11915     * @return A HardwareLayer ready to render, or null if an error occurred.
11916     */
11917    HardwareLayer getHardwareLayer() {
11918        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11919                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11920            return null;
11921        }
11922
11923        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11924
11925        final int width = mRight - mLeft;
11926        final int height = mBottom - mTop;
11927
11928        if (width == 0 || height == 0) {
11929            return null;
11930        }
11931
11932        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11933            if (mHardwareLayer == null) {
11934                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11935                        width, height, isOpaque());
11936                mLocalDirtyRect.set(0, 0, width, height);
11937            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11938                mHardwareLayer.resize(width, height);
11939                mLocalDirtyRect.set(0, 0, width, height);
11940            }
11941
11942            // The layer is not valid if the underlying GPU resources cannot be allocated
11943            if (!mHardwareLayer.isValid()) {
11944                return null;
11945            }
11946
11947            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11948            mLocalDirtyRect.setEmpty();
11949        }
11950
11951        return mHardwareLayer;
11952    }
11953
11954    /**
11955     * Destroys this View's hardware layer if possible.
11956     *
11957     * @return True if the layer was destroyed, false otherwise.
11958     *
11959     * @see #setLayerType(int, android.graphics.Paint)
11960     * @see #LAYER_TYPE_HARDWARE
11961     */
11962    boolean destroyLayer(boolean valid) {
11963        if (mHardwareLayer != null) {
11964            AttachInfo info = mAttachInfo;
11965            if (info != null && info.mHardwareRenderer != null &&
11966                    info.mHardwareRenderer.isEnabled() &&
11967                    (valid || info.mHardwareRenderer.validate())) {
11968                mHardwareLayer.destroy();
11969                mHardwareLayer = null;
11970
11971                invalidate(true);
11972                invalidateParentCaches();
11973            }
11974            return true;
11975        }
11976        return false;
11977    }
11978
11979    /**
11980     * Destroys all hardware rendering resources. This method is invoked
11981     * when the system needs to reclaim resources. Upon execution of this
11982     * method, you should free any OpenGL resources created by the view.
11983     *
11984     * Note: you <strong>must</strong> call
11985     * <code>super.destroyHardwareResources()</code> when overriding
11986     * this method.
11987     *
11988     * @hide
11989     */
11990    protected void destroyHardwareResources() {
11991        destroyLayer(true);
11992    }
11993
11994    /**
11995     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11996     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11997     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11998     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11999     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12000     * null.</p>
12001     *
12002     * <p>Enabling the drawing cache is similar to
12003     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12004     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12005     * drawing cache has no effect on rendering because the system uses a different mechanism
12006     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12007     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12008     * for information on how to enable software and hardware layers.</p>
12009     *
12010     * <p>This API can be used to manually generate
12011     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12012     * {@link #getDrawingCache()}.</p>
12013     *
12014     * @param enabled true to enable the drawing cache, false otherwise
12015     *
12016     * @see #isDrawingCacheEnabled()
12017     * @see #getDrawingCache()
12018     * @see #buildDrawingCache()
12019     * @see #setLayerType(int, android.graphics.Paint)
12020     */
12021    public void setDrawingCacheEnabled(boolean enabled) {
12022        mCachingFailed = false;
12023        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12024    }
12025
12026    /**
12027     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12028     *
12029     * @return true if the drawing cache is enabled
12030     *
12031     * @see #setDrawingCacheEnabled(boolean)
12032     * @see #getDrawingCache()
12033     */
12034    @ViewDebug.ExportedProperty(category = "drawing")
12035    public boolean isDrawingCacheEnabled() {
12036        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12037    }
12038
12039    /**
12040     * Debugging utility which recursively outputs the dirty state of a view and its
12041     * descendants.
12042     *
12043     * @hide
12044     */
12045    @SuppressWarnings({"UnusedDeclaration"})
12046    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12047        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12048                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12049                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12050                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12051        if (clear) {
12052            mPrivateFlags &= clearMask;
12053        }
12054        if (this instanceof ViewGroup) {
12055            ViewGroup parent = (ViewGroup) this;
12056            final int count = parent.getChildCount();
12057            for (int i = 0; i < count; i++) {
12058                final View child = parent.getChildAt(i);
12059                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12060            }
12061        }
12062    }
12063
12064    /**
12065     * This method is used by ViewGroup to cause its children to restore or recreate their
12066     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12067     * to recreate its own display list, which would happen if it went through the normal
12068     * draw/dispatchDraw mechanisms.
12069     *
12070     * @hide
12071     */
12072    protected void dispatchGetDisplayList() {}
12073
12074    /**
12075     * A view that is not attached or hardware accelerated cannot create a display list.
12076     * This method checks these conditions and returns the appropriate result.
12077     *
12078     * @return true if view has the ability to create a display list, false otherwise.
12079     *
12080     * @hide
12081     */
12082    public boolean canHaveDisplayList() {
12083        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12084    }
12085
12086    /**
12087     * @return The HardwareRenderer associated with that view or null if hardware rendering
12088     * is not supported or this this has not been attached to a window.
12089     *
12090     * @hide
12091     */
12092    public HardwareRenderer getHardwareRenderer() {
12093        if (mAttachInfo != null) {
12094            return mAttachInfo.mHardwareRenderer;
12095        }
12096        return null;
12097    }
12098
12099    /**
12100     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12101     * Otherwise, the same display list will be returned (after having been rendered into
12102     * along the way, depending on the invalidation state of the view).
12103     *
12104     * @param displayList The previous version of this displayList, could be null.
12105     * @param isLayer Whether the requester of the display list is a layer. If so,
12106     * the view will avoid creating a layer inside the resulting display list.
12107     * @return A new or reused DisplayList object.
12108     */
12109    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12110        if (!canHaveDisplayList()) {
12111            return null;
12112        }
12113
12114        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12115                displayList == null || !displayList.isValid() ||
12116                (!isLayer && mRecreateDisplayList))) {
12117            // Don't need to recreate the display list, just need to tell our
12118            // children to restore/recreate theirs
12119            if (displayList != null && displayList.isValid() &&
12120                    !isLayer && !mRecreateDisplayList) {
12121                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12122                mPrivateFlags &= ~DIRTY_MASK;
12123                dispatchGetDisplayList();
12124
12125                return displayList;
12126            }
12127
12128            if (!isLayer) {
12129                // If we got here, we're recreating it. Mark it as such to ensure that
12130                // we copy in child display lists into ours in drawChild()
12131                mRecreateDisplayList = true;
12132            }
12133            if (displayList == null) {
12134                final String name = getClass().getSimpleName();
12135                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12136                // If we're creating a new display list, make sure our parent gets invalidated
12137                // since they will need to recreate their display list to account for this
12138                // new child display list.
12139                invalidateParentCaches();
12140            }
12141
12142            boolean caching = false;
12143            final HardwareCanvas canvas = displayList.start();
12144            int width = mRight - mLeft;
12145            int height = mBottom - mTop;
12146
12147            try {
12148                canvas.setViewport(width, height);
12149                // The dirty rect should always be null for a display list
12150                canvas.onPreDraw(null);
12151                int layerType = (
12152                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12153                        getLayerType() : LAYER_TYPE_NONE;
12154                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12155                    if (layerType == LAYER_TYPE_HARDWARE) {
12156                        final HardwareLayer layer = getHardwareLayer();
12157                        if (layer != null && layer.isValid()) {
12158                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12159                        } else {
12160                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12161                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12162                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12163                        }
12164                        caching = true;
12165                    } else {
12166                        buildDrawingCache(true);
12167                        Bitmap cache = getDrawingCache(true);
12168                        if (cache != null) {
12169                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12170                            caching = true;
12171                        }
12172                    }
12173                } else {
12174
12175                    computeScroll();
12176
12177                    canvas.translate(-mScrollX, -mScrollY);
12178                    if (!isLayer) {
12179                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12180                        mPrivateFlags &= ~DIRTY_MASK;
12181                    }
12182
12183                    // Fast path for layouts with no backgrounds
12184                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12185                        dispatchDraw(canvas);
12186                    } else {
12187                        draw(canvas);
12188                    }
12189                }
12190            } finally {
12191                canvas.onPostDraw();
12192
12193                displayList.end();
12194                displayList.setCaching(caching);
12195                if (isLayer) {
12196                    displayList.setLeftTopRightBottom(0, 0, width, height);
12197                } else {
12198                    setDisplayListProperties(displayList);
12199                }
12200            }
12201        } else if (!isLayer) {
12202            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12203            mPrivateFlags &= ~DIRTY_MASK;
12204        }
12205
12206        return displayList;
12207    }
12208
12209    /**
12210     * Get the DisplayList for the HardwareLayer
12211     *
12212     * @param layer The HardwareLayer whose DisplayList we want
12213     * @return A DisplayList fopr the specified HardwareLayer
12214     */
12215    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12216        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12217        layer.setDisplayList(displayList);
12218        return displayList;
12219    }
12220
12221
12222    /**
12223     * <p>Returns a display list that can be used to draw this view again
12224     * without executing its draw method.</p>
12225     *
12226     * @return A DisplayList ready to replay, or null if caching is not enabled.
12227     *
12228     * @hide
12229     */
12230    public DisplayList getDisplayList() {
12231        mDisplayList = getDisplayList(mDisplayList, false);
12232        return mDisplayList;
12233    }
12234
12235    /**
12236     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12237     *
12238     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12239     *
12240     * @see #getDrawingCache(boolean)
12241     */
12242    public Bitmap getDrawingCache() {
12243        return getDrawingCache(false);
12244    }
12245
12246    /**
12247     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12248     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12249     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12250     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12251     * request the drawing cache by calling this method and draw it on screen if the
12252     * returned bitmap is not null.</p>
12253     *
12254     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12255     * this method will create a bitmap of the same size as this view. Because this bitmap
12256     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12257     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12258     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12259     * size than the view. This implies that your application must be able to handle this
12260     * size.</p>
12261     *
12262     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12263     *        the current density of the screen when the application is in compatibility
12264     *        mode.
12265     *
12266     * @return A bitmap representing this view or null if cache is disabled.
12267     *
12268     * @see #setDrawingCacheEnabled(boolean)
12269     * @see #isDrawingCacheEnabled()
12270     * @see #buildDrawingCache(boolean)
12271     * @see #destroyDrawingCache()
12272     */
12273    public Bitmap getDrawingCache(boolean autoScale) {
12274        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12275            return null;
12276        }
12277        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12278            buildDrawingCache(autoScale);
12279        }
12280        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12281    }
12282
12283    /**
12284     * <p>Frees the resources used by the drawing cache. If you call
12285     * {@link #buildDrawingCache()} manually without calling
12286     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12287     * should cleanup the cache with this method afterwards.</p>
12288     *
12289     * @see #setDrawingCacheEnabled(boolean)
12290     * @see #buildDrawingCache()
12291     * @see #getDrawingCache()
12292     */
12293    public void destroyDrawingCache() {
12294        if (mDrawingCache != null) {
12295            mDrawingCache.recycle();
12296            mDrawingCache = null;
12297        }
12298        if (mUnscaledDrawingCache != null) {
12299            mUnscaledDrawingCache.recycle();
12300            mUnscaledDrawingCache = null;
12301        }
12302    }
12303
12304    /**
12305     * Setting a solid background color for the drawing cache's bitmaps will improve
12306     * performance and memory usage. Note, though that this should only be used if this
12307     * view will always be drawn on top of a solid color.
12308     *
12309     * @param color The background color to use for the drawing cache's bitmap
12310     *
12311     * @see #setDrawingCacheEnabled(boolean)
12312     * @see #buildDrawingCache()
12313     * @see #getDrawingCache()
12314     */
12315    public void setDrawingCacheBackgroundColor(int color) {
12316        if (color != mDrawingCacheBackgroundColor) {
12317            mDrawingCacheBackgroundColor = color;
12318            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12319        }
12320    }
12321
12322    /**
12323     * @see #setDrawingCacheBackgroundColor(int)
12324     *
12325     * @return The background color to used for the drawing cache's bitmap
12326     */
12327    public int getDrawingCacheBackgroundColor() {
12328        return mDrawingCacheBackgroundColor;
12329    }
12330
12331    /**
12332     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12333     *
12334     * @see #buildDrawingCache(boolean)
12335     */
12336    public void buildDrawingCache() {
12337        buildDrawingCache(false);
12338    }
12339
12340    /**
12341     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12342     *
12343     * <p>If you call {@link #buildDrawingCache()} manually without calling
12344     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12345     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12346     *
12347     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12348     * this method will create a bitmap of the same size as this view. Because this bitmap
12349     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12350     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12351     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12352     * size than the view. This implies that your application must be able to handle this
12353     * size.</p>
12354     *
12355     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12356     * you do not need the drawing cache bitmap, calling this method will increase memory
12357     * usage and cause the view to be rendered in software once, thus negatively impacting
12358     * performance.</p>
12359     *
12360     * @see #getDrawingCache()
12361     * @see #destroyDrawingCache()
12362     */
12363    public void buildDrawingCache(boolean autoScale) {
12364        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12365                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12366            mCachingFailed = false;
12367
12368            if (ViewDebug.TRACE_HIERARCHY) {
12369                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
12370            }
12371
12372            int width = mRight - mLeft;
12373            int height = mBottom - mTop;
12374
12375            final AttachInfo attachInfo = mAttachInfo;
12376            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12377
12378            if (autoScale && scalingRequired) {
12379                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12380                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12381            }
12382
12383            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12384            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12385            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12386
12387            if (width <= 0 || height <= 0 ||
12388                     // Projected bitmap size in bytes
12389                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12390                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12391                destroyDrawingCache();
12392                mCachingFailed = true;
12393                return;
12394            }
12395
12396            boolean clear = true;
12397            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12398
12399            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12400                Bitmap.Config quality;
12401                if (!opaque) {
12402                    // Never pick ARGB_4444 because it looks awful
12403                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12404                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12405                        case DRAWING_CACHE_QUALITY_AUTO:
12406                            quality = Bitmap.Config.ARGB_8888;
12407                            break;
12408                        case DRAWING_CACHE_QUALITY_LOW:
12409                            quality = Bitmap.Config.ARGB_8888;
12410                            break;
12411                        case DRAWING_CACHE_QUALITY_HIGH:
12412                            quality = Bitmap.Config.ARGB_8888;
12413                            break;
12414                        default:
12415                            quality = Bitmap.Config.ARGB_8888;
12416                            break;
12417                    }
12418                } else {
12419                    // Optimization for translucent windows
12420                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12421                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12422                }
12423
12424                // Try to cleanup memory
12425                if (bitmap != null) bitmap.recycle();
12426
12427                try {
12428                    bitmap = Bitmap.createBitmap(width, height, quality);
12429                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12430                    if (autoScale) {
12431                        mDrawingCache = bitmap;
12432                    } else {
12433                        mUnscaledDrawingCache = bitmap;
12434                    }
12435                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12436                } catch (OutOfMemoryError e) {
12437                    // If there is not enough memory to create the bitmap cache, just
12438                    // ignore the issue as bitmap caches are not required to draw the
12439                    // view hierarchy
12440                    if (autoScale) {
12441                        mDrawingCache = null;
12442                    } else {
12443                        mUnscaledDrawingCache = null;
12444                    }
12445                    mCachingFailed = true;
12446                    return;
12447                }
12448
12449                clear = drawingCacheBackgroundColor != 0;
12450            }
12451
12452            Canvas canvas;
12453            if (attachInfo != null) {
12454                canvas = attachInfo.mCanvas;
12455                if (canvas == null) {
12456                    canvas = new Canvas();
12457                }
12458                canvas.setBitmap(bitmap);
12459                // Temporarily clobber the cached Canvas in case one of our children
12460                // is also using a drawing cache. Without this, the children would
12461                // steal the canvas by attaching their own bitmap to it and bad, bad
12462                // thing would happen (invisible views, corrupted drawings, etc.)
12463                attachInfo.mCanvas = null;
12464            } else {
12465                // This case should hopefully never or seldom happen
12466                canvas = new Canvas(bitmap);
12467            }
12468
12469            if (clear) {
12470                bitmap.eraseColor(drawingCacheBackgroundColor);
12471            }
12472
12473            computeScroll();
12474            final int restoreCount = canvas.save();
12475
12476            if (autoScale && scalingRequired) {
12477                final float scale = attachInfo.mApplicationScale;
12478                canvas.scale(scale, scale);
12479            }
12480
12481            canvas.translate(-mScrollX, -mScrollY);
12482
12483            mPrivateFlags |= DRAWN;
12484            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12485                    mLayerType != LAYER_TYPE_NONE) {
12486                mPrivateFlags |= DRAWING_CACHE_VALID;
12487            }
12488
12489            // Fast path for layouts with no backgrounds
12490            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12491                if (ViewDebug.TRACE_HIERARCHY) {
12492                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12493                }
12494                mPrivateFlags &= ~DIRTY_MASK;
12495                dispatchDraw(canvas);
12496            } else {
12497                draw(canvas);
12498            }
12499
12500            canvas.restoreToCount(restoreCount);
12501            canvas.setBitmap(null);
12502
12503            if (attachInfo != null) {
12504                // Restore the cached Canvas for our siblings
12505                attachInfo.mCanvas = canvas;
12506            }
12507        }
12508    }
12509
12510    /**
12511     * Create a snapshot of the view into a bitmap.  We should probably make
12512     * some form of this public, but should think about the API.
12513     */
12514    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12515        int width = mRight - mLeft;
12516        int height = mBottom - mTop;
12517
12518        final AttachInfo attachInfo = mAttachInfo;
12519        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12520        width = (int) ((width * scale) + 0.5f);
12521        height = (int) ((height * scale) + 0.5f);
12522
12523        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12524        if (bitmap == null) {
12525            throw new OutOfMemoryError();
12526        }
12527
12528        Resources resources = getResources();
12529        if (resources != null) {
12530            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12531        }
12532
12533        Canvas canvas;
12534        if (attachInfo != null) {
12535            canvas = attachInfo.mCanvas;
12536            if (canvas == null) {
12537                canvas = new Canvas();
12538            }
12539            canvas.setBitmap(bitmap);
12540            // Temporarily clobber the cached Canvas in case one of our children
12541            // is also using a drawing cache. Without this, the children would
12542            // steal the canvas by attaching their own bitmap to it and bad, bad
12543            // things would happen (invisible views, corrupted drawings, etc.)
12544            attachInfo.mCanvas = null;
12545        } else {
12546            // This case should hopefully never or seldom happen
12547            canvas = new Canvas(bitmap);
12548        }
12549
12550        if ((backgroundColor & 0xff000000) != 0) {
12551            bitmap.eraseColor(backgroundColor);
12552        }
12553
12554        computeScroll();
12555        final int restoreCount = canvas.save();
12556        canvas.scale(scale, scale);
12557        canvas.translate(-mScrollX, -mScrollY);
12558
12559        // Temporarily remove the dirty mask
12560        int flags = mPrivateFlags;
12561        mPrivateFlags &= ~DIRTY_MASK;
12562
12563        // Fast path for layouts with no backgrounds
12564        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12565            dispatchDraw(canvas);
12566        } else {
12567            draw(canvas);
12568        }
12569
12570        mPrivateFlags = flags;
12571
12572        canvas.restoreToCount(restoreCount);
12573        canvas.setBitmap(null);
12574
12575        if (attachInfo != null) {
12576            // Restore the cached Canvas for our siblings
12577            attachInfo.mCanvas = canvas;
12578        }
12579
12580        return bitmap;
12581    }
12582
12583    /**
12584     * Indicates whether this View is currently in edit mode. A View is usually
12585     * in edit mode when displayed within a developer tool. For instance, if
12586     * this View is being drawn by a visual user interface builder, this method
12587     * should return true.
12588     *
12589     * Subclasses should check the return value of this method to provide
12590     * different behaviors if their normal behavior might interfere with the
12591     * host environment. For instance: the class spawns a thread in its
12592     * constructor, the drawing code relies on device-specific features, etc.
12593     *
12594     * This method is usually checked in the drawing code of custom widgets.
12595     *
12596     * @return True if this View is in edit mode, false otherwise.
12597     */
12598    public boolean isInEditMode() {
12599        return false;
12600    }
12601
12602    /**
12603     * If the View draws content inside its padding and enables fading edges,
12604     * it needs to support padding offsets. Padding offsets are added to the
12605     * fading edges to extend the length of the fade so that it covers pixels
12606     * drawn inside the padding.
12607     *
12608     * Subclasses of this class should override this method if they need
12609     * to draw content inside the padding.
12610     *
12611     * @return True if padding offset must be applied, false otherwise.
12612     *
12613     * @see #getLeftPaddingOffset()
12614     * @see #getRightPaddingOffset()
12615     * @see #getTopPaddingOffset()
12616     * @see #getBottomPaddingOffset()
12617     *
12618     * @since CURRENT
12619     */
12620    protected boolean isPaddingOffsetRequired() {
12621        return false;
12622    }
12623
12624    /**
12625     * Amount by which to extend the left fading region. Called only when
12626     * {@link #isPaddingOffsetRequired()} returns true.
12627     *
12628     * @return The left padding offset in pixels.
12629     *
12630     * @see #isPaddingOffsetRequired()
12631     *
12632     * @since CURRENT
12633     */
12634    protected int getLeftPaddingOffset() {
12635        return 0;
12636    }
12637
12638    /**
12639     * Amount by which to extend the right fading region. Called only when
12640     * {@link #isPaddingOffsetRequired()} returns true.
12641     *
12642     * @return The right padding offset in pixels.
12643     *
12644     * @see #isPaddingOffsetRequired()
12645     *
12646     * @since CURRENT
12647     */
12648    protected int getRightPaddingOffset() {
12649        return 0;
12650    }
12651
12652    /**
12653     * Amount by which to extend the top fading region. Called only when
12654     * {@link #isPaddingOffsetRequired()} returns true.
12655     *
12656     * @return The top padding offset in pixels.
12657     *
12658     * @see #isPaddingOffsetRequired()
12659     *
12660     * @since CURRENT
12661     */
12662    protected int getTopPaddingOffset() {
12663        return 0;
12664    }
12665
12666    /**
12667     * Amount by which to extend the bottom fading region. Called only when
12668     * {@link #isPaddingOffsetRequired()} returns true.
12669     *
12670     * @return The bottom padding offset in pixels.
12671     *
12672     * @see #isPaddingOffsetRequired()
12673     *
12674     * @since CURRENT
12675     */
12676    protected int getBottomPaddingOffset() {
12677        return 0;
12678    }
12679
12680    /**
12681     * @hide
12682     * @param offsetRequired
12683     */
12684    protected int getFadeTop(boolean offsetRequired) {
12685        int top = mPaddingTop;
12686        if (offsetRequired) top += getTopPaddingOffset();
12687        return top;
12688    }
12689
12690    /**
12691     * @hide
12692     * @param offsetRequired
12693     */
12694    protected int getFadeHeight(boolean offsetRequired) {
12695        int padding = mPaddingTop;
12696        if (offsetRequired) padding += getTopPaddingOffset();
12697        return mBottom - mTop - mPaddingBottom - padding;
12698    }
12699
12700    /**
12701     * <p>Indicates whether this view is attached to a hardware accelerated
12702     * window or not.</p>
12703     *
12704     * <p>Even if this method returns true, it does not mean that every call
12705     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12706     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12707     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12708     * window is hardware accelerated,
12709     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12710     * return false, and this method will return true.</p>
12711     *
12712     * @return True if the view is attached to a window and the window is
12713     *         hardware accelerated; false in any other case.
12714     */
12715    public boolean isHardwareAccelerated() {
12716        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12717    }
12718
12719    /**
12720     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12721     * case of an active Animation being run on the view.
12722     */
12723    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12724            Animation a, boolean scalingRequired) {
12725        Transformation invalidationTransform;
12726        final int flags = parent.mGroupFlags;
12727        final boolean initialized = a.isInitialized();
12728        if (!initialized) {
12729            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12730            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12731            onAnimationStart();
12732        }
12733
12734        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12735        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12736            if (parent.mInvalidationTransformation == null) {
12737                parent.mInvalidationTransformation = new Transformation();
12738            }
12739            invalidationTransform = parent.mInvalidationTransformation;
12740            a.getTransformation(drawingTime, invalidationTransform, 1f);
12741        } else {
12742            invalidationTransform = parent.mChildTransformation;
12743        }
12744        if (more) {
12745            if (!a.willChangeBounds()) {
12746                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12747                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12748                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12749                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12750                    // The child need to draw an animation, potentially offscreen, so
12751                    // make sure we do not cancel invalidate requests
12752                    parent.mPrivateFlags |= DRAW_ANIMATION;
12753                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12754                }
12755            } else {
12756                if (parent.mInvalidateRegion == null) {
12757                    parent.mInvalidateRegion = new RectF();
12758                }
12759                final RectF region = parent.mInvalidateRegion;
12760                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12761                        invalidationTransform);
12762
12763                // The child need to draw an animation, potentially offscreen, so
12764                // make sure we do not cancel invalidate requests
12765                parent.mPrivateFlags |= DRAW_ANIMATION;
12766
12767                final int left = mLeft + (int) region.left;
12768                final int top = mTop + (int) region.top;
12769                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12770                        top + (int) (region.height() + .5f));
12771            }
12772        }
12773        return more;
12774    }
12775
12776    /**
12777     * This method is called by getDisplayList() when a display list is created or re-rendered.
12778     * It sets or resets the current value of all properties on that display list (resetting is
12779     * necessary when a display list is being re-created, because we need to make sure that
12780     * previously-set transform values
12781     */
12782    void setDisplayListProperties(DisplayList displayList) {
12783        if (displayList != null) {
12784            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12785            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12786            if (mParent instanceof ViewGroup) {
12787                displayList.setClipChildren(
12788                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12789            }
12790            float alpha = 1;
12791            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12792                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12793                ViewGroup parentVG = (ViewGroup) mParent;
12794                final boolean hasTransform =
12795                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12796                if (hasTransform) {
12797                    Transformation transform = parentVG.mChildTransformation;
12798                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12799                    if (transformType != Transformation.TYPE_IDENTITY) {
12800                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12801                            alpha = transform.getAlpha();
12802                        }
12803                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12804                            displayList.setStaticMatrix(transform.getMatrix());
12805                        }
12806                    }
12807                }
12808            }
12809            if (mTransformationInfo != null) {
12810                alpha *= mTransformationInfo.mAlpha;
12811                if (alpha < 1) {
12812                    final int multipliedAlpha = (int) (255 * alpha);
12813                    if (onSetAlpha(multipliedAlpha)) {
12814                        alpha = 1;
12815                    }
12816                }
12817                displayList.setTransformationInfo(alpha,
12818                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12819                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12820                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12821                        mTransformationInfo.mScaleY);
12822                if (mTransformationInfo.mCamera == null) {
12823                    mTransformationInfo.mCamera = new Camera();
12824                    mTransformationInfo.matrix3D = new Matrix();
12825                }
12826                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12827                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12828                    displayList.setPivotX(getPivotX());
12829                    displayList.setPivotY(getPivotY());
12830                }
12831            } else if (alpha < 1) {
12832                displayList.setAlpha(alpha);
12833            }
12834        }
12835    }
12836
12837    /**
12838     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12839     * This draw() method is an implementation detail and is not intended to be overridden or
12840     * to be called from anywhere else other than ViewGroup.drawChild().
12841     */
12842    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12843        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12844        boolean more = false;
12845        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12846        final int flags = parent.mGroupFlags;
12847
12848        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12849            parent.mChildTransformation.clear();
12850            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12851        }
12852
12853        Transformation transformToApply = null;
12854        boolean concatMatrix = false;
12855
12856        boolean scalingRequired = false;
12857        boolean caching;
12858        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12859
12860        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12861        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12862                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12863            caching = true;
12864            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12865            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12866        } else {
12867            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12868        }
12869
12870        final Animation a = getAnimation();
12871        if (a != null) {
12872            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12873            concatMatrix = a.willChangeTransformationMatrix();
12874            if (concatMatrix) {
12875                mPrivateFlags2 |= VIEW_IS_ANIMATING_TRANSFORM;
12876            }
12877            transformToApply = parent.mChildTransformation;
12878        } else {
12879            if ((mPrivateFlags2 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
12880                    mDisplayList != null) {
12881                // No longer animating: clear out old animation matrix
12882                mDisplayList.setAnimationMatrix(null);
12883                mPrivateFlags2 &= ~VIEW_IS_ANIMATING_TRANSFORM;
12884            }
12885            if (!useDisplayListProperties &&
12886                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12887                final boolean hasTransform =
12888                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
12889                if (hasTransform) {
12890                    final int transformType = parent.mChildTransformation.getTransformationType();
12891                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12892                            parent.mChildTransformation : null;
12893                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12894                }
12895            }
12896        }
12897
12898        concatMatrix |= !childHasIdentityMatrix;
12899
12900        // Sets the flag as early as possible to allow draw() implementations
12901        // to call invalidate() successfully when doing animations
12902        mPrivateFlags |= DRAWN;
12903
12904        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12905                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12906            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
12907            return more;
12908        }
12909        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
12910
12911        if (hardwareAccelerated) {
12912            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12913            // retain the flag's value temporarily in the mRecreateDisplayList flag
12914            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12915            mPrivateFlags &= ~INVALIDATED;
12916        }
12917
12918        computeScroll();
12919
12920        final int sx = mScrollX;
12921        final int sy = mScrollY;
12922
12923        DisplayList displayList = null;
12924        Bitmap cache = null;
12925        boolean hasDisplayList = false;
12926        if (caching) {
12927            if (!hardwareAccelerated) {
12928                if (layerType != LAYER_TYPE_NONE) {
12929                    layerType = LAYER_TYPE_SOFTWARE;
12930                    buildDrawingCache(true);
12931                }
12932                cache = getDrawingCache(true);
12933            } else {
12934                switch (layerType) {
12935                    case LAYER_TYPE_SOFTWARE:
12936                        if (useDisplayListProperties) {
12937                            hasDisplayList = canHaveDisplayList();
12938                        } else {
12939                            buildDrawingCache(true);
12940                            cache = getDrawingCache(true);
12941                        }
12942                        break;
12943                    case LAYER_TYPE_HARDWARE:
12944                        if (useDisplayListProperties) {
12945                            hasDisplayList = canHaveDisplayList();
12946                        }
12947                        break;
12948                    case LAYER_TYPE_NONE:
12949                        // Delay getting the display list until animation-driven alpha values are
12950                        // set up and possibly passed on to the view
12951                        hasDisplayList = canHaveDisplayList();
12952                        break;
12953                }
12954            }
12955        }
12956        useDisplayListProperties &= hasDisplayList;
12957        if (useDisplayListProperties) {
12958            displayList = getDisplayList();
12959            if (!displayList.isValid()) {
12960                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12961                // to getDisplayList(), the display list will be marked invalid and we should not
12962                // try to use it again.
12963                displayList = null;
12964                hasDisplayList = false;
12965                useDisplayListProperties = false;
12966            }
12967        }
12968
12969        final boolean hasNoCache = cache == null || hasDisplayList;
12970        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12971                layerType != LAYER_TYPE_HARDWARE;
12972
12973        int restoreTo = -1;
12974        if (!useDisplayListProperties || transformToApply != null) {
12975            restoreTo = canvas.save();
12976        }
12977        if (offsetForScroll) {
12978            canvas.translate(mLeft - sx, mTop - sy);
12979        } else {
12980            if (!useDisplayListProperties) {
12981                canvas.translate(mLeft, mTop);
12982            }
12983            if (scalingRequired) {
12984                if (useDisplayListProperties) {
12985                    // TODO: Might not need this if we put everything inside the DL
12986                    restoreTo = canvas.save();
12987                }
12988                // mAttachInfo cannot be null, otherwise scalingRequired == false
12989                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12990                canvas.scale(scale, scale);
12991            }
12992        }
12993
12994        float alpha = useDisplayListProperties ? 1 : getAlpha();
12995        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12996            if (transformToApply != null || !childHasIdentityMatrix) {
12997                int transX = 0;
12998                int transY = 0;
12999
13000                if (offsetForScroll) {
13001                    transX = -sx;
13002                    transY = -sy;
13003                }
13004
13005                if (transformToApply != null) {
13006                    if (concatMatrix) {
13007                        if (useDisplayListProperties) {
13008                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13009                        } else {
13010                            // Undo the scroll translation, apply the transformation matrix,
13011                            // then redo the scroll translate to get the correct result.
13012                            canvas.translate(-transX, -transY);
13013                            canvas.concat(transformToApply.getMatrix());
13014                            canvas.translate(transX, transY);
13015                        }
13016                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13017                    }
13018
13019                    float transformAlpha = transformToApply.getAlpha();
13020                    if (transformAlpha < 1) {
13021                        alpha *= transformToApply.getAlpha();
13022                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13023                    }
13024                }
13025
13026                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13027                    canvas.translate(-transX, -transY);
13028                    canvas.concat(getMatrix());
13029                    canvas.translate(transX, transY);
13030                }
13031            }
13032
13033            if (alpha < 1) {
13034                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13035                if (hasNoCache) {
13036                    final int multipliedAlpha = (int) (255 * alpha);
13037                    if (!onSetAlpha(multipliedAlpha)) {
13038                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13039                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13040                                layerType != LAYER_TYPE_NONE) {
13041                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13042                        }
13043                        if (useDisplayListProperties) {
13044                            displayList.setAlpha(alpha * getAlpha());
13045                        } else  if (layerType == LAYER_TYPE_NONE) {
13046                            final int scrollX = hasDisplayList ? 0 : sx;
13047                            final int scrollY = hasDisplayList ? 0 : sy;
13048                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13049                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13050                        }
13051                    } else {
13052                        // Alpha is handled by the child directly, clobber the layer's alpha
13053                        mPrivateFlags |= ALPHA_SET;
13054                    }
13055                }
13056            }
13057        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13058            onSetAlpha(255);
13059            mPrivateFlags &= ~ALPHA_SET;
13060        }
13061
13062        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13063                !useDisplayListProperties) {
13064            if (offsetForScroll) {
13065                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13066            } else {
13067                if (!scalingRequired || cache == null) {
13068                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13069                } else {
13070                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13071                }
13072            }
13073        }
13074
13075        if (!useDisplayListProperties && hasDisplayList) {
13076            displayList = getDisplayList();
13077            if (!displayList.isValid()) {
13078                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13079                // to getDisplayList(), the display list will be marked invalid and we should not
13080                // try to use it again.
13081                displayList = null;
13082                hasDisplayList = false;
13083            }
13084        }
13085
13086        if (hasNoCache) {
13087            boolean layerRendered = false;
13088            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13089                final HardwareLayer layer = getHardwareLayer();
13090                if (layer != null && layer.isValid()) {
13091                    mLayerPaint.setAlpha((int) (alpha * 255));
13092                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13093                    layerRendered = true;
13094                } else {
13095                    final int scrollX = hasDisplayList ? 0 : sx;
13096                    final int scrollY = hasDisplayList ? 0 : sy;
13097                    canvas.saveLayer(scrollX, scrollY,
13098                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13099                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13100                }
13101            }
13102
13103            if (!layerRendered) {
13104                if (!hasDisplayList) {
13105                    // Fast path for layouts with no backgrounds
13106                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13107                        if (ViewDebug.TRACE_HIERARCHY) {
13108                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
13109                        }
13110                        mPrivateFlags &= ~DIRTY_MASK;
13111                        dispatchDraw(canvas);
13112                    } else {
13113                        draw(canvas);
13114                    }
13115                } else {
13116                    mPrivateFlags &= ~DIRTY_MASK;
13117                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13118                }
13119            }
13120        } else if (cache != null) {
13121            mPrivateFlags &= ~DIRTY_MASK;
13122            Paint cachePaint;
13123
13124            if (layerType == LAYER_TYPE_NONE) {
13125                cachePaint = parent.mCachePaint;
13126                if (cachePaint == null) {
13127                    cachePaint = new Paint();
13128                    cachePaint.setDither(false);
13129                    parent.mCachePaint = cachePaint;
13130                }
13131                if (alpha < 1) {
13132                    cachePaint.setAlpha((int) (alpha * 255));
13133                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13134                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13135                    cachePaint.setAlpha(255);
13136                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13137                }
13138            } else {
13139                cachePaint = mLayerPaint;
13140                cachePaint.setAlpha((int) (alpha * 255));
13141            }
13142            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13143        }
13144
13145        if (restoreTo >= 0) {
13146            canvas.restoreToCount(restoreTo);
13147        }
13148
13149        if (a != null && !more) {
13150            if (!hardwareAccelerated && !a.getFillAfter()) {
13151                onSetAlpha(255);
13152            }
13153            parent.finishAnimatingView(this, a);
13154        }
13155
13156        if (more && hardwareAccelerated) {
13157            // invalidation is the trigger to recreate display lists, so if we're using
13158            // display lists to render, force an invalidate to allow the animation to
13159            // continue drawing another frame
13160            parent.invalidate(true);
13161            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13162                // alpha animations should cause the child to recreate its display list
13163                invalidate(true);
13164            }
13165        }
13166
13167        mRecreateDisplayList = false;
13168
13169        return more;
13170    }
13171
13172    /**
13173     * Manually render this view (and all of its children) to the given Canvas.
13174     * The view must have already done a full layout before this function is
13175     * called.  When implementing a view, implement
13176     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13177     * If you do need to override this method, call the superclass version.
13178     *
13179     * @param canvas The Canvas to which the View is rendered.
13180     */
13181    public void draw(Canvas canvas) {
13182        if (ViewDebug.TRACE_HIERARCHY) {
13183            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
13184        }
13185
13186        final int privateFlags = mPrivateFlags;
13187        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13188                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13189        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13190
13191        /*
13192         * Draw traversal performs several drawing steps which must be executed
13193         * in the appropriate order:
13194         *
13195         *      1. Draw the background
13196         *      2. If necessary, save the canvas' layers to prepare for fading
13197         *      3. Draw view's content
13198         *      4. Draw children
13199         *      5. If necessary, draw the fading edges and restore layers
13200         *      6. Draw decorations (scrollbars for instance)
13201         */
13202
13203        // Step 1, draw the background, if needed
13204        int saveCount;
13205
13206        if (!dirtyOpaque) {
13207            final Drawable background = mBackground;
13208            if (background != null) {
13209                final int scrollX = mScrollX;
13210                final int scrollY = mScrollY;
13211
13212                if (mBackgroundSizeChanged) {
13213                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13214                    mBackgroundSizeChanged = false;
13215                }
13216
13217                if ((scrollX | scrollY) == 0) {
13218                    background.draw(canvas);
13219                } else {
13220                    canvas.translate(scrollX, scrollY);
13221                    background.draw(canvas);
13222                    canvas.translate(-scrollX, -scrollY);
13223                }
13224            }
13225        }
13226
13227        // skip step 2 & 5 if possible (common case)
13228        final int viewFlags = mViewFlags;
13229        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13230        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13231        if (!verticalEdges && !horizontalEdges) {
13232            // Step 3, draw the content
13233            if (!dirtyOpaque) onDraw(canvas);
13234
13235            // Step 4, draw the children
13236            dispatchDraw(canvas);
13237
13238            // Step 6, draw decorations (scrollbars)
13239            onDrawScrollBars(canvas);
13240
13241            // we're done...
13242            return;
13243        }
13244
13245        /*
13246         * Here we do the full fledged routine...
13247         * (this is an uncommon case where speed matters less,
13248         * this is why we repeat some of the tests that have been
13249         * done above)
13250         */
13251
13252        boolean drawTop = false;
13253        boolean drawBottom = false;
13254        boolean drawLeft = false;
13255        boolean drawRight = false;
13256
13257        float topFadeStrength = 0.0f;
13258        float bottomFadeStrength = 0.0f;
13259        float leftFadeStrength = 0.0f;
13260        float rightFadeStrength = 0.0f;
13261
13262        // Step 2, save the canvas' layers
13263        int paddingLeft = mPaddingLeft;
13264
13265        final boolean offsetRequired = isPaddingOffsetRequired();
13266        if (offsetRequired) {
13267            paddingLeft += getLeftPaddingOffset();
13268        }
13269
13270        int left = mScrollX + paddingLeft;
13271        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13272        int top = mScrollY + getFadeTop(offsetRequired);
13273        int bottom = top + getFadeHeight(offsetRequired);
13274
13275        if (offsetRequired) {
13276            right += getRightPaddingOffset();
13277            bottom += getBottomPaddingOffset();
13278        }
13279
13280        final ScrollabilityCache scrollabilityCache = mScrollCache;
13281        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13282        int length = (int) fadeHeight;
13283
13284        // clip the fade length if top and bottom fades overlap
13285        // overlapping fades produce odd-looking artifacts
13286        if (verticalEdges && (top + length > bottom - length)) {
13287            length = (bottom - top) / 2;
13288        }
13289
13290        // also clip horizontal fades if necessary
13291        if (horizontalEdges && (left + length > right - length)) {
13292            length = (right - left) / 2;
13293        }
13294
13295        if (verticalEdges) {
13296            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13297            drawTop = topFadeStrength * fadeHeight > 1.0f;
13298            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13299            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13300        }
13301
13302        if (horizontalEdges) {
13303            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13304            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13305            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13306            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13307        }
13308
13309        saveCount = canvas.getSaveCount();
13310
13311        int solidColor = getSolidColor();
13312        if (solidColor == 0) {
13313            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13314
13315            if (drawTop) {
13316                canvas.saveLayer(left, top, right, top + length, null, flags);
13317            }
13318
13319            if (drawBottom) {
13320                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13321            }
13322
13323            if (drawLeft) {
13324                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13325            }
13326
13327            if (drawRight) {
13328                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13329            }
13330        } else {
13331            scrollabilityCache.setFadeColor(solidColor);
13332        }
13333
13334        // Step 3, draw the content
13335        if (!dirtyOpaque) onDraw(canvas);
13336
13337        // Step 4, draw the children
13338        dispatchDraw(canvas);
13339
13340        // Step 5, draw the fade effect and restore layers
13341        final Paint p = scrollabilityCache.paint;
13342        final Matrix matrix = scrollabilityCache.matrix;
13343        final Shader fade = scrollabilityCache.shader;
13344
13345        if (drawTop) {
13346            matrix.setScale(1, fadeHeight * topFadeStrength);
13347            matrix.postTranslate(left, top);
13348            fade.setLocalMatrix(matrix);
13349            canvas.drawRect(left, top, right, top + length, p);
13350        }
13351
13352        if (drawBottom) {
13353            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13354            matrix.postRotate(180);
13355            matrix.postTranslate(left, bottom);
13356            fade.setLocalMatrix(matrix);
13357            canvas.drawRect(left, bottom - length, right, bottom, p);
13358        }
13359
13360        if (drawLeft) {
13361            matrix.setScale(1, fadeHeight * leftFadeStrength);
13362            matrix.postRotate(-90);
13363            matrix.postTranslate(left, top);
13364            fade.setLocalMatrix(matrix);
13365            canvas.drawRect(left, top, left + length, bottom, p);
13366        }
13367
13368        if (drawRight) {
13369            matrix.setScale(1, fadeHeight * rightFadeStrength);
13370            matrix.postRotate(90);
13371            matrix.postTranslate(right, top);
13372            fade.setLocalMatrix(matrix);
13373            canvas.drawRect(right - length, top, right, bottom, p);
13374        }
13375
13376        canvas.restoreToCount(saveCount);
13377
13378        // Step 6, draw decorations (scrollbars)
13379        onDrawScrollBars(canvas);
13380    }
13381
13382    /**
13383     * Override this if your view is known to always be drawn on top of a solid color background,
13384     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13385     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13386     * should be set to 0xFF.
13387     *
13388     * @see #setVerticalFadingEdgeEnabled(boolean)
13389     * @see #setHorizontalFadingEdgeEnabled(boolean)
13390     *
13391     * @return The known solid color background for this view, or 0 if the color may vary
13392     */
13393    @ViewDebug.ExportedProperty(category = "drawing")
13394    public int getSolidColor() {
13395        return 0;
13396    }
13397
13398    /**
13399     * Build a human readable string representation of the specified view flags.
13400     *
13401     * @param flags the view flags to convert to a string
13402     * @return a String representing the supplied flags
13403     */
13404    private static String printFlags(int flags) {
13405        String output = "";
13406        int numFlags = 0;
13407        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13408            output += "TAKES_FOCUS";
13409            numFlags++;
13410        }
13411
13412        switch (flags & VISIBILITY_MASK) {
13413        case INVISIBLE:
13414            if (numFlags > 0) {
13415                output += " ";
13416            }
13417            output += "INVISIBLE";
13418            // USELESS HERE numFlags++;
13419            break;
13420        case GONE:
13421            if (numFlags > 0) {
13422                output += " ";
13423            }
13424            output += "GONE";
13425            // USELESS HERE numFlags++;
13426            break;
13427        default:
13428            break;
13429        }
13430        return output;
13431    }
13432
13433    /**
13434     * Build a human readable string representation of the specified private
13435     * view flags.
13436     *
13437     * @param privateFlags the private view flags to convert to a string
13438     * @return a String representing the supplied flags
13439     */
13440    private static String printPrivateFlags(int privateFlags) {
13441        String output = "";
13442        int numFlags = 0;
13443
13444        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13445            output += "WANTS_FOCUS";
13446            numFlags++;
13447        }
13448
13449        if ((privateFlags & FOCUSED) == FOCUSED) {
13450            if (numFlags > 0) {
13451                output += " ";
13452            }
13453            output += "FOCUSED";
13454            numFlags++;
13455        }
13456
13457        if ((privateFlags & SELECTED) == SELECTED) {
13458            if (numFlags > 0) {
13459                output += " ";
13460            }
13461            output += "SELECTED";
13462            numFlags++;
13463        }
13464
13465        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13466            if (numFlags > 0) {
13467                output += " ";
13468            }
13469            output += "IS_ROOT_NAMESPACE";
13470            numFlags++;
13471        }
13472
13473        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13474            if (numFlags > 0) {
13475                output += " ";
13476            }
13477            output += "HAS_BOUNDS";
13478            numFlags++;
13479        }
13480
13481        if ((privateFlags & DRAWN) == DRAWN) {
13482            if (numFlags > 0) {
13483                output += " ";
13484            }
13485            output += "DRAWN";
13486            // USELESS HERE numFlags++;
13487        }
13488        return output;
13489    }
13490
13491    /**
13492     * <p>Indicates whether or not this view's layout will be requested during
13493     * the next hierarchy layout pass.</p>
13494     *
13495     * @return true if the layout will be forced during next layout pass
13496     */
13497    public boolean isLayoutRequested() {
13498        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13499    }
13500
13501    /**
13502     * Assign a size and position to a view and all of its
13503     * descendants
13504     *
13505     * <p>This is the second phase of the layout mechanism.
13506     * (The first is measuring). In this phase, each parent calls
13507     * layout on all of its children to position them.
13508     * This is typically done using the child measurements
13509     * that were stored in the measure pass().</p>
13510     *
13511     * <p>Derived classes should not override this method.
13512     * Derived classes with children should override
13513     * onLayout. In that method, they should
13514     * call layout on each of their children.</p>
13515     *
13516     * @param l Left position, relative to parent
13517     * @param t Top position, relative to parent
13518     * @param r Right position, relative to parent
13519     * @param b Bottom position, relative to parent
13520     */
13521    @SuppressWarnings({"unchecked"})
13522    public void layout(int l, int t, int r, int b) {
13523        int oldL = mLeft;
13524        int oldT = mTop;
13525        int oldB = mBottom;
13526        int oldR = mRight;
13527        boolean changed = setFrame(l, t, r, b);
13528        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13529            if (ViewDebug.TRACE_HIERARCHY) {
13530                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13531            }
13532
13533            onLayout(changed, l, t, r, b);
13534            mPrivateFlags &= ~LAYOUT_REQUIRED;
13535
13536            ListenerInfo li = mListenerInfo;
13537            if (li != null && li.mOnLayoutChangeListeners != null) {
13538                ArrayList<OnLayoutChangeListener> listenersCopy =
13539                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13540                int numListeners = listenersCopy.size();
13541                for (int i = 0; i < numListeners; ++i) {
13542                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13543                }
13544            }
13545        }
13546        mPrivateFlags &= ~FORCE_LAYOUT;
13547    }
13548
13549    /**
13550     * Called from layout when this view should
13551     * assign a size and position to each of its children.
13552     *
13553     * Derived classes with children should override
13554     * this method and call layout on each of
13555     * their children.
13556     * @param changed This is a new size or position for this view
13557     * @param left Left position, relative to parent
13558     * @param top Top position, relative to parent
13559     * @param right Right position, relative to parent
13560     * @param bottom Bottom position, relative to parent
13561     */
13562    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13563    }
13564
13565    /**
13566     * Assign a size and position to this view.
13567     *
13568     * This is called from layout.
13569     *
13570     * @param left Left position, relative to parent
13571     * @param top Top position, relative to parent
13572     * @param right Right position, relative to parent
13573     * @param bottom Bottom position, relative to parent
13574     * @return true if the new size and position are different than the
13575     *         previous ones
13576     * {@hide}
13577     */
13578    protected boolean setFrame(int left, int top, int right, int bottom) {
13579        boolean changed = false;
13580
13581        if (DBG) {
13582            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13583                    + right + "," + bottom + ")");
13584        }
13585
13586        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13587            changed = true;
13588
13589            // Remember our drawn bit
13590            int drawn = mPrivateFlags & DRAWN;
13591
13592            int oldWidth = mRight - mLeft;
13593            int oldHeight = mBottom - mTop;
13594            int newWidth = right - left;
13595            int newHeight = bottom - top;
13596            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13597
13598            // Invalidate our old position
13599            invalidate(sizeChanged);
13600
13601            mLeft = left;
13602            mTop = top;
13603            mRight = right;
13604            mBottom = bottom;
13605            if (mDisplayList != null) {
13606                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13607            }
13608
13609            mPrivateFlags |= HAS_BOUNDS;
13610
13611
13612            if (sizeChanged) {
13613                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13614                    // A change in dimension means an auto-centered pivot point changes, too
13615                    if (mTransformationInfo != null) {
13616                        mTransformationInfo.mMatrixDirty = true;
13617                    }
13618                }
13619                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13620            }
13621
13622            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13623                // If we are visible, force the DRAWN bit to on so that
13624                // this invalidate will go through (at least to our parent).
13625                // This is because someone may have invalidated this view
13626                // before this call to setFrame came in, thereby clearing
13627                // the DRAWN bit.
13628                mPrivateFlags |= DRAWN;
13629                invalidate(sizeChanged);
13630                // parent display list may need to be recreated based on a change in the bounds
13631                // of any child
13632                invalidateParentCaches();
13633            }
13634
13635            // Reset drawn bit to original value (invalidate turns it off)
13636            mPrivateFlags |= drawn;
13637
13638            mBackgroundSizeChanged = true;
13639        }
13640        return changed;
13641    }
13642
13643    /**
13644     * Finalize inflating a view from XML.  This is called as the last phase
13645     * of inflation, after all child views have been added.
13646     *
13647     * <p>Even if the subclass overrides onFinishInflate, they should always be
13648     * sure to call the super method, so that we get called.
13649     */
13650    protected void onFinishInflate() {
13651    }
13652
13653    /**
13654     * Returns the resources associated with this view.
13655     *
13656     * @return Resources object.
13657     */
13658    public Resources getResources() {
13659        return mResources;
13660    }
13661
13662    /**
13663     * Invalidates the specified Drawable.
13664     *
13665     * @param drawable the drawable to invalidate
13666     */
13667    public void invalidateDrawable(Drawable drawable) {
13668        if (verifyDrawable(drawable)) {
13669            final Rect dirty = drawable.getBounds();
13670            final int scrollX = mScrollX;
13671            final int scrollY = mScrollY;
13672
13673            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13674                    dirty.right + scrollX, dirty.bottom + scrollY);
13675        }
13676    }
13677
13678    /**
13679     * Schedules an action on a drawable to occur at a specified time.
13680     *
13681     * @param who the recipient of the action
13682     * @param what the action to run on the drawable
13683     * @param when the time at which the action must occur. Uses the
13684     *        {@link SystemClock#uptimeMillis} timebase.
13685     */
13686    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13687        if (verifyDrawable(who) && what != null) {
13688            final long delay = when - SystemClock.uptimeMillis();
13689            if (mAttachInfo != null) {
13690                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13691                        Choreographer.CALLBACK_ANIMATION, what, who,
13692                        Choreographer.subtractFrameDelay(delay));
13693            } else {
13694                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13695            }
13696        }
13697    }
13698
13699    /**
13700     * Cancels a scheduled action on a drawable.
13701     *
13702     * @param who the recipient of the action
13703     * @param what the action to cancel
13704     */
13705    public void unscheduleDrawable(Drawable who, Runnable what) {
13706        if (verifyDrawable(who) && what != null) {
13707            if (mAttachInfo != null) {
13708                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13709                        Choreographer.CALLBACK_ANIMATION, what, who);
13710            } else {
13711                ViewRootImpl.getRunQueue().removeCallbacks(what);
13712            }
13713        }
13714    }
13715
13716    /**
13717     * Unschedule any events associated with the given Drawable.  This can be
13718     * used when selecting a new Drawable into a view, so that the previous
13719     * one is completely unscheduled.
13720     *
13721     * @param who The Drawable to unschedule.
13722     *
13723     * @see #drawableStateChanged
13724     */
13725    public void unscheduleDrawable(Drawable who) {
13726        if (mAttachInfo != null && who != null) {
13727            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13728                    Choreographer.CALLBACK_ANIMATION, null, who);
13729        }
13730    }
13731
13732    /**
13733    * Return the layout direction of a given Drawable.
13734    *
13735    * @param who the Drawable to query
13736    * @hide
13737    */
13738    public int getResolvedLayoutDirection(Drawable who) {
13739        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13740    }
13741
13742    /**
13743     * If your view subclass is displaying its own Drawable objects, it should
13744     * override this function and return true for any Drawable it is
13745     * displaying.  This allows animations for those drawables to be
13746     * scheduled.
13747     *
13748     * <p>Be sure to call through to the super class when overriding this
13749     * function.
13750     *
13751     * @param who The Drawable to verify.  Return true if it is one you are
13752     *            displaying, else return the result of calling through to the
13753     *            super class.
13754     *
13755     * @return boolean If true than the Drawable is being displayed in the
13756     *         view; else false and it is not allowed to animate.
13757     *
13758     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13759     * @see #drawableStateChanged()
13760     */
13761    protected boolean verifyDrawable(Drawable who) {
13762        return who == mBackground;
13763    }
13764
13765    /**
13766     * This function is called whenever the state of the view changes in such
13767     * a way that it impacts the state of drawables being shown.
13768     *
13769     * <p>Be sure to call through to the superclass when overriding this
13770     * function.
13771     *
13772     * @see Drawable#setState(int[])
13773     */
13774    protected void drawableStateChanged() {
13775        Drawable d = mBackground;
13776        if (d != null && d.isStateful()) {
13777            d.setState(getDrawableState());
13778        }
13779    }
13780
13781    /**
13782     * Call this to force a view to update its drawable state. This will cause
13783     * drawableStateChanged to be called on this view. Views that are interested
13784     * in the new state should call getDrawableState.
13785     *
13786     * @see #drawableStateChanged
13787     * @see #getDrawableState
13788     */
13789    public void refreshDrawableState() {
13790        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13791        drawableStateChanged();
13792
13793        ViewParent parent = mParent;
13794        if (parent != null) {
13795            parent.childDrawableStateChanged(this);
13796        }
13797    }
13798
13799    /**
13800     * Return an array of resource IDs of the drawable states representing the
13801     * current state of the view.
13802     *
13803     * @return The current drawable state
13804     *
13805     * @see Drawable#setState(int[])
13806     * @see #drawableStateChanged()
13807     * @see #onCreateDrawableState(int)
13808     */
13809    public final int[] getDrawableState() {
13810        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13811            return mDrawableState;
13812        } else {
13813            mDrawableState = onCreateDrawableState(0);
13814            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13815            return mDrawableState;
13816        }
13817    }
13818
13819    /**
13820     * Generate the new {@link android.graphics.drawable.Drawable} state for
13821     * this view. This is called by the view
13822     * system when the cached Drawable state is determined to be invalid.  To
13823     * retrieve the current state, you should use {@link #getDrawableState}.
13824     *
13825     * @param extraSpace if non-zero, this is the number of extra entries you
13826     * would like in the returned array in which you can place your own
13827     * states.
13828     *
13829     * @return Returns an array holding the current {@link Drawable} state of
13830     * the view.
13831     *
13832     * @see #mergeDrawableStates(int[], int[])
13833     */
13834    protected int[] onCreateDrawableState(int extraSpace) {
13835        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13836                mParent instanceof View) {
13837            return ((View) mParent).onCreateDrawableState(extraSpace);
13838        }
13839
13840        int[] drawableState;
13841
13842        int privateFlags = mPrivateFlags;
13843
13844        int viewStateIndex = 0;
13845        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13846        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13847        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13848        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13849        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13850        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13851        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13852                HardwareRenderer.isAvailable()) {
13853            // This is set if HW acceleration is requested, even if the current
13854            // process doesn't allow it.  This is just to allow app preview
13855            // windows to better match their app.
13856            viewStateIndex |= VIEW_STATE_ACCELERATED;
13857        }
13858        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13859
13860        final int privateFlags2 = mPrivateFlags2;
13861        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13862        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13863
13864        drawableState = VIEW_STATE_SETS[viewStateIndex];
13865
13866        //noinspection ConstantIfStatement
13867        if (false) {
13868            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13869            Log.i("View", toString()
13870                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13871                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13872                    + " fo=" + hasFocus()
13873                    + " sl=" + ((privateFlags & SELECTED) != 0)
13874                    + " wf=" + hasWindowFocus()
13875                    + ": " + Arrays.toString(drawableState));
13876        }
13877
13878        if (extraSpace == 0) {
13879            return drawableState;
13880        }
13881
13882        final int[] fullState;
13883        if (drawableState != null) {
13884            fullState = new int[drawableState.length + extraSpace];
13885            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13886        } else {
13887            fullState = new int[extraSpace];
13888        }
13889
13890        return fullState;
13891    }
13892
13893    /**
13894     * Merge your own state values in <var>additionalState</var> into the base
13895     * state values <var>baseState</var> that were returned by
13896     * {@link #onCreateDrawableState(int)}.
13897     *
13898     * @param baseState The base state values returned by
13899     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13900     * own additional state values.
13901     *
13902     * @param additionalState The additional state values you would like
13903     * added to <var>baseState</var>; this array is not modified.
13904     *
13905     * @return As a convenience, the <var>baseState</var> array you originally
13906     * passed into the function is returned.
13907     *
13908     * @see #onCreateDrawableState(int)
13909     */
13910    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13911        final int N = baseState.length;
13912        int i = N - 1;
13913        while (i >= 0 && baseState[i] == 0) {
13914            i--;
13915        }
13916        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13917        return baseState;
13918    }
13919
13920    /**
13921     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13922     * on all Drawable objects associated with this view.
13923     */
13924    public void jumpDrawablesToCurrentState() {
13925        if (mBackground != null) {
13926            mBackground.jumpToCurrentState();
13927        }
13928    }
13929
13930    /**
13931     * Sets the background color for this view.
13932     * @param color the color of the background
13933     */
13934    @RemotableViewMethod
13935    public void setBackgroundColor(int color) {
13936        if (mBackground instanceof ColorDrawable) {
13937            ((ColorDrawable) mBackground).setColor(color);
13938        } else {
13939            setBackground(new ColorDrawable(color));
13940        }
13941    }
13942
13943    /**
13944     * Set the background to a given resource. The resource should refer to
13945     * a Drawable object or 0 to remove the background.
13946     * @param resid The identifier of the resource.
13947     *
13948     * @attr ref android.R.styleable#View_background
13949     */
13950    @RemotableViewMethod
13951    public void setBackgroundResource(int resid) {
13952        if (resid != 0 && resid == mBackgroundResource) {
13953            return;
13954        }
13955
13956        Drawable d= null;
13957        if (resid != 0) {
13958            d = mResources.getDrawable(resid);
13959        }
13960        setBackground(d);
13961
13962        mBackgroundResource = resid;
13963    }
13964
13965    /**
13966     * Set the background to a given Drawable, or remove the background. If the
13967     * background has padding, this View's padding is set to the background's
13968     * padding. However, when a background is removed, this View's padding isn't
13969     * touched. If setting the padding is desired, please use
13970     * {@link #setPadding(int, int, int, int)}.
13971     *
13972     * @param background The Drawable to use as the background, or null to remove the
13973     *        background
13974     */
13975    public void setBackground(Drawable background) {
13976        //noinspection deprecation
13977        setBackgroundDrawable(background);
13978    }
13979
13980    /**
13981     * @deprecated use {@link #setBackground(Drawable)} instead
13982     */
13983    @Deprecated
13984    public void setBackgroundDrawable(Drawable background) {
13985        if (background == mBackground) {
13986            return;
13987        }
13988
13989        boolean requestLayout = false;
13990
13991        mBackgroundResource = 0;
13992
13993        /*
13994         * Regardless of whether we're setting a new background or not, we want
13995         * to clear the previous drawable.
13996         */
13997        if (mBackground != null) {
13998            mBackground.setCallback(null);
13999            unscheduleDrawable(mBackground);
14000        }
14001
14002        if (background != null) {
14003            Rect padding = sThreadLocal.get();
14004            if (padding == null) {
14005                padding = new Rect();
14006                sThreadLocal.set(padding);
14007            }
14008            if (background.getPadding(padding)) {
14009                switch (background.getResolvedLayoutDirectionSelf()) {
14010                    case LAYOUT_DIRECTION_RTL:
14011                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
14012                        break;
14013                    case LAYOUT_DIRECTION_LTR:
14014                    default:
14015                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14016                }
14017            }
14018
14019            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14020            // if it has a different minimum size, we should layout again
14021            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14022                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14023                requestLayout = true;
14024            }
14025
14026            background.setCallback(this);
14027            if (background.isStateful()) {
14028                background.setState(getDrawableState());
14029            }
14030            background.setVisible(getVisibility() == VISIBLE, false);
14031            mBackground = background;
14032
14033            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14034                mPrivateFlags &= ~SKIP_DRAW;
14035                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14036                requestLayout = true;
14037            }
14038        } else {
14039            /* Remove the background */
14040            mBackground = null;
14041
14042            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14043                /*
14044                 * This view ONLY drew the background before and we're removing
14045                 * the background, so now it won't draw anything
14046                 * (hence we SKIP_DRAW)
14047                 */
14048                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14049                mPrivateFlags |= SKIP_DRAW;
14050            }
14051
14052            /*
14053             * When the background is set, we try to apply its padding to this
14054             * View. When the background is removed, we don't touch this View's
14055             * padding. This is noted in the Javadocs. Hence, we don't need to
14056             * requestLayout(), the invalidate() below is sufficient.
14057             */
14058
14059            // The old background's minimum size could have affected this
14060            // View's layout, so let's requestLayout
14061            requestLayout = true;
14062        }
14063
14064        computeOpaqueFlags();
14065
14066        if (requestLayout) {
14067            requestLayout();
14068        }
14069
14070        mBackgroundSizeChanged = true;
14071        invalidate(true);
14072    }
14073
14074    /**
14075     * Gets the background drawable
14076     *
14077     * @return The drawable used as the background for this view, if any.
14078     *
14079     * @see #setBackground(Drawable)
14080     *
14081     * @attr ref android.R.styleable#View_background
14082     */
14083    public Drawable getBackground() {
14084        return mBackground;
14085    }
14086
14087    /**
14088     * Sets the padding. The view may add on the space required to display
14089     * the scrollbars, depending on the style and visibility of the scrollbars.
14090     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14091     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14092     * from the values set in this call.
14093     *
14094     * @attr ref android.R.styleable#View_padding
14095     * @attr ref android.R.styleable#View_paddingBottom
14096     * @attr ref android.R.styleable#View_paddingLeft
14097     * @attr ref android.R.styleable#View_paddingRight
14098     * @attr ref android.R.styleable#View_paddingTop
14099     * @param left the left padding in pixels
14100     * @param top the top padding in pixels
14101     * @param right the right padding in pixels
14102     * @param bottom the bottom padding in pixels
14103     */
14104    public void setPadding(int left, int top, int right, int bottom) {
14105        mUserPaddingStart = -1;
14106        mUserPaddingEnd = -1;
14107        mUserPaddingRelative = false;
14108
14109        internalSetPadding(left, top, right, bottom);
14110    }
14111
14112    private void internalSetPadding(int left, int top, int right, int bottom) {
14113        mUserPaddingLeft = left;
14114        mUserPaddingRight = right;
14115        mUserPaddingBottom = bottom;
14116
14117        final int viewFlags = mViewFlags;
14118        boolean changed = false;
14119
14120        // Common case is there are no scroll bars.
14121        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14122            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14123                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14124                        ? 0 : getVerticalScrollbarWidth();
14125                switch (mVerticalScrollbarPosition) {
14126                    case SCROLLBAR_POSITION_DEFAULT:
14127                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14128                            left += offset;
14129                        } else {
14130                            right += offset;
14131                        }
14132                        break;
14133                    case SCROLLBAR_POSITION_RIGHT:
14134                        right += offset;
14135                        break;
14136                    case SCROLLBAR_POSITION_LEFT:
14137                        left += offset;
14138                        break;
14139                }
14140            }
14141            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14142                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14143                        ? 0 : getHorizontalScrollbarHeight();
14144            }
14145        }
14146
14147        if (mPaddingLeft != left) {
14148            changed = true;
14149            mPaddingLeft = left;
14150        }
14151        if (mPaddingTop != top) {
14152            changed = true;
14153            mPaddingTop = top;
14154        }
14155        if (mPaddingRight != right) {
14156            changed = true;
14157            mPaddingRight = right;
14158        }
14159        if (mPaddingBottom != bottom) {
14160            changed = true;
14161            mPaddingBottom = bottom;
14162        }
14163
14164        if (changed) {
14165            requestLayout();
14166        }
14167    }
14168
14169    /**
14170     * Sets the relative padding. The view may add on the space required to display
14171     * the scrollbars, depending on the style and visibility of the scrollbars.
14172     * from the values set in this call.
14173     *
14174     * @param start the start padding in pixels
14175     * @param top the top padding in pixels
14176     * @param end the end padding in pixels
14177     * @param bottom the bottom padding in pixels
14178     * @hide
14179     */
14180    public void setPaddingRelative(int start, int top, int end, int bottom) {
14181        mUserPaddingStart = start;
14182        mUserPaddingEnd = end;
14183        mUserPaddingRelative = true;
14184
14185        switch(getResolvedLayoutDirection()) {
14186            case LAYOUT_DIRECTION_RTL:
14187                internalSetPadding(end, top, start, bottom);
14188                break;
14189            case LAYOUT_DIRECTION_LTR:
14190            default:
14191                internalSetPadding(start, top, end, bottom);
14192        }
14193    }
14194
14195    /**
14196     * Returns the top padding of this view.
14197     *
14198     * @return the top padding in pixels
14199     */
14200    public int getPaddingTop() {
14201        return mPaddingTop;
14202    }
14203
14204    /**
14205     * Returns the bottom padding of this view. If there are inset and enabled
14206     * scrollbars, this value may include the space required to display the
14207     * scrollbars as well.
14208     *
14209     * @return the bottom padding in pixels
14210     */
14211    public int getPaddingBottom() {
14212        return mPaddingBottom;
14213    }
14214
14215    /**
14216     * Returns the left padding of this view. If there are inset and enabled
14217     * scrollbars, this value may include the space required to display the
14218     * scrollbars as well.
14219     *
14220     * @return the left padding in pixels
14221     */
14222    public int getPaddingLeft() {
14223        return mPaddingLeft;
14224    }
14225
14226    /**
14227     * Returns the start padding of this view depending on its resolved layout direction.
14228     * If there are inset and enabled scrollbars, this value may include the space
14229     * required to display the scrollbars as well.
14230     *
14231     * @return the start padding in pixels
14232     * @hide
14233     */
14234    public int getPaddingStart() {
14235        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14236                mPaddingRight : mPaddingLeft;
14237    }
14238
14239    /**
14240     * Returns the right padding of this view. If there are inset and enabled
14241     * scrollbars, this value may include the space required to display the
14242     * scrollbars as well.
14243     *
14244     * @return the right padding in pixels
14245     */
14246    public int getPaddingRight() {
14247        return mPaddingRight;
14248    }
14249
14250    /**
14251     * Returns the end padding of this view depending on its resolved layout direction.
14252     * If there are inset and enabled scrollbars, this value may include the space
14253     * required to display the scrollbars as well.
14254     *
14255     * @return the end padding in pixels
14256     * @hide
14257     */
14258    public int getPaddingEnd() {
14259        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14260                mPaddingLeft : mPaddingRight;
14261    }
14262
14263    /**
14264     * Return if the padding as been set thru relative values
14265     * {@link #setPaddingRelative(int, int, int, int)}
14266     *
14267     * @return true if the padding is relative or false if it is not.
14268     * @hide
14269     */
14270    public boolean isPaddingRelative() {
14271        return mUserPaddingRelative;
14272    }
14273
14274    /**
14275     * @hide
14276     */
14277    public Insets getOpticalInsets() {
14278        if (mLayoutInsets == null) {
14279            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14280        }
14281        return mLayoutInsets;
14282    }
14283
14284    /**
14285     * @hide
14286     */
14287    public void setLayoutInsets(Insets layoutInsets) {
14288        mLayoutInsets = layoutInsets;
14289    }
14290
14291    /**
14292     * Changes the selection state of this view. A view can be selected or not.
14293     * Note that selection is not the same as focus. Views are typically
14294     * selected in the context of an AdapterView like ListView or GridView;
14295     * the selected view is the view that is highlighted.
14296     *
14297     * @param selected true if the view must be selected, false otherwise
14298     */
14299    public void setSelected(boolean selected) {
14300        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14301            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14302            if (!selected) resetPressedState();
14303            invalidate(true);
14304            refreshDrawableState();
14305            dispatchSetSelected(selected);
14306            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14307                notifyAccessibilityStateChanged();
14308            }
14309        }
14310    }
14311
14312    /**
14313     * Dispatch setSelected to all of this View's children.
14314     *
14315     * @see #setSelected(boolean)
14316     *
14317     * @param selected The new selected state
14318     */
14319    protected void dispatchSetSelected(boolean selected) {
14320    }
14321
14322    /**
14323     * Indicates the selection state of this view.
14324     *
14325     * @return true if the view is selected, false otherwise
14326     */
14327    @ViewDebug.ExportedProperty
14328    public boolean isSelected() {
14329        return (mPrivateFlags & SELECTED) != 0;
14330    }
14331
14332    /**
14333     * Changes the activated state of this view. A view can be activated or not.
14334     * Note that activation is not the same as selection.  Selection is
14335     * a transient property, representing the view (hierarchy) the user is
14336     * currently interacting with.  Activation is a longer-term state that the
14337     * user can move views in and out of.  For example, in a list view with
14338     * single or multiple selection enabled, the views in the current selection
14339     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14340     * here.)  The activated state is propagated down to children of the view it
14341     * is set on.
14342     *
14343     * @param activated true if the view must be activated, false otherwise
14344     */
14345    public void setActivated(boolean activated) {
14346        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14347            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14348            invalidate(true);
14349            refreshDrawableState();
14350            dispatchSetActivated(activated);
14351        }
14352    }
14353
14354    /**
14355     * Dispatch setActivated to all of this View's children.
14356     *
14357     * @see #setActivated(boolean)
14358     *
14359     * @param activated The new activated state
14360     */
14361    protected void dispatchSetActivated(boolean activated) {
14362    }
14363
14364    /**
14365     * Indicates the activation state of this view.
14366     *
14367     * @return true if the view is activated, false otherwise
14368     */
14369    @ViewDebug.ExportedProperty
14370    public boolean isActivated() {
14371        return (mPrivateFlags & ACTIVATED) != 0;
14372    }
14373
14374    /**
14375     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14376     * observer can be used to get notifications when global events, like
14377     * layout, happen.
14378     *
14379     * The returned ViewTreeObserver observer is not guaranteed to remain
14380     * valid for the lifetime of this View. If the caller of this method keeps
14381     * a long-lived reference to ViewTreeObserver, it should always check for
14382     * the return value of {@link ViewTreeObserver#isAlive()}.
14383     *
14384     * @return The ViewTreeObserver for this view's hierarchy.
14385     */
14386    public ViewTreeObserver getViewTreeObserver() {
14387        if (mAttachInfo != null) {
14388            return mAttachInfo.mTreeObserver;
14389        }
14390        if (mFloatingTreeObserver == null) {
14391            mFloatingTreeObserver = new ViewTreeObserver();
14392        }
14393        return mFloatingTreeObserver;
14394    }
14395
14396    /**
14397     * <p>Finds the topmost view in the current view hierarchy.</p>
14398     *
14399     * @return the topmost view containing this view
14400     */
14401    public View getRootView() {
14402        if (mAttachInfo != null) {
14403            final View v = mAttachInfo.mRootView;
14404            if (v != null) {
14405                return v;
14406            }
14407        }
14408
14409        View parent = this;
14410
14411        while (parent.mParent != null && parent.mParent instanceof View) {
14412            parent = (View) parent.mParent;
14413        }
14414
14415        return parent;
14416    }
14417
14418    /**
14419     * <p>Computes the coordinates of this view on the screen. The argument
14420     * must be an array of two integers. After the method returns, the array
14421     * contains the x and y location in that order.</p>
14422     *
14423     * @param location an array of two integers in which to hold the coordinates
14424     */
14425    public void getLocationOnScreen(int[] location) {
14426        getLocationInWindow(location);
14427
14428        final AttachInfo info = mAttachInfo;
14429        if (info != null) {
14430            location[0] += info.mWindowLeft;
14431            location[1] += info.mWindowTop;
14432        }
14433    }
14434
14435    /**
14436     * <p>Computes the coordinates of this view in its window. The argument
14437     * must be an array of two integers. After the method returns, the array
14438     * contains the x and y location in that order.</p>
14439     *
14440     * @param location an array of two integers in which to hold the coordinates
14441     */
14442    public void getLocationInWindow(int[] location) {
14443        if (location == null || location.length < 2) {
14444            throw new IllegalArgumentException("location must be an array of two integers");
14445        }
14446
14447        if (mAttachInfo == null) {
14448            // When the view is not attached to a window, this method does not make sense
14449            location[0] = location[1] = 0;
14450            return;
14451        }
14452
14453        float[] position = mAttachInfo.mTmpTransformLocation;
14454        position[0] = position[1] = 0.0f;
14455
14456        if (!hasIdentityMatrix()) {
14457            getMatrix().mapPoints(position);
14458        }
14459
14460        position[0] += mLeft;
14461        position[1] += mTop;
14462
14463        ViewParent viewParent = mParent;
14464        while (viewParent instanceof View) {
14465            final View view = (View) viewParent;
14466
14467            position[0] -= view.mScrollX;
14468            position[1] -= view.mScrollY;
14469
14470            if (!view.hasIdentityMatrix()) {
14471                view.getMatrix().mapPoints(position);
14472            }
14473
14474            position[0] += view.mLeft;
14475            position[1] += view.mTop;
14476
14477            viewParent = view.mParent;
14478         }
14479
14480        if (viewParent instanceof ViewRootImpl) {
14481            // *cough*
14482            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14483            position[1] -= vr.mCurScrollY;
14484        }
14485
14486        location[0] = (int) (position[0] + 0.5f);
14487        location[1] = (int) (position[1] + 0.5f);
14488    }
14489
14490    /**
14491     * {@hide}
14492     * @param id the id of the view to be found
14493     * @return the view of the specified id, null if cannot be found
14494     */
14495    protected View findViewTraversal(int id) {
14496        if (id == mID) {
14497            return this;
14498        }
14499        return null;
14500    }
14501
14502    /**
14503     * {@hide}
14504     * @param tag the tag of the view to be found
14505     * @return the view of specified tag, null if cannot be found
14506     */
14507    protected View findViewWithTagTraversal(Object tag) {
14508        if (tag != null && tag.equals(mTag)) {
14509            return this;
14510        }
14511        return null;
14512    }
14513
14514    /**
14515     * {@hide}
14516     * @param predicate The predicate to evaluate.
14517     * @param childToSkip If not null, ignores this child during the recursive traversal.
14518     * @return The first view that matches the predicate or null.
14519     */
14520    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14521        if (predicate.apply(this)) {
14522            return this;
14523        }
14524        return null;
14525    }
14526
14527    /**
14528     * Look for a child view with the given id.  If this view has the given
14529     * id, return this view.
14530     *
14531     * @param id The id to search for.
14532     * @return The view that has the given id in the hierarchy or null
14533     */
14534    public final View findViewById(int id) {
14535        if (id < 0) {
14536            return null;
14537        }
14538        return findViewTraversal(id);
14539    }
14540
14541    /**
14542     * Finds a view by its unuque and stable accessibility id.
14543     *
14544     * @param accessibilityId The searched accessibility id.
14545     * @return The found view.
14546     */
14547    final View findViewByAccessibilityId(int accessibilityId) {
14548        if (accessibilityId < 0) {
14549            return null;
14550        }
14551        return findViewByAccessibilityIdTraversal(accessibilityId);
14552    }
14553
14554    /**
14555     * Performs the traversal to find a view by its unuque and stable accessibility id.
14556     *
14557     * <strong>Note:</strong>This method does not stop at the root namespace
14558     * boundary since the user can touch the screen at an arbitrary location
14559     * potentially crossing the root namespace bounday which will send an
14560     * accessibility event to accessibility services and they should be able
14561     * to obtain the event source. Also accessibility ids are guaranteed to be
14562     * unique in the window.
14563     *
14564     * @param accessibilityId The accessibility id.
14565     * @return The found view.
14566     */
14567    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14568        if (getAccessibilityViewId() == accessibilityId) {
14569            return this;
14570        }
14571        return null;
14572    }
14573
14574    /**
14575     * Look for a child view with the given tag.  If this view has the given
14576     * tag, return this view.
14577     *
14578     * @param tag The tag to search for, using "tag.equals(getTag())".
14579     * @return The View that has the given tag in the hierarchy or null
14580     */
14581    public final View findViewWithTag(Object tag) {
14582        if (tag == null) {
14583            return null;
14584        }
14585        return findViewWithTagTraversal(tag);
14586    }
14587
14588    /**
14589     * {@hide}
14590     * Look for a child view that matches the specified predicate.
14591     * If this view matches the predicate, return this view.
14592     *
14593     * @param predicate The predicate to evaluate.
14594     * @return The first view that matches the predicate or null.
14595     */
14596    public final View findViewByPredicate(Predicate<View> predicate) {
14597        return findViewByPredicateTraversal(predicate, null);
14598    }
14599
14600    /**
14601     * {@hide}
14602     * Look for a child view that matches the specified predicate,
14603     * starting with the specified view and its descendents and then
14604     * recusively searching the ancestors and siblings of that view
14605     * until this view is reached.
14606     *
14607     * This method is useful in cases where the predicate does not match
14608     * a single unique view (perhaps multiple views use the same id)
14609     * and we are trying to find the view that is "closest" in scope to the
14610     * starting view.
14611     *
14612     * @param start The view to start from.
14613     * @param predicate The predicate to evaluate.
14614     * @return The first view that matches the predicate or null.
14615     */
14616    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14617        View childToSkip = null;
14618        for (;;) {
14619            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14620            if (view != null || start == this) {
14621                return view;
14622            }
14623
14624            ViewParent parent = start.getParent();
14625            if (parent == null || !(parent instanceof View)) {
14626                return null;
14627            }
14628
14629            childToSkip = start;
14630            start = (View) parent;
14631        }
14632    }
14633
14634    /**
14635     * Sets the identifier for this view. The identifier does not have to be
14636     * unique in this view's hierarchy. The identifier should be a positive
14637     * number.
14638     *
14639     * @see #NO_ID
14640     * @see #getId()
14641     * @see #findViewById(int)
14642     *
14643     * @param id a number used to identify the view
14644     *
14645     * @attr ref android.R.styleable#View_id
14646     */
14647    public void setId(int id) {
14648        mID = id;
14649    }
14650
14651    /**
14652     * {@hide}
14653     *
14654     * @param isRoot true if the view belongs to the root namespace, false
14655     *        otherwise
14656     */
14657    public void setIsRootNamespace(boolean isRoot) {
14658        if (isRoot) {
14659            mPrivateFlags |= IS_ROOT_NAMESPACE;
14660        } else {
14661            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14662        }
14663    }
14664
14665    /**
14666     * {@hide}
14667     *
14668     * @return true if the view belongs to the root namespace, false otherwise
14669     */
14670    public boolean isRootNamespace() {
14671        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14672    }
14673
14674    /**
14675     * Returns this view's identifier.
14676     *
14677     * @return a positive integer used to identify the view or {@link #NO_ID}
14678     *         if the view has no ID
14679     *
14680     * @see #setId(int)
14681     * @see #findViewById(int)
14682     * @attr ref android.R.styleable#View_id
14683     */
14684    @ViewDebug.CapturedViewProperty
14685    public int getId() {
14686        return mID;
14687    }
14688
14689    /**
14690     * Returns this view's tag.
14691     *
14692     * @return the Object stored in this view as a tag
14693     *
14694     * @see #setTag(Object)
14695     * @see #getTag(int)
14696     */
14697    @ViewDebug.ExportedProperty
14698    public Object getTag() {
14699        return mTag;
14700    }
14701
14702    /**
14703     * Sets the tag associated with this view. A tag can be used to mark
14704     * a view in its hierarchy and does not have to be unique within the
14705     * hierarchy. Tags can also be used to store data within a view without
14706     * resorting to another data structure.
14707     *
14708     * @param tag an Object to tag the view with
14709     *
14710     * @see #getTag()
14711     * @see #setTag(int, Object)
14712     */
14713    public void setTag(final Object tag) {
14714        mTag = tag;
14715    }
14716
14717    /**
14718     * Returns the tag associated with this view and the specified key.
14719     *
14720     * @param key The key identifying the tag
14721     *
14722     * @return the Object stored in this view as a tag
14723     *
14724     * @see #setTag(int, Object)
14725     * @see #getTag()
14726     */
14727    public Object getTag(int key) {
14728        if (mKeyedTags != null) return mKeyedTags.get(key);
14729        return null;
14730    }
14731
14732    /**
14733     * Sets a tag associated with this view and a key. A tag can be used
14734     * to mark a view in its hierarchy and does not have to be unique within
14735     * the hierarchy. Tags can also be used to store data within a view
14736     * without resorting to another data structure.
14737     *
14738     * The specified key should be an id declared in the resources of the
14739     * application to ensure it is unique (see the <a
14740     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14741     * Keys identified as belonging to
14742     * the Android framework or not associated with any package will cause
14743     * an {@link IllegalArgumentException} to be thrown.
14744     *
14745     * @param key The key identifying the tag
14746     * @param tag An Object to tag the view with
14747     *
14748     * @throws IllegalArgumentException If they specified key is not valid
14749     *
14750     * @see #setTag(Object)
14751     * @see #getTag(int)
14752     */
14753    public void setTag(int key, final Object tag) {
14754        // If the package id is 0x00 or 0x01, it's either an undefined package
14755        // or a framework id
14756        if ((key >>> 24) < 2) {
14757            throw new IllegalArgumentException("The key must be an application-specific "
14758                    + "resource id.");
14759        }
14760
14761        setKeyedTag(key, tag);
14762    }
14763
14764    /**
14765     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14766     * framework id.
14767     *
14768     * @hide
14769     */
14770    public void setTagInternal(int key, Object tag) {
14771        if ((key >>> 24) != 0x1) {
14772            throw new IllegalArgumentException("The key must be a framework-specific "
14773                    + "resource id.");
14774        }
14775
14776        setKeyedTag(key, tag);
14777    }
14778
14779    private void setKeyedTag(int key, Object tag) {
14780        if (mKeyedTags == null) {
14781            mKeyedTags = new SparseArray<Object>();
14782        }
14783
14784        mKeyedTags.put(key, tag);
14785    }
14786
14787    /**
14788     * @param consistency The type of consistency. See ViewDebug for more information.
14789     *
14790     * @hide
14791     */
14792    protected boolean dispatchConsistencyCheck(int consistency) {
14793        return onConsistencyCheck(consistency);
14794    }
14795
14796    /**
14797     * Method that subclasses should implement to check their consistency. The type of
14798     * consistency check is indicated by the bit field passed as a parameter.
14799     *
14800     * @param consistency The type of consistency. See ViewDebug for more information.
14801     *
14802     * @throws IllegalStateException if the view is in an inconsistent state.
14803     *
14804     * @hide
14805     */
14806    protected boolean onConsistencyCheck(int consistency) {
14807        boolean result = true;
14808
14809        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14810        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14811
14812        if (checkLayout) {
14813            if (getParent() == null) {
14814                result = false;
14815                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14816                        "View " + this + " does not have a parent.");
14817            }
14818
14819            if (mAttachInfo == null) {
14820                result = false;
14821                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14822                        "View " + this + " is not attached to a window.");
14823            }
14824        }
14825
14826        if (checkDrawing) {
14827            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14828            // from their draw() method
14829
14830            if ((mPrivateFlags & DRAWN) != DRAWN &&
14831                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14832                result = false;
14833                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14834                        "View " + this + " was invalidated but its drawing cache is valid.");
14835            }
14836        }
14837
14838        return result;
14839    }
14840
14841    /**
14842     * Prints information about this view in the log output, with the tag
14843     * {@link #VIEW_LOG_TAG}.
14844     *
14845     * @hide
14846     */
14847    public void debug() {
14848        debug(0);
14849    }
14850
14851    /**
14852     * Prints information about this view in the log output, with the tag
14853     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14854     * indentation defined by the <code>depth</code>.
14855     *
14856     * @param depth the indentation level
14857     *
14858     * @hide
14859     */
14860    protected void debug(int depth) {
14861        String output = debugIndent(depth - 1);
14862
14863        output += "+ " + this;
14864        int id = getId();
14865        if (id != -1) {
14866            output += " (id=" + id + ")";
14867        }
14868        Object tag = getTag();
14869        if (tag != null) {
14870            output += " (tag=" + tag + ")";
14871        }
14872        Log.d(VIEW_LOG_TAG, output);
14873
14874        if ((mPrivateFlags & FOCUSED) != 0) {
14875            output = debugIndent(depth) + " FOCUSED";
14876            Log.d(VIEW_LOG_TAG, output);
14877        }
14878
14879        output = debugIndent(depth);
14880        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14881                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14882                + "} ";
14883        Log.d(VIEW_LOG_TAG, output);
14884
14885        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14886                || mPaddingBottom != 0) {
14887            output = debugIndent(depth);
14888            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14889                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14890            Log.d(VIEW_LOG_TAG, output);
14891        }
14892
14893        output = debugIndent(depth);
14894        output += "mMeasureWidth=" + mMeasuredWidth +
14895                " mMeasureHeight=" + mMeasuredHeight;
14896        Log.d(VIEW_LOG_TAG, output);
14897
14898        output = debugIndent(depth);
14899        if (mLayoutParams == null) {
14900            output += "BAD! no layout params";
14901        } else {
14902            output = mLayoutParams.debug(output);
14903        }
14904        Log.d(VIEW_LOG_TAG, output);
14905
14906        output = debugIndent(depth);
14907        output += "flags={";
14908        output += View.printFlags(mViewFlags);
14909        output += "}";
14910        Log.d(VIEW_LOG_TAG, output);
14911
14912        output = debugIndent(depth);
14913        output += "privateFlags={";
14914        output += View.printPrivateFlags(mPrivateFlags);
14915        output += "}";
14916        Log.d(VIEW_LOG_TAG, output);
14917    }
14918
14919    /**
14920     * Creates a string of whitespaces used for indentation.
14921     *
14922     * @param depth the indentation level
14923     * @return a String containing (depth * 2 + 3) * 2 white spaces
14924     *
14925     * @hide
14926     */
14927    protected static String debugIndent(int depth) {
14928        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14929        for (int i = 0; i < (depth * 2) + 3; i++) {
14930            spaces.append(' ').append(' ');
14931        }
14932        return spaces.toString();
14933    }
14934
14935    /**
14936     * <p>Return the offset of the widget's text baseline from the widget's top
14937     * boundary. If this widget does not support baseline alignment, this
14938     * method returns -1. </p>
14939     *
14940     * @return the offset of the baseline within the widget's bounds or -1
14941     *         if baseline alignment is not supported
14942     */
14943    @ViewDebug.ExportedProperty(category = "layout")
14944    public int getBaseline() {
14945        return -1;
14946    }
14947
14948    /**
14949     * Call this when something has changed which has invalidated the
14950     * layout of this view. This will schedule a layout pass of the view
14951     * tree.
14952     */
14953    public void requestLayout() {
14954        if (ViewDebug.TRACE_HIERARCHY) {
14955            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14956        }
14957
14958        mPrivateFlags |= FORCE_LAYOUT;
14959        mPrivateFlags |= INVALIDATED;
14960
14961        if (mLayoutParams != null) {
14962            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14963        }
14964
14965        if (mParent != null && !mParent.isLayoutRequested()) {
14966            mParent.requestLayout();
14967        }
14968    }
14969
14970    /**
14971     * Forces this view to be laid out during the next layout pass.
14972     * This method does not call requestLayout() or forceLayout()
14973     * on the parent.
14974     */
14975    public void forceLayout() {
14976        mPrivateFlags |= FORCE_LAYOUT;
14977        mPrivateFlags |= INVALIDATED;
14978    }
14979
14980    /**
14981     * <p>
14982     * This is called to find out how big a view should be. The parent
14983     * supplies constraint information in the width and height parameters.
14984     * </p>
14985     *
14986     * <p>
14987     * The actual measurement work of a view is performed in
14988     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14989     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14990     * </p>
14991     *
14992     *
14993     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14994     *        parent
14995     * @param heightMeasureSpec Vertical space requirements as imposed by the
14996     *        parent
14997     *
14998     * @see #onMeasure(int, int)
14999     */
15000    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15001        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
15002                widthMeasureSpec != mOldWidthMeasureSpec ||
15003                heightMeasureSpec != mOldHeightMeasureSpec) {
15004
15005            // first clears the measured dimension flag
15006            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
15007
15008            if (ViewDebug.TRACE_HIERARCHY) {
15009                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
15010            }
15011
15012            // measure ourselves, this should set the measured dimension flag back
15013            onMeasure(widthMeasureSpec, heightMeasureSpec);
15014
15015            // flag not set, setMeasuredDimension() was not invoked, we raise
15016            // an exception to warn the developer
15017            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
15018                throw new IllegalStateException("onMeasure() did not set the"
15019                        + " measured dimension by calling"
15020                        + " setMeasuredDimension()");
15021            }
15022
15023            mPrivateFlags |= LAYOUT_REQUIRED;
15024        }
15025
15026        mOldWidthMeasureSpec = widthMeasureSpec;
15027        mOldHeightMeasureSpec = heightMeasureSpec;
15028    }
15029
15030    /**
15031     * <p>
15032     * Measure the view and its content to determine the measured width and the
15033     * measured height. This method is invoked by {@link #measure(int, int)} and
15034     * should be overriden by subclasses to provide accurate and efficient
15035     * measurement of their contents.
15036     * </p>
15037     *
15038     * <p>
15039     * <strong>CONTRACT:</strong> When overriding this method, you
15040     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15041     * measured width and height of this view. Failure to do so will trigger an
15042     * <code>IllegalStateException</code>, thrown by
15043     * {@link #measure(int, int)}. Calling the superclass'
15044     * {@link #onMeasure(int, int)} is a valid use.
15045     * </p>
15046     *
15047     * <p>
15048     * The base class implementation of measure defaults to the background size,
15049     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15050     * override {@link #onMeasure(int, int)} to provide better measurements of
15051     * their content.
15052     * </p>
15053     *
15054     * <p>
15055     * If this method is overridden, it is the subclass's responsibility to make
15056     * sure the measured height and width are at least the view's minimum height
15057     * and width ({@link #getSuggestedMinimumHeight()} and
15058     * {@link #getSuggestedMinimumWidth()}).
15059     * </p>
15060     *
15061     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15062     *                         The requirements are encoded with
15063     *                         {@link android.view.View.MeasureSpec}.
15064     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15065     *                         The requirements are encoded with
15066     *                         {@link android.view.View.MeasureSpec}.
15067     *
15068     * @see #getMeasuredWidth()
15069     * @see #getMeasuredHeight()
15070     * @see #setMeasuredDimension(int, int)
15071     * @see #getSuggestedMinimumHeight()
15072     * @see #getSuggestedMinimumWidth()
15073     * @see android.view.View.MeasureSpec#getMode(int)
15074     * @see android.view.View.MeasureSpec#getSize(int)
15075     */
15076    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15077        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15078                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15079    }
15080
15081    /**
15082     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15083     * measured width and measured height. Failing to do so will trigger an
15084     * exception at measurement time.</p>
15085     *
15086     * @param measuredWidth The measured width of this view.  May be a complex
15087     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15088     * {@link #MEASURED_STATE_TOO_SMALL}.
15089     * @param measuredHeight The measured height of this view.  May be a complex
15090     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15091     * {@link #MEASURED_STATE_TOO_SMALL}.
15092     */
15093    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15094        mMeasuredWidth = measuredWidth;
15095        mMeasuredHeight = measuredHeight;
15096
15097        mPrivateFlags |= MEASURED_DIMENSION_SET;
15098    }
15099
15100    /**
15101     * Merge two states as returned by {@link #getMeasuredState()}.
15102     * @param curState The current state as returned from a view or the result
15103     * of combining multiple views.
15104     * @param newState The new view state to combine.
15105     * @return Returns a new integer reflecting the combination of the two
15106     * states.
15107     */
15108    public static int combineMeasuredStates(int curState, int newState) {
15109        return curState | newState;
15110    }
15111
15112    /**
15113     * Version of {@link #resolveSizeAndState(int, int, int)}
15114     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15115     */
15116    public static int resolveSize(int size, int measureSpec) {
15117        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15118    }
15119
15120    /**
15121     * Utility to reconcile a desired size and state, with constraints imposed
15122     * by a MeasureSpec.  Will take the desired size, unless a different size
15123     * is imposed by the constraints.  The returned value is a compound integer,
15124     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15125     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15126     * size is smaller than the size the view wants to be.
15127     *
15128     * @param size How big the view wants to be
15129     * @param measureSpec Constraints imposed by the parent
15130     * @return Size information bit mask as defined by
15131     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15132     */
15133    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15134        int result = size;
15135        int specMode = MeasureSpec.getMode(measureSpec);
15136        int specSize =  MeasureSpec.getSize(measureSpec);
15137        switch (specMode) {
15138        case MeasureSpec.UNSPECIFIED:
15139            result = size;
15140            break;
15141        case MeasureSpec.AT_MOST:
15142            if (specSize < size) {
15143                result = specSize | MEASURED_STATE_TOO_SMALL;
15144            } else {
15145                result = size;
15146            }
15147            break;
15148        case MeasureSpec.EXACTLY:
15149            result = specSize;
15150            break;
15151        }
15152        return result | (childMeasuredState&MEASURED_STATE_MASK);
15153    }
15154
15155    /**
15156     * Utility to return a default size. Uses the supplied size if the
15157     * MeasureSpec imposed no constraints. Will get larger if allowed
15158     * by the MeasureSpec.
15159     *
15160     * @param size Default size for this view
15161     * @param measureSpec Constraints imposed by the parent
15162     * @return The size this view should be.
15163     */
15164    public static int getDefaultSize(int size, int measureSpec) {
15165        int result = size;
15166        int specMode = MeasureSpec.getMode(measureSpec);
15167        int specSize = MeasureSpec.getSize(measureSpec);
15168
15169        switch (specMode) {
15170        case MeasureSpec.UNSPECIFIED:
15171            result = size;
15172            break;
15173        case MeasureSpec.AT_MOST:
15174        case MeasureSpec.EXACTLY:
15175            result = specSize;
15176            break;
15177        }
15178        return result;
15179    }
15180
15181    /**
15182     * Returns the suggested minimum height that the view should use. This
15183     * returns the maximum of the view's minimum height
15184     * and the background's minimum height
15185     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15186     * <p>
15187     * When being used in {@link #onMeasure(int, int)}, the caller should still
15188     * ensure the returned height is within the requirements of the parent.
15189     *
15190     * @return The suggested minimum height of the view.
15191     */
15192    protected int getSuggestedMinimumHeight() {
15193        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15194
15195    }
15196
15197    /**
15198     * Returns the suggested minimum width that the view should use. This
15199     * returns the maximum of the view's minimum width)
15200     * and the background's minimum width
15201     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15202     * <p>
15203     * When being used in {@link #onMeasure(int, int)}, the caller should still
15204     * ensure the returned width is within the requirements of the parent.
15205     *
15206     * @return The suggested minimum width of the view.
15207     */
15208    protected int getSuggestedMinimumWidth() {
15209        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15210    }
15211
15212    /**
15213     * Returns the minimum height of the view.
15214     *
15215     * @return the minimum height the view will try to be.
15216     *
15217     * @see #setMinimumHeight(int)
15218     *
15219     * @attr ref android.R.styleable#View_minHeight
15220     */
15221    public int getMinimumHeight() {
15222        return mMinHeight;
15223    }
15224
15225    /**
15226     * Sets the minimum height of the view. It is not guaranteed the view will
15227     * be able to achieve this minimum height (for example, if its parent layout
15228     * constrains it with less available height).
15229     *
15230     * @param minHeight The minimum height the view will try to be.
15231     *
15232     * @see #getMinimumHeight()
15233     *
15234     * @attr ref android.R.styleable#View_minHeight
15235     */
15236    public void setMinimumHeight(int minHeight) {
15237        mMinHeight = minHeight;
15238        requestLayout();
15239    }
15240
15241    /**
15242     * Returns the minimum width of the view.
15243     *
15244     * @return the minimum width the view will try to be.
15245     *
15246     * @see #setMinimumWidth(int)
15247     *
15248     * @attr ref android.R.styleable#View_minWidth
15249     */
15250    public int getMinimumWidth() {
15251        return mMinWidth;
15252    }
15253
15254    /**
15255     * Sets the minimum width of the view. It is not guaranteed the view will
15256     * be able to achieve this minimum width (for example, if its parent layout
15257     * constrains it with less available width).
15258     *
15259     * @param minWidth The minimum width the view will try to be.
15260     *
15261     * @see #getMinimumWidth()
15262     *
15263     * @attr ref android.R.styleable#View_minWidth
15264     */
15265    public void setMinimumWidth(int minWidth) {
15266        mMinWidth = minWidth;
15267        requestLayout();
15268
15269    }
15270
15271    /**
15272     * Get the animation currently associated with this view.
15273     *
15274     * @return The animation that is currently playing or
15275     *         scheduled to play for this view.
15276     */
15277    public Animation getAnimation() {
15278        return mCurrentAnimation;
15279    }
15280
15281    /**
15282     * Start the specified animation now.
15283     *
15284     * @param animation the animation to start now
15285     */
15286    public void startAnimation(Animation animation) {
15287        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15288        setAnimation(animation);
15289        invalidateParentCaches();
15290        invalidate(true);
15291    }
15292
15293    /**
15294     * Cancels any animations for this view.
15295     */
15296    public void clearAnimation() {
15297        if (mCurrentAnimation != null) {
15298            mCurrentAnimation.detach();
15299        }
15300        mCurrentAnimation = null;
15301        invalidateParentIfNeeded();
15302    }
15303
15304    /**
15305     * Sets the next animation to play for this view.
15306     * If you want the animation to play immediately, use
15307     * {@link #startAnimation(android.view.animation.Animation)} instead.
15308     * This method provides allows fine-grained
15309     * control over the start time and invalidation, but you
15310     * must make sure that 1) the animation has a start time set, and
15311     * 2) the view's parent (which controls animations on its children)
15312     * will be invalidated when the animation is supposed to
15313     * start.
15314     *
15315     * @param animation The next animation, or null.
15316     */
15317    public void setAnimation(Animation animation) {
15318        mCurrentAnimation = animation;
15319
15320        if (animation != null) {
15321            // If the screen is off assume the animation start time is now instead of
15322            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15323            // would cause the animation to start when the screen turns back on
15324            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15325                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15326                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15327            }
15328            animation.reset();
15329        }
15330    }
15331
15332    /**
15333     * Invoked by a parent ViewGroup to notify the start of the animation
15334     * currently associated with this view. If you override this method,
15335     * always call super.onAnimationStart();
15336     *
15337     * @see #setAnimation(android.view.animation.Animation)
15338     * @see #getAnimation()
15339     */
15340    protected void onAnimationStart() {
15341        mPrivateFlags |= ANIMATION_STARTED;
15342    }
15343
15344    /**
15345     * Invoked by a parent ViewGroup to notify the end of the animation
15346     * currently associated with this view. If you override this method,
15347     * always call super.onAnimationEnd();
15348     *
15349     * @see #setAnimation(android.view.animation.Animation)
15350     * @see #getAnimation()
15351     */
15352    protected void onAnimationEnd() {
15353        mPrivateFlags &= ~ANIMATION_STARTED;
15354    }
15355
15356    /**
15357     * Invoked if there is a Transform that involves alpha. Subclass that can
15358     * draw themselves with the specified alpha should return true, and then
15359     * respect that alpha when their onDraw() is called. If this returns false
15360     * then the view may be redirected to draw into an offscreen buffer to
15361     * fulfill the request, which will look fine, but may be slower than if the
15362     * subclass handles it internally. The default implementation returns false.
15363     *
15364     * @param alpha The alpha (0..255) to apply to the view's drawing
15365     * @return true if the view can draw with the specified alpha.
15366     */
15367    protected boolean onSetAlpha(int alpha) {
15368        return false;
15369    }
15370
15371    /**
15372     * This is used by the RootView to perform an optimization when
15373     * the view hierarchy contains one or several SurfaceView.
15374     * SurfaceView is always considered transparent, but its children are not,
15375     * therefore all View objects remove themselves from the global transparent
15376     * region (passed as a parameter to this function).
15377     *
15378     * @param region The transparent region for this ViewAncestor (window).
15379     *
15380     * @return Returns true if the effective visibility of the view at this
15381     * point is opaque, regardless of the transparent region; returns false
15382     * if it is possible for underlying windows to be seen behind the view.
15383     *
15384     * {@hide}
15385     */
15386    public boolean gatherTransparentRegion(Region region) {
15387        final AttachInfo attachInfo = mAttachInfo;
15388        if (region != null && attachInfo != null) {
15389            final int pflags = mPrivateFlags;
15390            if ((pflags & SKIP_DRAW) == 0) {
15391                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15392                // remove it from the transparent region.
15393                final int[] location = attachInfo.mTransparentLocation;
15394                getLocationInWindow(location);
15395                region.op(location[0], location[1], location[0] + mRight - mLeft,
15396                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15397            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15398                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15399                // exists, so we remove the background drawable's non-transparent
15400                // parts from this transparent region.
15401                applyDrawableToTransparentRegion(mBackground, region);
15402            }
15403        }
15404        return true;
15405    }
15406
15407    /**
15408     * Play a sound effect for this view.
15409     *
15410     * <p>The framework will play sound effects for some built in actions, such as
15411     * clicking, but you may wish to play these effects in your widget,
15412     * for instance, for internal navigation.
15413     *
15414     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15415     * {@link #isSoundEffectsEnabled()} is true.
15416     *
15417     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15418     */
15419    public void playSoundEffect(int soundConstant) {
15420        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15421            return;
15422        }
15423        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15424    }
15425
15426    /**
15427     * BZZZTT!!1!
15428     *
15429     * <p>Provide haptic feedback to the user for this view.
15430     *
15431     * <p>The framework will provide haptic feedback for some built in actions,
15432     * such as long presses, but you may wish to provide feedback for your
15433     * own widget.
15434     *
15435     * <p>The feedback will only be performed if
15436     * {@link #isHapticFeedbackEnabled()} is true.
15437     *
15438     * @param feedbackConstant One of the constants defined in
15439     * {@link HapticFeedbackConstants}
15440     */
15441    public boolean performHapticFeedback(int feedbackConstant) {
15442        return performHapticFeedback(feedbackConstant, 0);
15443    }
15444
15445    /**
15446     * BZZZTT!!1!
15447     *
15448     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15449     *
15450     * @param feedbackConstant One of the constants defined in
15451     * {@link HapticFeedbackConstants}
15452     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15453     */
15454    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15455        if (mAttachInfo == null) {
15456            return false;
15457        }
15458        //noinspection SimplifiableIfStatement
15459        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15460                && !isHapticFeedbackEnabled()) {
15461            return false;
15462        }
15463        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15464                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15465    }
15466
15467    /**
15468     * Request that the visibility of the status bar or other screen/window
15469     * decorations be changed.
15470     *
15471     * <p>This method is used to put the over device UI into temporary modes
15472     * where the user's attention is focused more on the application content,
15473     * by dimming or hiding surrounding system affordances.  This is typically
15474     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15475     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15476     * to be placed behind the action bar (and with these flags other system
15477     * affordances) so that smooth transitions between hiding and showing them
15478     * can be done.
15479     *
15480     * <p>Two representative examples of the use of system UI visibility is
15481     * implementing a content browsing application (like a magazine reader)
15482     * and a video playing application.
15483     *
15484     * <p>The first code shows a typical implementation of a View in a content
15485     * browsing application.  In this implementation, the application goes
15486     * into a content-oriented mode by hiding the status bar and action bar,
15487     * and putting the navigation elements into lights out mode.  The user can
15488     * then interact with content while in this mode.  Such an application should
15489     * provide an easy way for the user to toggle out of the mode (such as to
15490     * check information in the status bar or access notifications).  In the
15491     * implementation here, this is done simply by tapping on the content.
15492     *
15493     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15494     *      content}
15495     *
15496     * <p>This second code sample shows a typical implementation of a View
15497     * in a video playing application.  In this situation, while the video is
15498     * playing the application would like to go into a complete full-screen mode,
15499     * to use as much of the display as possible for the video.  When in this state
15500     * the user can not interact with the application; the system intercepts
15501     * touching on the screen to pop the UI out of full screen mode.  See
15502     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15503     *
15504     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15505     *      content}
15506     *
15507     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15508     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15509     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15510     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15511     */
15512    public void setSystemUiVisibility(int visibility) {
15513        if (visibility != mSystemUiVisibility) {
15514            mSystemUiVisibility = visibility;
15515            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15516                mParent.recomputeViewAttributes(this);
15517            }
15518        }
15519    }
15520
15521    /**
15522     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15523     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15524     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15525     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15526     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15527     */
15528    public int getSystemUiVisibility() {
15529        return mSystemUiVisibility;
15530    }
15531
15532    /**
15533     * Returns the current system UI visibility that is currently set for
15534     * the entire window.  This is the combination of the
15535     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15536     * views in the window.
15537     */
15538    public int getWindowSystemUiVisibility() {
15539        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15540    }
15541
15542    /**
15543     * Override to find out when the window's requested system UI visibility
15544     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15545     * This is different from the callbacks recieved through
15546     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15547     * in that this is only telling you about the local request of the window,
15548     * not the actual values applied by the system.
15549     */
15550    public void onWindowSystemUiVisibilityChanged(int visible) {
15551    }
15552
15553    /**
15554     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15555     * the view hierarchy.
15556     */
15557    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15558        onWindowSystemUiVisibilityChanged(visible);
15559    }
15560
15561    /**
15562     * Set a listener to receive callbacks when the visibility of the system bar changes.
15563     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15564     */
15565    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15566        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15567        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15568            mParent.recomputeViewAttributes(this);
15569        }
15570    }
15571
15572    /**
15573     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15574     * the view hierarchy.
15575     */
15576    public void dispatchSystemUiVisibilityChanged(int visibility) {
15577        ListenerInfo li = mListenerInfo;
15578        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15579            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15580                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15581        }
15582    }
15583
15584    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15585        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15586        if (val != mSystemUiVisibility) {
15587            setSystemUiVisibility(val);
15588            return true;
15589        }
15590        return false;
15591    }
15592
15593    /** @hide */
15594    public void setDisabledSystemUiVisibility(int flags) {
15595        if (mAttachInfo != null) {
15596            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15597                mAttachInfo.mDisabledSystemUiVisibility = flags;
15598                if (mParent != null) {
15599                    mParent.recomputeViewAttributes(this);
15600                }
15601            }
15602        }
15603    }
15604
15605    /**
15606     * Creates an image that the system displays during the drag and drop
15607     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15608     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15609     * appearance as the given View. The default also positions the center of the drag shadow
15610     * directly under the touch point. If no View is provided (the constructor with no parameters
15611     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15612     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15613     * default is an invisible drag shadow.
15614     * <p>
15615     * You are not required to use the View you provide to the constructor as the basis of the
15616     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15617     * anything you want as the drag shadow.
15618     * </p>
15619     * <p>
15620     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15621     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15622     *  size and position of the drag shadow. It uses this data to construct a
15623     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15624     *  so that your application can draw the shadow image in the Canvas.
15625     * </p>
15626     *
15627     * <div class="special reference">
15628     * <h3>Developer Guides</h3>
15629     * <p>For a guide to implementing drag and drop features, read the
15630     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15631     * </div>
15632     */
15633    public static class DragShadowBuilder {
15634        private final WeakReference<View> mView;
15635
15636        /**
15637         * Constructs a shadow image builder based on a View. By default, the resulting drag
15638         * shadow will have the same appearance and dimensions as the View, with the touch point
15639         * over the center of the View.
15640         * @param view A View. Any View in scope can be used.
15641         */
15642        public DragShadowBuilder(View view) {
15643            mView = new WeakReference<View>(view);
15644        }
15645
15646        /**
15647         * Construct a shadow builder object with no associated View.  This
15648         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15649         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15650         * to supply the drag shadow's dimensions and appearance without
15651         * reference to any View object. If they are not overridden, then the result is an
15652         * invisible drag shadow.
15653         */
15654        public DragShadowBuilder() {
15655            mView = new WeakReference<View>(null);
15656        }
15657
15658        /**
15659         * Returns the View object that had been passed to the
15660         * {@link #View.DragShadowBuilder(View)}
15661         * constructor.  If that View parameter was {@code null} or if the
15662         * {@link #View.DragShadowBuilder()}
15663         * constructor was used to instantiate the builder object, this method will return
15664         * null.
15665         *
15666         * @return The View object associate with this builder object.
15667         */
15668        @SuppressWarnings({"JavadocReference"})
15669        final public View getView() {
15670            return mView.get();
15671        }
15672
15673        /**
15674         * Provides the metrics for the shadow image. These include the dimensions of
15675         * the shadow image, and the point within that shadow that should
15676         * be centered under the touch location while dragging.
15677         * <p>
15678         * The default implementation sets the dimensions of the shadow to be the
15679         * same as the dimensions of the View itself and centers the shadow under
15680         * the touch point.
15681         * </p>
15682         *
15683         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15684         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15685         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15686         * image.
15687         *
15688         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15689         * shadow image that should be underneath the touch point during the drag and drop
15690         * operation. Your application must set {@link android.graphics.Point#x} to the
15691         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15692         */
15693        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15694            final View view = mView.get();
15695            if (view != null) {
15696                shadowSize.set(view.getWidth(), view.getHeight());
15697                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15698            } else {
15699                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15700            }
15701        }
15702
15703        /**
15704         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15705         * based on the dimensions it received from the
15706         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15707         *
15708         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15709         */
15710        public void onDrawShadow(Canvas canvas) {
15711            final View view = mView.get();
15712            if (view != null) {
15713                view.draw(canvas);
15714            } else {
15715                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15716            }
15717        }
15718    }
15719
15720    /**
15721     * Starts a drag and drop operation. When your application calls this method, it passes a
15722     * {@link android.view.View.DragShadowBuilder} object to the system. The
15723     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15724     * to get metrics for the drag shadow, and then calls the object's
15725     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15726     * <p>
15727     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15728     *  drag events to all the View objects in your application that are currently visible. It does
15729     *  this either by calling the View object's drag listener (an implementation of
15730     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15731     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15732     *  Both are passed a {@link android.view.DragEvent} object that has a
15733     *  {@link android.view.DragEvent#getAction()} value of
15734     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15735     * </p>
15736     * <p>
15737     * Your application can invoke startDrag() on any attached View object. The View object does not
15738     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15739     * be related to the View the user selected for dragging.
15740     * </p>
15741     * @param data A {@link android.content.ClipData} object pointing to the data to be
15742     * transferred by the drag and drop operation.
15743     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15744     * drag shadow.
15745     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15746     * drop operation. This Object is put into every DragEvent object sent by the system during the
15747     * current drag.
15748     * <p>
15749     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15750     * to the target Views. For example, it can contain flags that differentiate between a
15751     * a copy operation and a move operation.
15752     * </p>
15753     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15754     * so the parameter should be set to 0.
15755     * @return {@code true} if the method completes successfully, or
15756     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15757     * do a drag, and so no drag operation is in progress.
15758     */
15759    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15760            Object myLocalState, int flags) {
15761        if (ViewDebug.DEBUG_DRAG) {
15762            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15763        }
15764        boolean okay = false;
15765
15766        Point shadowSize = new Point();
15767        Point shadowTouchPoint = new Point();
15768        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15769
15770        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15771                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15772            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15773        }
15774
15775        if (ViewDebug.DEBUG_DRAG) {
15776            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15777                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15778        }
15779        Surface surface = new Surface();
15780        try {
15781            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15782                    flags, shadowSize.x, shadowSize.y, surface);
15783            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15784                    + " surface=" + surface);
15785            if (token != null) {
15786                Canvas canvas = surface.lockCanvas(null);
15787                try {
15788                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15789                    shadowBuilder.onDrawShadow(canvas);
15790                } finally {
15791                    surface.unlockCanvasAndPost(canvas);
15792                }
15793
15794                final ViewRootImpl root = getViewRootImpl();
15795
15796                // Cache the local state object for delivery with DragEvents
15797                root.setLocalDragState(myLocalState);
15798
15799                // repurpose 'shadowSize' for the last touch point
15800                root.getLastTouchPoint(shadowSize);
15801
15802                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15803                        shadowSize.x, shadowSize.y,
15804                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15805                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15806
15807                // Off and running!  Release our local surface instance; the drag
15808                // shadow surface is now managed by the system process.
15809                surface.release();
15810            }
15811        } catch (Exception e) {
15812            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15813            surface.destroy();
15814        }
15815
15816        return okay;
15817    }
15818
15819    /**
15820     * Handles drag events sent by the system following a call to
15821     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15822     *<p>
15823     * When the system calls this method, it passes a
15824     * {@link android.view.DragEvent} object. A call to
15825     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15826     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15827     * operation.
15828     * @param event The {@link android.view.DragEvent} sent by the system.
15829     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15830     * in DragEvent, indicating the type of drag event represented by this object.
15831     * @return {@code true} if the method was successful, otherwise {@code false}.
15832     * <p>
15833     *  The method should return {@code true} in response to an action type of
15834     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15835     *  operation.
15836     * </p>
15837     * <p>
15838     *  The method should also return {@code true} in response to an action type of
15839     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15840     *  {@code false} if it didn't.
15841     * </p>
15842     */
15843    public boolean onDragEvent(DragEvent event) {
15844        return false;
15845    }
15846
15847    /**
15848     * Detects if this View is enabled and has a drag event listener.
15849     * If both are true, then it calls the drag event listener with the
15850     * {@link android.view.DragEvent} it received. If the drag event listener returns
15851     * {@code true}, then dispatchDragEvent() returns {@code true}.
15852     * <p>
15853     * For all other cases, the method calls the
15854     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15855     * method and returns its result.
15856     * </p>
15857     * <p>
15858     * This ensures that a drag event is always consumed, even if the View does not have a drag
15859     * event listener. However, if the View has a listener and the listener returns true, then
15860     * onDragEvent() is not called.
15861     * </p>
15862     */
15863    public boolean dispatchDragEvent(DragEvent event) {
15864        //noinspection SimplifiableIfStatement
15865        ListenerInfo li = mListenerInfo;
15866        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15867                && li.mOnDragListener.onDrag(this, event)) {
15868            return true;
15869        }
15870        return onDragEvent(event);
15871    }
15872
15873    boolean canAcceptDrag() {
15874        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15875    }
15876
15877    /**
15878     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15879     * it is ever exposed at all.
15880     * @hide
15881     */
15882    public void onCloseSystemDialogs(String reason) {
15883    }
15884
15885    /**
15886     * Given a Drawable whose bounds have been set to draw into this view,
15887     * update a Region being computed for
15888     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15889     * that any non-transparent parts of the Drawable are removed from the
15890     * given transparent region.
15891     *
15892     * @param dr The Drawable whose transparency is to be applied to the region.
15893     * @param region A Region holding the current transparency information,
15894     * where any parts of the region that are set are considered to be
15895     * transparent.  On return, this region will be modified to have the
15896     * transparency information reduced by the corresponding parts of the
15897     * Drawable that are not transparent.
15898     * {@hide}
15899     */
15900    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15901        if (DBG) {
15902            Log.i("View", "Getting transparent region for: " + this);
15903        }
15904        final Region r = dr.getTransparentRegion();
15905        final Rect db = dr.getBounds();
15906        final AttachInfo attachInfo = mAttachInfo;
15907        if (r != null && attachInfo != null) {
15908            final int w = getRight()-getLeft();
15909            final int h = getBottom()-getTop();
15910            if (db.left > 0) {
15911                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15912                r.op(0, 0, db.left, h, Region.Op.UNION);
15913            }
15914            if (db.right < w) {
15915                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15916                r.op(db.right, 0, w, h, Region.Op.UNION);
15917            }
15918            if (db.top > 0) {
15919                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15920                r.op(0, 0, w, db.top, Region.Op.UNION);
15921            }
15922            if (db.bottom < h) {
15923                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15924                r.op(0, db.bottom, w, h, Region.Op.UNION);
15925            }
15926            final int[] location = attachInfo.mTransparentLocation;
15927            getLocationInWindow(location);
15928            r.translate(location[0], location[1]);
15929            region.op(r, Region.Op.INTERSECT);
15930        } else {
15931            region.op(db, Region.Op.DIFFERENCE);
15932        }
15933    }
15934
15935    private void checkForLongClick(int delayOffset) {
15936        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15937            mHasPerformedLongPress = false;
15938
15939            if (mPendingCheckForLongPress == null) {
15940                mPendingCheckForLongPress = new CheckForLongPress();
15941            }
15942            mPendingCheckForLongPress.rememberWindowAttachCount();
15943            postDelayed(mPendingCheckForLongPress,
15944                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15945        }
15946    }
15947
15948    /**
15949     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15950     * LayoutInflater} class, which provides a full range of options for view inflation.
15951     *
15952     * @param context The Context object for your activity or application.
15953     * @param resource The resource ID to inflate
15954     * @param root A view group that will be the parent.  Used to properly inflate the
15955     * layout_* parameters.
15956     * @see LayoutInflater
15957     */
15958    public static View inflate(Context context, int resource, ViewGroup root) {
15959        LayoutInflater factory = LayoutInflater.from(context);
15960        return factory.inflate(resource, root);
15961    }
15962
15963    /**
15964     * Scroll the view with standard behavior for scrolling beyond the normal
15965     * content boundaries. Views that call this method should override
15966     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15967     * results of an over-scroll operation.
15968     *
15969     * Views can use this method to handle any touch or fling-based scrolling.
15970     *
15971     * @param deltaX Change in X in pixels
15972     * @param deltaY Change in Y in pixels
15973     * @param scrollX Current X scroll value in pixels before applying deltaX
15974     * @param scrollY Current Y scroll value in pixels before applying deltaY
15975     * @param scrollRangeX Maximum content scroll range along the X axis
15976     * @param scrollRangeY Maximum content scroll range along the Y axis
15977     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15978     *          along the X axis.
15979     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15980     *          along the Y axis.
15981     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15982     * @return true if scrolling was clamped to an over-scroll boundary along either
15983     *          axis, false otherwise.
15984     */
15985    @SuppressWarnings({"UnusedParameters"})
15986    protected boolean overScrollBy(int deltaX, int deltaY,
15987            int scrollX, int scrollY,
15988            int scrollRangeX, int scrollRangeY,
15989            int maxOverScrollX, int maxOverScrollY,
15990            boolean isTouchEvent) {
15991        final int overScrollMode = mOverScrollMode;
15992        final boolean canScrollHorizontal =
15993                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15994        final boolean canScrollVertical =
15995                computeVerticalScrollRange() > computeVerticalScrollExtent();
15996        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15997                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15998        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15999                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16000
16001        int newScrollX = scrollX + deltaX;
16002        if (!overScrollHorizontal) {
16003            maxOverScrollX = 0;
16004        }
16005
16006        int newScrollY = scrollY + deltaY;
16007        if (!overScrollVertical) {
16008            maxOverScrollY = 0;
16009        }
16010
16011        // Clamp values if at the limits and record
16012        final int left = -maxOverScrollX;
16013        final int right = maxOverScrollX + scrollRangeX;
16014        final int top = -maxOverScrollY;
16015        final int bottom = maxOverScrollY + scrollRangeY;
16016
16017        boolean clampedX = false;
16018        if (newScrollX > right) {
16019            newScrollX = right;
16020            clampedX = true;
16021        } else if (newScrollX < left) {
16022            newScrollX = left;
16023            clampedX = true;
16024        }
16025
16026        boolean clampedY = false;
16027        if (newScrollY > bottom) {
16028            newScrollY = bottom;
16029            clampedY = true;
16030        } else if (newScrollY < top) {
16031            newScrollY = top;
16032            clampedY = true;
16033        }
16034
16035        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16036
16037        return clampedX || clampedY;
16038    }
16039
16040    /**
16041     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16042     * respond to the results of an over-scroll operation.
16043     *
16044     * @param scrollX New X scroll value in pixels
16045     * @param scrollY New Y scroll value in pixels
16046     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16047     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16048     */
16049    protected void onOverScrolled(int scrollX, int scrollY,
16050            boolean clampedX, boolean clampedY) {
16051        // Intentionally empty.
16052    }
16053
16054    /**
16055     * Returns the over-scroll mode for this view. The result will be
16056     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16057     * (allow over-scrolling only if the view content is larger than the container),
16058     * or {@link #OVER_SCROLL_NEVER}.
16059     *
16060     * @return This view's over-scroll mode.
16061     */
16062    public int getOverScrollMode() {
16063        return mOverScrollMode;
16064    }
16065
16066    /**
16067     * Set the over-scroll mode for this view. Valid over-scroll modes are
16068     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16069     * (allow over-scrolling only if the view content is larger than the container),
16070     * or {@link #OVER_SCROLL_NEVER}.
16071     *
16072     * Setting the over-scroll mode of a view will have an effect only if the
16073     * view is capable of scrolling.
16074     *
16075     * @param overScrollMode The new over-scroll mode for this view.
16076     */
16077    public void setOverScrollMode(int overScrollMode) {
16078        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16079                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16080                overScrollMode != OVER_SCROLL_NEVER) {
16081            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16082        }
16083        mOverScrollMode = overScrollMode;
16084    }
16085
16086    /**
16087     * Gets a scale factor that determines the distance the view should scroll
16088     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16089     * @return The vertical scroll scale factor.
16090     * @hide
16091     */
16092    protected float getVerticalScrollFactor() {
16093        if (mVerticalScrollFactor == 0) {
16094            TypedValue outValue = new TypedValue();
16095            if (!mContext.getTheme().resolveAttribute(
16096                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16097                throw new IllegalStateException(
16098                        "Expected theme to define listPreferredItemHeight.");
16099            }
16100            mVerticalScrollFactor = outValue.getDimension(
16101                    mContext.getResources().getDisplayMetrics());
16102        }
16103        return mVerticalScrollFactor;
16104    }
16105
16106    /**
16107     * Gets a scale factor that determines the distance the view should scroll
16108     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16109     * @return The horizontal scroll scale factor.
16110     * @hide
16111     */
16112    protected float getHorizontalScrollFactor() {
16113        // TODO: Should use something else.
16114        return getVerticalScrollFactor();
16115    }
16116
16117    /**
16118     * Return the value specifying the text direction or policy that was set with
16119     * {@link #setTextDirection(int)}.
16120     *
16121     * @return the defined text direction. It can be one of:
16122     *
16123     * {@link #TEXT_DIRECTION_INHERIT},
16124     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16125     * {@link #TEXT_DIRECTION_ANY_RTL},
16126     * {@link #TEXT_DIRECTION_LTR},
16127     * {@link #TEXT_DIRECTION_RTL},
16128     * {@link #TEXT_DIRECTION_LOCALE}
16129     * @hide
16130     */
16131    @ViewDebug.ExportedProperty(category = "text", mapping = {
16132            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16133            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16134            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16135            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16136            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16137            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16138    })
16139    public int getTextDirection() {
16140        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16141    }
16142
16143    /**
16144     * Set the text direction.
16145     *
16146     * @param textDirection the direction to set. Should be one of:
16147     *
16148     * {@link #TEXT_DIRECTION_INHERIT},
16149     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16150     * {@link #TEXT_DIRECTION_ANY_RTL},
16151     * {@link #TEXT_DIRECTION_LTR},
16152     * {@link #TEXT_DIRECTION_RTL},
16153     * {@link #TEXT_DIRECTION_LOCALE}
16154     * @hide
16155     */
16156    public void setTextDirection(int textDirection) {
16157        if (getTextDirection() != textDirection) {
16158            // Reset the current text direction and the resolved one
16159            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16160            resetResolvedTextDirection();
16161            // Set the new text direction
16162            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16163            // Refresh
16164            requestLayout();
16165            invalidate(true);
16166        }
16167    }
16168
16169    /**
16170     * Return the resolved text direction.
16171     *
16172     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16173     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16174     * up the parent chain of the view. if there is no parent, then it will return the default
16175     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16176     *
16177     * @return the resolved text direction. Returns one of:
16178     *
16179     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16180     * {@link #TEXT_DIRECTION_ANY_RTL},
16181     * {@link #TEXT_DIRECTION_LTR},
16182     * {@link #TEXT_DIRECTION_RTL},
16183     * {@link #TEXT_DIRECTION_LOCALE}
16184     * @hide
16185     */
16186    public int getResolvedTextDirection() {
16187        // The text direction will be resolved only if needed
16188        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16189            resolveTextDirection();
16190        }
16191        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16192    }
16193
16194    /**
16195     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16196     * resolution is done.
16197     * @hide
16198     */
16199    public void resolveTextDirection() {
16200        // Reset any previous text direction resolution
16201        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16202
16203        if (hasRtlSupport()) {
16204            // Set resolved text direction flag depending on text direction flag
16205            final int textDirection = getTextDirection();
16206            switch(textDirection) {
16207                case TEXT_DIRECTION_INHERIT:
16208                    if (canResolveTextDirection()) {
16209                        ViewGroup viewGroup = ((ViewGroup) mParent);
16210
16211                        // Set current resolved direction to the same value as the parent's one
16212                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16213                        switch (parentResolvedDirection) {
16214                            case TEXT_DIRECTION_FIRST_STRONG:
16215                            case TEXT_DIRECTION_ANY_RTL:
16216                            case TEXT_DIRECTION_LTR:
16217                            case TEXT_DIRECTION_RTL:
16218                            case TEXT_DIRECTION_LOCALE:
16219                                mPrivateFlags2 |=
16220                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16221                                break;
16222                            default:
16223                                // Default resolved direction is "first strong" heuristic
16224                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16225                        }
16226                    } else {
16227                        // We cannot do the resolution if there is no parent, so use the default one
16228                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16229                    }
16230                    break;
16231                case TEXT_DIRECTION_FIRST_STRONG:
16232                case TEXT_DIRECTION_ANY_RTL:
16233                case TEXT_DIRECTION_LTR:
16234                case TEXT_DIRECTION_RTL:
16235                case TEXT_DIRECTION_LOCALE:
16236                    // Resolved direction is the same as text direction
16237                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16238                    break;
16239                default:
16240                    // Default resolved direction is "first strong" heuristic
16241                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16242            }
16243        } else {
16244            // Default resolved direction is "first strong" heuristic
16245            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16246        }
16247
16248        // Set to resolved
16249        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16250        onResolvedTextDirectionChanged();
16251    }
16252
16253    /**
16254     * Called when text direction has been resolved. Subclasses that care about text direction
16255     * resolution should override this method.
16256     *
16257     * The default implementation does nothing.
16258     * @hide
16259     */
16260    public void onResolvedTextDirectionChanged() {
16261    }
16262
16263    /**
16264     * Check if text direction resolution can be done.
16265     *
16266     * @return true if text direction resolution can be done otherwise return false.
16267     * @hide
16268     */
16269    public boolean canResolveTextDirection() {
16270        switch (getTextDirection()) {
16271            case TEXT_DIRECTION_INHERIT:
16272                return (mParent != null) && (mParent instanceof ViewGroup);
16273            default:
16274                return true;
16275        }
16276    }
16277
16278    /**
16279     * Reset resolved text direction. Text direction can be resolved with a call to
16280     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16281     * reset is done.
16282     * @hide
16283     */
16284    public void resetResolvedTextDirection() {
16285        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16286        onResolvedTextDirectionReset();
16287    }
16288
16289    /**
16290     * Called when text direction is reset. Subclasses that care about text direction reset should
16291     * override this method and do a reset of the text direction of their children. The default
16292     * implementation does nothing.
16293     * @hide
16294     */
16295    public void onResolvedTextDirectionReset() {
16296    }
16297
16298    /**
16299     * Return the value specifying the text alignment or policy that was set with
16300     * {@link #setTextAlignment(int)}.
16301     *
16302     * @return the defined text alignment. It can be one of:
16303     *
16304     * {@link #TEXT_ALIGNMENT_INHERIT},
16305     * {@link #TEXT_ALIGNMENT_GRAVITY},
16306     * {@link #TEXT_ALIGNMENT_CENTER},
16307     * {@link #TEXT_ALIGNMENT_TEXT_START},
16308     * {@link #TEXT_ALIGNMENT_TEXT_END},
16309     * {@link #TEXT_ALIGNMENT_VIEW_START},
16310     * {@link #TEXT_ALIGNMENT_VIEW_END}
16311     * @hide
16312     */
16313    @ViewDebug.ExportedProperty(category = "text", mapping = {
16314            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16315            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16316            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16317            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16318            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16319            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16320            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16321    })
16322    public int getTextAlignment() {
16323        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16324    }
16325
16326    /**
16327     * Set the text alignment.
16328     *
16329     * @param textAlignment The text alignment to set. Should be one of
16330     *
16331     * {@link #TEXT_ALIGNMENT_INHERIT},
16332     * {@link #TEXT_ALIGNMENT_GRAVITY},
16333     * {@link #TEXT_ALIGNMENT_CENTER},
16334     * {@link #TEXT_ALIGNMENT_TEXT_START},
16335     * {@link #TEXT_ALIGNMENT_TEXT_END},
16336     * {@link #TEXT_ALIGNMENT_VIEW_START},
16337     * {@link #TEXT_ALIGNMENT_VIEW_END}
16338     *
16339     * @attr ref android.R.styleable#View_textAlignment
16340     * @hide
16341     */
16342    public void setTextAlignment(int textAlignment) {
16343        if (textAlignment != getTextAlignment()) {
16344            // Reset the current and resolved text alignment
16345            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16346            resetResolvedTextAlignment();
16347            // Set the new text alignment
16348            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16349            // Refresh
16350            requestLayout();
16351            invalidate(true);
16352        }
16353    }
16354
16355    /**
16356     * Return the resolved text alignment.
16357     *
16358     * The resolved text alignment. This needs resolution if the value is
16359     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16360     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16361     *
16362     * @return the resolved text alignment. Returns one of:
16363     *
16364     * {@link #TEXT_ALIGNMENT_GRAVITY},
16365     * {@link #TEXT_ALIGNMENT_CENTER},
16366     * {@link #TEXT_ALIGNMENT_TEXT_START},
16367     * {@link #TEXT_ALIGNMENT_TEXT_END},
16368     * {@link #TEXT_ALIGNMENT_VIEW_START},
16369     * {@link #TEXT_ALIGNMENT_VIEW_END}
16370     * @hide
16371     */
16372    @ViewDebug.ExportedProperty(category = "text", mapping = {
16373            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16374            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16375            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16376            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16377            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16378            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16379            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16380    })
16381    public int getResolvedTextAlignment() {
16382        // If text alignment is not resolved, then resolve it
16383        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16384            resolveTextAlignment();
16385        }
16386        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16387    }
16388
16389    /**
16390     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16391     * resolution is done.
16392     * @hide
16393     */
16394    public void resolveTextAlignment() {
16395        // Reset any previous text alignment resolution
16396        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16397
16398        if (hasRtlSupport()) {
16399            // Set resolved text alignment flag depending on text alignment flag
16400            final int textAlignment = getTextAlignment();
16401            switch (textAlignment) {
16402                case TEXT_ALIGNMENT_INHERIT:
16403                    // Check if we can resolve the text alignment
16404                    if (canResolveLayoutDirection() && mParent instanceof View) {
16405                        View view = (View) mParent;
16406
16407                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16408                        switch (parentResolvedTextAlignment) {
16409                            case TEXT_ALIGNMENT_GRAVITY:
16410                            case TEXT_ALIGNMENT_TEXT_START:
16411                            case TEXT_ALIGNMENT_TEXT_END:
16412                            case TEXT_ALIGNMENT_CENTER:
16413                            case TEXT_ALIGNMENT_VIEW_START:
16414                            case TEXT_ALIGNMENT_VIEW_END:
16415                                // Resolved text alignment is the same as the parent resolved
16416                                // text alignment
16417                                mPrivateFlags2 |=
16418                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16419                                break;
16420                            default:
16421                                // Use default resolved text alignment
16422                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16423                        }
16424                    }
16425                    else {
16426                        // We cannot do the resolution if there is no parent so use the default
16427                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16428                    }
16429                    break;
16430                case TEXT_ALIGNMENT_GRAVITY:
16431                case TEXT_ALIGNMENT_TEXT_START:
16432                case TEXT_ALIGNMENT_TEXT_END:
16433                case TEXT_ALIGNMENT_CENTER:
16434                case TEXT_ALIGNMENT_VIEW_START:
16435                case TEXT_ALIGNMENT_VIEW_END:
16436                    // Resolved text alignment is the same as text alignment
16437                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16438                    break;
16439                default:
16440                    // Use default resolved text alignment
16441                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16442            }
16443        } else {
16444            // Use default resolved text alignment
16445            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16446        }
16447
16448        // Set the resolved
16449        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16450        onResolvedTextAlignmentChanged();
16451    }
16452
16453    /**
16454     * Check if text alignment resolution can be done.
16455     *
16456     * @return true if text alignment resolution can be done otherwise return false.
16457     * @hide
16458     */
16459    public boolean canResolveTextAlignment() {
16460        switch (getTextAlignment()) {
16461            case TEXT_DIRECTION_INHERIT:
16462                return (mParent != null);
16463            default:
16464                return true;
16465        }
16466    }
16467
16468    /**
16469     * Called when text alignment has been resolved. Subclasses that care about text alignment
16470     * resolution should override this method.
16471     *
16472     * The default implementation does nothing.
16473     * @hide
16474     */
16475    public void onResolvedTextAlignmentChanged() {
16476    }
16477
16478    /**
16479     * Reset resolved text alignment. Text alignment can be resolved with a call to
16480     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16481     * reset is done.
16482     * @hide
16483     */
16484    public void resetResolvedTextAlignment() {
16485        // Reset any previous text alignment resolution
16486        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16487        onResolvedTextAlignmentReset();
16488    }
16489
16490    /**
16491     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16492     * override this method and do a reset of the text alignment of their children. The default
16493     * implementation does nothing.
16494     * @hide
16495     */
16496    public void onResolvedTextAlignmentReset() {
16497    }
16498
16499    //
16500    // Properties
16501    //
16502    /**
16503     * A Property wrapper around the <code>alpha</code> functionality handled by the
16504     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16505     */
16506    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16507        @Override
16508        public void setValue(View object, float value) {
16509            object.setAlpha(value);
16510        }
16511
16512        @Override
16513        public Float get(View object) {
16514            return object.getAlpha();
16515        }
16516    };
16517
16518    /**
16519     * A Property wrapper around the <code>translationX</code> functionality handled by the
16520     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16521     */
16522    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16523        @Override
16524        public void setValue(View object, float value) {
16525            object.setTranslationX(value);
16526        }
16527
16528                @Override
16529        public Float get(View object) {
16530            return object.getTranslationX();
16531        }
16532    };
16533
16534    /**
16535     * A Property wrapper around the <code>translationY</code> functionality handled by the
16536     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16537     */
16538    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16539        @Override
16540        public void setValue(View object, float value) {
16541            object.setTranslationY(value);
16542        }
16543
16544        @Override
16545        public Float get(View object) {
16546            return object.getTranslationY();
16547        }
16548    };
16549
16550    /**
16551     * A Property wrapper around the <code>x</code> functionality handled by the
16552     * {@link View#setX(float)} and {@link View#getX()} methods.
16553     */
16554    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16555        @Override
16556        public void setValue(View object, float value) {
16557            object.setX(value);
16558        }
16559
16560        @Override
16561        public Float get(View object) {
16562            return object.getX();
16563        }
16564    };
16565
16566    /**
16567     * A Property wrapper around the <code>y</code> functionality handled by the
16568     * {@link View#setY(float)} and {@link View#getY()} methods.
16569     */
16570    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16571        @Override
16572        public void setValue(View object, float value) {
16573            object.setY(value);
16574        }
16575
16576        @Override
16577        public Float get(View object) {
16578            return object.getY();
16579        }
16580    };
16581
16582    /**
16583     * A Property wrapper around the <code>rotation</code> functionality handled by the
16584     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16585     */
16586    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16587        @Override
16588        public void setValue(View object, float value) {
16589            object.setRotation(value);
16590        }
16591
16592        @Override
16593        public Float get(View object) {
16594            return object.getRotation();
16595        }
16596    };
16597
16598    /**
16599     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16600     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16601     */
16602    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16603        @Override
16604        public void setValue(View object, float value) {
16605            object.setRotationX(value);
16606        }
16607
16608        @Override
16609        public Float get(View object) {
16610            return object.getRotationX();
16611        }
16612    };
16613
16614    /**
16615     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16616     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16617     */
16618    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16619        @Override
16620        public void setValue(View object, float value) {
16621            object.setRotationY(value);
16622        }
16623
16624        @Override
16625        public Float get(View object) {
16626            return object.getRotationY();
16627        }
16628    };
16629
16630    /**
16631     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16632     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16633     */
16634    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16635        @Override
16636        public void setValue(View object, float value) {
16637            object.setScaleX(value);
16638        }
16639
16640        @Override
16641        public Float get(View object) {
16642            return object.getScaleX();
16643        }
16644    };
16645
16646    /**
16647     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16648     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16649     */
16650    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16651        @Override
16652        public void setValue(View object, float value) {
16653            object.setScaleY(value);
16654        }
16655
16656        @Override
16657        public Float get(View object) {
16658            return object.getScaleY();
16659        }
16660    };
16661
16662    /**
16663     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16664     * Each MeasureSpec represents a requirement for either the width or the height.
16665     * A MeasureSpec is comprised of a size and a mode. There are three possible
16666     * modes:
16667     * <dl>
16668     * <dt>UNSPECIFIED</dt>
16669     * <dd>
16670     * The parent has not imposed any constraint on the child. It can be whatever size
16671     * it wants.
16672     * </dd>
16673     *
16674     * <dt>EXACTLY</dt>
16675     * <dd>
16676     * The parent has determined an exact size for the child. The child is going to be
16677     * given those bounds regardless of how big it wants to be.
16678     * </dd>
16679     *
16680     * <dt>AT_MOST</dt>
16681     * <dd>
16682     * The child can be as large as it wants up to the specified size.
16683     * </dd>
16684     * </dl>
16685     *
16686     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16687     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16688     */
16689    public static class MeasureSpec {
16690        private static final int MODE_SHIFT = 30;
16691        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16692
16693        /**
16694         * Measure specification mode: The parent has not imposed any constraint
16695         * on the child. It can be whatever size it wants.
16696         */
16697        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16698
16699        /**
16700         * Measure specification mode: The parent has determined an exact size
16701         * for the child. The child is going to be given those bounds regardless
16702         * of how big it wants to be.
16703         */
16704        public static final int EXACTLY     = 1 << MODE_SHIFT;
16705
16706        /**
16707         * Measure specification mode: The child can be as large as it wants up
16708         * to the specified size.
16709         */
16710        public static final int AT_MOST     = 2 << MODE_SHIFT;
16711
16712        /**
16713         * Creates a measure specification based on the supplied size and mode.
16714         *
16715         * The mode must always be one of the following:
16716         * <ul>
16717         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16718         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16719         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16720         * </ul>
16721         *
16722         * @param size the size of the measure specification
16723         * @param mode the mode of the measure specification
16724         * @return the measure specification based on size and mode
16725         */
16726        public static int makeMeasureSpec(int size, int mode) {
16727            return size + mode;
16728        }
16729
16730        /**
16731         * Extracts the mode from the supplied measure specification.
16732         *
16733         * @param measureSpec the measure specification to extract the mode from
16734         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16735         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16736         *         {@link android.view.View.MeasureSpec#EXACTLY}
16737         */
16738        public static int getMode(int measureSpec) {
16739            return (measureSpec & MODE_MASK);
16740        }
16741
16742        /**
16743         * Extracts the size from the supplied measure specification.
16744         *
16745         * @param measureSpec the measure specification to extract the size from
16746         * @return the size in pixels defined in the supplied measure specification
16747         */
16748        public static int getSize(int measureSpec) {
16749            return (measureSpec & ~MODE_MASK);
16750        }
16751
16752        /**
16753         * Returns a String representation of the specified measure
16754         * specification.
16755         *
16756         * @param measureSpec the measure specification to convert to a String
16757         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16758         */
16759        public static String toString(int measureSpec) {
16760            int mode = getMode(measureSpec);
16761            int size = getSize(measureSpec);
16762
16763            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16764
16765            if (mode == UNSPECIFIED)
16766                sb.append("UNSPECIFIED ");
16767            else if (mode == EXACTLY)
16768                sb.append("EXACTLY ");
16769            else if (mode == AT_MOST)
16770                sb.append("AT_MOST ");
16771            else
16772                sb.append(mode).append(" ");
16773
16774            sb.append(size);
16775            return sb.toString();
16776        }
16777    }
16778
16779    class CheckForLongPress implements Runnable {
16780
16781        private int mOriginalWindowAttachCount;
16782
16783        public void run() {
16784            if (isPressed() && (mParent != null)
16785                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16786                if (performLongClick()) {
16787                    mHasPerformedLongPress = true;
16788                }
16789            }
16790        }
16791
16792        public void rememberWindowAttachCount() {
16793            mOriginalWindowAttachCount = mWindowAttachCount;
16794        }
16795    }
16796
16797    private final class CheckForTap implements Runnable {
16798        public void run() {
16799            mPrivateFlags &= ~PREPRESSED;
16800            setPressed(true);
16801            checkForLongClick(ViewConfiguration.getTapTimeout());
16802        }
16803    }
16804
16805    private final class PerformClick implements Runnable {
16806        public void run() {
16807            performClick();
16808        }
16809    }
16810
16811    /** @hide */
16812    public void hackTurnOffWindowResizeAnim(boolean off) {
16813        mAttachInfo.mTurnOffWindowResizeAnim = off;
16814    }
16815
16816    /**
16817     * This method returns a ViewPropertyAnimator object, which can be used to animate
16818     * specific properties on this View.
16819     *
16820     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16821     */
16822    public ViewPropertyAnimator animate() {
16823        if (mAnimator == null) {
16824            mAnimator = new ViewPropertyAnimator(this);
16825        }
16826        return mAnimator;
16827    }
16828
16829    /**
16830     * Interface definition for a callback to be invoked when a key event is
16831     * dispatched to this view. The callback will be invoked before the key
16832     * event is given to the view.
16833     */
16834    public interface OnKeyListener {
16835        /**
16836         * Called when a key is dispatched to a view. This allows listeners to
16837         * get a chance to respond before the target view.
16838         *
16839         * @param v The view the key has been dispatched to.
16840         * @param keyCode The code for the physical key that was pressed
16841         * @param event The KeyEvent object containing full information about
16842         *        the event.
16843         * @return True if the listener has consumed the event, false otherwise.
16844         */
16845        boolean onKey(View v, int keyCode, KeyEvent event);
16846    }
16847
16848    /**
16849     * Interface definition for a callback to be invoked when a touch event is
16850     * dispatched to this view. The callback will be invoked before the touch
16851     * event is given to the view.
16852     */
16853    public interface OnTouchListener {
16854        /**
16855         * Called when a touch event is dispatched to a view. This allows listeners to
16856         * get a chance to respond before the target view.
16857         *
16858         * @param v The view the touch event has been dispatched to.
16859         * @param event The MotionEvent object containing full information about
16860         *        the event.
16861         * @return True if the listener has consumed the event, false otherwise.
16862         */
16863        boolean onTouch(View v, MotionEvent event);
16864    }
16865
16866    /**
16867     * Interface definition for a callback to be invoked when a hover event is
16868     * dispatched to this view. The callback will be invoked before the hover
16869     * event is given to the view.
16870     */
16871    public interface OnHoverListener {
16872        /**
16873         * Called when a hover event is dispatched to a view. This allows listeners to
16874         * get a chance to respond before the target view.
16875         *
16876         * @param v The view the hover event has been dispatched to.
16877         * @param event The MotionEvent object containing full information about
16878         *        the event.
16879         * @return True if the listener has consumed the event, false otherwise.
16880         */
16881        boolean onHover(View v, MotionEvent event);
16882    }
16883
16884    /**
16885     * Interface definition for a callback to be invoked when a generic motion event is
16886     * dispatched to this view. The callback will be invoked before the generic motion
16887     * event is given to the view.
16888     */
16889    public interface OnGenericMotionListener {
16890        /**
16891         * Called when a generic motion event is dispatched to a view. This allows listeners to
16892         * get a chance to respond before the target view.
16893         *
16894         * @param v The view the generic motion event has been dispatched to.
16895         * @param event The MotionEvent object containing full information about
16896         *        the event.
16897         * @return True if the listener has consumed the event, false otherwise.
16898         */
16899        boolean onGenericMotion(View v, MotionEvent event);
16900    }
16901
16902    /**
16903     * Interface definition for a callback to be invoked when a view has been clicked and held.
16904     */
16905    public interface OnLongClickListener {
16906        /**
16907         * Called when a view has been clicked and held.
16908         *
16909         * @param v The view that was clicked and held.
16910         *
16911         * @return true if the callback consumed the long click, false otherwise.
16912         */
16913        boolean onLongClick(View v);
16914    }
16915
16916    /**
16917     * Interface definition for a callback to be invoked when a drag is being dispatched
16918     * to this view.  The callback will be invoked before the hosting view's own
16919     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16920     * onDrag(event) behavior, it should return 'false' from this callback.
16921     *
16922     * <div class="special reference">
16923     * <h3>Developer Guides</h3>
16924     * <p>For a guide to implementing drag and drop features, read the
16925     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16926     * </div>
16927     */
16928    public interface OnDragListener {
16929        /**
16930         * Called when a drag event is dispatched to a view. This allows listeners
16931         * to get a chance to override base View behavior.
16932         *
16933         * @param v The View that received the drag event.
16934         * @param event The {@link android.view.DragEvent} object for the drag event.
16935         * @return {@code true} if the drag event was handled successfully, or {@code false}
16936         * if the drag event was not handled. Note that {@code false} will trigger the View
16937         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16938         */
16939        boolean onDrag(View v, DragEvent event);
16940    }
16941
16942    /**
16943     * Interface definition for a callback to be invoked when the focus state of
16944     * a view changed.
16945     */
16946    public interface OnFocusChangeListener {
16947        /**
16948         * Called when the focus state of a view has changed.
16949         *
16950         * @param v The view whose state has changed.
16951         * @param hasFocus The new focus state of v.
16952         */
16953        void onFocusChange(View v, boolean hasFocus);
16954    }
16955
16956    /**
16957     * Interface definition for a callback to be invoked when a view is clicked.
16958     */
16959    public interface OnClickListener {
16960        /**
16961         * Called when a view has been clicked.
16962         *
16963         * @param v The view that was clicked.
16964         */
16965        void onClick(View v);
16966    }
16967
16968    /**
16969     * Interface definition for a callback to be invoked when the context menu
16970     * for this view is being built.
16971     */
16972    public interface OnCreateContextMenuListener {
16973        /**
16974         * Called when the context menu for this view is being built. It is not
16975         * safe to hold onto the menu after this method returns.
16976         *
16977         * @param menu The context menu that is being built
16978         * @param v The view for which the context menu is being built
16979         * @param menuInfo Extra information about the item for which the
16980         *            context menu should be shown. This information will vary
16981         *            depending on the class of v.
16982         */
16983        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16984    }
16985
16986    /**
16987     * Interface definition for a callback to be invoked when the status bar changes
16988     * visibility.  This reports <strong>global</strong> changes to the system UI
16989     * state, not what the application is requesting.
16990     *
16991     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16992     */
16993    public interface OnSystemUiVisibilityChangeListener {
16994        /**
16995         * Called when the status bar changes visibility because of a call to
16996         * {@link View#setSystemUiVisibility(int)}.
16997         *
16998         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16999         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17000         * This tells you the <strong>global</strong> state of these UI visibility
17001         * flags, not what your app is currently applying.
17002         */
17003        public void onSystemUiVisibilityChange(int visibility);
17004    }
17005
17006    /**
17007     * Interface definition for a callback to be invoked when this view is attached
17008     * or detached from its window.
17009     */
17010    public interface OnAttachStateChangeListener {
17011        /**
17012         * Called when the view is attached to a window.
17013         * @param v The view that was attached
17014         */
17015        public void onViewAttachedToWindow(View v);
17016        /**
17017         * Called when the view is detached from a window.
17018         * @param v The view that was detached
17019         */
17020        public void onViewDetachedFromWindow(View v);
17021    }
17022
17023    private final class UnsetPressedState implements Runnable {
17024        public void run() {
17025            setPressed(false);
17026        }
17027    }
17028
17029    /**
17030     * Base class for derived classes that want to save and restore their own
17031     * state in {@link android.view.View#onSaveInstanceState()}.
17032     */
17033    public static class BaseSavedState extends AbsSavedState {
17034        /**
17035         * Constructor used when reading from a parcel. Reads the state of the superclass.
17036         *
17037         * @param source
17038         */
17039        public BaseSavedState(Parcel source) {
17040            super(source);
17041        }
17042
17043        /**
17044         * Constructor called by derived classes when creating their SavedState objects
17045         *
17046         * @param superState The state of the superclass of this view
17047         */
17048        public BaseSavedState(Parcelable superState) {
17049            super(superState);
17050        }
17051
17052        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17053                new Parcelable.Creator<BaseSavedState>() {
17054            public BaseSavedState createFromParcel(Parcel in) {
17055                return new BaseSavedState(in);
17056            }
17057
17058            public BaseSavedState[] newArray(int size) {
17059                return new BaseSavedState[size];
17060            }
17061        };
17062    }
17063
17064    /**
17065     * A set of information given to a view when it is attached to its parent
17066     * window.
17067     */
17068    static class AttachInfo {
17069        interface Callbacks {
17070            void playSoundEffect(int effectId);
17071            boolean performHapticFeedback(int effectId, boolean always);
17072        }
17073
17074        /**
17075         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17076         * to a Handler. This class contains the target (View) to invalidate and
17077         * the coordinates of the dirty rectangle.
17078         *
17079         * For performance purposes, this class also implements a pool of up to
17080         * POOL_LIMIT objects that get reused. This reduces memory allocations
17081         * whenever possible.
17082         */
17083        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17084            private static final int POOL_LIMIT = 10;
17085            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17086                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17087                        public InvalidateInfo newInstance() {
17088                            return new InvalidateInfo();
17089                        }
17090
17091                        public void onAcquired(InvalidateInfo element) {
17092                        }
17093
17094                        public void onReleased(InvalidateInfo element) {
17095                            element.target = null;
17096                        }
17097                    }, POOL_LIMIT)
17098            );
17099
17100            private InvalidateInfo mNext;
17101            private boolean mIsPooled;
17102
17103            View target;
17104
17105            int left;
17106            int top;
17107            int right;
17108            int bottom;
17109
17110            public void setNextPoolable(InvalidateInfo element) {
17111                mNext = element;
17112            }
17113
17114            public InvalidateInfo getNextPoolable() {
17115                return mNext;
17116            }
17117
17118            static InvalidateInfo acquire() {
17119                return sPool.acquire();
17120            }
17121
17122            void release() {
17123                sPool.release(this);
17124            }
17125
17126            public boolean isPooled() {
17127                return mIsPooled;
17128            }
17129
17130            public void setPooled(boolean isPooled) {
17131                mIsPooled = isPooled;
17132            }
17133        }
17134
17135        final IWindowSession mSession;
17136
17137        final IWindow mWindow;
17138
17139        final IBinder mWindowToken;
17140
17141        final Callbacks mRootCallbacks;
17142
17143        HardwareCanvas mHardwareCanvas;
17144
17145        /**
17146         * The top view of the hierarchy.
17147         */
17148        View mRootView;
17149
17150        IBinder mPanelParentWindowToken;
17151        Surface mSurface;
17152
17153        boolean mHardwareAccelerated;
17154        boolean mHardwareAccelerationRequested;
17155        HardwareRenderer mHardwareRenderer;
17156
17157        boolean mScreenOn;
17158
17159        /**
17160         * Scale factor used by the compatibility mode
17161         */
17162        float mApplicationScale;
17163
17164        /**
17165         * Indicates whether the application is in compatibility mode
17166         */
17167        boolean mScalingRequired;
17168
17169        /**
17170         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17171         */
17172        boolean mTurnOffWindowResizeAnim;
17173
17174        /**
17175         * Left position of this view's window
17176         */
17177        int mWindowLeft;
17178
17179        /**
17180         * Top position of this view's window
17181         */
17182        int mWindowTop;
17183
17184        /**
17185         * Indicates whether views need to use 32-bit drawing caches
17186         */
17187        boolean mUse32BitDrawingCache;
17188
17189        /**
17190         * For windows that are full-screen but using insets to layout inside
17191         * of the screen decorations, these are the current insets for the
17192         * content of the window.
17193         */
17194        final Rect mContentInsets = new Rect();
17195
17196        /**
17197         * For windows that are full-screen but using insets to layout inside
17198         * of the screen decorations, these are the current insets for the
17199         * actual visible parts of the window.
17200         */
17201        final Rect mVisibleInsets = new Rect();
17202
17203        /**
17204         * The internal insets given by this window.  This value is
17205         * supplied by the client (through
17206         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17207         * be given to the window manager when changed to be used in laying
17208         * out windows behind it.
17209         */
17210        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17211                = new ViewTreeObserver.InternalInsetsInfo();
17212
17213        /**
17214         * All views in the window's hierarchy that serve as scroll containers,
17215         * used to determine if the window can be resized or must be panned
17216         * to adjust for a soft input area.
17217         */
17218        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17219
17220        final KeyEvent.DispatcherState mKeyDispatchState
17221                = new KeyEvent.DispatcherState();
17222
17223        /**
17224         * Indicates whether the view's window currently has the focus.
17225         */
17226        boolean mHasWindowFocus;
17227
17228        /**
17229         * The current visibility of the window.
17230         */
17231        int mWindowVisibility;
17232
17233        /**
17234         * Indicates the time at which drawing started to occur.
17235         */
17236        long mDrawingTime;
17237
17238        /**
17239         * Indicates whether or not ignoring the DIRTY_MASK flags.
17240         */
17241        boolean mIgnoreDirtyState;
17242
17243        /**
17244         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17245         * to avoid clearing that flag prematurely.
17246         */
17247        boolean mSetIgnoreDirtyState = false;
17248
17249        /**
17250         * Indicates whether the view's window is currently in touch mode.
17251         */
17252        boolean mInTouchMode;
17253
17254        /**
17255         * Indicates that ViewAncestor should trigger a global layout change
17256         * the next time it performs a traversal
17257         */
17258        boolean mRecomputeGlobalAttributes;
17259
17260        /**
17261         * Always report new attributes at next traversal.
17262         */
17263        boolean mForceReportNewAttributes;
17264
17265        /**
17266         * Set during a traveral if any views want to keep the screen on.
17267         */
17268        boolean mKeepScreenOn;
17269
17270        /**
17271         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17272         */
17273        int mSystemUiVisibility;
17274
17275        /**
17276         * Hack to force certain system UI visibility flags to be cleared.
17277         */
17278        int mDisabledSystemUiVisibility;
17279
17280        /**
17281         * Last global system UI visibility reported by the window manager.
17282         */
17283        int mGlobalSystemUiVisibility;
17284
17285        /**
17286         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17287         * attached.
17288         */
17289        boolean mHasSystemUiListeners;
17290
17291        /**
17292         * Set if the visibility of any views has changed.
17293         */
17294        boolean mViewVisibilityChanged;
17295
17296        /**
17297         * Set to true if a view has been scrolled.
17298         */
17299        boolean mViewScrollChanged;
17300
17301        /**
17302         * Global to the view hierarchy used as a temporary for dealing with
17303         * x/y points in the transparent region computations.
17304         */
17305        final int[] mTransparentLocation = new int[2];
17306
17307        /**
17308         * Global to the view hierarchy used as a temporary for dealing with
17309         * x/y points in the ViewGroup.invalidateChild implementation.
17310         */
17311        final int[] mInvalidateChildLocation = new int[2];
17312
17313
17314        /**
17315         * Global to the view hierarchy used as a temporary for dealing with
17316         * x/y location when view is transformed.
17317         */
17318        final float[] mTmpTransformLocation = new float[2];
17319
17320        /**
17321         * The view tree observer used to dispatch global events like
17322         * layout, pre-draw, touch mode change, etc.
17323         */
17324        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17325
17326        /**
17327         * A Canvas used by the view hierarchy to perform bitmap caching.
17328         */
17329        Canvas mCanvas;
17330
17331        /**
17332         * The view root impl.
17333         */
17334        final ViewRootImpl mViewRootImpl;
17335
17336        /**
17337         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17338         * handler can be used to pump events in the UI events queue.
17339         */
17340        final Handler mHandler;
17341
17342        /**
17343         * Temporary for use in computing invalidate rectangles while
17344         * calling up the hierarchy.
17345         */
17346        final Rect mTmpInvalRect = new Rect();
17347
17348        /**
17349         * Temporary for use in computing hit areas with transformed views
17350         */
17351        final RectF mTmpTransformRect = new RectF();
17352
17353        /**
17354         * Temporary list for use in collecting focusable descendents of a view.
17355         */
17356        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17357
17358        /**
17359         * The id of the window for accessibility purposes.
17360         */
17361        int mAccessibilityWindowId = View.NO_ID;
17362
17363        /**
17364         * Whether to ingore not exposed for accessibility Views when
17365         * reporting the view tree to accessibility services.
17366         */
17367        boolean mIncludeNotImportantViews;
17368
17369        /**
17370         * The drawable for highlighting accessibility focus.
17371         */
17372        Drawable mAccessibilityFocusDrawable;
17373
17374        /**
17375         * Show where the margins, bounds and layout bounds are for each view.
17376         */
17377        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17378
17379        /**
17380         * Point used to compute visible regions.
17381         */
17382        final Point mPoint = new Point();
17383
17384        /**
17385         * Creates a new set of attachment information with the specified
17386         * events handler and thread.
17387         *
17388         * @param handler the events handler the view must use
17389         */
17390        AttachInfo(IWindowSession session, IWindow window,
17391                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17392            mSession = session;
17393            mWindow = window;
17394            mWindowToken = window.asBinder();
17395            mViewRootImpl = viewRootImpl;
17396            mHandler = handler;
17397            mRootCallbacks = effectPlayer;
17398        }
17399    }
17400
17401    /**
17402     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17403     * is supported. This avoids keeping too many unused fields in most
17404     * instances of View.</p>
17405     */
17406    private static class ScrollabilityCache implements Runnable {
17407
17408        /**
17409         * Scrollbars are not visible
17410         */
17411        public static final int OFF = 0;
17412
17413        /**
17414         * Scrollbars are visible
17415         */
17416        public static final int ON = 1;
17417
17418        /**
17419         * Scrollbars are fading away
17420         */
17421        public static final int FADING = 2;
17422
17423        public boolean fadeScrollBars;
17424
17425        public int fadingEdgeLength;
17426        public int scrollBarDefaultDelayBeforeFade;
17427        public int scrollBarFadeDuration;
17428
17429        public int scrollBarSize;
17430        public ScrollBarDrawable scrollBar;
17431        public float[] interpolatorValues;
17432        public View host;
17433
17434        public final Paint paint;
17435        public final Matrix matrix;
17436        public Shader shader;
17437
17438        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17439
17440        private static final float[] OPAQUE = { 255 };
17441        private static final float[] TRANSPARENT = { 0.0f };
17442
17443        /**
17444         * When fading should start. This time moves into the future every time
17445         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17446         */
17447        public long fadeStartTime;
17448
17449
17450        /**
17451         * The current state of the scrollbars: ON, OFF, or FADING
17452         */
17453        public int state = OFF;
17454
17455        private int mLastColor;
17456
17457        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17458            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17459            scrollBarSize = configuration.getScaledScrollBarSize();
17460            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17461            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17462
17463            paint = new Paint();
17464            matrix = new Matrix();
17465            // use use a height of 1, and then wack the matrix each time we
17466            // actually use it.
17467            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17468
17469            paint.setShader(shader);
17470            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17471            this.host = host;
17472        }
17473
17474        public void setFadeColor(int color) {
17475            if (color != 0 && color != mLastColor) {
17476                mLastColor = color;
17477                color |= 0xFF000000;
17478
17479                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17480                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17481
17482                paint.setShader(shader);
17483                // Restore the default transfer mode (src_over)
17484                paint.setXfermode(null);
17485            }
17486        }
17487
17488        public void run() {
17489            long now = AnimationUtils.currentAnimationTimeMillis();
17490            if (now >= fadeStartTime) {
17491
17492                // the animation fades the scrollbars out by changing
17493                // the opacity (alpha) from fully opaque to fully
17494                // transparent
17495                int nextFrame = (int) now;
17496                int framesCount = 0;
17497
17498                Interpolator interpolator = scrollBarInterpolator;
17499
17500                // Start opaque
17501                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17502
17503                // End transparent
17504                nextFrame += scrollBarFadeDuration;
17505                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17506
17507                state = FADING;
17508
17509                // Kick off the fade animation
17510                host.invalidate(true);
17511            }
17512        }
17513    }
17514
17515    /**
17516     * Resuable callback for sending
17517     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17518     */
17519    private class SendViewScrolledAccessibilityEvent implements Runnable {
17520        public volatile boolean mIsPending;
17521
17522        public void run() {
17523            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17524            mIsPending = false;
17525        }
17526    }
17527
17528    /**
17529     * <p>
17530     * This class represents a delegate that can be registered in a {@link View}
17531     * to enhance accessibility support via composition rather via inheritance.
17532     * It is specifically targeted to widget developers that extend basic View
17533     * classes i.e. classes in package android.view, that would like their
17534     * applications to be backwards compatible.
17535     * </p>
17536     * <div class="special reference">
17537     * <h3>Developer Guides</h3>
17538     * <p>For more information about making applications accessible, read the
17539     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17540     * developer guide.</p>
17541     * </div>
17542     * <p>
17543     * A scenario in which a developer would like to use an accessibility delegate
17544     * is overriding a method introduced in a later API version then the minimal API
17545     * version supported by the application. For example, the method
17546     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17547     * in API version 4 when the accessibility APIs were first introduced. If a
17548     * developer would like his application to run on API version 4 devices (assuming
17549     * all other APIs used by the application are version 4 or lower) and take advantage
17550     * of this method, instead of overriding the method which would break the application's
17551     * backwards compatibility, he can override the corresponding method in this
17552     * delegate and register the delegate in the target View if the API version of
17553     * the system is high enough i.e. the API version is same or higher to the API
17554     * version that introduced
17555     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17556     * </p>
17557     * <p>
17558     * Here is an example implementation:
17559     * </p>
17560     * <code><pre><p>
17561     * if (Build.VERSION.SDK_INT >= 14) {
17562     *     // If the API version is equal of higher than the version in
17563     *     // which onInitializeAccessibilityNodeInfo was introduced we
17564     *     // register a delegate with a customized implementation.
17565     *     View view = findViewById(R.id.view_id);
17566     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17567     *         public void onInitializeAccessibilityNodeInfo(View host,
17568     *                 AccessibilityNodeInfo info) {
17569     *             // Let the default implementation populate the info.
17570     *             super.onInitializeAccessibilityNodeInfo(host, info);
17571     *             // Set some other information.
17572     *             info.setEnabled(host.isEnabled());
17573     *         }
17574     *     });
17575     * }
17576     * </code></pre></p>
17577     * <p>
17578     * This delegate contains methods that correspond to the accessibility methods
17579     * in View. If a delegate has been specified the implementation in View hands
17580     * off handling to the corresponding method in this delegate. The default
17581     * implementation the delegate methods behaves exactly as the corresponding
17582     * method in View for the case of no accessibility delegate been set. Hence,
17583     * to customize the behavior of a View method, clients can override only the
17584     * corresponding delegate method without altering the behavior of the rest
17585     * accessibility related methods of the host view.
17586     * </p>
17587     */
17588    public static class AccessibilityDelegate {
17589
17590        /**
17591         * Sends an accessibility event of the given type. If accessibility is not
17592         * enabled this method has no effect.
17593         * <p>
17594         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17595         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17596         * been set.
17597         * </p>
17598         *
17599         * @param host The View hosting the delegate.
17600         * @param eventType The type of the event to send.
17601         *
17602         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17603         */
17604        public void sendAccessibilityEvent(View host, int eventType) {
17605            host.sendAccessibilityEventInternal(eventType);
17606        }
17607
17608        /**
17609         * Performs the specified accessibility action on the view. For
17610         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17611         * <p>
17612         * The default implementation behaves as
17613         * {@link View#performAccessibilityAction(int, Bundle)
17614         *  View#performAccessibilityAction(int, Bundle)} for the case of
17615         *  no accessibility delegate been set.
17616         * </p>
17617         *
17618         * @param action The action to perform.
17619         * @return Whether the action was performed.
17620         *
17621         * @see View#performAccessibilityAction(int, Bundle)
17622         *      View#performAccessibilityAction(int, Bundle)
17623         */
17624        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17625            return host.performAccessibilityActionInternal(action, args);
17626        }
17627
17628        /**
17629         * Sends an accessibility event. This method behaves exactly as
17630         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17631         * empty {@link AccessibilityEvent} and does not perform a check whether
17632         * accessibility is enabled.
17633         * <p>
17634         * The default implementation behaves as
17635         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17636         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17637         * the case of no accessibility delegate been set.
17638         * </p>
17639         *
17640         * @param host The View hosting the delegate.
17641         * @param event The event to send.
17642         *
17643         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17644         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17645         */
17646        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17647            host.sendAccessibilityEventUncheckedInternal(event);
17648        }
17649
17650        /**
17651         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17652         * to its children for adding their text content to the event.
17653         * <p>
17654         * The default implementation behaves as
17655         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17656         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17657         * the case of no accessibility delegate been set.
17658         * </p>
17659         *
17660         * @param host The View hosting the delegate.
17661         * @param event The event.
17662         * @return True if the event population was completed.
17663         *
17664         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17665         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17666         */
17667        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17668            return host.dispatchPopulateAccessibilityEventInternal(event);
17669        }
17670
17671        /**
17672         * Gives a chance to the host View to populate the accessibility event with its
17673         * text content.
17674         * <p>
17675         * The default implementation behaves as
17676         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17677         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17678         * the case of no accessibility delegate been set.
17679         * </p>
17680         *
17681         * @param host The View hosting the delegate.
17682         * @param event The accessibility event which to populate.
17683         *
17684         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17685         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17686         */
17687        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17688            host.onPopulateAccessibilityEventInternal(event);
17689        }
17690
17691        /**
17692         * Initializes an {@link AccessibilityEvent} with information about the
17693         * the host View which is the event source.
17694         * <p>
17695         * The default implementation behaves as
17696         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17697         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17698         * the case of no accessibility delegate been set.
17699         * </p>
17700         *
17701         * @param host The View hosting the delegate.
17702         * @param event The event to initialize.
17703         *
17704         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17705         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17706         */
17707        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17708            host.onInitializeAccessibilityEventInternal(event);
17709        }
17710
17711        /**
17712         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17713         * <p>
17714         * The default implementation behaves as
17715         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17716         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17717         * the case of no accessibility delegate been set.
17718         * </p>
17719         *
17720         * @param host The View hosting the delegate.
17721         * @param info The instance to initialize.
17722         *
17723         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17724         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17725         */
17726        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17727            host.onInitializeAccessibilityNodeInfoInternal(info);
17728        }
17729
17730        /**
17731         * Called when a child of the host View has requested sending an
17732         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17733         * to augment the event.
17734         * <p>
17735         * The default implementation behaves as
17736         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17737         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17738         * the case of no accessibility delegate been set.
17739         * </p>
17740         *
17741         * @param host The View hosting the delegate.
17742         * @param child The child which requests sending the event.
17743         * @param event The event to be sent.
17744         * @return True if the event should be sent
17745         *
17746         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17747         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17748         */
17749        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17750                AccessibilityEvent event) {
17751            return host.onRequestSendAccessibilityEventInternal(child, event);
17752        }
17753
17754        /**
17755         * Gets the provider for managing a virtual view hierarchy rooted at this View
17756         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17757         * that explore the window content.
17758         * <p>
17759         * The default implementation behaves as
17760         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17761         * the case of no accessibility delegate been set.
17762         * </p>
17763         *
17764         * @return The provider.
17765         *
17766         * @see AccessibilityNodeProvider
17767         */
17768        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17769            return null;
17770        }
17771    }
17772}
17773