View.java revision c00d00865d51e8c08d1f90b2b34c699b63a7105e
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            }
4329        }
4330
4331        InputMethodManager imm = InputMethodManager.peekInstance();
4332        if (!gainFocus) {
4333            if (isPressed()) {
4334                setPressed(false);
4335            }
4336            if (imm != null && mAttachInfo != null
4337                    && mAttachInfo.mHasWindowFocus) {
4338                imm.focusOut(this);
4339            }
4340            onFocusLost();
4341        } else if (imm != null && mAttachInfo != null
4342                && mAttachInfo.mHasWindowFocus) {
4343            imm.focusIn(this);
4344        }
4345
4346        invalidate(true);
4347        ListenerInfo li = mListenerInfo;
4348        if (li != null && li.mOnFocusChangeListener != null) {
4349            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4350        }
4351
4352        if (mAttachInfo != null) {
4353            mAttachInfo.mKeyDispatchState.reset(this);
4354        }
4355    }
4356
4357    /**
4358     * Sends an accessibility event of the given type. If accessiiblity is
4359     * not enabled this method has no effect. The default implementation calls
4360     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4361     * to populate information about the event source (this View), then calls
4362     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4363     * populate the text content of the event source including its descendants,
4364     * and last calls
4365     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4366     * on its parent to resuest sending of the event to interested parties.
4367     * <p>
4368     * If an {@link AccessibilityDelegate} has been specified via calling
4369     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4370     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4371     * responsible for handling this call.
4372     * </p>
4373     *
4374     * @param eventType The type of the event to send, as defined by several types from
4375     * {@link android.view.accessibility.AccessibilityEvent}, such as
4376     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4377     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4378     *
4379     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4380     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4381     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4382     * @see AccessibilityDelegate
4383     */
4384    public void sendAccessibilityEvent(int eventType) {
4385        if (mAccessibilityDelegate != null) {
4386            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4387        } else {
4388            sendAccessibilityEventInternal(eventType);
4389        }
4390    }
4391
4392    /**
4393     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4394     * {@link AccessibilityEvent} to make an announcement which is related to some
4395     * sort of a context change for which none of the events representing UI transitions
4396     * is a good fit. For example, announcing a new page in a book. If accessibility
4397     * is not enabled this method does nothing.
4398     *
4399     * @param text The announcement text.
4400     */
4401    public void announceForAccessibility(CharSequence text) {
4402        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4403            AccessibilityEvent event = AccessibilityEvent.obtain(
4404                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4405            event.getText().add(text);
4406            sendAccessibilityEventUnchecked(event);
4407        }
4408    }
4409
4410    /**
4411     * @see #sendAccessibilityEvent(int)
4412     *
4413     * Note: Called from the default {@link AccessibilityDelegate}.
4414     */
4415    void sendAccessibilityEventInternal(int eventType) {
4416        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4417            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4418        }
4419    }
4420
4421    /**
4422     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4423     * takes as an argument an empty {@link AccessibilityEvent} and does not
4424     * perform a check whether accessibility is enabled.
4425     * <p>
4426     * If an {@link AccessibilityDelegate} has been specified via calling
4427     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4428     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4429     * is responsible for handling this call.
4430     * </p>
4431     *
4432     * @param event The event to send.
4433     *
4434     * @see #sendAccessibilityEvent(int)
4435     */
4436    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4437        if (mAccessibilityDelegate != null) {
4438            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4439        } else {
4440            sendAccessibilityEventUncheckedInternal(event);
4441        }
4442    }
4443
4444    /**
4445     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4446     *
4447     * Note: Called from the default {@link AccessibilityDelegate}.
4448     */
4449    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4450        if (!isShown()) {
4451            return;
4452        }
4453        onInitializeAccessibilityEvent(event);
4454        // Only a subset of accessibility events populates text content.
4455        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4456            dispatchPopulateAccessibilityEvent(event);
4457        }
4458        // Intercept accessibility focus events fired by virtual nodes to keep
4459        // track of accessibility focus position in such nodes.
4460        final int eventType = event.getEventType();
4461        switch (eventType) {
4462            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4463                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4464                        event.getSourceNodeId());
4465                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4466                    ViewRootImpl viewRootImpl = getViewRootImpl();
4467                    if (viewRootImpl != null) {
4468                        viewRootImpl.setAccessibilityFocusedHost(this);
4469                    }
4470                }
4471            } break;
4472            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4473                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4474                        event.getSourceNodeId());
4475                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4476                    ViewRootImpl viewRootImpl = getViewRootImpl();
4477                    if (viewRootImpl != null) {
4478                        viewRootImpl.setAccessibilityFocusedHost(null);
4479                    }
4480                }
4481            } break;
4482        }
4483        // In the beginning we called #isShown(), so we know that getParent() is not null.
4484        getParent().requestSendAccessibilityEvent(this, event);
4485    }
4486
4487    /**
4488     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4489     * to its children for adding their text content to the event. Note that the
4490     * event text is populated in a separate dispatch path since we add to the
4491     * event not only the text of the source but also the text of all its descendants.
4492     * A typical implementation will call
4493     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4494     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4495     * on each child. Override this method if custom population of the event text
4496     * content is required.
4497     * <p>
4498     * If an {@link AccessibilityDelegate} has been specified via calling
4499     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4500     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4501     * is responsible for handling this call.
4502     * </p>
4503     * <p>
4504     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4505     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4506     * </p>
4507     *
4508     * @param event The event.
4509     *
4510     * @return True if the event population was completed.
4511     */
4512    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4513        if (mAccessibilityDelegate != null) {
4514            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4515        } else {
4516            return dispatchPopulateAccessibilityEventInternal(event);
4517        }
4518    }
4519
4520    /**
4521     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4522     *
4523     * Note: Called from the default {@link AccessibilityDelegate}.
4524     */
4525    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4526        onPopulateAccessibilityEvent(event);
4527        return false;
4528    }
4529
4530    /**
4531     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4532     * giving a chance to this View to populate the accessibility event with its
4533     * text content. While this method is free to modify event
4534     * attributes other than text content, doing so should normally be performed in
4535     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4536     * <p>
4537     * Example: Adding formatted date string to an accessibility event in addition
4538     *          to the text added by the super implementation:
4539     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4540     *     super.onPopulateAccessibilityEvent(event);
4541     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4542     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4543     *         mCurrentDate.getTimeInMillis(), flags);
4544     *     event.getText().add(selectedDateUtterance);
4545     * }</pre>
4546     * <p>
4547     * If an {@link AccessibilityDelegate} has been specified via calling
4548     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4549     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4550     * is responsible for handling this call.
4551     * </p>
4552     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4553     * information to the event, in case the default implementation has basic information to add.
4554     * </p>
4555     *
4556     * @param event The accessibility event which to populate.
4557     *
4558     * @see #sendAccessibilityEvent(int)
4559     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4560     */
4561    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4562        if (mAccessibilityDelegate != null) {
4563            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4564        } else {
4565            onPopulateAccessibilityEventInternal(event);
4566        }
4567    }
4568
4569    /**
4570     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4571     *
4572     * Note: Called from the default {@link AccessibilityDelegate}.
4573     */
4574    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4575
4576    }
4577
4578    /**
4579     * Initializes an {@link AccessibilityEvent} with information about
4580     * this View which is the event source. In other words, the source of
4581     * an accessibility event is the view whose state change triggered firing
4582     * the event.
4583     * <p>
4584     * Example: Setting the password property of an event in addition
4585     *          to properties set by the super implementation:
4586     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4587     *     super.onInitializeAccessibilityEvent(event);
4588     *     event.setPassword(true);
4589     * }</pre>
4590     * <p>
4591     * If an {@link AccessibilityDelegate} has been specified via calling
4592     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4593     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4594     * is responsible for handling this call.
4595     * </p>
4596     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4597     * information to the event, in case the default implementation has basic information to add.
4598     * </p>
4599     * @param event The event to initialize.
4600     *
4601     * @see #sendAccessibilityEvent(int)
4602     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4603     */
4604    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4605        if (mAccessibilityDelegate != null) {
4606            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4607        } else {
4608            onInitializeAccessibilityEventInternal(event);
4609        }
4610    }
4611
4612    /**
4613     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4614     *
4615     * Note: Called from the default {@link AccessibilityDelegate}.
4616     */
4617    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4618        event.setSource(this);
4619        event.setClassName(View.class.getName());
4620        event.setPackageName(getContext().getPackageName());
4621        event.setEnabled(isEnabled());
4622        event.setContentDescription(mContentDescription);
4623
4624        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4625            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4626            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4627                    FOCUSABLES_ALL);
4628            event.setItemCount(focusablesTempList.size());
4629            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4630            focusablesTempList.clear();
4631        }
4632    }
4633
4634    /**
4635     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4636     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4637     * This method is responsible for obtaining an accessibility node info from a
4638     * pool of reusable instances and calling
4639     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4640     * initialize the former.
4641     * <p>
4642     * Note: The client is responsible for recycling the obtained instance by calling
4643     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4644     * </p>
4645     *
4646     * @return A populated {@link AccessibilityNodeInfo}.
4647     *
4648     * @see AccessibilityNodeInfo
4649     */
4650    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4651        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4652        if (provider != null) {
4653            return provider.createAccessibilityNodeInfo(View.NO_ID);
4654        } else {
4655            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4656            onInitializeAccessibilityNodeInfo(info);
4657            return info;
4658        }
4659    }
4660
4661    /**
4662     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4663     * The base implementation sets:
4664     * <ul>
4665     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4666     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4667     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4668     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4669     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4670     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4671     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4672     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4673     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4674     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4675     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4676     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4677     * </ul>
4678     * <p>
4679     * Subclasses should override this method, call the super implementation,
4680     * and set additional attributes.
4681     * </p>
4682     * <p>
4683     * If an {@link AccessibilityDelegate} has been specified via calling
4684     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4685     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4686     * is responsible for handling this call.
4687     * </p>
4688     *
4689     * @param info The instance to initialize.
4690     */
4691    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4692        if (mAccessibilityDelegate != null) {
4693            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4694        } else {
4695            onInitializeAccessibilityNodeInfoInternal(info);
4696        }
4697    }
4698
4699    /**
4700     * Gets the location of this view in screen coordintates.
4701     *
4702     * @param outRect The output location
4703     */
4704    private void getBoundsOnScreen(Rect outRect) {
4705        if (mAttachInfo == null) {
4706            return;
4707        }
4708
4709        RectF position = mAttachInfo.mTmpTransformRect;
4710        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4711
4712        if (!hasIdentityMatrix()) {
4713            getMatrix().mapRect(position);
4714        }
4715
4716        position.offset(mLeft, mTop);
4717
4718        ViewParent parent = mParent;
4719        while (parent instanceof View) {
4720            View parentView = (View) parent;
4721
4722            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4723
4724            if (!parentView.hasIdentityMatrix()) {
4725                parentView.getMatrix().mapRect(position);
4726            }
4727
4728            position.offset(parentView.mLeft, parentView.mTop);
4729
4730            parent = parentView.mParent;
4731        }
4732
4733        if (parent instanceof ViewRootImpl) {
4734            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4735            position.offset(0, -viewRootImpl.mCurScrollY);
4736        }
4737
4738        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4739
4740        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4741                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4742    }
4743
4744    /**
4745     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4746     *
4747     * Note: Called from the default {@link AccessibilityDelegate}.
4748     */
4749    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4750        Rect bounds = mAttachInfo.mTmpInvalRect;
4751        getDrawingRect(bounds);
4752        info.setBoundsInParent(bounds);
4753
4754        getBoundsOnScreen(bounds);
4755        info.setBoundsInScreen(bounds);
4756
4757        ViewParent parent = getParentForAccessibility();
4758        if (parent instanceof View) {
4759            info.setParent((View) parent);
4760        }
4761
4762        info.setVisibleToUser(isVisibleToUser());
4763
4764        info.setPackageName(mContext.getPackageName());
4765        info.setClassName(View.class.getName());
4766        info.setContentDescription(getContentDescription());
4767
4768        info.setEnabled(isEnabled());
4769        info.setClickable(isClickable());
4770        info.setFocusable(isFocusable());
4771        info.setFocused(isFocused());
4772        info.setAccessibilityFocused(isAccessibilityFocused());
4773        info.setSelected(isSelected());
4774        info.setLongClickable(isLongClickable());
4775
4776        // TODO: These make sense only if we are in an AdapterView but all
4777        // views can be selected. Maybe from accessiiblity perspective
4778        // we should report as selectable view in an AdapterView.
4779        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4780        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4781
4782        if (isFocusable()) {
4783            if (isFocused()) {
4784                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4785            } else {
4786                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4787            }
4788        }
4789
4790        if (!isAccessibilityFocused()) {
4791            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4792        } else {
4793            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4794        }
4795
4796        if (isClickable() && isEnabled()) {
4797            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4798        }
4799
4800        if (isLongClickable() && isEnabled()) {
4801            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4802        }
4803
4804        if (mContentDescription != null && mContentDescription.length() > 0) {
4805            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4806            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4807            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4808                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4809                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4810        }
4811    }
4812
4813    /**
4814     * Computes whether this view is visible to the user. Such a view is
4815     * attached, visible, all its predecessors are visible, it is not clipped
4816     * entirely by its predecessors, and has an alpha greater than zero.
4817     *
4818     * @return Whether the view is visible on the screen.
4819     *
4820     * @hide
4821     */
4822    protected boolean isVisibleToUser() {
4823        return isVisibleToUser(null);
4824    }
4825
4826    /**
4827     * Computes whether the given portion of this view is visible to the user. Such a view is
4828     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4829     * the specified portion is not clipped entirely by its predecessors.
4830     *
4831     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4832     *                    <code>null</code>, and the entire view will be tested in this case.
4833     *                    When <code>true</code> is returned by the function, the actual visible
4834     *                    region will be stored in this parameter; that is, if boundInView is fully
4835     *                    contained within the view, no modification will be made, otherwise regions
4836     *                    outside of the visible area of the view will be clipped.
4837     *
4838     * @return Whether the specified portion of the view is visible on the screen.
4839     *
4840     * @hide
4841     */
4842    protected boolean isVisibleToUser(Rect boundInView) {
4843        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4844        Point offset = mAttachInfo.mPoint;
4845        // The first two checks are made also made by isShown() which
4846        // however traverses the tree up to the parent to catch that.
4847        // Therefore, we do some fail fast check to minimize the up
4848        // tree traversal.
4849        boolean isVisible = mAttachInfo != null
4850            && mAttachInfo.mWindowVisibility == View.VISIBLE
4851            && getAlpha() > 0
4852            && isShown()
4853            && getGlobalVisibleRect(visibleRect, offset);
4854            if (isVisible && boundInView != null) {
4855                visibleRect.offset(-offset.x, -offset.y);
4856                isVisible &= boundInView.intersect(visibleRect);
4857            }
4858            return isVisible;
4859    }
4860
4861    /**
4862     * Sets a delegate for implementing accessibility support via compositon as
4863     * opposed to inheritance. The delegate's primary use is for implementing
4864     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4865     *
4866     * @param delegate The delegate instance.
4867     *
4868     * @see AccessibilityDelegate
4869     */
4870    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4871        mAccessibilityDelegate = delegate;
4872    }
4873
4874    /**
4875     * Gets the provider for managing a virtual view hierarchy rooted at this View
4876     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4877     * that explore the window content.
4878     * <p>
4879     * If this method returns an instance, this instance is responsible for managing
4880     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4881     * View including the one representing the View itself. Similarly the returned
4882     * instance is responsible for performing accessibility actions on any virtual
4883     * view or the root view itself.
4884     * </p>
4885     * <p>
4886     * If an {@link AccessibilityDelegate} has been specified via calling
4887     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4888     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4889     * is responsible for handling this call.
4890     * </p>
4891     *
4892     * @return The provider.
4893     *
4894     * @see AccessibilityNodeProvider
4895     */
4896    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4897        if (mAccessibilityDelegate != null) {
4898            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4899        } else {
4900            return null;
4901        }
4902    }
4903
4904    /**
4905     * Gets the unique identifier of this view on the screen for accessibility purposes.
4906     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4907     *
4908     * @return The view accessibility id.
4909     *
4910     * @hide
4911     */
4912    public int getAccessibilityViewId() {
4913        if (mAccessibilityViewId == NO_ID) {
4914            mAccessibilityViewId = sNextAccessibilityViewId++;
4915        }
4916        return mAccessibilityViewId;
4917    }
4918
4919    /**
4920     * Gets the unique identifier of the window in which this View reseides.
4921     *
4922     * @return The window accessibility id.
4923     *
4924     * @hide
4925     */
4926    public int getAccessibilityWindowId() {
4927        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4928    }
4929
4930    /**
4931     * Gets the {@link View} description. It briefly describes the view and is
4932     * primarily used for accessibility support. Set this property to enable
4933     * better accessibility support for your application. This is especially
4934     * true for views that do not have textual representation (For example,
4935     * ImageButton).
4936     *
4937     * @return The content description.
4938     *
4939     * @attr ref android.R.styleable#View_contentDescription
4940     */
4941    @ViewDebug.ExportedProperty(category = "accessibility")
4942    public CharSequence getContentDescription() {
4943        return mContentDescription;
4944    }
4945
4946    /**
4947     * Sets the {@link View} description. It briefly describes the view and is
4948     * primarily used for accessibility support. Set this property to enable
4949     * better accessibility support for your application. This is especially
4950     * true for views that do not have textual representation (For example,
4951     * ImageButton).
4952     *
4953     * @param contentDescription The content description.
4954     *
4955     * @attr ref android.R.styleable#View_contentDescription
4956     */
4957    @RemotableViewMethod
4958    public void setContentDescription(CharSequence contentDescription) {
4959        mContentDescription = contentDescription;
4960    }
4961
4962    /**
4963     * Invoked whenever this view loses focus, either by losing window focus or by losing
4964     * focus within its window. This method can be used to clear any state tied to the
4965     * focus. For instance, if a button is held pressed with the trackball and the window
4966     * loses focus, this method can be used to cancel the press.
4967     *
4968     * Subclasses of View overriding this method should always call super.onFocusLost().
4969     *
4970     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4971     * @see #onWindowFocusChanged(boolean)
4972     *
4973     * @hide pending API council approval
4974     */
4975    protected void onFocusLost() {
4976        resetPressedState();
4977    }
4978
4979    private void resetPressedState() {
4980        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4981            return;
4982        }
4983
4984        if (isPressed()) {
4985            setPressed(false);
4986
4987            if (!mHasPerformedLongPress) {
4988                removeLongPressCallback();
4989            }
4990        }
4991    }
4992
4993    /**
4994     * Returns true if this view has focus
4995     *
4996     * @return True if this view has focus, false otherwise.
4997     */
4998    @ViewDebug.ExportedProperty(category = "focus")
4999    public boolean isFocused() {
5000        return (mPrivateFlags & FOCUSED) != 0;
5001    }
5002
5003    /**
5004     * Find the view in the hierarchy rooted at this view that currently has
5005     * focus.
5006     *
5007     * @return The view that currently has focus, or null if no focused view can
5008     *         be found.
5009     */
5010    public View findFocus() {
5011        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
5012    }
5013
5014    /**
5015     * Indicates whether this view is one of the set of scrollable containers in
5016     * its window.
5017     *
5018     * @return whether this view is one of the set of scrollable containers in
5019     * its window
5020     *
5021     * @attr ref android.R.styleable#View_isScrollContainer
5022     */
5023    public boolean isScrollContainer() {
5024        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5025    }
5026
5027    /**
5028     * Change whether this view is one of the set of scrollable containers in
5029     * its window.  This will be used to determine whether the window can
5030     * resize or must pan when a soft input area is open -- scrollable
5031     * containers allow the window to use resize mode since the container
5032     * will appropriately shrink.
5033     *
5034     * @attr ref android.R.styleable#View_isScrollContainer
5035     */
5036    public void setScrollContainer(boolean isScrollContainer) {
5037        if (isScrollContainer) {
5038            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5039                mAttachInfo.mScrollContainers.add(this);
5040                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5041            }
5042            mPrivateFlags |= SCROLL_CONTAINER;
5043        } else {
5044            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5045                mAttachInfo.mScrollContainers.remove(this);
5046            }
5047            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5048        }
5049    }
5050
5051    /**
5052     * Returns the quality of the drawing cache.
5053     *
5054     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5055     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5056     *
5057     * @see #setDrawingCacheQuality(int)
5058     * @see #setDrawingCacheEnabled(boolean)
5059     * @see #isDrawingCacheEnabled()
5060     *
5061     * @attr ref android.R.styleable#View_drawingCacheQuality
5062     */
5063    public int getDrawingCacheQuality() {
5064        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5065    }
5066
5067    /**
5068     * Set the drawing cache quality of this view. This value is used only when the
5069     * drawing cache is enabled
5070     *
5071     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5072     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5073     *
5074     * @see #getDrawingCacheQuality()
5075     * @see #setDrawingCacheEnabled(boolean)
5076     * @see #isDrawingCacheEnabled()
5077     *
5078     * @attr ref android.R.styleable#View_drawingCacheQuality
5079     */
5080    public void setDrawingCacheQuality(int quality) {
5081        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5082    }
5083
5084    /**
5085     * Returns whether the screen should remain on, corresponding to the current
5086     * value of {@link #KEEP_SCREEN_ON}.
5087     *
5088     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5089     *
5090     * @see #setKeepScreenOn(boolean)
5091     *
5092     * @attr ref android.R.styleable#View_keepScreenOn
5093     */
5094    public boolean getKeepScreenOn() {
5095        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5096    }
5097
5098    /**
5099     * Controls whether the screen should remain on, modifying the
5100     * value of {@link #KEEP_SCREEN_ON}.
5101     *
5102     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5103     *
5104     * @see #getKeepScreenOn()
5105     *
5106     * @attr ref android.R.styleable#View_keepScreenOn
5107     */
5108    public void setKeepScreenOn(boolean keepScreenOn) {
5109        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5110    }
5111
5112    /**
5113     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5114     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5115     *
5116     * @attr ref android.R.styleable#View_nextFocusLeft
5117     */
5118    public int getNextFocusLeftId() {
5119        return mNextFocusLeftId;
5120    }
5121
5122    /**
5123     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5124     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5125     * decide automatically.
5126     *
5127     * @attr ref android.R.styleable#View_nextFocusLeft
5128     */
5129    public void setNextFocusLeftId(int nextFocusLeftId) {
5130        mNextFocusLeftId = nextFocusLeftId;
5131    }
5132
5133    /**
5134     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5135     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5136     *
5137     * @attr ref android.R.styleable#View_nextFocusRight
5138     */
5139    public int getNextFocusRightId() {
5140        return mNextFocusRightId;
5141    }
5142
5143    /**
5144     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5145     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5146     * decide automatically.
5147     *
5148     * @attr ref android.R.styleable#View_nextFocusRight
5149     */
5150    public void setNextFocusRightId(int nextFocusRightId) {
5151        mNextFocusRightId = nextFocusRightId;
5152    }
5153
5154    /**
5155     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5156     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5157     *
5158     * @attr ref android.R.styleable#View_nextFocusUp
5159     */
5160    public int getNextFocusUpId() {
5161        return mNextFocusUpId;
5162    }
5163
5164    /**
5165     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5166     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5167     * decide automatically.
5168     *
5169     * @attr ref android.R.styleable#View_nextFocusUp
5170     */
5171    public void setNextFocusUpId(int nextFocusUpId) {
5172        mNextFocusUpId = nextFocusUpId;
5173    }
5174
5175    /**
5176     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5177     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5178     *
5179     * @attr ref android.R.styleable#View_nextFocusDown
5180     */
5181    public int getNextFocusDownId() {
5182        return mNextFocusDownId;
5183    }
5184
5185    /**
5186     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5187     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5188     * decide automatically.
5189     *
5190     * @attr ref android.R.styleable#View_nextFocusDown
5191     */
5192    public void setNextFocusDownId(int nextFocusDownId) {
5193        mNextFocusDownId = nextFocusDownId;
5194    }
5195
5196    /**
5197     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5198     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5199     *
5200     * @attr ref android.R.styleable#View_nextFocusForward
5201     */
5202    public int getNextFocusForwardId() {
5203        return mNextFocusForwardId;
5204    }
5205
5206    /**
5207     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5208     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5209     * decide automatically.
5210     *
5211     * @attr ref android.R.styleable#View_nextFocusForward
5212     */
5213    public void setNextFocusForwardId(int nextFocusForwardId) {
5214        mNextFocusForwardId = nextFocusForwardId;
5215    }
5216
5217    /**
5218     * Returns the visibility of this view and all of its ancestors
5219     *
5220     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5221     */
5222    public boolean isShown() {
5223        View current = this;
5224        //noinspection ConstantConditions
5225        do {
5226            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5227                return false;
5228            }
5229            ViewParent parent = current.mParent;
5230            if (parent == null) {
5231                return false; // We are not attached to the view root
5232            }
5233            if (!(parent instanceof View)) {
5234                return true;
5235            }
5236            current = (View) parent;
5237        } while (current != null);
5238
5239        return false;
5240    }
5241
5242    /**
5243     * Called by the view hierarchy when the content insets for a window have
5244     * changed, to allow it to adjust its content to fit within those windows.
5245     * The content insets tell you the space that the status bar, input method,
5246     * and other system windows infringe on the application's window.
5247     *
5248     * <p>You do not normally need to deal with this function, since the default
5249     * window decoration given to applications takes care of applying it to the
5250     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5251     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5252     * and your content can be placed under those system elements.  You can then
5253     * use this method within your view hierarchy if you have parts of your UI
5254     * which you would like to ensure are not being covered.
5255     *
5256     * <p>The default implementation of this method simply applies the content
5257     * inset's to the view's padding, consuming that content (modifying the
5258     * insets to be 0), and returning true.  This behavior is off by default, but can
5259     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5260     *
5261     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5262     * insets object is propagated down the hierarchy, so any changes made to it will
5263     * be seen by all following views (including potentially ones above in
5264     * the hierarchy since this is a depth-first traversal).  The first view
5265     * that returns true will abort the entire traversal.
5266     *
5267     * <p>The default implementation works well for a situation where it is
5268     * used with a container that covers the entire window, allowing it to
5269     * apply the appropriate insets to its content on all edges.  If you need
5270     * a more complicated layout (such as two different views fitting system
5271     * windows, one on the top of the window, and one on the bottom),
5272     * you can override the method and handle the insets however you would like.
5273     * Note that the insets provided by the framework are always relative to the
5274     * far edges of the window, not accounting for the location of the called view
5275     * within that window.  (In fact when this method is called you do not yet know
5276     * where the layout will place the view, as it is done before layout happens.)
5277     *
5278     * <p>Note: unlike many View methods, there is no dispatch phase to this
5279     * call.  If you are overriding it in a ViewGroup and want to allow the
5280     * call to continue to your children, you must be sure to call the super
5281     * implementation.
5282     *
5283     * <p>Here is a sample layout that makes use of fitting system windows
5284     * to have controls for a video view placed inside of the window decorations
5285     * that it hides and shows.  This can be used with code like the second
5286     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5287     *
5288     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5289     *
5290     * @param insets Current content insets of the window.  Prior to
5291     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5292     * the insets or else you and Android will be unhappy.
5293     *
5294     * @return Return true if this view applied the insets and it should not
5295     * continue propagating further down the hierarchy, false otherwise.
5296     * @see #getFitsSystemWindows()
5297     * @see #setFitsSystemWindows()
5298     * @see #setSystemUiVisibility(int)
5299     */
5300    protected boolean fitSystemWindows(Rect insets) {
5301        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5302            mUserPaddingStart = -1;
5303            mUserPaddingEnd = -1;
5304            mUserPaddingRelative = false;
5305            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5306                    || mAttachInfo == null
5307                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5308                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5309                return true;
5310            } else {
5311                internalSetPadding(0, 0, 0, 0);
5312                return false;
5313            }
5314        }
5315        return false;
5316    }
5317
5318    /**
5319     * Sets whether or not this view should account for system screen decorations
5320     * such as the status bar and inset its content; that is, controlling whether
5321     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5322     * executed.  See that method for more details.
5323     *
5324     * <p>Note that if you are providing your own implementation of
5325     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5326     * flag to true -- your implementation will be overriding the default
5327     * implementation that checks this flag.
5328     *
5329     * @param fitSystemWindows If true, then the default implementation of
5330     * {@link #fitSystemWindows(Rect)} will be executed.
5331     *
5332     * @attr ref android.R.styleable#View_fitsSystemWindows
5333     * @see #getFitsSystemWindows()
5334     * @see #fitSystemWindows(Rect)
5335     * @see #setSystemUiVisibility(int)
5336     */
5337    public void setFitsSystemWindows(boolean fitSystemWindows) {
5338        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5339    }
5340
5341    /**
5342     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5343     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5344     * will be executed.
5345     *
5346     * @return Returns true if the default implementation of
5347     * {@link #fitSystemWindows(Rect)} will be executed.
5348     *
5349     * @attr ref android.R.styleable#View_fitsSystemWindows
5350     * @see #setFitsSystemWindows()
5351     * @see #fitSystemWindows(Rect)
5352     * @see #setSystemUiVisibility(int)
5353     */
5354    public boolean getFitsSystemWindows() {
5355        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5356    }
5357
5358    /** @hide */
5359    public boolean fitsSystemWindows() {
5360        return getFitsSystemWindows();
5361    }
5362
5363    /**
5364     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5365     */
5366    public void requestFitSystemWindows() {
5367        if (mParent != null) {
5368            mParent.requestFitSystemWindows();
5369        }
5370    }
5371
5372    /**
5373     * For use by PhoneWindow to make its own system window fitting optional.
5374     * @hide
5375     */
5376    public void makeOptionalFitsSystemWindows() {
5377        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5378    }
5379
5380    /**
5381     * Returns the visibility status for this view.
5382     *
5383     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5384     * @attr ref android.R.styleable#View_visibility
5385     */
5386    @ViewDebug.ExportedProperty(mapping = {
5387        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5388        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5389        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5390    })
5391    public int getVisibility() {
5392        return mViewFlags & VISIBILITY_MASK;
5393    }
5394
5395    /**
5396     * Set the enabled state of this view.
5397     *
5398     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5399     * @attr ref android.R.styleable#View_visibility
5400     */
5401    @RemotableViewMethod
5402    public void setVisibility(int visibility) {
5403        setFlags(visibility, VISIBILITY_MASK);
5404        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5405    }
5406
5407    /**
5408     * Returns the enabled status for this view. The interpretation of the
5409     * enabled state varies by subclass.
5410     *
5411     * @return True if this view is enabled, false otherwise.
5412     */
5413    @ViewDebug.ExportedProperty
5414    public boolean isEnabled() {
5415        return (mViewFlags & ENABLED_MASK) == ENABLED;
5416    }
5417
5418    /**
5419     * Set the enabled state of this view. The interpretation of the enabled
5420     * state varies by subclass.
5421     *
5422     * @param enabled True if this view is enabled, false otherwise.
5423     */
5424    @RemotableViewMethod
5425    public void setEnabled(boolean enabled) {
5426        if (enabled == isEnabled()) return;
5427
5428        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5429
5430        /*
5431         * The View most likely has to change its appearance, so refresh
5432         * the drawable state.
5433         */
5434        refreshDrawableState();
5435
5436        // Invalidate too, since the default behavior for views is to be
5437        // be drawn at 50% alpha rather than to change the drawable.
5438        invalidate(true);
5439    }
5440
5441    /**
5442     * Set whether this view can receive the focus.
5443     *
5444     * Setting this to false will also ensure that this view is not focusable
5445     * in touch mode.
5446     *
5447     * @param focusable If true, this view can receive the focus.
5448     *
5449     * @see #setFocusableInTouchMode(boolean)
5450     * @attr ref android.R.styleable#View_focusable
5451     */
5452    public void setFocusable(boolean focusable) {
5453        if (!focusable) {
5454            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5455        }
5456        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5457    }
5458
5459    /**
5460     * Set whether this view can receive focus while in touch mode.
5461     *
5462     * Setting this to true will also ensure that this view is focusable.
5463     *
5464     * @param focusableInTouchMode If true, this view can receive the focus while
5465     *   in touch mode.
5466     *
5467     * @see #setFocusable(boolean)
5468     * @attr ref android.R.styleable#View_focusableInTouchMode
5469     */
5470    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5471        // Focusable in touch mode should always be set before the focusable flag
5472        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5473        // which, in touch mode, will not successfully request focus on this view
5474        // because the focusable in touch mode flag is not set
5475        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5476        if (focusableInTouchMode) {
5477            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5478        }
5479    }
5480
5481    /**
5482     * Set whether this view should have sound effects enabled for events such as
5483     * clicking and touching.
5484     *
5485     * <p>You may wish to disable sound effects for a view if you already play sounds,
5486     * for instance, a dial key that plays dtmf tones.
5487     *
5488     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5489     * @see #isSoundEffectsEnabled()
5490     * @see #playSoundEffect(int)
5491     * @attr ref android.R.styleable#View_soundEffectsEnabled
5492     */
5493    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5494        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5495    }
5496
5497    /**
5498     * @return whether this view should have sound effects enabled for events such as
5499     *     clicking and touching.
5500     *
5501     * @see #setSoundEffectsEnabled(boolean)
5502     * @see #playSoundEffect(int)
5503     * @attr ref android.R.styleable#View_soundEffectsEnabled
5504     */
5505    @ViewDebug.ExportedProperty
5506    public boolean isSoundEffectsEnabled() {
5507        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5508    }
5509
5510    /**
5511     * Set whether this view should have haptic feedback for events such as
5512     * long presses.
5513     *
5514     * <p>You may wish to disable haptic feedback if your view already controls
5515     * its own haptic feedback.
5516     *
5517     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5518     * @see #isHapticFeedbackEnabled()
5519     * @see #performHapticFeedback(int)
5520     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5521     */
5522    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5523        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5524    }
5525
5526    /**
5527     * @return whether this view should have haptic feedback enabled for events
5528     * long presses.
5529     *
5530     * @see #setHapticFeedbackEnabled(boolean)
5531     * @see #performHapticFeedback(int)
5532     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5533     */
5534    @ViewDebug.ExportedProperty
5535    public boolean isHapticFeedbackEnabled() {
5536        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5537    }
5538
5539    /**
5540     * Returns the layout direction for this view.
5541     *
5542     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5543     *   {@link #LAYOUT_DIRECTION_RTL},
5544     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5545     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5546     *
5547     * @attr ref android.R.styleable#View_layoutDirection
5548     * @hide
5549     */
5550    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5551        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5552        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5553        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5554        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5555    })
5556    public int getLayoutDirection() {
5557        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5558    }
5559
5560    /**
5561     * Set the layout direction for this view. This will propagate a reset of layout direction
5562     * resolution to the view's children and resolve layout direction for this view.
5563     *
5564     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5565     *   {@link #LAYOUT_DIRECTION_RTL},
5566     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5567     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5568     *
5569     * @attr ref android.R.styleable#View_layoutDirection
5570     * @hide
5571     */
5572    @RemotableViewMethod
5573    public void setLayoutDirection(int layoutDirection) {
5574        if (getLayoutDirection() != layoutDirection) {
5575            // Reset the current layout direction and the resolved one
5576            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5577            resetResolvedLayoutDirection();
5578            // Set the new layout direction (filtered) and ask for a layout pass
5579            mPrivateFlags2 |=
5580                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5581            requestLayout();
5582        }
5583    }
5584
5585    /**
5586     * Returns the resolved layout direction for this view.
5587     *
5588     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5589     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5590     * @hide
5591     */
5592    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5593        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5594        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5595    })
5596    public int getResolvedLayoutDirection() {
5597        // The layout diretion will be resolved only if needed
5598        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5599            resolveLayoutDirection();
5600        }
5601        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5602                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5603    }
5604
5605    /**
5606     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5607     * layout attribute and/or the inherited value from the parent
5608     *
5609     * @return true if the layout is right-to-left.
5610     * @hide
5611     */
5612    @ViewDebug.ExportedProperty(category = "layout")
5613    public boolean isLayoutRtl() {
5614        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5615    }
5616
5617    /**
5618     * Indicates whether the view is currently tracking transient state that the
5619     * app should not need to concern itself with saving and restoring, but that
5620     * the framework should take special note to preserve when possible.
5621     *
5622     * <p>A view with transient state cannot be trivially rebound from an external
5623     * data source, such as an adapter binding item views in a list. This may be
5624     * because the view is performing an animation, tracking user selection
5625     * of content, or similar.</p>
5626     *
5627     * @return true if the view has transient state
5628     */
5629    @ViewDebug.ExportedProperty(category = "layout")
5630    public boolean hasTransientState() {
5631        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5632    }
5633
5634    /**
5635     * Set whether this view is currently tracking transient state that the
5636     * framework should attempt to preserve when possible. This flag is reference counted,
5637     * so every call to setHasTransientState(true) should be paired with a later call
5638     * to setHasTransientState(false).
5639     *
5640     * <p>A view with transient state cannot be trivially rebound from an external
5641     * data source, such as an adapter binding item views in a list. This may be
5642     * because the view is performing an animation, tracking user selection
5643     * of content, or similar.</p>
5644     *
5645     * @param hasTransientState true if this view has transient state
5646     */
5647    public void setHasTransientState(boolean hasTransientState) {
5648        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5649                mTransientStateCount - 1;
5650        if (mTransientStateCount < 0) {
5651            mTransientStateCount = 0;
5652            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5653                    "unmatched pair of setHasTransientState calls");
5654        }
5655        if ((hasTransientState && mTransientStateCount == 1) ||
5656                (!hasTransientState && mTransientStateCount == 0)) {
5657            // update flag if we've just incremented up from 0 or decremented down to 0
5658            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5659                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5660            if (mParent != null) {
5661                try {
5662                    mParent.childHasTransientStateChanged(this, hasTransientState);
5663                } catch (AbstractMethodError e) {
5664                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5665                            " does not fully implement ViewParent", e);
5666                }
5667            }
5668        }
5669    }
5670
5671    /**
5672     * If this view doesn't do any drawing on its own, set this flag to
5673     * allow further optimizations. By default, this flag is not set on
5674     * View, but could be set on some View subclasses such as ViewGroup.
5675     *
5676     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5677     * you should clear this flag.
5678     *
5679     * @param willNotDraw whether or not this View draw on its own
5680     */
5681    public void setWillNotDraw(boolean willNotDraw) {
5682        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5683    }
5684
5685    /**
5686     * Returns whether or not this View draws on its own.
5687     *
5688     * @return true if this view has nothing to draw, false otherwise
5689     */
5690    @ViewDebug.ExportedProperty(category = "drawing")
5691    public boolean willNotDraw() {
5692        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5693    }
5694
5695    /**
5696     * When a View's drawing cache is enabled, drawing is redirected to an
5697     * offscreen bitmap. Some views, like an ImageView, must be able to
5698     * bypass this mechanism if they already draw a single bitmap, to avoid
5699     * unnecessary usage of the memory.
5700     *
5701     * @param willNotCacheDrawing true if this view does not cache its
5702     *        drawing, false otherwise
5703     */
5704    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5705        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5706    }
5707
5708    /**
5709     * Returns whether or not this View can cache its drawing or not.
5710     *
5711     * @return true if this view does not cache its drawing, false otherwise
5712     */
5713    @ViewDebug.ExportedProperty(category = "drawing")
5714    public boolean willNotCacheDrawing() {
5715        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5716    }
5717
5718    /**
5719     * Indicates whether this view reacts to click events or not.
5720     *
5721     * @return true if the view is clickable, false otherwise
5722     *
5723     * @see #setClickable(boolean)
5724     * @attr ref android.R.styleable#View_clickable
5725     */
5726    @ViewDebug.ExportedProperty
5727    public boolean isClickable() {
5728        return (mViewFlags & CLICKABLE) == CLICKABLE;
5729    }
5730
5731    /**
5732     * Enables or disables click events for this view. When a view
5733     * is clickable it will change its state to "pressed" on every click.
5734     * Subclasses should set the view clickable to visually react to
5735     * user's clicks.
5736     *
5737     * @param clickable true to make the view clickable, false otherwise
5738     *
5739     * @see #isClickable()
5740     * @attr ref android.R.styleable#View_clickable
5741     */
5742    public void setClickable(boolean clickable) {
5743        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5744    }
5745
5746    /**
5747     * Indicates whether this view reacts to long click events or not.
5748     *
5749     * @return true if the view is long clickable, false otherwise
5750     *
5751     * @see #setLongClickable(boolean)
5752     * @attr ref android.R.styleable#View_longClickable
5753     */
5754    public boolean isLongClickable() {
5755        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5756    }
5757
5758    /**
5759     * Enables or disables long click events for this view. When a view is long
5760     * clickable it reacts to the user holding down the button for a longer
5761     * duration than a tap. This event can either launch the listener or a
5762     * context menu.
5763     *
5764     * @param longClickable true to make the view long clickable, false otherwise
5765     * @see #isLongClickable()
5766     * @attr ref android.R.styleable#View_longClickable
5767     */
5768    public void setLongClickable(boolean longClickable) {
5769        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5770    }
5771
5772    /**
5773     * Sets the pressed state for this view.
5774     *
5775     * @see #isClickable()
5776     * @see #setClickable(boolean)
5777     *
5778     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5779     *        the View's internal state from a previously set "pressed" state.
5780     */
5781    public void setPressed(boolean pressed) {
5782        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5783
5784        if (pressed) {
5785            mPrivateFlags |= PRESSED;
5786        } else {
5787            mPrivateFlags &= ~PRESSED;
5788        }
5789
5790        if (needsRefresh) {
5791            refreshDrawableState();
5792        }
5793        dispatchSetPressed(pressed);
5794    }
5795
5796    /**
5797     * Dispatch setPressed to all of this View's children.
5798     *
5799     * @see #setPressed(boolean)
5800     *
5801     * @param pressed The new pressed state
5802     */
5803    protected void dispatchSetPressed(boolean pressed) {
5804    }
5805
5806    /**
5807     * Indicates whether the view is currently in pressed state. Unless
5808     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5809     * the pressed state.
5810     *
5811     * @see #setPressed(boolean)
5812     * @see #isClickable()
5813     * @see #setClickable(boolean)
5814     *
5815     * @return true if the view is currently pressed, false otherwise
5816     */
5817    public boolean isPressed() {
5818        return (mPrivateFlags & PRESSED) == PRESSED;
5819    }
5820
5821    /**
5822     * Indicates whether this view will save its state (that is,
5823     * whether its {@link #onSaveInstanceState} method will be called).
5824     *
5825     * @return Returns true if the view state saving is enabled, else false.
5826     *
5827     * @see #setSaveEnabled(boolean)
5828     * @attr ref android.R.styleable#View_saveEnabled
5829     */
5830    public boolean isSaveEnabled() {
5831        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5832    }
5833
5834    /**
5835     * Controls whether the saving of this view's state is
5836     * enabled (that is, whether its {@link #onSaveInstanceState} method
5837     * will be called).  Note that even if freezing is enabled, the
5838     * view still must have an id assigned to it (via {@link #setId(int)})
5839     * for its state to be saved.  This flag can only disable the
5840     * saving of this view; any child views may still have their state saved.
5841     *
5842     * @param enabled Set to false to <em>disable</em> state saving, or true
5843     * (the default) to allow it.
5844     *
5845     * @see #isSaveEnabled()
5846     * @see #setId(int)
5847     * @see #onSaveInstanceState()
5848     * @attr ref android.R.styleable#View_saveEnabled
5849     */
5850    public void setSaveEnabled(boolean enabled) {
5851        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5852    }
5853
5854    /**
5855     * Gets whether the framework should discard touches when the view's
5856     * window is obscured by another visible window.
5857     * Refer to the {@link View} security documentation for more details.
5858     *
5859     * @return True if touch filtering is enabled.
5860     *
5861     * @see #setFilterTouchesWhenObscured(boolean)
5862     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5863     */
5864    @ViewDebug.ExportedProperty
5865    public boolean getFilterTouchesWhenObscured() {
5866        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5867    }
5868
5869    /**
5870     * Sets whether the framework should discard touches when the view's
5871     * window is obscured by another visible window.
5872     * Refer to the {@link View} security documentation for more details.
5873     *
5874     * @param enabled True if touch filtering should be enabled.
5875     *
5876     * @see #getFilterTouchesWhenObscured
5877     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5878     */
5879    public void setFilterTouchesWhenObscured(boolean enabled) {
5880        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5881                FILTER_TOUCHES_WHEN_OBSCURED);
5882    }
5883
5884    /**
5885     * Indicates whether the entire hierarchy under this view will save its
5886     * state when a state saving traversal occurs from its parent.  The default
5887     * is true; if false, these views will not be saved unless
5888     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5889     *
5890     * @return Returns true if the view state saving from parent is enabled, else false.
5891     *
5892     * @see #setSaveFromParentEnabled(boolean)
5893     */
5894    public boolean isSaveFromParentEnabled() {
5895        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5896    }
5897
5898    /**
5899     * Controls whether the entire hierarchy under this view will save its
5900     * state when a state saving traversal occurs from its parent.  The default
5901     * is true; if false, these views will not be saved unless
5902     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5903     *
5904     * @param enabled Set to false to <em>disable</em> state saving, or true
5905     * (the default) to allow it.
5906     *
5907     * @see #isSaveFromParentEnabled()
5908     * @see #setId(int)
5909     * @see #onSaveInstanceState()
5910     */
5911    public void setSaveFromParentEnabled(boolean enabled) {
5912        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5913    }
5914
5915
5916    /**
5917     * Returns whether this View is able to take focus.
5918     *
5919     * @return True if this view can take focus, or false otherwise.
5920     * @attr ref android.R.styleable#View_focusable
5921     */
5922    @ViewDebug.ExportedProperty(category = "focus")
5923    public final boolean isFocusable() {
5924        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5925    }
5926
5927    /**
5928     * When a view is focusable, it may not want to take focus when in touch mode.
5929     * For example, a button would like focus when the user is navigating via a D-pad
5930     * so that the user can click on it, but once the user starts touching the screen,
5931     * the button shouldn't take focus
5932     * @return Whether the view is focusable in touch mode.
5933     * @attr ref android.R.styleable#View_focusableInTouchMode
5934     */
5935    @ViewDebug.ExportedProperty
5936    public final boolean isFocusableInTouchMode() {
5937        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5938    }
5939
5940    /**
5941     * Find the nearest view in the specified direction that can take focus.
5942     * This does not actually give focus to that view.
5943     *
5944     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5945     *
5946     * @return The nearest focusable in the specified direction, or null if none
5947     *         can be found.
5948     */
5949    public View focusSearch(int direction) {
5950        if (mParent != null) {
5951            return mParent.focusSearch(this, direction);
5952        } else {
5953            return null;
5954        }
5955    }
5956
5957    /**
5958     * This method is the last chance for the focused view and its ancestors to
5959     * respond to an arrow key. This is called when the focused view did not
5960     * consume the key internally, nor could the view system find a new view in
5961     * the requested direction to give focus to.
5962     *
5963     * @param focused The currently focused view.
5964     * @param direction The direction focus wants to move. One of FOCUS_UP,
5965     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5966     * @return True if the this view consumed this unhandled move.
5967     */
5968    public boolean dispatchUnhandledMove(View focused, int direction) {
5969        return false;
5970    }
5971
5972    /**
5973     * If a user manually specified the next view id for a particular direction,
5974     * use the root to look up the view.
5975     * @param root The root view of the hierarchy containing this view.
5976     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5977     * or FOCUS_BACKWARD.
5978     * @return The user specified next view, or null if there is none.
5979     */
5980    View findUserSetNextFocus(View root, int direction) {
5981        switch (direction) {
5982            case FOCUS_LEFT:
5983                if (mNextFocusLeftId == View.NO_ID) return null;
5984                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5985            case FOCUS_RIGHT:
5986                if (mNextFocusRightId == View.NO_ID) return null;
5987                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5988            case FOCUS_UP:
5989                if (mNextFocusUpId == View.NO_ID) return null;
5990                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5991            case FOCUS_DOWN:
5992                if (mNextFocusDownId == View.NO_ID) return null;
5993                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5994            case FOCUS_FORWARD:
5995                if (mNextFocusForwardId == View.NO_ID) return null;
5996                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5997            case FOCUS_BACKWARD: {
5998                if (mID == View.NO_ID) return null;
5999                final int id = mID;
6000                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6001                    @Override
6002                    public boolean apply(View t) {
6003                        return t.mNextFocusForwardId == id;
6004                    }
6005                });
6006            }
6007        }
6008        return null;
6009    }
6010
6011    private View findViewInsideOutShouldExist(View root, final int childViewId) {
6012        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6013            @Override
6014            public boolean apply(View t) {
6015                return t.mID == childViewId;
6016            }
6017        });
6018
6019        if (result == null) {
6020            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
6021                    + "by user for id " + childViewId);
6022        }
6023        return result;
6024    }
6025
6026    /**
6027     * Find and return all focusable views that are descendants of this view,
6028     * possibly including this view if it is focusable itself.
6029     *
6030     * @param direction The direction of the focus
6031     * @return A list of focusable views
6032     */
6033    public ArrayList<View> getFocusables(int direction) {
6034        ArrayList<View> result = new ArrayList<View>(24);
6035        addFocusables(result, direction);
6036        return result;
6037    }
6038
6039    /**
6040     * Add any focusable views that are descendants of this view (possibly
6041     * including this view if it is focusable itself) to views.  If we are in touch mode,
6042     * only add views that are also focusable in touch mode.
6043     *
6044     * @param views Focusable views found so far
6045     * @param direction The direction of the focus
6046     */
6047    public void addFocusables(ArrayList<View> views, int direction) {
6048        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6049    }
6050
6051    /**
6052     * Adds any focusable views that are descendants of this view (possibly
6053     * including this view if it is focusable itself) to views. This method
6054     * adds all focusable views regardless if we are in touch mode or
6055     * only views focusable in touch mode if we are in touch mode or
6056     * only views that can take accessibility focus if accessibility is enabeld
6057     * depending on the focusable mode paramater.
6058     *
6059     * @param views Focusable views found so far or null if all we are interested is
6060     *        the number of focusables.
6061     * @param direction The direction of the focus.
6062     * @param focusableMode The type of focusables to be added.
6063     *
6064     * @see #FOCUSABLES_ALL
6065     * @see #FOCUSABLES_TOUCH_MODE
6066     */
6067    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6068        if (views == null) {
6069            return;
6070        }
6071        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
6072            if (canTakeAccessibilityFocusFromHover() || getAccessibilityNodeProvider() != null) {
6073                views.add(this);
6074                return;
6075            }
6076        }
6077        if (!isFocusable()) {
6078            return;
6079        }
6080        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6081                && isInTouchMode() && !isFocusableInTouchMode()) {
6082            return;
6083        }
6084        views.add(this);
6085    }
6086
6087    /**
6088     * Finds the Views that contain given text. The containment is case insensitive.
6089     * The search is performed by either the text that the View renders or the content
6090     * description that describes the view for accessibility purposes and the view does
6091     * not render or both. Clients can specify how the search is to be performed via
6092     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6093     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6094     *
6095     * @param outViews The output list of matching Views.
6096     * @param searched The text to match against.
6097     *
6098     * @see #FIND_VIEWS_WITH_TEXT
6099     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6100     * @see #setContentDescription(CharSequence)
6101     */
6102    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6103        if (getAccessibilityNodeProvider() != null) {
6104            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6105                outViews.add(this);
6106            }
6107        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6108                && (searched != null && searched.length() > 0)
6109                && (mContentDescription != null && mContentDescription.length() > 0)) {
6110            String searchedLowerCase = searched.toString().toLowerCase();
6111            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6112            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6113                outViews.add(this);
6114            }
6115        }
6116    }
6117
6118    /**
6119     * Find and return all touchable views that are descendants of this view,
6120     * possibly including this view if it is touchable itself.
6121     *
6122     * @return A list of touchable views
6123     */
6124    public ArrayList<View> getTouchables() {
6125        ArrayList<View> result = new ArrayList<View>();
6126        addTouchables(result);
6127        return result;
6128    }
6129
6130    /**
6131     * Add any touchable views that are descendants of this view (possibly
6132     * including this view if it is touchable itself) to views.
6133     *
6134     * @param views Touchable views found so far
6135     */
6136    public void addTouchables(ArrayList<View> views) {
6137        final int viewFlags = mViewFlags;
6138
6139        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6140                && (viewFlags & ENABLED_MASK) == ENABLED) {
6141            views.add(this);
6142        }
6143    }
6144
6145    /**
6146     * Returns whether this View is accessibility focused.
6147     *
6148     * @return True if this View is accessibility focused.
6149     */
6150    boolean isAccessibilityFocused() {
6151        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6152    }
6153
6154    /**
6155     * Call this to try to give accessibility focus to this view.
6156     *
6157     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6158     * returns false or the view is no visible or the view already has accessibility
6159     * focus.
6160     *
6161     * See also {@link #focusSearch(int)}, which is what you call to say that you
6162     * have focus, and you want your parent to look for the next one.
6163     *
6164     * @return Whether this view actually took accessibility focus.
6165     *
6166     * @hide
6167     */
6168    public boolean requestAccessibilityFocus() {
6169        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6170        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6171            return false;
6172        }
6173        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6174            return false;
6175        }
6176        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6177            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6178            ViewRootImpl viewRootImpl = getViewRootImpl();
6179            if (viewRootImpl != null) {
6180                viewRootImpl.setAccessibilityFocusedHost(this);
6181            }
6182            invalidate();
6183            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6184            notifyAccessibilityStateChanged();
6185            return true;
6186        }
6187        return false;
6188    }
6189
6190    /**
6191     * Call this to try to clear accessibility focus of this view.
6192     *
6193     * See also {@link #focusSearch(int)}, which is what you call to say that you
6194     * have focus, and you want your parent to look for the next one.
6195     *
6196     * @hide
6197     */
6198    public void clearAccessibilityFocus() {
6199        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6200            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6201            invalidate();
6202            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6203            notifyAccessibilityStateChanged();
6204            // Clear the text navigation state.
6205            setAccessibilityCursorPosition(-1);
6206        }
6207        // Clear the global reference of accessibility focus if this
6208        // view or any of its descendants had accessibility focus.
6209        ViewRootImpl viewRootImpl = getViewRootImpl();
6210        if (viewRootImpl != null) {
6211            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6212            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6213                viewRootImpl.setAccessibilityFocusedHost(null);
6214            }
6215        }
6216    }
6217
6218    private void requestAccessibilityFocusFromHover() {
6219        if (includeForAccessibility() && isActionableForAccessibility()) {
6220            requestAccessibilityFocus();
6221            requestFocusNoSearch(View.FOCUS_DOWN, null);
6222        } else {
6223            if (mParent != null) {
6224                View nextFocus = mParent.findViewToTakeAccessibilityFocusFromHover(this, this);
6225                if (nextFocus != null) {
6226                    nextFocus.requestAccessibilityFocus();
6227                    nextFocus.requestFocusNoSearch(View.FOCUS_DOWN, null);
6228                }
6229            }
6230        }
6231    }
6232
6233    /**
6234     * @hide
6235     */
6236    public boolean canTakeAccessibilityFocusFromHover() {
6237        if (includeForAccessibility() && isActionableForAccessibility()) {
6238            return true;
6239        }
6240        if (mParent != null) {
6241            return (mParent.findViewToTakeAccessibilityFocusFromHover(this, this) == this);
6242        }
6243        return false;
6244    }
6245
6246    /**
6247     * Clears accessibility focus without calling any callback methods
6248     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6249     * is used for clearing accessibility focus when giving this focus to
6250     * another view.
6251     */
6252    void clearAccessibilityFocusNoCallbacks() {
6253        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6254            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6255            invalidate();
6256        }
6257    }
6258
6259    /**
6260     * Call this to try to give focus to a specific view or to one of its
6261     * descendants.
6262     *
6263     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6264     * false), or if it is focusable and it is not focusable in touch mode
6265     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6266     *
6267     * See also {@link #focusSearch(int)}, which is what you call to say that you
6268     * have focus, and you want your parent to look for the next one.
6269     *
6270     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6271     * {@link #FOCUS_DOWN} and <code>null</code>.
6272     *
6273     * @return Whether this view or one of its descendants actually took focus.
6274     */
6275    public final boolean requestFocus() {
6276        return requestFocus(View.FOCUS_DOWN);
6277    }
6278
6279    /**
6280     * Call this to try to give focus to a specific view or to one of its
6281     * descendants and give it a hint about what direction focus is heading.
6282     *
6283     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6284     * false), or if it is focusable and it is not focusable in touch mode
6285     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6286     *
6287     * See also {@link #focusSearch(int)}, which is what you call to say that you
6288     * have focus, and you want your parent to look for the next one.
6289     *
6290     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6291     * <code>null</code> set for the previously focused rectangle.
6292     *
6293     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6294     * @return Whether this view or one of its descendants actually took focus.
6295     */
6296    public final boolean requestFocus(int direction) {
6297        return requestFocus(direction, null);
6298    }
6299
6300    /**
6301     * Call this to try to give focus to a specific view or to one of its descendants
6302     * and give it hints about the direction and a specific rectangle that the focus
6303     * is coming from.  The rectangle can help give larger views a finer grained hint
6304     * about where focus is coming from, and therefore, where to show selection, or
6305     * forward focus change internally.
6306     *
6307     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6308     * false), or if it is focusable and it is not focusable in touch mode
6309     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6310     *
6311     * A View will not take focus if it is not visible.
6312     *
6313     * A View will not take focus if one of its parents has
6314     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6315     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6316     *
6317     * See also {@link #focusSearch(int)}, which is what you call to say that you
6318     * have focus, and you want your parent to look for the next one.
6319     *
6320     * You may wish to override this method if your custom {@link View} has an internal
6321     * {@link View} that it wishes to forward the request to.
6322     *
6323     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6324     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6325     *        to give a finer grained hint about where focus is coming from.  May be null
6326     *        if there is no hint.
6327     * @return Whether this view or one of its descendants actually took focus.
6328     */
6329    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6330        return requestFocusNoSearch(direction, previouslyFocusedRect);
6331    }
6332
6333    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6334        // need to be focusable
6335        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6336                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6337            return false;
6338        }
6339
6340        // need to be focusable in touch mode if in touch mode
6341        if (isInTouchMode() &&
6342            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6343               return false;
6344        }
6345
6346        // need to not have any parents blocking us
6347        if (hasAncestorThatBlocksDescendantFocus()) {
6348            return false;
6349        }
6350
6351        handleFocusGainInternal(direction, previouslyFocusedRect);
6352        return true;
6353    }
6354
6355    /**
6356     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6357     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6358     * touch mode to request focus when they are touched.
6359     *
6360     * @return Whether this view or one of its descendants actually took focus.
6361     *
6362     * @see #isInTouchMode()
6363     *
6364     */
6365    public final boolean requestFocusFromTouch() {
6366        // Leave touch mode if we need to
6367        if (isInTouchMode()) {
6368            ViewRootImpl viewRoot = getViewRootImpl();
6369            if (viewRoot != null) {
6370                viewRoot.ensureTouchMode(false);
6371            }
6372        }
6373        return requestFocus(View.FOCUS_DOWN);
6374    }
6375
6376    /**
6377     * @return Whether any ancestor of this view blocks descendant focus.
6378     */
6379    private boolean hasAncestorThatBlocksDescendantFocus() {
6380        ViewParent ancestor = mParent;
6381        while (ancestor instanceof ViewGroup) {
6382            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6383            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6384                return true;
6385            } else {
6386                ancestor = vgAncestor.getParent();
6387            }
6388        }
6389        return false;
6390    }
6391
6392    /**
6393     * Gets the mode for determining whether this View is important for accessibility
6394     * which is if it fires accessibility events and if it is reported to
6395     * accessibility services that query the screen.
6396     *
6397     * @return The mode for determining whether a View is important for accessibility.
6398     *
6399     * @attr ref android.R.styleable#View_importantForAccessibility
6400     *
6401     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6402     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6403     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6404     */
6405    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6406            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6407                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6408            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6409                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6410            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6411                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6412        })
6413    public int getImportantForAccessibility() {
6414        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6415                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6416    }
6417
6418    /**
6419     * Sets how to determine whether this view is important for accessibility
6420     * which is if it fires accessibility events and if it is reported to
6421     * accessibility services that query the screen.
6422     *
6423     * @param mode How to determine whether this view is important for accessibility.
6424     *
6425     * @attr ref android.R.styleable#View_importantForAccessibility
6426     *
6427     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6428     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6429     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6430     */
6431    public void setImportantForAccessibility(int mode) {
6432        if (mode != getImportantForAccessibility()) {
6433            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6434            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6435                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6436            notifyAccessibilityStateChanged();
6437        }
6438    }
6439
6440    /**
6441     * Gets whether this view should be exposed for accessibility.
6442     *
6443     * @return Whether the view is exposed for accessibility.
6444     *
6445     * @hide
6446     */
6447    public boolean isImportantForAccessibility() {
6448        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6449                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6450        switch (mode) {
6451            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6452                return true;
6453            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6454                return false;
6455            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6456                return isActionableForAccessibility() || hasListenersForAccessibility();
6457            default:
6458                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6459                        + mode);
6460        }
6461    }
6462
6463    /**
6464     * Gets the parent for accessibility purposes. Note that the parent for
6465     * accessibility is not necessary the immediate parent. It is the first
6466     * predecessor that is important for accessibility.
6467     *
6468     * @return The parent for accessibility purposes.
6469     */
6470    public ViewParent getParentForAccessibility() {
6471        if (mParent instanceof View) {
6472            View parentView = (View) mParent;
6473            if (parentView.includeForAccessibility()) {
6474                return mParent;
6475            } else {
6476                return mParent.getParentForAccessibility();
6477            }
6478        }
6479        return null;
6480    }
6481
6482    /**
6483     * Adds the children of a given View for accessibility. Since some Views are
6484     * not important for accessibility the children for accessibility are not
6485     * necessarily direct children of the riew, rather they are the first level of
6486     * descendants important for accessibility.
6487     *
6488     * @param children The list of children for accessibility.
6489     */
6490    public void addChildrenForAccessibility(ArrayList<View> children) {
6491        if (includeForAccessibility()) {
6492            children.add(this);
6493        }
6494    }
6495
6496    /**
6497     * Whether to regard this view for accessibility. A view is regarded for
6498     * accessibility if it is important for accessibility or the querying
6499     * accessibility service has explicitly requested that view not
6500     * important for accessibility are regarded.
6501     *
6502     * @return Whether to regard the view for accessibility.
6503     *
6504     * @hide
6505     */
6506    public boolean includeForAccessibility() {
6507        if (mAttachInfo != null) {
6508            if (!mAttachInfo.mIncludeNotImportantViews) {
6509                return isImportantForAccessibility();
6510            }
6511            return true;
6512        }
6513        return false;
6514    }
6515
6516    /**
6517     * Returns whether the View is considered actionable from
6518     * accessibility perspective. Such view are important for
6519     * accessiiblity.
6520     *
6521     * @return True if the view is actionable for accessibility.
6522     *
6523     * @hide
6524     */
6525    public boolean isActionableForAccessibility() {
6526        return (isClickable() || isLongClickable() || isFocusable());
6527    }
6528
6529    /**
6530     * Returns whether the View has registered callbacks wich makes it
6531     * important for accessiiblity.
6532     *
6533     * @return True if the view is actionable for accessibility.
6534     */
6535    private boolean hasListenersForAccessibility() {
6536        ListenerInfo info = getListenerInfo();
6537        return mTouchDelegate != null || info.mOnKeyListener != null
6538                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6539                || info.mOnHoverListener != null || info.mOnDragListener != null;
6540    }
6541
6542    /**
6543     * Notifies accessibility services that some view's important for
6544     * accessibility state has changed. Note that such notifications
6545     * are made at most once every
6546     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6547     * to avoid unnecessary load to the system. Also once a view has
6548     * made a notifucation this method is a NOP until the notification has
6549     * been sent to clients.
6550     *
6551     * @hide
6552     *
6553     * TODO: Makse sure this method is called for any view state change
6554     *       that is interesting for accessilility purposes.
6555     */
6556    public void notifyAccessibilityStateChanged() {
6557        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6558            return;
6559        }
6560        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6561            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6562            if (mParent != null) {
6563                mParent.childAccessibilityStateChanged(this);
6564            }
6565        }
6566    }
6567
6568    /**
6569     * Reset the state indicating the this view has requested clients
6570     * interested in its accessiblity state to be notified.
6571     *
6572     * @hide
6573     */
6574    public void resetAccessibilityStateChanged() {
6575        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6576    }
6577
6578    /**
6579     * Performs the specified accessibility action on the view. For
6580     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6581    * <p>
6582    * If an {@link AccessibilityDelegate} has been specified via calling
6583    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6584    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6585    * is responsible for handling this call.
6586    * </p>
6587     *
6588     * @param action The action to perform.
6589     * @param arguments Optional action arguments.
6590     * @return Whether the action was performed.
6591     */
6592    public boolean performAccessibilityAction(int action, Bundle arguments) {
6593      if (mAccessibilityDelegate != null) {
6594          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6595      } else {
6596          return performAccessibilityActionInternal(action, arguments);
6597      }
6598    }
6599
6600   /**
6601    * @see #performAccessibilityAction(int, Bundle)
6602    *
6603    * Note: Called from the default {@link AccessibilityDelegate}.
6604    */
6605    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6606        switch (action) {
6607            case AccessibilityNodeInfo.ACTION_CLICK: {
6608                if (isClickable()) {
6609                    return performClick();
6610                }
6611            } break;
6612            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6613                if (isLongClickable()) {
6614                    return performLongClick();
6615                }
6616            } break;
6617            case AccessibilityNodeInfo.ACTION_FOCUS: {
6618                if (!hasFocus()) {
6619                    // Get out of touch mode since accessibility
6620                    // wants to move focus around.
6621                    getViewRootImpl().ensureTouchMode(false);
6622                    return requestFocus();
6623                }
6624            } break;
6625            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6626                if (hasFocus()) {
6627                    clearFocus();
6628                    return !isFocused();
6629                }
6630            } break;
6631            case AccessibilityNodeInfo.ACTION_SELECT: {
6632                if (!isSelected()) {
6633                    setSelected(true);
6634                    return isSelected();
6635                }
6636            } break;
6637            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6638                if (isSelected()) {
6639                    setSelected(false);
6640                    return !isSelected();
6641                }
6642            } break;
6643            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6644                if (!isAccessibilityFocused()) {
6645                    return requestAccessibilityFocus();
6646                }
6647            } break;
6648            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6649                if (isAccessibilityFocused()) {
6650                    clearAccessibilityFocus();
6651                    return true;
6652                }
6653            } break;
6654            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6655                if (arguments != null) {
6656                    final int granularity = arguments.getInt(
6657                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6658                    return nextAtGranularity(granularity);
6659                }
6660            } break;
6661            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6662                if (arguments != null) {
6663                    final int granularity = arguments.getInt(
6664                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6665                    return previousAtGranularity(granularity);
6666                }
6667            } break;
6668        }
6669        return false;
6670    }
6671
6672    private boolean nextAtGranularity(int granularity) {
6673        CharSequence text = getIterableTextForAccessibility();
6674        if (text == null || text.length() == 0) {
6675            return false;
6676        }
6677        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6678        if (iterator == null) {
6679            return false;
6680        }
6681        final int current = getAccessibilityCursorPosition();
6682        final int[] range = iterator.following(current);
6683        if (range == null) {
6684            setAccessibilityCursorPosition(-1);
6685            return false;
6686        }
6687        final int start = range[0];
6688        final int end = range[1];
6689        setAccessibilityCursorPosition(start);
6690        sendViewTextTraversedAtGranularityEvent(
6691                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6692                granularity, start, end);
6693        return true;
6694    }
6695
6696    private boolean previousAtGranularity(int granularity) {
6697        CharSequence text = getIterableTextForAccessibility();
6698        if (text == null || text.length() == 0) {
6699            return false;
6700        }
6701        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6702        if (iterator == null) {
6703            return false;
6704        }
6705        final int selectionStart = getAccessibilityCursorPosition();
6706        final int current = selectionStart >= 0 ? selectionStart : text.length() + 1;
6707        final int[] range = iterator.preceding(current);
6708        if (range == null) {
6709            setAccessibilityCursorPosition(-1);
6710            return false;
6711        }
6712        final int start = range[0];
6713        final int end = range[1];
6714        setAccessibilityCursorPosition(end);
6715        sendViewTextTraversedAtGranularityEvent(
6716                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6717                granularity, start, end);
6718        return true;
6719    }
6720
6721    /**
6722     * Gets the text reported for accessibility purposes.
6723     *
6724     * @return The accessibility text.
6725     *
6726     * @hide
6727     */
6728    public CharSequence getIterableTextForAccessibility() {
6729        return mContentDescription;
6730    }
6731
6732    /**
6733     * @hide
6734     */
6735    public int getAccessibilityCursorPosition() {
6736        return mAccessibilityCursorPosition;
6737    }
6738
6739    /**
6740     * @hide
6741     */
6742    public void setAccessibilityCursorPosition(int position) {
6743        mAccessibilityCursorPosition = position;
6744    }
6745
6746    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6747            int fromIndex, int toIndex) {
6748        if (mParent == null) {
6749            return;
6750        }
6751        AccessibilityEvent event = AccessibilityEvent.obtain(
6752                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6753        onInitializeAccessibilityEvent(event);
6754        onPopulateAccessibilityEvent(event);
6755        event.setFromIndex(fromIndex);
6756        event.setToIndex(toIndex);
6757        event.setAction(action);
6758        event.setMovementGranularity(granularity);
6759        mParent.requestSendAccessibilityEvent(this, event);
6760    }
6761
6762    /**
6763     * @hide
6764     */
6765    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6766        switch (granularity) {
6767            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6768                CharSequence text = getIterableTextForAccessibility();
6769                if (text != null && text.length() > 0) {
6770                    CharacterTextSegmentIterator iterator =
6771                        CharacterTextSegmentIterator.getInstance(mContext);
6772                    iterator.initialize(text.toString());
6773                    return iterator;
6774                }
6775            } break;
6776            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6777                CharSequence text = getIterableTextForAccessibility();
6778                if (text != null && text.length() > 0) {
6779                    WordTextSegmentIterator iterator =
6780                        WordTextSegmentIterator.getInstance(mContext);
6781                    iterator.initialize(text.toString());
6782                    return iterator;
6783                }
6784            } break;
6785            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6786                CharSequence text = getIterableTextForAccessibility();
6787                if (text != null && text.length() > 0) {
6788                    ParagraphTextSegmentIterator iterator =
6789                        ParagraphTextSegmentIterator.getInstance();
6790                    iterator.initialize(text.toString());
6791                    return iterator;
6792                }
6793            } break;
6794        }
6795        return null;
6796    }
6797
6798    /**
6799     * @hide
6800     */
6801    public void dispatchStartTemporaryDetach() {
6802        clearAccessibilityFocus();
6803        onStartTemporaryDetach();
6804    }
6805
6806    /**
6807     * This is called when a container is going to temporarily detach a child, with
6808     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6809     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6810     * {@link #onDetachedFromWindow()} when the container is done.
6811     */
6812    public void onStartTemporaryDetach() {
6813        removeUnsetPressCallback();
6814        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6815    }
6816
6817    /**
6818     * @hide
6819     */
6820    public void dispatchFinishTemporaryDetach() {
6821        onFinishTemporaryDetach();
6822    }
6823
6824    /**
6825     * Called after {@link #onStartTemporaryDetach} when the container is done
6826     * changing the view.
6827     */
6828    public void onFinishTemporaryDetach() {
6829    }
6830
6831    /**
6832     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6833     * for this view's window.  Returns null if the view is not currently attached
6834     * to the window.  Normally you will not need to use this directly, but
6835     * just use the standard high-level event callbacks like
6836     * {@link #onKeyDown(int, KeyEvent)}.
6837     */
6838    public KeyEvent.DispatcherState getKeyDispatcherState() {
6839        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6840    }
6841
6842    /**
6843     * Dispatch a key event before it is processed by any input method
6844     * associated with the view hierarchy.  This can be used to intercept
6845     * key events in special situations before the IME consumes them; a
6846     * typical example would be handling the BACK key to update the application's
6847     * UI instead of allowing the IME to see it and close itself.
6848     *
6849     * @param event The key event to be dispatched.
6850     * @return True if the event was handled, false otherwise.
6851     */
6852    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6853        return onKeyPreIme(event.getKeyCode(), event);
6854    }
6855
6856    /**
6857     * Dispatch a key event to the next view on the focus path. This path runs
6858     * from the top of the view tree down to the currently focused view. If this
6859     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6860     * the next node down the focus path. This method also fires any key
6861     * listeners.
6862     *
6863     * @param event The key event to be dispatched.
6864     * @return True if the event was handled, false otherwise.
6865     */
6866    public boolean dispatchKeyEvent(KeyEvent event) {
6867        if (mInputEventConsistencyVerifier != null) {
6868            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6869        }
6870
6871        // Give any attached key listener a first crack at the event.
6872        //noinspection SimplifiableIfStatement
6873        ListenerInfo li = mListenerInfo;
6874        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6875                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6876            return true;
6877        }
6878
6879        if (event.dispatch(this, mAttachInfo != null
6880                ? mAttachInfo.mKeyDispatchState : null, this)) {
6881            return true;
6882        }
6883
6884        if (mInputEventConsistencyVerifier != null) {
6885            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6886        }
6887        return false;
6888    }
6889
6890    /**
6891     * Dispatches a key shortcut event.
6892     *
6893     * @param event The key event to be dispatched.
6894     * @return True if the event was handled by the view, false otherwise.
6895     */
6896    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6897        return onKeyShortcut(event.getKeyCode(), event);
6898    }
6899
6900    /**
6901     * Pass the touch screen motion event down to the target view, or this
6902     * view if it is the target.
6903     *
6904     * @param event The motion event to be dispatched.
6905     * @return True if the event was handled by the view, false otherwise.
6906     */
6907    public boolean dispatchTouchEvent(MotionEvent event) {
6908        if (mInputEventConsistencyVerifier != null) {
6909            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6910        }
6911
6912        if (onFilterTouchEventForSecurity(event)) {
6913            //noinspection SimplifiableIfStatement
6914            ListenerInfo li = mListenerInfo;
6915            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6916                    && li.mOnTouchListener.onTouch(this, event)) {
6917                return true;
6918            }
6919
6920            if (onTouchEvent(event)) {
6921                return true;
6922            }
6923        }
6924
6925        if (mInputEventConsistencyVerifier != null) {
6926            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6927        }
6928        return false;
6929    }
6930
6931    /**
6932     * Filter the touch event to apply security policies.
6933     *
6934     * @param event The motion event to be filtered.
6935     * @return True if the event should be dispatched, false if the event should be dropped.
6936     *
6937     * @see #getFilterTouchesWhenObscured
6938     */
6939    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6940        //noinspection RedundantIfStatement
6941        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6942                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6943            // Window is obscured, drop this touch.
6944            return false;
6945        }
6946        return true;
6947    }
6948
6949    /**
6950     * Pass a trackball motion event down to the focused view.
6951     *
6952     * @param event The motion event to be dispatched.
6953     * @return True if the event was handled by the view, false otherwise.
6954     */
6955    public boolean dispatchTrackballEvent(MotionEvent event) {
6956        if (mInputEventConsistencyVerifier != null) {
6957            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6958        }
6959
6960        return onTrackballEvent(event);
6961    }
6962
6963    /**
6964     * Dispatch a generic motion event.
6965     * <p>
6966     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6967     * are delivered to the view under the pointer.  All other generic motion events are
6968     * delivered to the focused view.  Hover events are handled specially and are delivered
6969     * to {@link #onHoverEvent(MotionEvent)}.
6970     * </p>
6971     *
6972     * @param event The motion event to be dispatched.
6973     * @return True if the event was handled by the view, false otherwise.
6974     */
6975    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6976        if (mInputEventConsistencyVerifier != null) {
6977            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6978        }
6979
6980        final int source = event.getSource();
6981        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6982            final int action = event.getAction();
6983            if (action == MotionEvent.ACTION_HOVER_ENTER
6984                    || action == MotionEvent.ACTION_HOVER_MOVE
6985                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6986                if (dispatchHoverEvent(event)) {
6987                    return true;
6988                }
6989            } else if (dispatchGenericPointerEvent(event)) {
6990                return true;
6991            }
6992        } else if (dispatchGenericFocusedEvent(event)) {
6993            return true;
6994        }
6995
6996        if (dispatchGenericMotionEventInternal(event)) {
6997            return true;
6998        }
6999
7000        if (mInputEventConsistencyVerifier != null) {
7001            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7002        }
7003        return false;
7004    }
7005
7006    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7007        //noinspection SimplifiableIfStatement
7008        ListenerInfo li = mListenerInfo;
7009        if (li != null && li.mOnGenericMotionListener != null
7010                && (mViewFlags & ENABLED_MASK) == ENABLED
7011                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7012            return true;
7013        }
7014
7015        if (onGenericMotionEvent(event)) {
7016            return true;
7017        }
7018
7019        if (mInputEventConsistencyVerifier != null) {
7020            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7021        }
7022        return false;
7023    }
7024
7025    /**
7026     * Dispatch a hover event.
7027     * <p>
7028     * Do not call this method directly.
7029     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7030     * </p>
7031     *
7032     * @param event The motion event to be dispatched.
7033     * @return True if the event was handled by the view, false otherwise.
7034     */
7035    protected boolean dispatchHoverEvent(MotionEvent event) {
7036        //noinspection SimplifiableIfStatement
7037        ListenerInfo li = mListenerInfo;
7038        if (li != null && li.mOnHoverListener != null
7039                && (mViewFlags & ENABLED_MASK) == ENABLED
7040                && li.mOnHoverListener.onHover(this, event)) {
7041            return true;
7042        }
7043
7044        return onHoverEvent(event);
7045    }
7046
7047    /**
7048     * Returns true if the view has a child to which it has recently sent
7049     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7050     * it does not have a hovered child, then it must be the innermost hovered view.
7051     * @hide
7052     */
7053    protected boolean hasHoveredChild() {
7054        return false;
7055    }
7056
7057    /**
7058     * Dispatch a generic motion event to the view under the first pointer.
7059     * <p>
7060     * Do not call this method directly.
7061     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7062     * </p>
7063     *
7064     * @param event The motion event to be dispatched.
7065     * @return True if the event was handled by the view, false otherwise.
7066     */
7067    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7068        return false;
7069    }
7070
7071    /**
7072     * Dispatch a generic motion event to the currently focused view.
7073     * <p>
7074     * Do not call this method directly.
7075     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
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     */
7081    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7082        return false;
7083    }
7084
7085    /**
7086     * Dispatch a pointer event.
7087     * <p>
7088     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7089     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7090     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7091     * and should not be expected to handle other pointing device features.
7092     * </p>
7093     *
7094     * @param event The motion event to be dispatched.
7095     * @return True if the event was handled by the view, false otherwise.
7096     * @hide
7097     */
7098    public final boolean dispatchPointerEvent(MotionEvent event) {
7099        if (event.isTouchEvent()) {
7100            return dispatchTouchEvent(event);
7101        } else {
7102            return dispatchGenericMotionEvent(event);
7103        }
7104    }
7105
7106    /**
7107     * Called when the window containing this view gains or loses window focus.
7108     * ViewGroups should override to route to their children.
7109     *
7110     * @param hasFocus True if the window containing this view now has focus,
7111     *        false otherwise.
7112     */
7113    public void dispatchWindowFocusChanged(boolean hasFocus) {
7114        onWindowFocusChanged(hasFocus);
7115    }
7116
7117    /**
7118     * Called when the window containing this view gains or loses focus.  Note
7119     * that this is separate from view focus: to receive key events, both
7120     * your view and its window must have focus.  If a window is displayed
7121     * on top of yours that takes input focus, then your own window will lose
7122     * focus but the view focus will remain unchanged.
7123     *
7124     * @param hasWindowFocus True if the window containing this view now has
7125     *        focus, false otherwise.
7126     */
7127    public void onWindowFocusChanged(boolean hasWindowFocus) {
7128        InputMethodManager imm = InputMethodManager.peekInstance();
7129        if (!hasWindowFocus) {
7130            if (isPressed()) {
7131                setPressed(false);
7132            }
7133            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7134                imm.focusOut(this);
7135            }
7136            removeLongPressCallback();
7137            removeTapCallback();
7138            onFocusLost();
7139        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7140            imm.focusIn(this);
7141        }
7142        refreshDrawableState();
7143    }
7144
7145    /**
7146     * Returns true if this view is in a window that currently has window focus.
7147     * Note that this is not the same as the view itself having focus.
7148     *
7149     * @return True if this view is in a window that currently has window focus.
7150     */
7151    public boolean hasWindowFocus() {
7152        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7153    }
7154
7155    /**
7156     * Dispatch a view visibility change down the view hierarchy.
7157     * ViewGroups should override to route to their children.
7158     * @param changedView The view whose visibility changed. Could be 'this' or
7159     * an ancestor view.
7160     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7161     * {@link #INVISIBLE} or {@link #GONE}.
7162     */
7163    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7164        onVisibilityChanged(changedView, visibility);
7165    }
7166
7167    /**
7168     * Called when the visibility of the view or an ancestor of the view is changed.
7169     * @param changedView The view whose visibility changed. Could be 'this' or
7170     * an ancestor view.
7171     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7172     * {@link #INVISIBLE} or {@link #GONE}.
7173     */
7174    protected void onVisibilityChanged(View changedView, int visibility) {
7175        if (visibility == VISIBLE) {
7176            if (mAttachInfo != null) {
7177                initialAwakenScrollBars();
7178            } else {
7179                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7180            }
7181        }
7182    }
7183
7184    /**
7185     * Dispatch a hint about whether this view is displayed. For instance, when
7186     * a View moves out of the screen, it might receives a display hint indicating
7187     * the view is not displayed. Applications should not <em>rely</em> on this hint
7188     * as there is no guarantee that they will receive one.
7189     *
7190     * @param hint A hint about whether or not this view is displayed:
7191     * {@link #VISIBLE} or {@link #INVISIBLE}.
7192     */
7193    public void dispatchDisplayHint(int hint) {
7194        onDisplayHint(hint);
7195    }
7196
7197    /**
7198     * Gives this view a hint about whether is displayed or not. For instance, when
7199     * a View moves out of the screen, it might receives a display hint indicating
7200     * the view is not displayed. Applications should not <em>rely</em> on this hint
7201     * as there is no guarantee that they will receive one.
7202     *
7203     * @param hint A hint about whether or not this view is displayed:
7204     * {@link #VISIBLE} or {@link #INVISIBLE}.
7205     */
7206    protected void onDisplayHint(int hint) {
7207    }
7208
7209    /**
7210     * Dispatch a window visibility change down the view hierarchy.
7211     * ViewGroups should override to route to their children.
7212     *
7213     * @param visibility The new visibility of the window.
7214     *
7215     * @see #onWindowVisibilityChanged(int)
7216     */
7217    public void dispatchWindowVisibilityChanged(int visibility) {
7218        onWindowVisibilityChanged(visibility);
7219    }
7220
7221    /**
7222     * Called when the window containing has change its visibility
7223     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7224     * that this tells you whether or not your window is being made visible
7225     * to the window manager; this does <em>not</em> tell you whether or not
7226     * your window is obscured by other windows on the screen, even if it
7227     * is itself visible.
7228     *
7229     * @param visibility The new visibility of the window.
7230     */
7231    protected void onWindowVisibilityChanged(int visibility) {
7232        if (visibility == VISIBLE) {
7233            initialAwakenScrollBars();
7234        }
7235    }
7236
7237    /**
7238     * Returns the current visibility of the window this view is attached to
7239     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7240     *
7241     * @return Returns the current visibility of the view's window.
7242     */
7243    public int getWindowVisibility() {
7244        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7245    }
7246
7247    /**
7248     * Retrieve the overall visible display size in which the window this view is
7249     * attached to has been positioned in.  This takes into account screen
7250     * decorations above the window, for both cases where the window itself
7251     * is being position inside of them or the window is being placed under
7252     * then and covered insets are used for the window to position its content
7253     * inside.  In effect, this tells you the available area where content can
7254     * be placed and remain visible to users.
7255     *
7256     * <p>This function requires an IPC back to the window manager to retrieve
7257     * the requested information, so should not be used in performance critical
7258     * code like drawing.
7259     *
7260     * @param outRect Filled in with the visible display frame.  If the view
7261     * is not attached to a window, this is simply the raw display size.
7262     */
7263    public void getWindowVisibleDisplayFrame(Rect outRect) {
7264        if (mAttachInfo != null) {
7265            try {
7266                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7267            } catch (RemoteException e) {
7268                return;
7269            }
7270            // XXX This is really broken, and probably all needs to be done
7271            // in the window manager, and we need to know more about whether
7272            // we want the area behind or in front of the IME.
7273            final Rect insets = mAttachInfo.mVisibleInsets;
7274            outRect.left += insets.left;
7275            outRect.top += insets.top;
7276            outRect.right -= insets.right;
7277            outRect.bottom -= insets.bottom;
7278            return;
7279        }
7280        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7281        d.getRectSize(outRect);
7282    }
7283
7284    /**
7285     * Dispatch a notification about a resource configuration change down
7286     * the view hierarchy.
7287     * ViewGroups should override to route to their children.
7288     *
7289     * @param newConfig The new resource configuration.
7290     *
7291     * @see #onConfigurationChanged(android.content.res.Configuration)
7292     */
7293    public void dispatchConfigurationChanged(Configuration newConfig) {
7294        onConfigurationChanged(newConfig);
7295    }
7296
7297    /**
7298     * Called when the current configuration of the resources being used
7299     * by the application have changed.  You can use this to decide when
7300     * to reload resources that can changed based on orientation and other
7301     * configuration characterstics.  You only need to use this if you are
7302     * not relying on the normal {@link android.app.Activity} mechanism of
7303     * recreating the activity instance upon a configuration change.
7304     *
7305     * @param newConfig The new resource configuration.
7306     */
7307    protected void onConfigurationChanged(Configuration newConfig) {
7308    }
7309
7310    /**
7311     * Private function to aggregate all per-view attributes in to the view
7312     * root.
7313     */
7314    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7315        performCollectViewAttributes(attachInfo, visibility);
7316    }
7317
7318    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7319        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7320            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7321                attachInfo.mKeepScreenOn = true;
7322            }
7323            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7324            ListenerInfo li = mListenerInfo;
7325            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7326                attachInfo.mHasSystemUiListeners = true;
7327            }
7328        }
7329    }
7330
7331    void needGlobalAttributesUpdate(boolean force) {
7332        final AttachInfo ai = mAttachInfo;
7333        if (ai != null) {
7334            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7335                    || ai.mHasSystemUiListeners) {
7336                ai.mRecomputeGlobalAttributes = true;
7337            }
7338        }
7339    }
7340
7341    /**
7342     * Returns whether the device is currently in touch mode.  Touch mode is entered
7343     * once the user begins interacting with the device by touch, and affects various
7344     * things like whether focus is always visible to the user.
7345     *
7346     * @return Whether the device is in touch mode.
7347     */
7348    @ViewDebug.ExportedProperty
7349    public boolean isInTouchMode() {
7350        if (mAttachInfo != null) {
7351            return mAttachInfo.mInTouchMode;
7352        } else {
7353            return ViewRootImpl.isInTouchMode();
7354        }
7355    }
7356
7357    /**
7358     * Returns the context the view is running in, through which it can
7359     * access the current theme, resources, etc.
7360     *
7361     * @return The view's Context.
7362     */
7363    @ViewDebug.CapturedViewProperty
7364    public final Context getContext() {
7365        return mContext;
7366    }
7367
7368    /**
7369     * Handle a key event before it is processed by any input method
7370     * associated with the view hierarchy.  This can be used to intercept
7371     * key events in special situations before the IME consumes them; a
7372     * typical example would be handling the BACK key to update the application's
7373     * UI instead of allowing the IME to see it and close itself.
7374     *
7375     * @param keyCode The value in event.getKeyCode().
7376     * @param event Description of the key event.
7377     * @return If you handled the event, return true. If you want to allow the
7378     *         event to be handled by the next receiver, return false.
7379     */
7380    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7381        return false;
7382    }
7383
7384    /**
7385     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7386     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7387     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7388     * is released, if the view is enabled and clickable.
7389     *
7390     * @param keyCode A key code that represents the button pressed, from
7391     *                {@link android.view.KeyEvent}.
7392     * @param event   The KeyEvent object that defines the button action.
7393     */
7394    public boolean onKeyDown(int keyCode, KeyEvent event) {
7395        boolean result = false;
7396
7397        switch (keyCode) {
7398            case KeyEvent.KEYCODE_DPAD_CENTER:
7399            case KeyEvent.KEYCODE_ENTER: {
7400                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7401                    return true;
7402                }
7403                // Long clickable items don't necessarily have to be clickable
7404                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7405                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7406                        (event.getRepeatCount() == 0)) {
7407                    setPressed(true);
7408                    checkForLongClick(0);
7409                    return true;
7410                }
7411                break;
7412            }
7413        }
7414        return result;
7415    }
7416
7417    /**
7418     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7419     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7420     * the event).
7421     */
7422    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7423        return false;
7424    }
7425
7426    /**
7427     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7428     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7429     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7430     * {@link KeyEvent#KEYCODE_ENTER} is released.
7431     *
7432     * @param keyCode A key code that represents the button pressed, from
7433     *                {@link android.view.KeyEvent}.
7434     * @param event   The KeyEvent object that defines the button action.
7435     */
7436    public boolean onKeyUp(int keyCode, KeyEvent event) {
7437        boolean result = false;
7438
7439        switch (keyCode) {
7440            case KeyEvent.KEYCODE_DPAD_CENTER:
7441            case KeyEvent.KEYCODE_ENTER: {
7442                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7443                    return true;
7444                }
7445                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7446                    setPressed(false);
7447
7448                    if (!mHasPerformedLongPress) {
7449                        // This is a tap, so remove the longpress check
7450                        removeLongPressCallback();
7451
7452                        result = performClick();
7453                    }
7454                }
7455                break;
7456            }
7457        }
7458        return result;
7459    }
7460
7461    /**
7462     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7463     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7464     * the event).
7465     *
7466     * @param keyCode     A key code that represents the button pressed, from
7467     *                    {@link android.view.KeyEvent}.
7468     * @param repeatCount The number of times the action was made.
7469     * @param event       The KeyEvent object that defines the button action.
7470     */
7471    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7472        return false;
7473    }
7474
7475    /**
7476     * Called on the focused view when a key shortcut event is not handled.
7477     * Override this method to implement local key shortcuts for the View.
7478     * Key shortcuts can also be implemented by setting the
7479     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7480     *
7481     * @param keyCode The value in event.getKeyCode().
7482     * @param event Description of the key event.
7483     * @return If you handled the event, return true. If you want to allow the
7484     *         event to be handled by the next receiver, return false.
7485     */
7486    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7487        return false;
7488    }
7489
7490    /**
7491     * Check whether the called view is a text editor, in which case it
7492     * would make sense to automatically display a soft input window for
7493     * it.  Subclasses should override this if they implement
7494     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7495     * a call on that method would return a non-null InputConnection, and
7496     * they are really a first-class editor that the user would normally
7497     * start typing on when the go into a window containing your view.
7498     *
7499     * <p>The default implementation always returns false.  This does
7500     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7501     * will not be called or the user can not otherwise perform edits on your
7502     * view; it is just a hint to the system that this is not the primary
7503     * purpose of this view.
7504     *
7505     * @return Returns true if this view is a text editor, else false.
7506     */
7507    public boolean onCheckIsTextEditor() {
7508        return false;
7509    }
7510
7511    /**
7512     * Create a new InputConnection for an InputMethod to interact
7513     * with the view.  The default implementation returns null, since it doesn't
7514     * support input methods.  You can override this to implement such support.
7515     * This is only needed for views that take focus and text input.
7516     *
7517     * <p>When implementing this, you probably also want to implement
7518     * {@link #onCheckIsTextEditor()} to indicate you will return a
7519     * non-null InputConnection.
7520     *
7521     * @param outAttrs Fill in with attribute information about the connection.
7522     */
7523    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7524        return null;
7525    }
7526
7527    /**
7528     * Called by the {@link android.view.inputmethod.InputMethodManager}
7529     * when a view who is not the current
7530     * input connection target is trying to make a call on the manager.  The
7531     * default implementation returns false; you can override this to return
7532     * true for certain views if you are performing InputConnection proxying
7533     * to them.
7534     * @param view The View that is making the InputMethodManager call.
7535     * @return Return true to allow the call, false to reject.
7536     */
7537    public boolean checkInputConnectionProxy(View view) {
7538        return false;
7539    }
7540
7541    /**
7542     * Show the context menu for this view. It is not safe to hold on to the
7543     * menu after returning from this method.
7544     *
7545     * You should normally not overload this method. Overload
7546     * {@link #onCreateContextMenu(ContextMenu)} or define an
7547     * {@link OnCreateContextMenuListener} to add items to the context menu.
7548     *
7549     * @param menu The context menu to populate
7550     */
7551    public void createContextMenu(ContextMenu menu) {
7552        ContextMenuInfo menuInfo = getContextMenuInfo();
7553
7554        // Sets the current menu info so all items added to menu will have
7555        // my extra info set.
7556        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7557
7558        onCreateContextMenu(menu);
7559        ListenerInfo li = mListenerInfo;
7560        if (li != null && li.mOnCreateContextMenuListener != null) {
7561            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7562        }
7563
7564        // Clear the extra information so subsequent items that aren't mine don't
7565        // have my extra info.
7566        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7567
7568        if (mParent != null) {
7569            mParent.createContextMenu(menu);
7570        }
7571    }
7572
7573    /**
7574     * Views should implement this if they have extra information to associate
7575     * with the context menu. The return result is supplied as a parameter to
7576     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7577     * callback.
7578     *
7579     * @return Extra information about the item for which the context menu
7580     *         should be shown. This information will vary across different
7581     *         subclasses of View.
7582     */
7583    protected ContextMenuInfo getContextMenuInfo() {
7584        return null;
7585    }
7586
7587    /**
7588     * Views should implement this if the view itself is going to add items to
7589     * the context menu.
7590     *
7591     * @param menu the context menu to populate
7592     */
7593    protected void onCreateContextMenu(ContextMenu menu) {
7594    }
7595
7596    /**
7597     * Implement this method to handle trackball motion events.  The
7598     * <em>relative</em> movement of the trackball since the last event
7599     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7600     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7601     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7602     * they will often be fractional values, representing the more fine-grained
7603     * movement information available from a trackball).
7604     *
7605     * @param event The motion event.
7606     * @return True if the event was handled, false otherwise.
7607     */
7608    public boolean onTrackballEvent(MotionEvent event) {
7609        return false;
7610    }
7611
7612    /**
7613     * Implement this method to handle generic motion events.
7614     * <p>
7615     * Generic motion events describe joystick movements, mouse hovers, track pad
7616     * touches, scroll wheel movements and other input events.  The
7617     * {@link MotionEvent#getSource() source} of the motion event specifies
7618     * the class of input that was received.  Implementations of this method
7619     * must examine the bits in the source before processing the event.
7620     * The following code example shows how this is done.
7621     * </p><p>
7622     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7623     * are delivered to the view under the pointer.  All other generic motion events are
7624     * delivered to the focused view.
7625     * </p>
7626     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7627     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7628     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7629     *             // process the joystick movement...
7630     *             return true;
7631     *         }
7632     *     }
7633     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7634     *         switch (event.getAction()) {
7635     *             case MotionEvent.ACTION_HOVER_MOVE:
7636     *                 // process the mouse hover movement...
7637     *                 return true;
7638     *             case MotionEvent.ACTION_SCROLL:
7639     *                 // process the scroll wheel movement...
7640     *                 return true;
7641     *         }
7642     *     }
7643     *     return super.onGenericMotionEvent(event);
7644     * }</pre>
7645     *
7646     * @param event The generic motion event being processed.
7647     * @return True if the event was handled, false otherwise.
7648     */
7649    public boolean onGenericMotionEvent(MotionEvent event) {
7650        return false;
7651    }
7652
7653    /**
7654     * Implement this method to handle hover events.
7655     * <p>
7656     * This method is called whenever a pointer is hovering into, over, or out of the
7657     * bounds of a view and the view is not currently being touched.
7658     * Hover events are represented as pointer events with action
7659     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7660     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7661     * </p>
7662     * <ul>
7663     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7664     * when the pointer enters the bounds of the view.</li>
7665     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7666     * when the pointer has already entered the bounds of the view and has moved.</li>
7667     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7668     * when the pointer has exited the bounds of the view or when the pointer is
7669     * about to go down due to a button click, tap, or similar user action that
7670     * causes the view to be touched.</li>
7671     * </ul>
7672     * <p>
7673     * The view should implement this method to return true to indicate that it is
7674     * handling the hover event, such as by changing its drawable state.
7675     * </p><p>
7676     * The default implementation calls {@link #setHovered} to update the hovered state
7677     * of the view when a hover enter or hover exit event is received, if the view
7678     * is enabled and is clickable.  The default implementation also sends hover
7679     * accessibility events.
7680     * </p>
7681     *
7682     * @param event The motion event that describes the hover.
7683     * @return True if the view handled the hover event.
7684     *
7685     * @see #isHovered
7686     * @see #setHovered
7687     * @see #onHoverChanged
7688     */
7689    public boolean onHoverEvent(MotionEvent event) {
7690        // The root view may receive hover (or touch) events that are outside the bounds of
7691        // the window.  This code ensures that we only send accessibility events for
7692        // hovers that are actually within the bounds of the root view.
7693        final int action = event.getActionMasked();
7694        if (!mSendingHoverAccessibilityEvents) {
7695            if ((action == MotionEvent.ACTION_HOVER_ENTER
7696                    || action == MotionEvent.ACTION_HOVER_MOVE)
7697                    && !hasHoveredChild()
7698                    && pointInView(event.getX(), event.getY())) {
7699                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7700                mSendingHoverAccessibilityEvents = true;
7701                requestAccessibilityFocusFromHover();
7702            }
7703        } else {
7704            if (action == MotionEvent.ACTION_HOVER_EXIT
7705                    || (action == MotionEvent.ACTION_MOVE
7706                            && !pointInView(event.getX(), event.getY()))) {
7707                mSendingHoverAccessibilityEvents = false;
7708                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7709                // If the window does not have input focus we take away accessibility
7710                // focus as soon as the user stop hovering over the view.
7711                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7712                    getViewRootImpl().setAccessibilityFocusedHost(null);
7713                }
7714            }
7715        }
7716
7717        if (isHoverable()) {
7718            switch (action) {
7719                case MotionEvent.ACTION_HOVER_ENTER:
7720                    setHovered(true);
7721                    break;
7722                case MotionEvent.ACTION_HOVER_EXIT:
7723                    setHovered(false);
7724                    break;
7725            }
7726
7727            // Dispatch the event to onGenericMotionEvent before returning true.
7728            // This is to provide compatibility with existing applications that
7729            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7730            // break because of the new default handling for hoverable views
7731            // in onHoverEvent.
7732            // Note that onGenericMotionEvent will be called by default when
7733            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7734            dispatchGenericMotionEventInternal(event);
7735            return true;
7736        }
7737
7738        return false;
7739    }
7740
7741    /**
7742     * Returns true if the view should handle {@link #onHoverEvent}
7743     * by calling {@link #setHovered} to change its hovered state.
7744     *
7745     * @return True if the view is hoverable.
7746     */
7747    private boolean isHoverable() {
7748        final int viewFlags = mViewFlags;
7749        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7750            return false;
7751        }
7752
7753        return (viewFlags & CLICKABLE) == CLICKABLE
7754                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7755    }
7756
7757    /**
7758     * Returns true if the view is currently hovered.
7759     *
7760     * @return True if the view is currently hovered.
7761     *
7762     * @see #setHovered
7763     * @see #onHoverChanged
7764     */
7765    @ViewDebug.ExportedProperty
7766    public boolean isHovered() {
7767        return (mPrivateFlags & HOVERED) != 0;
7768    }
7769
7770    /**
7771     * Sets whether the view is currently hovered.
7772     * <p>
7773     * Calling this method also changes the drawable state of the view.  This
7774     * enables the view to react to hover by using different drawable resources
7775     * to change its appearance.
7776     * </p><p>
7777     * The {@link #onHoverChanged} method is called when the hovered state changes.
7778     * </p>
7779     *
7780     * @param hovered True if the view is hovered.
7781     *
7782     * @see #isHovered
7783     * @see #onHoverChanged
7784     */
7785    public void setHovered(boolean hovered) {
7786        if (hovered) {
7787            if ((mPrivateFlags & HOVERED) == 0) {
7788                mPrivateFlags |= HOVERED;
7789                refreshDrawableState();
7790                onHoverChanged(true);
7791            }
7792        } else {
7793            if ((mPrivateFlags & HOVERED) != 0) {
7794                mPrivateFlags &= ~HOVERED;
7795                refreshDrawableState();
7796                onHoverChanged(false);
7797            }
7798        }
7799    }
7800
7801    /**
7802     * Implement this method to handle hover state changes.
7803     * <p>
7804     * This method is called whenever the hover state changes as a result of a
7805     * call to {@link #setHovered}.
7806     * </p>
7807     *
7808     * @param hovered The current hover state, as returned by {@link #isHovered}.
7809     *
7810     * @see #isHovered
7811     * @see #setHovered
7812     */
7813    public void onHoverChanged(boolean hovered) {
7814    }
7815
7816    /**
7817     * Implement this method to handle touch screen motion events.
7818     *
7819     * @param event The motion event.
7820     * @return True if the event was handled, false otherwise.
7821     */
7822    public boolean onTouchEvent(MotionEvent event) {
7823        final int viewFlags = mViewFlags;
7824
7825        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7826            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7827                setPressed(false);
7828            }
7829            // A disabled view that is clickable still consumes the touch
7830            // events, it just doesn't respond to them.
7831            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7832                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7833        }
7834
7835        if (mTouchDelegate != null) {
7836            if (mTouchDelegate.onTouchEvent(event)) {
7837                return true;
7838            }
7839        }
7840
7841        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7842                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7843            switch (event.getAction()) {
7844                case MotionEvent.ACTION_UP:
7845                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7846                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7847                        // take focus if we don't have it already and we should in
7848                        // touch mode.
7849                        boolean focusTaken = false;
7850                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7851                            focusTaken = requestFocus();
7852                        }
7853
7854                        if (prepressed) {
7855                            // The button is being released before we actually
7856                            // showed it as pressed.  Make it show the pressed
7857                            // state now (before scheduling the click) to ensure
7858                            // the user sees it.
7859                            setPressed(true);
7860                       }
7861
7862                        if (!mHasPerformedLongPress) {
7863                            // This is a tap, so remove the longpress check
7864                            removeLongPressCallback();
7865
7866                            // Only perform take click actions if we were in the pressed state
7867                            if (!focusTaken) {
7868                                // Use a Runnable and post this rather than calling
7869                                // performClick directly. This lets other visual state
7870                                // of the view update before click actions start.
7871                                if (mPerformClick == null) {
7872                                    mPerformClick = new PerformClick();
7873                                }
7874                                if (!post(mPerformClick)) {
7875                                    performClick();
7876                                }
7877                            }
7878                        }
7879
7880                        if (mUnsetPressedState == null) {
7881                            mUnsetPressedState = new UnsetPressedState();
7882                        }
7883
7884                        if (prepressed) {
7885                            postDelayed(mUnsetPressedState,
7886                                    ViewConfiguration.getPressedStateDuration());
7887                        } else if (!post(mUnsetPressedState)) {
7888                            // If the post failed, unpress right now
7889                            mUnsetPressedState.run();
7890                        }
7891                        removeTapCallback();
7892                    }
7893                    break;
7894
7895                case MotionEvent.ACTION_DOWN:
7896                    mHasPerformedLongPress = false;
7897
7898                    if (performButtonActionOnTouchDown(event)) {
7899                        break;
7900                    }
7901
7902                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7903                    boolean isInScrollingContainer = isInScrollingContainer();
7904
7905                    // For views inside a scrolling container, delay the pressed feedback for
7906                    // a short period in case this is a scroll.
7907                    if (isInScrollingContainer) {
7908                        mPrivateFlags |= PREPRESSED;
7909                        if (mPendingCheckForTap == null) {
7910                            mPendingCheckForTap = new CheckForTap();
7911                        }
7912                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7913                    } else {
7914                        // Not inside a scrolling container, so show the feedback right away
7915                        setPressed(true);
7916                        checkForLongClick(0);
7917                    }
7918                    break;
7919
7920                case MotionEvent.ACTION_CANCEL:
7921                    setPressed(false);
7922                    removeTapCallback();
7923                    break;
7924
7925                case MotionEvent.ACTION_MOVE:
7926                    final int x = (int) event.getX();
7927                    final int y = (int) event.getY();
7928
7929                    // Be lenient about moving outside of buttons
7930                    if (!pointInView(x, y, mTouchSlop)) {
7931                        // Outside button
7932                        removeTapCallback();
7933                        if ((mPrivateFlags & PRESSED) != 0) {
7934                            // Remove any future long press/tap checks
7935                            removeLongPressCallback();
7936
7937                            setPressed(false);
7938                        }
7939                    }
7940                    break;
7941            }
7942            return true;
7943        }
7944
7945        return false;
7946    }
7947
7948    /**
7949     * @hide
7950     */
7951    public boolean isInScrollingContainer() {
7952        ViewParent p = getParent();
7953        while (p != null && p instanceof ViewGroup) {
7954            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7955                return true;
7956            }
7957            p = p.getParent();
7958        }
7959        return false;
7960    }
7961
7962    /**
7963     * Remove the longpress detection timer.
7964     */
7965    private void removeLongPressCallback() {
7966        if (mPendingCheckForLongPress != null) {
7967          removeCallbacks(mPendingCheckForLongPress);
7968        }
7969    }
7970
7971    /**
7972     * Remove the pending click action
7973     */
7974    private void removePerformClickCallback() {
7975        if (mPerformClick != null) {
7976            removeCallbacks(mPerformClick);
7977        }
7978    }
7979
7980    /**
7981     * Remove the prepress detection timer.
7982     */
7983    private void removeUnsetPressCallback() {
7984        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7985            setPressed(false);
7986            removeCallbacks(mUnsetPressedState);
7987        }
7988    }
7989
7990    /**
7991     * Remove the tap detection timer.
7992     */
7993    private void removeTapCallback() {
7994        if (mPendingCheckForTap != null) {
7995            mPrivateFlags &= ~PREPRESSED;
7996            removeCallbacks(mPendingCheckForTap);
7997        }
7998    }
7999
8000    /**
8001     * Cancels a pending long press.  Your subclass can use this if you
8002     * want the context menu to come up if the user presses and holds
8003     * at the same place, but you don't want it to come up if they press
8004     * and then move around enough to cause scrolling.
8005     */
8006    public void cancelLongPress() {
8007        removeLongPressCallback();
8008
8009        /*
8010         * The prepressed state handled by the tap callback is a display
8011         * construct, but the tap callback will post a long press callback
8012         * less its own timeout. Remove it here.
8013         */
8014        removeTapCallback();
8015    }
8016
8017    /**
8018     * Remove the pending callback for sending a
8019     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8020     */
8021    private void removeSendViewScrolledAccessibilityEventCallback() {
8022        if (mSendViewScrolledAccessibilityEvent != null) {
8023            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8024        }
8025    }
8026
8027    /**
8028     * Sets the TouchDelegate for this View.
8029     */
8030    public void setTouchDelegate(TouchDelegate delegate) {
8031        mTouchDelegate = delegate;
8032    }
8033
8034    /**
8035     * Gets the TouchDelegate for this View.
8036     */
8037    public TouchDelegate getTouchDelegate() {
8038        return mTouchDelegate;
8039    }
8040
8041    /**
8042     * Set flags controlling behavior of this view.
8043     *
8044     * @param flags Constant indicating the value which should be set
8045     * @param mask Constant indicating the bit range that should be changed
8046     */
8047    void setFlags(int flags, int mask) {
8048        int old = mViewFlags;
8049        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8050
8051        int changed = mViewFlags ^ old;
8052        if (changed == 0) {
8053            return;
8054        }
8055        int privateFlags = mPrivateFlags;
8056
8057        /* Check if the FOCUSABLE bit has changed */
8058        if (((changed & FOCUSABLE_MASK) != 0) &&
8059                ((privateFlags & HAS_BOUNDS) !=0)) {
8060            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8061                    && ((privateFlags & FOCUSED) != 0)) {
8062                /* Give up focus if we are no longer focusable */
8063                clearFocus();
8064            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8065                    && ((privateFlags & FOCUSED) == 0)) {
8066                /*
8067                 * Tell the view system that we are now available to take focus
8068                 * if no one else already has it.
8069                 */
8070                if (mParent != null) mParent.focusableViewAvailable(this);
8071            }
8072            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8073                notifyAccessibilityStateChanged();
8074            }
8075        }
8076
8077        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8078            if ((changed & VISIBILITY_MASK) != 0) {
8079                /*
8080                 * If this view is becoming visible, invalidate it in case it changed while
8081                 * it was not visible. Marking it drawn ensures that the invalidation will
8082                 * go through.
8083                 */
8084                mPrivateFlags |= DRAWN;
8085                invalidate(true);
8086
8087                needGlobalAttributesUpdate(true);
8088
8089                // a view becoming visible is worth notifying the parent
8090                // about in case nothing has focus.  even if this specific view
8091                // isn't focusable, it may contain something that is, so let
8092                // the root view try to give this focus if nothing else does.
8093                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8094                    mParent.focusableViewAvailable(this);
8095                }
8096            }
8097        }
8098
8099        /* Check if the GONE bit has changed */
8100        if ((changed & GONE) != 0) {
8101            needGlobalAttributesUpdate(false);
8102            requestLayout();
8103
8104            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8105                if (hasFocus()) clearFocus();
8106                clearAccessibilityFocus();
8107                destroyDrawingCache();
8108                if (mParent instanceof View) {
8109                    // GONE views noop invalidation, so invalidate the parent
8110                    ((View) mParent).invalidate(true);
8111                }
8112                // Mark the view drawn to ensure that it gets invalidated properly the next
8113                // time it is visible and gets invalidated
8114                mPrivateFlags |= DRAWN;
8115            }
8116            if (mAttachInfo != null) {
8117                mAttachInfo.mViewVisibilityChanged = true;
8118            }
8119        }
8120
8121        /* Check if the VISIBLE bit has changed */
8122        if ((changed & INVISIBLE) != 0) {
8123            needGlobalAttributesUpdate(false);
8124            /*
8125             * If this view is becoming invisible, set the DRAWN flag so that
8126             * the next invalidate() will not be skipped.
8127             */
8128            mPrivateFlags |= DRAWN;
8129
8130            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8131                // root view becoming invisible shouldn't clear focus and accessibility focus
8132                if (getRootView() != this) {
8133                    clearFocus();
8134                    clearAccessibilityFocus();
8135                }
8136            }
8137            if (mAttachInfo != null) {
8138                mAttachInfo.mViewVisibilityChanged = true;
8139            }
8140        }
8141
8142        if ((changed & VISIBILITY_MASK) != 0) {
8143            if (mParent instanceof ViewGroup) {
8144                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8145                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8146                ((View) mParent).invalidate(true);
8147            } else if (mParent != null) {
8148                mParent.invalidateChild(this, null);
8149            }
8150            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8151        }
8152
8153        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8154            destroyDrawingCache();
8155        }
8156
8157        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8158            destroyDrawingCache();
8159            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8160            invalidateParentCaches();
8161        }
8162
8163        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8164            destroyDrawingCache();
8165            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8166        }
8167
8168        if ((changed & DRAW_MASK) != 0) {
8169            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8170                if (mBackground != null) {
8171                    mPrivateFlags &= ~SKIP_DRAW;
8172                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8173                } else {
8174                    mPrivateFlags |= SKIP_DRAW;
8175                }
8176            } else {
8177                mPrivateFlags &= ~SKIP_DRAW;
8178            }
8179            requestLayout();
8180            invalidate(true);
8181        }
8182
8183        if ((changed & KEEP_SCREEN_ON) != 0) {
8184            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8185                mParent.recomputeViewAttributes(this);
8186            }
8187        }
8188
8189        if (AccessibilityManager.getInstance(mContext).isEnabled()
8190                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8191                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8192            notifyAccessibilityStateChanged();
8193        }
8194    }
8195
8196    /**
8197     * Change the view's z order in the tree, so it's on top of other sibling
8198     * views
8199     */
8200    public void bringToFront() {
8201        if (mParent != null) {
8202            mParent.bringChildToFront(this);
8203        }
8204    }
8205
8206    /**
8207     * This is called in response to an internal scroll in this view (i.e., the
8208     * view scrolled its own contents). This is typically as a result of
8209     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8210     * called.
8211     *
8212     * @param l Current horizontal scroll origin.
8213     * @param t Current vertical scroll origin.
8214     * @param oldl Previous horizontal scroll origin.
8215     * @param oldt Previous vertical scroll origin.
8216     */
8217    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8218        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8219            postSendViewScrolledAccessibilityEventCallback();
8220        }
8221
8222        mBackgroundSizeChanged = true;
8223
8224        final AttachInfo ai = mAttachInfo;
8225        if (ai != null) {
8226            ai.mViewScrollChanged = true;
8227        }
8228    }
8229
8230    /**
8231     * Interface definition for a callback to be invoked when the layout bounds of a view
8232     * changes due to layout processing.
8233     */
8234    public interface OnLayoutChangeListener {
8235        /**
8236         * Called when the focus state of a view has changed.
8237         *
8238         * @param v The view whose state has changed.
8239         * @param left The new value of the view's left property.
8240         * @param top The new value of the view's top property.
8241         * @param right The new value of the view's right property.
8242         * @param bottom The new value of the view's bottom property.
8243         * @param oldLeft The previous value of the view's left property.
8244         * @param oldTop The previous value of the view's top property.
8245         * @param oldRight The previous value of the view's right property.
8246         * @param oldBottom The previous value of the view's bottom property.
8247         */
8248        void onLayoutChange(View v, int left, int top, int right, int bottom,
8249            int oldLeft, int oldTop, int oldRight, int oldBottom);
8250    }
8251
8252    /**
8253     * This is called during layout when the size of this view has changed. If
8254     * you were just added to the view hierarchy, you're called with the old
8255     * values of 0.
8256     *
8257     * @param w Current width of this view.
8258     * @param h Current height of this view.
8259     * @param oldw Old width of this view.
8260     * @param oldh Old height of this view.
8261     */
8262    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8263    }
8264
8265    /**
8266     * Called by draw to draw the child views. This may be overridden
8267     * by derived classes to gain control just before its children are drawn
8268     * (but after its own view has been drawn).
8269     * @param canvas the canvas on which to draw the view
8270     */
8271    protected void dispatchDraw(Canvas canvas) {
8272
8273    }
8274
8275    /**
8276     * Gets the parent of this view. Note that the parent is a
8277     * ViewParent and not necessarily a View.
8278     *
8279     * @return Parent of this view.
8280     */
8281    public final ViewParent getParent() {
8282        return mParent;
8283    }
8284
8285    /**
8286     * Set the horizontal scrolled position of your view. This will cause a call to
8287     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8288     * invalidated.
8289     * @param value the x position to scroll to
8290     */
8291    public void setScrollX(int value) {
8292        scrollTo(value, mScrollY);
8293    }
8294
8295    /**
8296     * Set the vertical scrolled position of your view. This will cause a call to
8297     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8298     * invalidated.
8299     * @param value the y position to scroll to
8300     */
8301    public void setScrollY(int value) {
8302        scrollTo(mScrollX, value);
8303    }
8304
8305    /**
8306     * Return the scrolled left position of this view. This is the left edge of
8307     * the displayed part of your view. You do not need to draw any pixels
8308     * farther left, since those are outside of the frame of your view on
8309     * screen.
8310     *
8311     * @return The left edge of the displayed part of your view, in pixels.
8312     */
8313    public final int getScrollX() {
8314        return mScrollX;
8315    }
8316
8317    /**
8318     * Return the scrolled top position of this view. This is the top edge of
8319     * the displayed part of your view. You do not need to draw any pixels above
8320     * it, since those are outside of the frame of your view on screen.
8321     *
8322     * @return The top edge of the displayed part of your view, in pixels.
8323     */
8324    public final int getScrollY() {
8325        return mScrollY;
8326    }
8327
8328    /**
8329     * Return the width of the your view.
8330     *
8331     * @return The width of your view, in pixels.
8332     */
8333    @ViewDebug.ExportedProperty(category = "layout")
8334    public final int getWidth() {
8335        return mRight - mLeft;
8336    }
8337
8338    /**
8339     * Return the height of your view.
8340     *
8341     * @return The height of your view, in pixels.
8342     */
8343    @ViewDebug.ExportedProperty(category = "layout")
8344    public final int getHeight() {
8345        return mBottom - mTop;
8346    }
8347
8348    /**
8349     * Return the visible drawing bounds of your view. Fills in the output
8350     * rectangle with the values from getScrollX(), getScrollY(),
8351     * getWidth(), and getHeight().
8352     *
8353     * @param outRect The (scrolled) drawing bounds of the view.
8354     */
8355    public void getDrawingRect(Rect outRect) {
8356        outRect.left = mScrollX;
8357        outRect.top = mScrollY;
8358        outRect.right = mScrollX + (mRight - mLeft);
8359        outRect.bottom = mScrollY + (mBottom - mTop);
8360    }
8361
8362    /**
8363     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8364     * raw width component (that is the result is masked by
8365     * {@link #MEASURED_SIZE_MASK}).
8366     *
8367     * @return The raw measured width of this view.
8368     */
8369    public final int getMeasuredWidth() {
8370        return mMeasuredWidth & MEASURED_SIZE_MASK;
8371    }
8372
8373    /**
8374     * Return the full width measurement information for this view as computed
8375     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8376     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8377     * This should be used during measurement and layout calculations only. Use
8378     * {@link #getWidth()} to see how wide a view is after layout.
8379     *
8380     * @return The measured width of this view as a bit mask.
8381     */
8382    public final int getMeasuredWidthAndState() {
8383        return mMeasuredWidth;
8384    }
8385
8386    /**
8387     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8388     * raw width component (that is the result is masked by
8389     * {@link #MEASURED_SIZE_MASK}).
8390     *
8391     * @return The raw measured height of this view.
8392     */
8393    public final int getMeasuredHeight() {
8394        return mMeasuredHeight & MEASURED_SIZE_MASK;
8395    }
8396
8397    /**
8398     * Return the full height measurement information for this view as computed
8399     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8400     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8401     * This should be used during measurement and layout calculations only. Use
8402     * {@link #getHeight()} to see how wide a view is after layout.
8403     *
8404     * @return The measured width of this view as a bit mask.
8405     */
8406    public final int getMeasuredHeightAndState() {
8407        return mMeasuredHeight;
8408    }
8409
8410    /**
8411     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8412     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8413     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8414     * and the height component is at the shifted bits
8415     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8416     */
8417    public final int getMeasuredState() {
8418        return (mMeasuredWidth&MEASURED_STATE_MASK)
8419                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8420                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8421    }
8422
8423    /**
8424     * The transform matrix of this view, which is calculated based on the current
8425     * roation, scale, and pivot properties.
8426     *
8427     * @see #getRotation()
8428     * @see #getScaleX()
8429     * @see #getScaleY()
8430     * @see #getPivotX()
8431     * @see #getPivotY()
8432     * @return The current transform matrix for the view
8433     */
8434    public Matrix getMatrix() {
8435        if (mTransformationInfo != null) {
8436            updateMatrix();
8437            return mTransformationInfo.mMatrix;
8438        }
8439        return Matrix.IDENTITY_MATRIX;
8440    }
8441
8442    /**
8443     * Utility function to determine if the value is far enough away from zero to be
8444     * considered non-zero.
8445     * @param value A floating point value to check for zero-ness
8446     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8447     */
8448    private static boolean nonzero(float value) {
8449        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8450    }
8451
8452    /**
8453     * Returns true if the transform matrix is the identity matrix.
8454     * Recomputes the matrix if necessary.
8455     *
8456     * @return True if the transform matrix is the identity matrix, false otherwise.
8457     */
8458    final boolean hasIdentityMatrix() {
8459        if (mTransformationInfo != null) {
8460            updateMatrix();
8461            return mTransformationInfo.mMatrixIsIdentity;
8462        }
8463        return true;
8464    }
8465
8466    void ensureTransformationInfo() {
8467        if (mTransformationInfo == null) {
8468            mTransformationInfo = new TransformationInfo();
8469        }
8470    }
8471
8472    /**
8473     * Recomputes the transform matrix if necessary.
8474     */
8475    private void updateMatrix() {
8476        final TransformationInfo info = mTransformationInfo;
8477        if (info == null) {
8478            return;
8479        }
8480        if (info.mMatrixDirty) {
8481            // transform-related properties have changed since the last time someone
8482            // asked for the matrix; recalculate it with the current values
8483
8484            // Figure out if we need to update the pivot point
8485            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8486                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8487                    info.mPrevWidth = mRight - mLeft;
8488                    info.mPrevHeight = mBottom - mTop;
8489                    info.mPivotX = info.mPrevWidth / 2f;
8490                    info.mPivotY = info.mPrevHeight / 2f;
8491                }
8492            }
8493            info.mMatrix.reset();
8494            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8495                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8496                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8497                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8498            } else {
8499                if (info.mCamera == null) {
8500                    info.mCamera = new Camera();
8501                    info.matrix3D = new Matrix();
8502                }
8503                info.mCamera.save();
8504                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8505                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8506                info.mCamera.getMatrix(info.matrix3D);
8507                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8508                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8509                        info.mPivotY + info.mTranslationY);
8510                info.mMatrix.postConcat(info.matrix3D);
8511                info.mCamera.restore();
8512            }
8513            info.mMatrixDirty = false;
8514            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8515            info.mInverseMatrixDirty = true;
8516        }
8517    }
8518
8519    /**
8520     * Utility method to retrieve the inverse of the current mMatrix property.
8521     * We cache the matrix to avoid recalculating it when transform properties
8522     * have not changed.
8523     *
8524     * @return The inverse of the current matrix of this view.
8525     */
8526    final Matrix getInverseMatrix() {
8527        final TransformationInfo info = mTransformationInfo;
8528        if (info != null) {
8529            updateMatrix();
8530            if (info.mInverseMatrixDirty) {
8531                if (info.mInverseMatrix == null) {
8532                    info.mInverseMatrix = new Matrix();
8533                }
8534                info.mMatrix.invert(info.mInverseMatrix);
8535                info.mInverseMatrixDirty = false;
8536            }
8537            return info.mInverseMatrix;
8538        }
8539        return Matrix.IDENTITY_MATRIX;
8540    }
8541
8542    /**
8543     * Gets the distance along the Z axis from the camera to this view.
8544     *
8545     * @see #setCameraDistance(float)
8546     *
8547     * @return The distance along the Z axis.
8548     */
8549    public float getCameraDistance() {
8550        ensureTransformationInfo();
8551        final float dpi = mResources.getDisplayMetrics().densityDpi;
8552        final TransformationInfo info = mTransformationInfo;
8553        if (info.mCamera == null) {
8554            info.mCamera = new Camera();
8555            info.matrix3D = new Matrix();
8556        }
8557        return -(info.mCamera.getLocationZ() * dpi);
8558    }
8559
8560    /**
8561     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8562     * views are drawn) from the camera to this view. The camera's distance
8563     * affects 3D transformations, for instance rotations around the X and Y
8564     * axis. If the rotationX or rotationY properties are changed and this view is
8565     * large (more than half the size of the screen), it is recommended to always
8566     * use a camera distance that's greater than the height (X axis rotation) or
8567     * the width (Y axis rotation) of this view.</p>
8568     *
8569     * <p>The distance of the camera from the view plane can have an affect on the
8570     * perspective distortion of the view when it is rotated around the x or y axis.
8571     * For example, a large distance will result in a large viewing angle, and there
8572     * will not be much perspective distortion of the view as it rotates. A short
8573     * distance may cause much more perspective distortion upon rotation, and can
8574     * also result in some drawing artifacts if the rotated view ends up partially
8575     * behind the camera (which is why the recommendation is to use a distance at
8576     * least as far as the size of the view, if the view is to be rotated.)</p>
8577     *
8578     * <p>The distance is expressed in "depth pixels." The default distance depends
8579     * on the screen density. For instance, on a medium density display, the
8580     * default distance is 1280. On a high density display, the default distance
8581     * is 1920.</p>
8582     *
8583     * <p>If you want to specify a distance that leads to visually consistent
8584     * results across various densities, use the following formula:</p>
8585     * <pre>
8586     * float scale = context.getResources().getDisplayMetrics().density;
8587     * view.setCameraDistance(distance * scale);
8588     * </pre>
8589     *
8590     * <p>The density scale factor of a high density display is 1.5,
8591     * and 1920 = 1280 * 1.5.</p>
8592     *
8593     * @param distance The distance in "depth pixels", if negative the opposite
8594     *        value is used
8595     *
8596     * @see #setRotationX(float)
8597     * @see #setRotationY(float)
8598     */
8599    public void setCameraDistance(float distance) {
8600        invalidateViewProperty(true, false);
8601
8602        ensureTransformationInfo();
8603        final float dpi = mResources.getDisplayMetrics().densityDpi;
8604        final TransformationInfo info = mTransformationInfo;
8605        if (info.mCamera == null) {
8606            info.mCamera = new Camera();
8607            info.matrix3D = new Matrix();
8608        }
8609
8610        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8611        info.mMatrixDirty = true;
8612
8613        invalidateViewProperty(false, false);
8614        if (mDisplayList != null) {
8615            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8616        }
8617        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8618            // View was rejected last time it was drawn by its parent; this may have changed
8619            invalidateParentIfNeeded();
8620        }
8621    }
8622
8623    /**
8624     * The degrees that the view is rotated around the pivot point.
8625     *
8626     * @see #setRotation(float)
8627     * @see #getPivotX()
8628     * @see #getPivotY()
8629     *
8630     * @return The degrees of rotation.
8631     */
8632    @ViewDebug.ExportedProperty(category = "drawing")
8633    public float getRotation() {
8634        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8635    }
8636
8637    /**
8638     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8639     * result in clockwise rotation.
8640     *
8641     * @param rotation The degrees of rotation.
8642     *
8643     * @see #getRotation()
8644     * @see #getPivotX()
8645     * @see #getPivotY()
8646     * @see #setRotationX(float)
8647     * @see #setRotationY(float)
8648     *
8649     * @attr ref android.R.styleable#View_rotation
8650     */
8651    public void setRotation(float rotation) {
8652        ensureTransformationInfo();
8653        final TransformationInfo info = mTransformationInfo;
8654        if (info.mRotation != rotation) {
8655            // Double-invalidation is necessary to capture view's old and new areas
8656            invalidateViewProperty(true, false);
8657            info.mRotation = rotation;
8658            info.mMatrixDirty = true;
8659            invalidateViewProperty(false, true);
8660            if (mDisplayList != null) {
8661                mDisplayList.setRotation(rotation);
8662            }
8663            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8664                // View was rejected last time it was drawn by its parent; this may have changed
8665                invalidateParentIfNeeded();
8666            }
8667        }
8668    }
8669
8670    /**
8671     * The degrees that the view is rotated around the vertical axis through the pivot point.
8672     *
8673     * @see #getPivotX()
8674     * @see #getPivotY()
8675     * @see #setRotationY(float)
8676     *
8677     * @return The degrees of Y rotation.
8678     */
8679    @ViewDebug.ExportedProperty(category = "drawing")
8680    public float getRotationY() {
8681        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8682    }
8683
8684    /**
8685     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8686     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8687     * down the y axis.
8688     *
8689     * When rotating large views, it is recommended to adjust the camera distance
8690     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8691     *
8692     * @param rotationY The degrees of Y rotation.
8693     *
8694     * @see #getRotationY()
8695     * @see #getPivotX()
8696     * @see #getPivotY()
8697     * @see #setRotation(float)
8698     * @see #setRotationX(float)
8699     * @see #setCameraDistance(float)
8700     *
8701     * @attr ref android.R.styleable#View_rotationY
8702     */
8703    public void setRotationY(float rotationY) {
8704        ensureTransformationInfo();
8705        final TransformationInfo info = mTransformationInfo;
8706        if (info.mRotationY != rotationY) {
8707            invalidateViewProperty(true, false);
8708            info.mRotationY = rotationY;
8709            info.mMatrixDirty = true;
8710            invalidateViewProperty(false, true);
8711            if (mDisplayList != null) {
8712                mDisplayList.setRotationY(rotationY);
8713            }
8714            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8715                // View was rejected last time it was drawn by its parent; this may have changed
8716                invalidateParentIfNeeded();
8717            }
8718        }
8719    }
8720
8721    /**
8722     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8723     *
8724     * @see #getPivotX()
8725     * @see #getPivotY()
8726     * @see #setRotationX(float)
8727     *
8728     * @return The degrees of X rotation.
8729     */
8730    @ViewDebug.ExportedProperty(category = "drawing")
8731    public float getRotationX() {
8732        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8733    }
8734
8735    /**
8736     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8737     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8738     * x axis.
8739     *
8740     * When rotating large views, it is recommended to adjust the camera distance
8741     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8742     *
8743     * @param rotationX The degrees of X rotation.
8744     *
8745     * @see #getRotationX()
8746     * @see #getPivotX()
8747     * @see #getPivotY()
8748     * @see #setRotation(float)
8749     * @see #setRotationY(float)
8750     * @see #setCameraDistance(float)
8751     *
8752     * @attr ref android.R.styleable#View_rotationX
8753     */
8754    public void setRotationX(float rotationX) {
8755        ensureTransformationInfo();
8756        final TransformationInfo info = mTransformationInfo;
8757        if (info.mRotationX != rotationX) {
8758            invalidateViewProperty(true, false);
8759            info.mRotationX = rotationX;
8760            info.mMatrixDirty = true;
8761            invalidateViewProperty(false, true);
8762            if (mDisplayList != null) {
8763                mDisplayList.setRotationX(rotationX);
8764            }
8765            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8766                // View was rejected last time it was drawn by its parent; this may have changed
8767                invalidateParentIfNeeded();
8768            }
8769        }
8770    }
8771
8772    /**
8773     * The amount that the view is scaled in x around the pivot point, as a proportion of
8774     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8775     *
8776     * <p>By default, this is 1.0f.
8777     *
8778     * @see #getPivotX()
8779     * @see #getPivotY()
8780     * @return The scaling factor.
8781     */
8782    @ViewDebug.ExportedProperty(category = "drawing")
8783    public float getScaleX() {
8784        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8785    }
8786
8787    /**
8788     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8789     * the view's unscaled width. A value of 1 means that no scaling is applied.
8790     *
8791     * @param scaleX The scaling factor.
8792     * @see #getPivotX()
8793     * @see #getPivotY()
8794     *
8795     * @attr ref android.R.styleable#View_scaleX
8796     */
8797    public void setScaleX(float scaleX) {
8798        ensureTransformationInfo();
8799        final TransformationInfo info = mTransformationInfo;
8800        if (info.mScaleX != scaleX) {
8801            invalidateViewProperty(true, false);
8802            info.mScaleX = scaleX;
8803            info.mMatrixDirty = true;
8804            invalidateViewProperty(false, true);
8805            if (mDisplayList != null) {
8806                mDisplayList.setScaleX(scaleX);
8807            }
8808            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8809                // View was rejected last time it was drawn by its parent; this may have changed
8810                invalidateParentIfNeeded();
8811            }
8812        }
8813    }
8814
8815    /**
8816     * The amount that the view is scaled in y around the pivot point, as a proportion of
8817     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8818     *
8819     * <p>By default, this is 1.0f.
8820     *
8821     * @see #getPivotX()
8822     * @see #getPivotY()
8823     * @return The scaling factor.
8824     */
8825    @ViewDebug.ExportedProperty(category = "drawing")
8826    public float getScaleY() {
8827        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8828    }
8829
8830    /**
8831     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8832     * the view's unscaled width. A value of 1 means that no scaling is applied.
8833     *
8834     * @param scaleY The scaling factor.
8835     * @see #getPivotX()
8836     * @see #getPivotY()
8837     *
8838     * @attr ref android.R.styleable#View_scaleY
8839     */
8840    public void setScaleY(float scaleY) {
8841        ensureTransformationInfo();
8842        final TransformationInfo info = mTransformationInfo;
8843        if (info.mScaleY != scaleY) {
8844            invalidateViewProperty(true, false);
8845            info.mScaleY = scaleY;
8846            info.mMatrixDirty = true;
8847            invalidateViewProperty(false, true);
8848            if (mDisplayList != null) {
8849                mDisplayList.setScaleY(scaleY);
8850            }
8851            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8852                // View was rejected last time it was drawn by its parent; this may have changed
8853                invalidateParentIfNeeded();
8854            }
8855        }
8856    }
8857
8858    /**
8859     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8860     * and {@link #setScaleX(float) scaled}.
8861     *
8862     * @see #getRotation()
8863     * @see #getScaleX()
8864     * @see #getScaleY()
8865     * @see #getPivotY()
8866     * @return The x location of the pivot point.
8867     *
8868     * @attr ref android.R.styleable#View_transformPivotX
8869     */
8870    @ViewDebug.ExportedProperty(category = "drawing")
8871    public float getPivotX() {
8872        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8873    }
8874
8875    /**
8876     * Sets the x location of the point around which the view is
8877     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8878     * By default, the pivot point is centered on the object.
8879     * Setting this property disables this behavior and causes the view to use only the
8880     * explicitly set pivotX and pivotY values.
8881     *
8882     * @param pivotX The x location of the pivot point.
8883     * @see #getRotation()
8884     * @see #getScaleX()
8885     * @see #getScaleY()
8886     * @see #getPivotY()
8887     *
8888     * @attr ref android.R.styleable#View_transformPivotX
8889     */
8890    public void setPivotX(float pivotX) {
8891        ensureTransformationInfo();
8892        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8893        final TransformationInfo info = mTransformationInfo;
8894        if (info.mPivotX != pivotX) {
8895            invalidateViewProperty(true, false);
8896            info.mPivotX = pivotX;
8897            info.mMatrixDirty = true;
8898            invalidateViewProperty(false, true);
8899            if (mDisplayList != null) {
8900                mDisplayList.setPivotX(pivotX);
8901            }
8902            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8903                // View was rejected last time it was drawn by its parent; this may have changed
8904                invalidateParentIfNeeded();
8905            }
8906        }
8907    }
8908
8909    /**
8910     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8911     * and {@link #setScaleY(float) scaled}.
8912     *
8913     * @see #getRotation()
8914     * @see #getScaleX()
8915     * @see #getScaleY()
8916     * @see #getPivotY()
8917     * @return The y location of the pivot point.
8918     *
8919     * @attr ref android.R.styleable#View_transformPivotY
8920     */
8921    @ViewDebug.ExportedProperty(category = "drawing")
8922    public float getPivotY() {
8923        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8924    }
8925
8926    /**
8927     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8928     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8929     * Setting this property disables this behavior and causes the view to use only the
8930     * explicitly set pivotX and pivotY values.
8931     *
8932     * @param pivotY The y location of the pivot point.
8933     * @see #getRotation()
8934     * @see #getScaleX()
8935     * @see #getScaleY()
8936     * @see #getPivotY()
8937     *
8938     * @attr ref android.R.styleable#View_transformPivotY
8939     */
8940    public void setPivotY(float pivotY) {
8941        ensureTransformationInfo();
8942        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8943        final TransformationInfo info = mTransformationInfo;
8944        if (info.mPivotY != pivotY) {
8945            invalidateViewProperty(true, false);
8946            info.mPivotY = pivotY;
8947            info.mMatrixDirty = true;
8948            invalidateViewProperty(false, true);
8949            if (mDisplayList != null) {
8950                mDisplayList.setPivotY(pivotY);
8951            }
8952            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8953                // View was rejected last time it was drawn by its parent; this may have changed
8954                invalidateParentIfNeeded();
8955            }
8956        }
8957    }
8958
8959    /**
8960     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8961     * completely transparent and 1 means the view is completely opaque.
8962     *
8963     * <p>By default this is 1.0f.
8964     * @return The opacity of the view.
8965     */
8966    @ViewDebug.ExportedProperty(category = "drawing")
8967    public float getAlpha() {
8968        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8969    }
8970
8971    /**
8972     * Returns whether this View has content which overlaps. This function, intended to be
8973     * overridden by specific View types, is an optimization when alpha is set on a view. If
8974     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8975     * and then composited it into place, which can be expensive. If the view has no overlapping
8976     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8977     * An example of overlapping rendering is a TextView with a background image, such as a
8978     * Button. An example of non-overlapping rendering is a TextView with no background, or
8979     * an ImageView with only the foreground image. The default implementation returns true;
8980     * subclasses should override if they have cases which can be optimized.
8981     *
8982     * @return true if the content in this view might overlap, false otherwise.
8983     */
8984    public boolean hasOverlappingRendering() {
8985        return true;
8986    }
8987
8988    /**
8989     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8990     * completely transparent and 1 means the view is completely opaque.</p>
8991     *
8992     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8993     * responsible for applying the opacity itself. Otherwise, calling this method is
8994     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8995     * setting a hardware layer.</p>
8996     *
8997     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8998     * performance implications. It is generally best to use the alpha property sparingly and
8999     * transiently, as in the case of fading animations.</p>
9000     *
9001     * @param alpha The opacity of the view.
9002     *
9003     * @see #setLayerType(int, android.graphics.Paint)
9004     *
9005     * @attr ref android.R.styleable#View_alpha
9006     */
9007    public void setAlpha(float alpha) {
9008        ensureTransformationInfo();
9009        if (mTransformationInfo.mAlpha != alpha) {
9010            mTransformationInfo.mAlpha = alpha;
9011            if (onSetAlpha((int) (alpha * 255))) {
9012                mPrivateFlags |= ALPHA_SET;
9013                // subclass is handling alpha - don't optimize rendering cache invalidation
9014                invalidateParentCaches();
9015                invalidate(true);
9016            } else {
9017                mPrivateFlags &= ~ALPHA_SET;
9018                invalidateViewProperty(true, false);
9019                if (mDisplayList != null) {
9020                    mDisplayList.setAlpha(alpha);
9021                }
9022            }
9023        }
9024    }
9025
9026    /**
9027     * Faster version of setAlpha() which performs the same steps except there are
9028     * no calls to invalidate(). The caller of this function should perform proper invalidation
9029     * on the parent and this object. The return value indicates whether the subclass handles
9030     * alpha (the return value for onSetAlpha()).
9031     *
9032     * @param alpha The new value for the alpha property
9033     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9034     *         the new value for the alpha property is different from the old value
9035     */
9036    boolean setAlphaNoInvalidation(float alpha) {
9037        ensureTransformationInfo();
9038        if (mTransformationInfo.mAlpha != alpha) {
9039            mTransformationInfo.mAlpha = alpha;
9040            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9041            if (subclassHandlesAlpha) {
9042                mPrivateFlags |= ALPHA_SET;
9043                return true;
9044            } else {
9045                mPrivateFlags &= ~ALPHA_SET;
9046                if (mDisplayList != null) {
9047                    mDisplayList.setAlpha(alpha);
9048                }
9049            }
9050        }
9051        return false;
9052    }
9053
9054    /**
9055     * Top position of this view relative to its parent.
9056     *
9057     * @return The top of this view, in pixels.
9058     */
9059    @ViewDebug.CapturedViewProperty
9060    public final int getTop() {
9061        return mTop;
9062    }
9063
9064    /**
9065     * Sets the top position of this view relative to its parent. This method is meant to be called
9066     * by the layout system and should not generally be called otherwise, because the property
9067     * may be changed at any time by the layout.
9068     *
9069     * @param top The top of this view, in pixels.
9070     */
9071    public final void setTop(int top) {
9072        if (top != mTop) {
9073            updateMatrix();
9074            final boolean matrixIsIdentity = mTransformationInfo == null
9075                    || mTransformationInfo.mMatrixIsIdentity;
9076            if (matrixIsIdentity) {
9077                if (mAttachInfo != null) {
9078                    int minTop;
9079                    int yLoc;
9080                    if (top < mTop) {
9081                        minTop = top;
9082                        yLoc = top - mTop;
9083                    } else {
9084                        minTop = mTop;
9085                        yLoc = 0;
9086                    }
9087                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9088                }
9089            } else {
9090                // Double-invalidation is necessary to capture view's old and new areas
9091                invalidate(true);
9092            }
9093
9094            int width = mRight - mLeft;
9095            int oldHeight = mBottom - mTop;
9096
9097            mTop = top;
9098            if (mDisplayList != null) {
9099                mDisplayList.setTop(mTop);
9100            }
9101
9102            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9103
9104            if (!matrixIsIdentity) {
9105                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9106                    // A change in dimension means an auto-centered pivot point changes, too
9107                    mTransformationInfo.mMatrixDirty = true;
9108                }
9109                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9110                invalidate(true);
9111            }
9112            mBackgroundSizeChanged = true;
9113            invalidateParentIfNeeded();
9114            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9115                // View was rejected last time it was drawn by its parent; this may have changed
9116                invalidateParentIfNeeded();
9117            }
9118        }
9119    }
9120
9121    /**
9122     * Bottom position of this view relative to its parent.
9123     *
9124     * @return The bottom of this view, in pixels.
9125     */
9126    @ViewDebug.CapturedViewProperty
9127    public final int getBottom() {
9128        return mBottom;
9129    }
9130
9131    /**
9132     * True if this view has changed since the last time being drawn.
9133     *
9134     * @return The dirty state of this view.
9135     */
9136    public boolean isDirty() {
9137        return (mPrivateFlags & DIRTY_MASK) != 0;
9138    }
9139
9140    /**
9141     * Sets the bottom position of this view relative to its parent. This method is meant to be
9142     * called by the layout system and should not generally be called otherwise, because the
9143     * property may be changed at any time by the layout.
9144     *
9145     * @param bottom The bottom of this view, in pixels.
9146     */
9147    public final void setBottom(int bottom) {
9148        if (bottom != mBottom) {
9149            updateMatrix();
9150            final boolean matrixIsIdentity = mTransformationInfo == null
9151                    || mTransformationInfo.mMatrixIsIdentity;
9152            if (matrixIsIdentity) {
9153                if (mAttachInfo != null) {
9154                    int maxBottom;
9155                    if (bottom < mBottom) {
9156                        maxBottom = mBottom;
9157                    } else {
9158                        maxBottom = bottom;
9159                    }
9160                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9161                }
9162            } else {
9163                // Double-invalidation is necessary to capture view's old and new areas
9164                invalidate(true);
9165            }
9166
9167            int width = mRight - mLeft;
9168            int oldHeight = mBottom - mTop;
9169
9170            mBottom = bottom;
9171            if (mDisplayList != null) {
9172                mDisplayList.setBottom(mBottom);
9173            }
9174
9175            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9176
9177            if (!matrixIsIdentity) {
9178                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9179                    // A change in dimension means an auto-centered pivot point changes, too
9180                    mTransformationInfo.mMatrixDirty = true;
9181                }
9182                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9183                invalidate(true);
9184            }
9185            mBackgroundSizeChanged = true;
9186            invalidateParentIfNeeded();
9187            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9188                // View was rejected last time it was drawn by its parent; this may have changed
9189                invalidateParentIfNeeded();
9190            }
9191        }
9192    }
9193
9194    /**
9195     * Left position of this view relative to its parent.
9196     *
9197     * @return The left edge of this view, in pixels.
9198     */
9199    @ViewDebug.CapturedViewProperty
9200    public final int getLeft() {
9201        return mLeft;
9202    }
9203
9204    /**
9205     * Sets the left position of this view relative to its parent. This method is meant to be called
9206     * by the layout system and should not generally be called otherwise, because the property
9207     * may be changed at any time by the layout.
9208     *
9209     * @param left The bottom of this view, in pixels.
9210     */
9211    public final void setLeft(int left) {
9212        if (left != mLeft) {
9213            updateMatrix();
9214            final boolean matrixIsIdentity = mTransformationInfo == null
9215                    || mTransformationInfo.mMatrixIsIdentity;
9216            if (matrixIsIdentity) {
9217                if (mAttachInfo != null) {
9218                    int minLeft;
9219                    int xLoc;
9220                    if (left < mLeft) {
9221                        minLeft = left;
9222                        xLoc = left - mLeft;
9223                    } else {
9224                        minLeft = mLeft;
9225                        xLoc = 0;
9226                    }
9227                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9228                }
9229            } else {
9230                // Double-invalidation is necessary to capture view's old and new areas
9231                invalidate(true);
9232            }
9233
9234            int oldWidth = mRight - mLeft;
9235            int height = mBottom - mTop;
9236
9237            mLeft = left;
9238            if (mDisplayList != null) {
9239                mDisplayList.setLeft(left);
9240            }
9241
9242            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9243
9244            if (!matrixIsIdentity) {
9245                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9246                    // A change in dimension means an auto-centered pivot point changes, too
9247                    mTransformationInfo.mMatrixDirty = true;
9248                }
9249                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9250                invalidate(true);
9251            }
9252            mBackgroundSizeChanged = true;
9253            invalidateParentIfNeeded();
9254            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9255                // View was rejected last time it was drawn by its parent; this may have changed
9256                invalidateParentIfNeeded();
9257            }
9258        }
9259    }
9260
9261    /**
9262     * Right position of this view relative to its parent.
9263     *
9264     * @return The right edge of this view, in pixels.
9265     */
9266    @ViewDebug.CapturedViewProperty
9267    public final int getRight() {
9268        return mRight;
9269    }
9270
9271    /**
9272     * Sets the right position of this view relative to its parent. This method is meant to be called
9273     * by the layout system and should not generally be called otherwise, because the property
9274     * may be changed at any time by the layout.
9275     *
9276     * @param right The bottom of this view, in pixels.
9277     */
9278    public final void setRight(int right) {
9279        if (right != mRight) {
9280            updateMatrix();
9281            final boolean matrixIsIdentity = mTransformationInfo == null
9282                    || mTransformationInfo.mMatrixIsIdentity;
9283            if (matrixIsIdentity) {
9284                if (mAttachInfo != null) {
9285                    int maxRight;
9286                    if (right < mRight) {
9287                        maxRight = mRight;
9288                    } else {
9289                        maxRight = right;
9290                    }
9291                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9292                }
9293            } else {
9294                // Double-invalidation is necessary to capture view's old and new areas
9295                invalidate(true);
9296            }
9297
9298            int oldWidth = mRight - mLeft;
9299            int height = mBottom - mTop;
9300
9301            mRight = right;
9302            if (mDisplayList != null) {
9303                mDisplayList.setRight(mRight);
9304            }
9305
9306            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9307
9308            if (!matrixIsIdentity) {
9309                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9310                    // A change in dimension means an auto-centered pivot point changes, too
9311                    mTransformationInfo.mMatrixDirty = true;
9312                }
9313                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9314                invalidate(true);
9315            }
9316            mBackgroundSizeChanged = true;
9317            invalidateParentIfNeeded();
9318            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9319                // View was rejected last time it was drawn by its parent; this may have changed
9320                invalidateParentIfNeeded();
9321            }
9322        }
9323    }
9324
9325    /**
9326     * The visual x position of this view, in pixels. This is equivalent to the
9327     * {@link #setTranslationX(float) translationX} property plus the current
9328     * {@link #getLeft() left} property.
9329     *
9330     * @return The visual x position of this view, in pixels.
9331     */
9332    @ViewDebug.ExportedProperty(category = "drawing")
9333    public float getX() {
9334        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9335    }
9336
9337    /**
9338     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9339     * {@link #setTranslationX(float) translationX} property to be the difference between
9340     * the x value passed in and the current {@link #getLeft() left} property.
9341     *
9342     * @param x The visual x position of this view, in pixels.
9343     */
9344    public void setX(float x) {
9345        setTranslationX(x - mLeft);
9346    }
9347
9348    /**
9349     * The visual y position of this view, in pixels. This is equivalent to the
9350     * {@link #setTranslationY(float) translationY} property plus the current
9351     * {@link #getTop() top} property.
9352     *
9353     * @return The visual y position of this view, in pixels.
9354     */
9355    @ViewDebug.ExportedProperty(category = "drawing")
9356    public float getY() {
9357        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9358    }
9359
9360    /**
9361     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9362     * {@link #setTranslationY(float) translationY} property to be the difference between
9363     * the y value passed in and the current {@link #getTop() top} property.
9364     *
9365     * @param y The visual y position of this view, in pixels.
9366     */
9367    public void setY(float y) {
9368        setTranslationY(y - mTop);
9369    }
9370
9371
9372    /**
9373     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9374     * This position is post-layout, in addition to wherever the object's
9375     * layout placed it.
9376     *
9377     * @return The horizontal position of this view relative to its left position, in pixels.
9378     */
9379    @ViewDebug.ExportedProperty(category = "drawing")
9380    public float getTranslationX() {
9381        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9382    }
9383
9384    /**
9385     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9386     * This effectively positions the object post-layout, in addition to wherever the object's
9387     * layout placed it.
9388     *
9389     * @param translationX The horizontal position of this view relative to its left position,
9390     * in pixels.
9391     *
9392     * @attr ref android.R.styleable#View_translationX
9393     */
9394    public void setTranslationX(float translationX) {
9395        ensureTransformationInfo();
9396        final TransformationInfo info = mTransformationInfo;
9397        if (info.mTranslationX != translationX) {
9398            // Double-invalidation is necessary to capture view's old and new areas
9399            invalidateViewProperty(true, false);
9400            info.mTranslationX = translationX;
9401            info.mMatrixDirty = true;
9402            invalidateViewProperty(false, true);
9403            if (mDisplayList != null) {
9404                mDisplayList.setTranslationX(translationX);
9405            }
9406            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9407                // View was rejected last time it was drawn by its parent; this may have changed
9408                invalidateParentIfNeeded();
9409            }
9410        }
9411    }
9412
9413    /**
9414     * The horizontal location of this view relative to its {@link #getTop() top} position.
9415     * This position is post-layout, in addition to wherever the object's
9416     * layout placed it.
9417     *
9418     * @return The vertical position of this view relative to its top position,
9419     * in pixels.
9420     */
9421    @ViewDebug.ExportedProperty(category = "drawing")
9422    public float getTranslationY() {
9423        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9424    }
9425
9426    /**
9427     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9428     * This effectively positions the object post-layout, in addition to wherever the object's
9429     * layout placed it.
9430     *
9431     * @param translationY The vertical position of this view relative to its top position,
9432     * in pixels.
9433     *
9434     * @attr ref android.R.styleable#View_translationY
9435     */
9436    public void setTranslationY(float translationY) {
9437        ensureTransformationInfo();
9438        final TransformationInfo info = mTransformationInfo;
9439        if (info.mTranslationY != translationY) {
9440            invalidateViewProperty(true, false);
9441            info.mTranslationY = translationY;
9442            info.mMatrixDirty = true;
9443            invalidateViewProperty(false, true);
9444            if (mDisplayList != null) {
9445                mDisplayList.setTranslationY(translationY);
9446            }
9447            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9448                // View was rejected last time it was drawn by its parent; this may have changed
9449                invalidateParentIfNeeded();
9450            }
9451        }
9452    }
9453
9454    /**
9455     * Hit rectangle in parent's coordinates
9456     *
9457     * @param outRect The hit rectangle of the view.
9458     */
9459    public void getHitRect(Rect outRect) {
9460        updateMatrix();
9461        final TransformationInfo info = mTransformationInfo;
9462        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9463            outRect.set(mLeft, mTop, mRight, mBottom);
9464        } else {
9465            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9466            tmpRect.set(-info.mPivotX, -info.mPivotY,
9467                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9468            info.mMatrix.mapRect(tmpRect);
9469            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9470                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9471        }
9472    }
9473
9474    /**
9475     * Determines whether the given point, in local coordinates is inside the view.
9476     */
9477    /*package*/ final boolean pointInView(float localX, float localY) {
9478        return localX >= 0 && localX < (mRight - mLeft)
9479                && localY >= 0 && localY < (mBottom - mTop);
9480    }
9481
9482    /**
9483     * Utility method to determine whether the given point, in local coordinates,
9484     * is inside the view, where the area of the view is expanded by the slop factor.
9485     * This method is called while processing touch-move events to determine if the event
9486     * is still within the view.
9487     */
9488    private boolean pointInView(float localX, float localY, float slop) {
9489        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9490                localY < ((mBottom - mTop) + slop);
9491    }
9492
9493    /**
9494     * When a view has focus and the user navigates away from it, the next view is searched for
9495     * starting from the rectangle filled in by this method.
9496     *
9497     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9498     * of the view.  However, if your view maintains some idea of internal selection,
9499     * such as a cursor, or a selected row or column, you should override this method and
9500     * fill in a more specific rectangle.
9501     *
9502     * @param r The rectangle to fill in, in this view's coordinates.
9503     */
9504    public void getFocusedRect(Rect r) {
9505        getDrawingRect(r);
9506    }
9507
9508    /**
9509     * If some part of this view is not clipped by any of its parents, then
9510     * return that area in r in global (root) coordinates. To convert r to local
9511     * coordinates (without taking possible View rotations into account), offset
9512     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9513     * If the view is completely clipped or translated out, return false.
9514     *
9515     * @param r If true is returned, r holds the global coordinates of the
9516     *        visible portion of this view.
9517     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9518     *        between this view and its root. globalOffet may be null.
9519     * @return true if r is non-empty (i.e. part of the view is visible at the
9520     *         root level.
9521     */
9522    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9523        int width = mRight - mLeft;
9524        int height = mBottom - mTop;
9525        if (width > 0 && height > 0) {
9526            r.set(0, 0, width, height);
9527            if (globalOffset != null) {
9528                globalOffset.set(-mScrollX, -mScrollY);
9529            }
9530            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9531        }
9532        return false;
9533    }
9534
9535    public final boolean getGlobalVisibleRect(Rect r) {
9536        return getGlobalVisibleRect(r, null);
9537    }
9538
9539    public final boolean getLocalVisibleRect(Rect r) {
9540        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9541        if (getGlobalVisibleRect(r, offset)) {
9542            r.offset(-offset.x, -offset.y); // make r local
9543            return true;
9544        }
9545        return false;
9546    }
9547
9548    /**
9549     * Offset this view's vertical location by the specified number of pixels.
9550     *
9551     * @param offset the number of pixels to offset the view by
9552     */
9553    public void offsetTopAndBottom(int offset) {
9554        if (offset != 0) {
9555            updateMatrix();
9556            final boolean matrixIsIdentity = mTransformationInfo == null
9557                    || mTransformationInfo.mMatrixIsIdentity;
9558            if (matrixIsIdentity) {
9559                if (mDisplayList != null) {
9560                    invalidateViewProperty(false, false);
9561                } else {
9562                    final ViewParent p = mParent;
9563                    if (p != null && mAttachInfo != null) {
9564                        final Rect r = mAttachInfo.mTmpInvalRect;
9565                        int minTop;
9566                        int maxBottom;
9567                        int yLoc;
9568                        if (offset < 0) {
9569                            minTop = mTop + offset;
9570                            maxBottom = mBottom;
9571                            yLoc = offset;
9572                        } else {
9573                            minTop = mTop;
9574                            maxBottom = mBottom + offset;
9575                            yLoc = 0;
9576                        }
9577                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9578                        p.invalidateChild(this, r);
9579                    }
9580                }
9581            } else {
9582                invalidateViewProperty(false, false);
9583            }
9584
9585            mTop += offset;
9586            mBottom += offset;
9587            if (mDisplayList != null) {
9588                mDisplayList.offsetTopBottom(offset);
9589                invalidateViewProperty(false, false);
9590            } else {
9591                if (!matrixIsIdentity) {
9592                    invalidateViewProperty(false, true);
9593                }
9594                invalidateParentIfNeeded();
9595            }
9596        }
9597    }
9598
9599    /**
9600     * Offset this view's horizontal location by the specified amount of pixels.
9601     *
9602     * @param offset the numer of pixels to offset the view by
9603     */
9604    public void offsetLeftAndRight(int offset) {
9605        if (offset != 0) {
9606            updateMatrix();
9607            final boolean matrixIsIdentity = mTransformationInfo == null
9608                    || mTransformationInfo.mMatrixIsIdentity;
9609            if (matrixIsIdentity) {
9610                if (mDisplayList != null) {
9611                    invalidateViewProperty(false, false);
9612                } else {
9613                    final ViewParent p = mParent;
9614                    if (p != null && mAttachInfo != null) {
9615                        final Rect r = mAttachInfo.mTmpInvalRect;
9616                        int minLeft;
9617                        int maxRight;
9618                        if (offset < 0) {
9619                            minLeft = mLeft + offset;
9620                            maxRight = mRight;
9621                        } else {
9622                            minLeft = mLeft;
9623                            maxRight = mRight + offset;
9624                        }
9625                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9626                        p.invalidateChild(this, r);
9627                    }
9628                }
9629            } else {
9630                invalidateViewProperty(false, false);
9631            }
9632
9633            mLeft += offset;
9634            mRight += offset;
9635            if (mDisplayList != null) {
9636                mDisplayList.offsetLeftRight(offset);
9637                invalidateViewProperty(false, false);
9638            } else {
9639                if (!matrixIsIdentity) {
9640                    invalidateViewProperty(false, true);
9641                }
9642                invalidateParentIfNeeded();
9643            }
9644        }
9645    }
9646
9647    /**
9648     * Get the LayoutParams associated with this view. All views should have
9649     * layout parameters. These supply parameters to the <i>parent</i> of this
9650     * view specifying how it should be arranged. There are many subclasses of
9651     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9652     * of ViewGroup that are responsible for arranging their children.
9653     *
9654     * This method may return null if this View is not attached to a parent
9655     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9656     * was not invoked successfully. When a View is attached to a parent
9657     * ViewGroup, this method must not return null.
9658     *
9659     * @return The LayoutParams associated with this view, or null if no
9660     *         parameters have been set yet
9661     */
9662    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9663    public ViewGroup.LayoutParams getLayoutParams() {
9664        return mLayoutParams;
9665    }
9666
9667    /**
9668     * Set the layout parameters associated with this view. These supply
9669     * parameters to the <i>parent</i> of this view specifying how it should be
9670     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9671     * correspond to the different subclasses of ViewGroup that are responsible
9672     * for arranging their children.
9673     *
9674     * @param params The layout parameters for this view, cannot be null
9675     */
9676    public void setLayoutParams(ViewGroup.LayoutParams params) {
9677        if (params == null) {
9678            throw new NullPointerException("Layout parameters cannot be null");
9679        }
9680        mLayoutParams = params;
9681        if (mParent instanceof ViewGroup) {
9682            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9683        }
9684        requestLayout();
9685    }
9686
9687    /**
9688     * Set the scrolled position of your view. This will cause a call to
9689     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9690     * invalidated.
9691     * @param x the x position to scroll to
9692     * @param y the y position to scroll to
9693     */
9694    public void scrollTo(int x, int y) {
9695        if (mScrollX != x || mScrollY != y) {
9696            int oldX = mScrollX;
9697            int oldY = mScrollY;
9698            mScrollX = x;
9699            mScrollY = y;
9700            invalidateParentCaches();
9701            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9702            if (!awakenScrollBars()) {
9703                postInvalidateOnAnimation();
9704            }
9705        }
9706    }
9707
9708    /**
9709     * Move the scrolled position of your view. This will cause a call to
9710     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9711     * invalidated.
9712     * @param x the amount of pixels to scroll by horizontally
9713     * @param y the amount of pixels to scroll by vertically
9714     */
9715    public void scrollBy(int x, int y) {
9716        scrollTo(mScrollX + x, mScrollY + y);
9717    }
9718
9719    /**
9720     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9721     * animation to fade the scrollbars out after a default delay. If a subclass
9722     * provides animated scrolling, the start delay should equal the duration
9723     * of the scrolling animation.</p>
9724     *
9725     * <p>The animation starts only if at least one of the scrollbars is
9726     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9727     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9728     * this method returns true, and false otherwise. If the animation is
9729     * started, this method calls {@link #invalidate()}; in that case the
9730     * caller should not call {@link #invalidate()}.</p>
9731     *
9732     * <p>This method should be invoked every time a subclass directly updates
9733     * the scroll parameters.</p>
9734     *
9735     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9736     * and {@link #scrollTo(int, int)}.</p>
9737     *
9738     * @return true if the animation is played, false otherwise
9739     *
9740     * @see #awakenScrollBars(int)
9741     * @see #scrollBy(int, int)
9742     * @see #scrollTo(int, int)
9743     * @see #isHorizontalScrollBarEnabled()
9744     * @see #isVerticalScrollBarEnabled()
9745     * @see #setHorizontalScrollBarEnabled(boolean)
9746     * @see #setVerticalScrollBarEnabled(boolean)
9747     */
9748    protected boolean awakenScrollBars() {
9749        return mScrollCache != null &&
9750                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9751    }
9752
9753    /**
9754     * Trigger the scrollbars to draw.
9755     * This method differs from awakenScrollBars() only in its default duration.
9756     * initialAwakenScrollBars() will show the scroll bars for longer than
9757     * usual to give the user more of a chance to notice them.
9758     *
9759     * @return true if the animation is played, false otherwise.
9760     */
9761    private boolean initialAwakenScrollBars() {
9762        return mScrollCache != null &&
9763                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9764    }
9765
9766    /**
9767     * <p>
9768     * Trigger the scrollbars to draw. When invoked this method starts an
9769     * animation to fade the scrollbars out after a fixed delay. If a subclass
9770     * provides animated scrolling, the start delay should equal the duration of
9771     * the scrolling animation.
9772     * </p>
9773     *
9774     * <p>
9775     * The animation starts only if at least one of the scrollbars is enabled,
9776     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9777     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9778     * this method returns true, and false otherwise. If the animation is
9779     * started, this method calls {@link #invalidate()}; in that case the caller
9780     * should not call {@link #invalidate()}.
9781     * </p>
9782     *
9783     * <p>
9784     * This method should be invoked everytime a subclass directly updates the
9785     * scroll parameters.
9786     * </p>
9787     *
9788     * @param startDelay the delay, in milliseconds, after which the animation
9789     *        should start; when the delay is 0, the animation starts
9790     *        immediately
9791     * @return true if the animation is played, false otherwise
9792     *
9793     * @see #scrollBy(int, int)
9794     * @see #scrollTo(int, int)
9795     * @see #isHorizontalScrollBarEnabled()
9796     * @see #isVerticalScrollBarEnabled()
9797     * @see #setHorizontalScrollBarEnabled(boolean)
9798     * @see #setVerticalScrollBarEnabled(boolean)
9799     */
9800    protected boolean awakenScrollBars(int startDelay) {
9801        return awakenScrollBars(startDelay, true);
9802    }
9803
9804    /**
9805     * <p>
9806     * Trigger the scrollbars to draw. When invoked this method starts an
9807     * animation to fade the scrollbars out after a fixed delay. If a subclass
9808     * provides animated scrolling, the start delay should equal the duration of
9809     * the scrolling animation.
9810     * </p>
9811     *
9812     * <p>
9813     * The animation starts only if at least one of the scrollbars is enabled,
9814     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9815     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9816     * this method returns true, and false otherwise. If the animation is
9817     * started, this method calls {@link #invalidate()} if the invalidate parameter
9818     * is set to true; in that case the caller
9819     * should not call {@link #invalidate()}.
9820     * </p>
9821     *
9822     * <p>
9823     * This method should be invoked everytime a subclass directly updates the
9824     * scroll parameters.
9825     * </p>
9826     *
9827     * @param startDelay the delay, in milliseconds, after which the animation
9828     *        should start; when the delay is 0, the animation starts
9829     *        immediately
9830     *
9831     * @param invalidate Wheter this method should call invalidate
9832     *
9833     * @return true if the animation is played, false otherwise
9834     *
9835     * @see #scrollBy(int, int)
9836     * @see #scrollTo(int, int)
9837     * @see #isHorizontalScrollBarEnabled()
9838     * @see #isVerticalScrollBarEnabled()
9839     * @see #setHorizontalScrollBarEnabled(boolean)
9840     * @see #setVerticalScrollBarEnabled(boolean)
9841     */
9842    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9843        final ScrollabilityCache scrollCache = mScrollCache;
9844
9845        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9846            return false;
9847        }
9848
9849        if (scrollCache.scrollBar == null) {
9850            scrollCache.scrollBar = new ScrollBarDrawable();
9851        }
9852
9853        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9854
9855            if (invalidate) {
9856                // Invalidate to show the scrollbars
9857                postInvalidateOnAnimation();
9858            }
9859
9860            if (scrollCache.state == ScrollabilityCache.OFF) {
9861                // FIXME: this is copied from WindowManagerService.
9862                // We should get this value from the system when it
9863                // is possible to do so.
9864                final int KEY_REPEAT_FIRST_DELAY = 750;
9865                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9866            }
9867
9868            // Tell mScrollCache when we should start fading. This may
9869            // extend the fade start time if one was already scheduled
9870            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9871            scrollCache.fadeStartTime = fadeStartTime;
9872            scrollCache.state = ScrollabilityCache.ON;
9873
9874            // Schedule our fader to run, unscheduling any old ones first
9875            if (mAttachInfo != null) {
9876                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9877                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9878            }
9879
9880            return true;
9881        }
9882
9883        return false;
9884    }
9885
9886    /**
9887     * Do not invalidate views which are not visible and which are not running an animation. They
9888     * will not get drawn and they should not set dirty flags as if they will be drawn
9889     */
9890    private boolean skipInvalidate() {
9891        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9892                (!(mParent instanceof ViewGroup) ||
9893                        !((ViewGroup) mParent).isViewTransitioning(this));
9894    }
9895    /**
9896     * Mark the area defined by dirty as needing to be drawn. If the view is
9897     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9898     * in the future. This must be called from a UI thread. To call from a non-UI
9899     * thread, call {@link #postInvalidate()}.
9900     *
9901     * WARNING: This method is destructive to dirty.
9902     * @param dirty the rectangle representing the bounds of the dirty region
9903     */
9904    public void invalidate(Rect dirty) {
9905        if (skipInvalidate()) {
9906            return;
9907        }
9908        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9909                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9910                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9911            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9912            mPrivateFlags |= INVALIDATED;
9913            mPrivateFlags |= DIRTY;
9914            final ViewParent p = mParent;
9915            final AttachInfo ai = mAttachInfo;
9916            //noinspection PointlessBooleanExpression,ConstantConditions
9917            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9918                if (p != null && ai != null && ai.mHardwareAccelerated) {
9919                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9920                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9921                    p.invalidateChild(this, null);
9922                    return;
9923                }
9924            }
9925            if (p != null && ai != null) {
9926                final int scrollX = mScrollX;
9927                final int scrollY = mScrollY;
9928                final Rect r = ai.mTmpInvalRect;
9929                r.set(dirty.left - scrollX, dirty.top - scrollY,
9930                        dirty.right - scrollX, dirty.bottom - scrollY);
9931                mParent.invalidateChild(this, r);
9932            }
9933        }
9934    }
9935
9936    /**
9937     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9938     * The coordinates of the dirty rect are relative to the view.
9939     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9940     * will be called at some point in the future. This must be called from
9941     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9942     * @param l the left position of the dirty region
9943     * @param t the top position of the dirty region
9944     * @param r the right position of the dirty region
9945     * @param b the bottom position of the dirty region
9946     */
9947    public void invalidate(int l, int t, int r, int b) {
9948        if (skipInvalidate()) {
9949            return;
9950        }
9951        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9952                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9953                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9954            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9955            mPrivateFlags |= INVALIDATED;
9956            mPrivateFlags |= DIRTY;
9957            final ViewParent p = mParent;
9958            final AttachInfo ai = mAttachInfo;
9959            //noinspection PointlessBooleanExpression,ConstantConditions
9960            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9961                if (p != null && ai != null && ai.mHardwareAccelerated) {
9962                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9963                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9964                    p.invalidateChild(this, null);
9965                    return;
9966                }
9967            }
9968            if (p != null && ai != null && l < r && t < b) {
9969                final int scrollX = mScrollX;
9970                final int scrollY = mScrollY;
9971                final Rect tmpr = ai.mTmpInvalRect;
9972                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9973                p.invalidateChild(this, tmpr);
9974            }
9975        }
9976    }
9977
9978    /**
9979     * Invalidate the whole view. If the view is visible,
9980     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9981     * the future. This must be called from a UI thread. To call from a non-UI thread,
9982     * call {@link #postInvalidate()}.
9983     */
9984    public void invalidate() {
9985        invalidate(true);
9986    }
9987
9988    /**
9989     * This is where the invalidate() work actually happens. A full invalidate()
9990     * causes the drawing cache to be invalidated, but this function can be called with
9991     * invalidateCache set to false to skip that invalidation step for cases that do not
9992     * need it (for example, a component that remains at the same dimensions with the same
9993     * content).
9994     *
9995     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9996     * well. This is usually true for a full invalidate, but may be set to false if the
9997     * View's contents or dimensions have not changed.
9998     */
9999    void invalidate(boolean invalidateCache) {
10000        if (skipInvalidate()) {
10001            return;
10002        }
10003        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10004                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
10005                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
10006            mLastIsOpaque = isOpaque();
10007            mPrivateFlags &= ~DRAWN;
10008            mPrivateFlags |= DIRTY;
10009            if (invalidateCache) {
10010                mPrivateFlags |= INVALIDATED;
10011                mPrivateFlags &= ~DRAWING_CACHE_VALID;
10012            }
10013            final AttachInfo ai = mAttachInfo;
10014            final ViewParent p = mParent;
10015            //noinspection PointlessBooleanExpression,ConstantConditions
10016            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10017                if (p != null && ai != null && ai.mHardwareAccelerated) {
10018                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10019                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10020                    p.invalidateChild(this, null);
10021                    return;
10022                }
10023            }
10024
10025            if (p != null && ai != null) {
10026                final Rect r = ai.mTmpInvalRect;
10027                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10028                // Don't call invalidate -- we don't want to internally scroll
10029                // our own bounds
10030                p.invalidateChild(this, r);
10031            }
10032        }
10033    }
10034
10035    /**
10036     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10037     * set any flags or handle all of the cases handled by the default invalidation methods.
10038     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10039     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10040     * walk up the hierarchy, transforming the dirty rect as necessary.
10041     *
10042     * The method also handles normal invalidation logic if display list properties are not
10043     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10044     * backup approach, to handle these cases used in the various property-setting methods.
10045     *
10046     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10047     * are not being used in this view
10048     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10049     * list properties are not being used in this view
10050     */
10051    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10052        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10053            if (invalidateParent) {
10054                invalidateParentCaches();
10055            }
10056            if (forceRedraw) {
10057                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10058            }
10059            invalidate(false);
10060        } else {
10061            final AttachInfo ai = mAttachInfo;
10062            final ViewParent p = mParent;
10063            if (p != null && ai != null) {
10064                final Rect r = ai.mTmpInvalRect;
10065                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10066                if (mParent instanceof ViewGroup) {
10067                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10068                } else {
10069                    mParent.invalidateChild(this, r);
10070                }
10071            }
10072        }
10073    }
10074
10075    /**
10076     * Utility method to transform a given Rect by the current matrix of this view.
10077     */
10078    void transformRect(final Rect rect) {
10079        if (!getMatrix().isIdentity()) {
10080            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10081            boundingRect.set(rect);
10082            getMatrix().mapRect(boundingRect);
10083            rect.set((int) (boundingRect.left - 0.5f),
10084                    (int) (boundingRect.top - 0.5f),
10085                    (int) (boundingRect.right + 0.5f),
10086                    (int) (boundingRect.bottom + 0.5f));
10087        }
10088    }
10089
10090    /**
10091     * Used to indicate that the parent of this view should clear its caches. This functionality
10092     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10093     * which is necessary when various parent-managed properties of the view change, such as
10094     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10095     * clears the parent caches and does not causes an invalidate event.
10096     *
10097     * @hide
10098     */
10099    protected void invalidateParentCaches() {
10100        if (mParent instanceof View) {
10101            ((View) mParent).mPrivateFlags |= INVALIDATED;
10102        }
10103    }
10104
10105    /**
10106     * Used to indicate that the parent of this view should be invalidated. This functionality
10107     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10108     * which is necessary when various parent-managed properties of the view change, such as
10109     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10110     * an invalidation event to the parent.
10111     *
10112     * @hide
10113     */
10114    protected void invalidateParentIfNeeded() {
10115        if (isHardwareAccelerated() && mParent instanceof View) {
10116            ((View) mParent).invalidate(true);
10117        }
10118    }
10119
10120    /**
10121     * Indicates whether this View is opaque. An opaque View guarantees that it will
10122     * draw all the pixels overlapping its bounds using a fully opaque color.
10123     *
10124     * Subclasses of View should override this method whenever possible to indicate
10125     * whether an instance is opaque. Opaque Views are treated in a special way by
10126     * the View hierarchy, possibly allowing it to perform optimizations during
10127     * invalidate/draw passes.
10128     *
10129     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10130     */
10131    @ViewDebug.ExportedProperty(category = "drawing")
10132    public boolean isOpaque() {
10133        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10134                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10135                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10136    }
10137
10138    /**
10139     * @hide
10140     */
10141    protected void computeOpaqueFlags() {
10142        // Opaque if:
10143        //   - Has a background
10144        //   - Background is opaque
10145        //   - Doesn't have scrollbars or scrollbars are inside overlay
10146
10147        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10148            mPrivateFlags |= OPAQUE_BACKGROUND;
10149        } else {
10150            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10151        }
10152
10153        final int flags = mViewFlags;
10154        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10155                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10156            mPrivateFlags |= OPAQUE_SCROLLBARS;
10157        } else {
10158            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10159        }
10160    }
10161
10162    /**
10163     * @hide
10164     */
10165    protected boolean hasOpaqueScrollbars() {
10166        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10167    }
10168
10169    /**
10170     * @return A handler associated with the thread running the View. This
10171     * handler can be used to pump events in the UI events queue.
10172     */
10173    public Handler getHandler() {
10174        if (mAttachInfo != null) {
10175            return mAttachInfo.mHandler;
10176        }
10177        return null;
10178    }
10179
10180    /**
10181     * Gets the view root associated with the View.
10182     * @return The view root, or null if none.
10183     * @hide
10184     */
10185    public ViewRootImpl getViewRootImpl() {
10186        if (mAttachInfo != null) {
10187            return mAttachInfo.mViewRootImpl;
10188        }
10189        return null;
10190    }
10191
10192    /**
10193     * <p>Causes the Runnable to be added to the message queue.
10194     * The runnable will be run on the user interface thread.</p>
10195     *
10196     * <p>This method can be invoked from outside of the UI thread
10197     * only when this View is attached to a window.</p>
10198     *
10199     * @param action The Runnable that will be executed.
10200     *
10201     * @return Returns true if the Runnable was successfully placed in to the
10202     *         message queue.  Returns false on failure, usually because the
10203     *         looper processing the message queue is exiting.
10204     *
10205     * @see #postDelayed
10206     * @see #removeCallbacks
10207     */
10208    public boolean post(Runnable action) {
10209        final AttachInfo attachInfo = mAttachInfo;
10210        if (attachInfo != null) {
10211            return attachInfo.mHandler.post(action);
10212        }
10213        // Assume that post will succeed later
10214        ViewRootImpl.getRunQueue().post(action);
10215        return true;
10216    }
10217
10218    /**
10219     * <p>Causes the Runnable to be added to the message queue, to be run
10220     * after the specified amount of time elapses.
10221     * The runnable will be run on the user interface thread.</p>
10222     *
10223     * <p>This method can be invoked from outside of the UI thread
10224     * only when this View is attached to a window.</p>
10225     *
10226     * @param action The Runnable that will be executed.
10227     * @param delayMillis The delay (in milliseconds) until the Runnable
10228     *        will be executed.
10229     *
10230     * @return true if the Runnable was successfully placed in to the
10231     *         message queue.  Returns false on failure, usually because the
10232     *         looper processing the message queue is exiting.  Note that a
10233     *         result of true does not mean the Runnable will be processed --
10234     *         if the looper is quit before the delivery time of the message
10235     *         occurs then the message will be dropped.
10236     *
10237     * @see #post
10238     * @see #removeCallbacks
10239     */
10240    public boolean postDelayed(Runnable action, long delayMillis) {
10241        final AttachInfo attachInfo = mAttachInfo;
10242        if (attachInfo != null) {
10243            return attachInfo.mHandler.postDelayed(action, delayMillis);
10244        }
10245        // Assume that post will succeed later
10246        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10247        return true;
10248    }
10249
10250    /**
10251     * <p>Causes the Runnable to execute on the next animation time step.
10252     * The runnable will be run on the user interface thread.</p>
10253     *
10254     * <p>This method can be invoked from outside of the UI thread
10255     * only when this View is attached to a window.</p>
10256     *
10257     * @param action The Runnable that will be executed.
10258     *
10259     * @see #postOnAnimationDelayed
10260     * @see #removeCallbacks
10261     */
10262    public void postOnAnimation(Runnable action) {
10263        final AttachInfo attachInfo = mAttachInfo;
10264        if (attachInfo != null) {
10265            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10266                    Choreographer.CALLBACK_ANIMATION, action, null);
10267        } else {
10268            // Assume that post will succeed later
10269            ViewRootImpl.getRunQueue().post(action);
10270        }
10271    }
10272
10273    /**
10274     * <p>Causes the Runnable to execute on the next animation time step,
10275     * after the specified amount of time elapses.
10276     * The runnable will be run on the user interface thread.</p>
10277     *
10278     * <p>This method can be invoked from outside of the UI thread
10279     * only when this View is attached to a window.</p>
10280     *
10281     * @param action The Runnable that will be executed.
10282     * @param delayMillis The delay (in milliseconds) until the Runnable
10283     *        will be executed.
10284     *
10285     * @see #postOnAnimation
10286     * @see #removeCallbacks
10287     */
10288    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10289        final AttachInfo attachInfo = mAttachInfo;
10290        if (attachInfo != null) {
10291            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10292                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10293        } else {
10294            // Assume that post will succeed later
10295            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10296        }
10297    }
10298
10299    /**
10300     * <p>Removes the specified Runnable from the message queue.</p>
10301     *
10302     * <p>This method can be invoked from outside of the UI thread
10303     * only when this View is attached to a window.</p>
10304     *
10305     * @param action The Runnable to remove from the message handling queue
10306     *
10307     * @return true if this view could ask the Handler to remove the Runnable,
10308     *         false otherwise. When the returned value is true, the Runnable
10309     *         may or may not have been actually removed from the message queue
10310     *         (for instance, if the Runnable was not in the queue already.)
10311     *
10312     * @see #post
10313     * @see #postDelayed
10314     * @see #postOnAnimation
10315     * @see #postOnAnimationDelayed
10316     */
10317    public boolean removeCallbacks(Runnable action) {
10318        if (action != null) {
10319            final AttachInfo attachInfo = mAttachInfo;
10320            if (attachInfo != null) {
10321                attachInfo.mHandler.removeCallbacks(action);
10322                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10323                        Choreographer.CALLBACK_ANIMATION, action, null);
10324            } else {
10325                // Assume that post will succeed later
10326                ViewRootImpl.getRunQueue().removeCallbacks(action);
10327            }
10328        }
10329        return true;
10330    }
10331
10332    /**
10333     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10334     * Use this to invalidate the View from a non-UI thread.</p>
10335     *
10336     * <p>This method can be invoked from outside of the UI thread
10337     * only when this View is attached to a window.</p>
10338     *
10339     * @see #invalidate()
10340     * @see #postInvalidateDelayed(long)
10341     */
10342    public void postInvalidate() {
10343        postInvalidateDelayed(0);
10344    }
10345
10346    /**
10347     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10348     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10349     *
10350     * <p>This method can be invoked from outside of the UI thread
10351     * only when this View is attached to a window.</p>
10352     *
10353     * @param left The left coordinate of the rectangle to invalidate.
10354     * @param top The top coordinate of the rectangle to invalidate.
10355     * @param right The right coordinate of the rectangle to invalidate.
10356     * @param bottom The bottom coordinate of the rectangle to invalidate.
10357     *
10358     * @see #invalidate(int, int, int, int)
10359     * @see #invalidate(Rect)
10360     * @see #postInvalidateDelayed(long, int, int, int, int)
10361     */
10362    public void postInvalidate(int left, int top, int right, int bottom) {
10363        postInvalidateDelayed(0, left, top, right, bottom);
10364    }
10365
10366    /**
10367     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10368     * loop. Waits for the specified amount of time.</p>
10369     *
10370     * <p>This method can be invoked from outside of the UI thread
10371     * only when this View is attached to a window.</p>
10372     *
10373     * @param delayMilliseconds the duration in milliseconds to delay the
10374     *         invalidation by
10375     *
10376     * @see #invalidate()
10377     * @see #postInvalidate()
10378     */
10379    public void postInvalidateDelayed(long delayMilliseconds) {
10380        // We try only with the AttachInfo because there's no point in invalidating
10381        // if we are not attached to our window
10382        final AttachInfo attachInfo = mAttachInfo;
10383        if (attachInfo != null) {
10384            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10385        }
10386    }
10387
10388    /**
10389     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10390     * through the event loop. Waits for the specified amount of time.</p>
10391     *
10392     * <p>This method can be invoked from outside of the UI thread
10393     * only when this View is attached to a window.</p>
10394     *
10395     * @param delayMilliseconds the duration in milliseconds to delay the
10396     *         invalidation by
10397     * @param left The left coordinate of the rectangle to invalidate.
10398     * @param top The top coordinate of the rectangle to invalidate.
10399     * @param right The right coordinate of the rectangle to invalidate.
10400     * @param bottom The bottom coordinate of the rectangle to invalidate.
10401     *
10402     * @see #invalidate(int, int, int, int)
10403     * @see #invalidate(Rect)
10404     * @see #postInvalidate(int, int, int, int)
10405     */
10406    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10407            int right, int bottom) {
10408
10409        // We try only with the AttachInfo because there's no point in invalidating
10410        // if we are not attached to our window
10411        final AttachInfo attachInfo = mAttachInfo;
10412        if (attachInfo != null) {
10413            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10414            info.target = this;
10415            info.left = left;
10416            info.top = top;
10417            info.right = right;
10418            info.bottom = bottom;
10419
10420            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10421        }
10422    }
10423
10424    /**
10425     * <p>Cause an invalidate to happen on the next animation time step, typically the
10426     * next display frame.</p>
10427     *
10428     * <p>This method can be invoked from outside of the UI thread
10429     * only when this View is attached to a window.</p>
10430     *
10431     * @see #invalidate()
10432     */
10433    public void postInvalidateOnAnimation() {
10434        // We try only with the AttachInfo because there's no point in invalidating
10435        // if we are not attached to our window
10436        final AttachInfo attachInfo = mAttachInfo;
10437        if (attachInfo != null) {
10438            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10439        }
10440    }
10441
10442    /**
10443     * <p>Cause an invalidate of the specified area to happen on the next animation
10444     * time step, typically the next display frame.</p>
10445     *
10446     * <p>This method can be invoked from outside of the UI thread
10447     * only when this View is attached to a window.</p>
10448     *
10449     * @param left The left coordinate of the rectangle to invalidate.
10450     * @param top The top coordinate of the rectangle to invalidate.
10451     * @param right The right coordinate of the rectangle to invalidate.
10452     * @param bottom The bottom coordinate of the rectangle to invalidate.
10453     *
10454     * @see #invalidate(int, int, int, int)
10455     * @see #invalidate(Rect)
10456     */
10457    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10458        // We try only with the AttachInfo because there's no point in invalidating
10459        // if we are not attached to our window
10460        final AttachInfo attachInfo = mAttachInfo;
10461        if (attachInfo != null) {
10462            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10463            info.target = this;
10464            info.left = left;
10465            info.top = top;
10466            info.right = right;
10467            info.bottom = bottom;
10468
10469            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10470        }
10471    }
10472
10473    /**
10474     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10475     * This event is sent at most once every
10476     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10477     */
10478    private void postSendViewScrolledAccessibilityEventCallback() {
10479        if (mSendViewScrolledAccessibilityEvent == null) {
10480            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10481        }
10482        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10483            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10484            postDelayed(mSendViewScrolledAccessibilityEvent,
10485                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10486        }
10487    }
10488
10489    /**
10490     * Called by a parent to request that a child update its values for mScrollX
10491     * and mScrollY if necessary. This will typically be done if the child is
10492     * animating a scroll using a {@link android.widget.Scroller Scroller}
10493     * object.
10494     */
10495    public void computeScroll() {
10496    }
10497
10498    /**
10499     * <p>Indicate whether the horizontal edges are faded when the view is
10500     * scrolled horizontally.</p>
10501     *
10502     * @return true if the horizontal edges should are faded on scroll, false
10503     *         otherwise
10504     *
10505     * @see #setHorizontalFadingEdgeEnabled(boolean)
10506     *
10507     * @attr ref android.R.styleable#View_requiresFadingEdge
10508     */
10509    public boolean isHorizontalFadingEdgeEnabled() {
10510        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10511    }
10512
10513    /**
10514     * <p>Define whether the horizontal edges should be faded when this view
10515     * is scrolled horizontally.</p>
10516     *
10517     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10518     *                                    be faded when the view is scrolled
10519     *                                    horizontally
10520     *
10521     * @see #isHorizontalFadingEdgeEnabled()
10522     *
10523     * @attr ref android.R.styleable#View_requiresFadingEdge
10524     */
10525    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10526        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10527            if (horizontalFadingEdgeEnabled) {
10528                initScrollCache();
10529            }
10530
10531            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10532        }
10533    }
10534
10535    /**
10536     * <p>Indicate whether the vertical edges are faded when the view is
10537     * scrolled horizontally.</p>
10538     *
10539     * @return true if the vertical edges should are faded on scroll, false
10540     *         otherwise
10541     *
10542     * @see #setVerticalFadingEdgeEnabled(boolean)
10543     *
10544     * @attr ref android.R.styleable#View_requiresFadingEdge
10545     */
10546    public boolean isVerticalFadingEdgeEnabled() {
10547        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10548    }
10549
10550    /**
10551     * <p>Define whether the vertical edges should be faded when this view
10552     * is scrolled vertically.</p>
10553     *
10554     * @param verticalFadingEdgeEnabled true if the vertical edges should
10555     *                                  be faded when the view is scrolled
10556     *                                  vertically
10557     *
10558     * @see #isVerticalFadingEdgeEnabled()
10559     *
10560     * @attr ref android.R.styleable#View_requiresFadingEdge
10561     */
10562    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10563        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10564            if (verticalFadingEdgeEnabled) {
10565                initScrollCache();
10566            }
10567
10568            mViewFlags ^= FADING_EDGE_VERTICAL;
10569        }
10570    }
10571
10572    /**
10573     * Returns the strength, or intensity, of the top faded edge. The strength is
10574     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10575     * returns 0.0 or 1.0 but no value in between.
10576     *
10577     * Subclasses should override this method to provide a smoother fade transition
10578     * when scrolling occurs.
10579     *
10580     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10581     */
10582    protected float getTopFadingEdgeStrength() {
10583        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10584    }
10585
10586    /**
10587     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10588     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10589     * returns 0.0 or 1.0 but no value in between.
10590     *
10591     * Subclasses should override this method to provide a smoother fade transition
10592     * when scrolling occurs.
10593     *
10594     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10595     */
10596    protected float getBottomFadingEdgeStrength() {
10597        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10598                computeVerticalScrollRange() ? 1.0f : 0.0f;
10599    }
10600
10601    /**
10602     * Returns the strength, or intensity, of the left faded edge. The strength is
10603     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10604     * returns 0.0 or 1.0 but no value in between.
10605     *
10606     * Subclasses should override this method to provide a smoother fade transition
10607     * when scrolling occurs.
10608     *
10609     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10610     */
10611    protected float getLeftFadingEdgeStrength() {
10612        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10613    }
10614
10615    /**
10616     * Returns the strength, or intensity, of the right faded edge. The strength is
10617     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10618     * returns 0.0 or 1.0 but no value in between.
10619     *
10620     * Subclasses should override this method to provide a smoother fade transition
10621     * when scrolling occurs.
10622     *
10623     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10624     */
10625    protected float getRightFadingEdgeStrength() {
10626        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10627                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10628    }
10629
10630    /**
10631     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10632     * scrollbar is not drawn by default.</p>
10633     *
10634     * @return true if the horizontal scrollbar should be painted, false
10635     *         otherwise
10636     *
10637     * @see #setHorizontalScrollBarEnabled(boolean)
10638     */
10639    public boolean isHorizontalScrollBarEnabled() {
10640        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10641    }
10642
10643    /**
10644     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10645     * scrollbar is not drawn by default.</p>
10646     *
10647     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10648     *                                   be painted
10649     *
10650     * @see #isHorizontalScrollBarEnabled()
10651     */
10652    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10653        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10654            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10655            computeOpaqueFlags();
10656            resolvePadding();
10657        }
10658    }
10659
10660    /**
10661     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10662     * scrollbar is not drawn by default.</p>
10663     *
10664     * @return true if the vertical scrollbar should be painted, false
10665     *         otherwise
10666     *
10667     * @see #setVerticalScrollBarEnabled(boolean)
10668     */
10669    public boolean isVerticalScrollBarEnabled() {
10670        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10671    }
10672
10673    /**
10674     * <p>Define whether the vertical scrollbar should be drawn or not. The
10675     * scrollbar is not drawn by default.</p>
10676     *
10677     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10678     *                                 be painted
10679     *
10680     * @see #isVerticalScrollBarEnabled()
10681     */
10682    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10683        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10684            mViewFlags ^= SCROLLBARS_VERTICAL;
10685            computeOpaqueFlags();
10686            resolvePadding();
10687        }
10688    }
10689
10690    /**
10691     * @hide
10692     */
10693    protected void recomputePadding() {
10694        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10695    }
10696
10697    /**
10698     * Define whether scrollbars will fade when the view is not scrolling.
10699     *
10700     * @param fadeScrollbars wheter to enable fading
10701     *
10702     * @attr ref android.R.styleable#View_fadeScrollbars
10703     */
10704    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10705        initScrollCache();
10706        final ScrollabilityCache scrollabilityCache = mScrollCache;
10707        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10708        if (fadeScrollbars) {
10709            scrollabilityCache.state = ScrollabilityCache.OFF;
10710        } else {
10711            scrollabilityCache.state = ScrollabilityCache.ON;
10712        }
10713    }
10714
10715    /**
10716     *
10717     * Returns true if scrollbars will fade when this view is not scrolling
10718     *
10719     * @return true if scrollbar fading is enabled
10720     *
10721     * @attr ref android.R.styleable#View_fadeScrollbars
10722     */
10723    public boolean isScrollbarFadingEnabled() {
10724        return mScrollCache != null && mScrollCache.fadeScrollBars;
10725    }
10726
10727    /**
10728     *
10729     * Returns the delay before scrollbars fade.
10730     *
10731     * @return the delay before scrollbars fade
10732     *
10733     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10734     */
10735    public int getScrollBarDefaultDelayBeforeFade() {
10736        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10737                mScrollCache.scrollBarDefaultDelayBeforeFade;
10738    }
10739
10740    /**
10741     * Define the delay before scrollbars fade.
10742     *
10743     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10744     *
10745     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10746     */
10747    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10748        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10749    }
10750
10751    /**
10752     *
10753     * Returns the scrollbar fade duration.
10754     *
10755     * @return the scrollbar fade duration
10756     *
10757     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10758     */
10759    public int getScrollBarFadeDuration() {
10760        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10761                mScrollCache.scrollBarFadeDuration;
10762    }
10763
10764    /**
10765     * Define the scrollbar fade duration.
10766     *
10767     * @param scrollBarFadeDuration - the scrollbar fade duration
10768     *
10769     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10770     */
10771    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10772        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10773    }
10774
10775    /**
10776     *
10777     * Returns the scrollbar size.
10778     *
10779     * @return the scrollbar size
10780     *
10781     * @attr ref android.R.styleable#View_scrollbarSize
10782     */
10783    public int getScrollBarSize() {
10784        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10785                mScrollCache.scrollBarSize;
10786    }
10787
10788    /**
10789     * Define the scrollbar size.
10790     *
10791     * @param scrollBarSize - the scrollbar size
10792     *
10793     * @attr ref android.R.styleable#View_scrollbarSize
10794     */
10795    public void setScrollBarSize(int scrollBarSize) {
10796        getScrollCache().scrollBarSize = scrollBarSize;
10797    }
10798
10799    /**
10800     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10801     * inset. When inset, they add to the padding of the view. And the scrollbars
10802     * can be drawn inside the padding area or on the edge of the view. For example,
10803     * if a view has a background drawable and you want to draw the scrollbars
10804     * inside the padding specified by the drawable, you can use
10805     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10806     * appear at the edge of the view, ignoring the padding, then you can use
10807     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10808     * @param style the style of the scrollbars. Should be one of
10809     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10810     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10811     * @see #SCROLLBARS_INSIDE_OVERLAY
10812     * @see #SCROLLBARS_INSIDE_INSET
10813     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10814     * @see #SCROLLBARS_OUTSIDE_INSET
10815     *
10816     * @attr ref android.R.styleable#View_scrollbarStyle
10817     */
10818    public void setScrollBarStyle(int style) {
10819        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10820            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10821            computeOpaqueFlags();
10822            resolvePadding();
10823        }
10824    }
10825
10826    /**
10827     * <p>Returns the current scrollbar style.</p>
10828     * @return the current scrollbar style
10829     * @see #SCROLLBARS_INSIDE_OVERLAY
10830     * @see #SCROLLBARS_INSIDE_INSET
10831     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10832     * @see #SCROLLBARS_OUTSIDE_INSET
10833     *
10834     * @attr ref android.R.styleable#View_scrollbarStyle
10835     */
10836    @ViewDebug.ExportedProperty(mapping = {
10837            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10838            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10839            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10840            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10841    })
10842    public int getScrollBarStyle() {
10843        return mViewFlags & SCROLLBARS_STYLE_MASK;
10844    }
10845
10846    /**
10847     * <p>Compute the horizontal range that the horizontal scrollbar
10848     * represents.</p>
10849     *
10850     * <p>The range is expressed in arbitrary units that must be the same as the
10851     * units used by {@link #computeHorizontalScrollExtent()} and
10852     * {@link #computeHorizontalScrollOffset()}.</p>
10853     *
10854     * <p>The default range is the drawing width of this view.</p>
10855     *
10856     * @return the total horizontal range represented by the horizontal
10857     *         scrollbar
10858     *
10859     * @see #computeHorizontalScrollExtent()
10860     * @see #computeHorizontalScrollOffset()
10861     * @see android.widget.ScrollBarDrawable
10862     */
10863    protected int computeHorizontalScrollRange() {
10864        return getWidth();
10865    }
10866
10867    /**
10868     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10869     * within the horizontal range. This value is used to compute the position
10870     * of the thumb within the scrollbar's track.</p>
10871     *
10872     * <p>The range is expressed in arbitrary units that must be the same as the
10873     * units used by {@link #computeHorizontalScrollRange()} and
10874     * {@link #computeHorizontalScrollExtent()}.</p>
10875     *
10876     * <p>The default offset is the scroll offset of this view.</p>
10877     *
10878     * @return the horizontal offset of the scrollbar's thumb
10879     *
10880     * @see #computeHorizontalScrollRange()
10881     * @see #computeHorizontalScrollExtent()
10882     * @see android.widget.ScrollBarDrawable
10883     */
10884    protected int computeHorizontalScrollOffset() {
10885        return mScrollX;
10886    }
10887
10888    /**
10889     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10890     * within the horizontal range. This value is used to compute the length
10891     * of the thumb within the scrollbar's track.</p>
10892     *
10893     * <p>The range is expressed in arbitrary units that must be the same as the
10894     * units used by {@link #computeHorizontalScrollRange()} and
10895     * {@link #computeHorizontalScrollOffset()}.</p>
10896     *
10897     * <p>The default extent is the drawing width of this view.</p>
10898     *
10899     * @return the horizontal extent of the scrollbar's thumb
10900     *
10901     * @see #computeHorizontalScrollRange()
10902     * @see #computeHorizontalScrollOffset()
10903     * @see android.widget.ScrollBarDrawable
10904     */
10905    protected int computeHorizontalScrollExtent() {
10906        return getWidth();
10907    }
10908
10909    /**
10910     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10911     *
10912     * <p>The range is expressed in arbitrary units that must be the same as the
10913     * units used by {@link #computeVerticalScrollExtent()} and
10914     * {@link #computeVerticalScrollOffset()}.</p>
10915     *
10916     * @return the total vertical range represented by the vertical scrollbar
10917     *
10918     * <p>The default range is the drawing height of this view.</p>
10919     *
10920     * @see #computeVerticalScrollExtent()
10921     * @see #computeVerticalScrollOffset()
10922     * @see android.widget.ScrollBarDrawable
10923     */
10924    protected int computeVerticalScrollRange() {
10925        return getHeight();
10926    }
10927
10928    /**
10929     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10930     * within the horizontal range. This value is used to compute the position
10931     * of the thumb within the scrollbar's track.</p>
10932     *
10933     * <p>The range is expressed in arbitrary units that must be the same as the
10934     * units used by {@link #computeVerticalScrollRange()} and
10935     * {@link #computeVerticalScrollExtent()}.</p>
10936     *
10937     * <p>The default offset is the scroll offset of this view.</p>
10938     *
10939     * @return the vertical offset of the scrollbar's thumb
10940     *
10941     * @see #computeVerticalScrollRange()
10942     * @see #computeVerticalScrollExtent()
10943     * @see android.widget.ScrollBarDrawable
10944     */
10945    protected int computeVerticalScrollOffset() {
10946        return mScrollY;
10947    }
10948
10949    /**
10950     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10951     * within the vertical range. This value is used to compute the length
10952     * of the thumb within the scrollbar's track.</p>
10953     *
10954     * <p>The range is expressed in arbitrary units that must be the same as the
10955     * units used by {@link #computeVerticalScrollRange()} and
10956     * {@link #computeVerticalScrollOffset()}.</p>
10957     *
10958     * <p>The default extent is the drawing height of this view.</p>
10959     *
10960     * @return the vertical extent of the scrollbar's thumb
10961     *
10962     * @see #computeVerticalScrollRange()
10963     * @see #computeVerticalScrollOffset()
10964     * @see android.widget.ScrollBarDrawable
10965     */
10966    protected int computeVerticalScrollExtent() {
10967        return getHeight();
10968    }
10969
10970    /**
10971     * Check if this view can be scrolled horizontally in a certain direction.
10972     *
10973     * @param direction Negative to check scrolling left, positive to check scrolling right.
10974     * @return true if this view can be scrolled in the specified direction, false otherwise.
10975     */
10976    public boolean canScrollHorizontally(int direction) {
10977        final int offset = computeHorizontalScrollOffset();
10978        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10979        if (range == 0) return false;
10980        if (direction < 0) {
10981            return offset > 0;
10982        } else {
10983            return offset < range - 1;
10984        }
10985    }
10986
10987    /**
10988     * Check if this view can be scrolled vertically in a certain direction.
10989     *
10990     * @param direction Negative to check scrolling up, positive to check scrolling down.
10991     * @return true if this view can be scrolled in the specified direction, false otherwise.
10992     */
10993    public boolean canScrollVertically(int direction) {
10994        final int offset = computeVerticalScrollOffset();
10995        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10996        if (range == 0) return false;
10997        if (direction < 0) {
10998            return offset > 0;
10999        } else {
11000            return offset < range - 1;
11001        }
11002    }
11003
11004    /**
11005     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11006     * scrollbars are painted only if they have been awakened first.</p>
11007     *
11008     * @param canvas the canvas on which to draw the scrollbars
11009     *
11010     * @see #awakenScrollBars(int)
11011     */
11012    protected final void onDrawScrollBars(Canvas canvas) {
11013        // scrollbars are drawn only when the animation is running
11014        final ScrollabilityCache cache = mScrollCache;
11015        if (cache != null) {
11016
11017            int state = cache.state;
11018
11019            if (state == ScrollabilityCache.OFF) {
11020                return;
11021            }
11022
11023            boolean invalidate = false;
11024
11025            if (state == ScrollabilityCache.FADING) {
11026                // We're fading -- get our fade interpolation
11027                if (cache.interpolatorValues == null) {
11028                    cache.interpolatorValues = new float[1];
11029                }
11030
11031                float[] values = cache.interpolatorValues;
11032
11033                // Stops the animation if we're done
11034                if (cache.scrollBarInterpolator.timeToValues(values) ==
11035                        Interpolator.Result.FREEZE_END) {
11036                    cache.state = ScrollabilityCache.OFF;
11037                } else {
11038                    cache.scrollBar.setAlpha(Math.round(values[0]));
11039                }
11040
11041                // This will make the scroll bars inval themselves after
11042                // drawing. We only want this when we're fading so that
11043                // we prevent excessive redraws
11044                invalidate = true;
11045            } else {
11046                // We're just on -- but we may have been fading before so
11047                // reset alpha
11048                cache.scrollBar.setAlpha(255);
11049            }
11050
11051
11052            final int viewFlags = mViewFlags;
11053
11054            final boolean drawHorizontalScrollBar =
11055                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11056            final boolean drawVerticalScrollBar =
11057                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11058                && !isVerticalScrollBarHidden();
11059
11060            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11061                final int width = mRight - mLeft;
11062                final int height = mBottom - mTop;
11063
11064                final ScrollBarDrawable scrollBar = cache.scrollBar;
11065
11066                final int scrollX = mScrollX;
11067                final int scrollY = mScrollY;
11068                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11069
11070                int left, top, right, bottom;
11071
11072                if (drawHorizontalScrollBar) {
11073                    int size = scrollBar.getSize(false);
11074                    if (size <= 0) {
11075                        size = cache.scrollBarSize;
11076                    }
11077
11078                    scrollBar.setParameters(computeHorizontalScrollRange(),
11079                                            computeHorizontalScrollOffset(),
11080                                            computeHorizontalScrollExtent(), false);
11081                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11082                            getVerticalScrollbarWidth() : 0;
11083                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11084                    left = scrollX + (mPaddingLeft & inside);
11085                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11086                    bottom = top + size;
11087                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11088                    if (invalidate) {
11089                        invalidate(left, top, right, bottom);
11090                    }
11091                }
11092
11093                if (drawVerticalScrollBar) {
11094                    int size = scrollBar.getSize(true);
11095                    if (size <= 0) {
11096                        size = cache.scrollBarSize;
11097                    }
11098
11099                    scrollBar.setParameters(computeVerticalScrollRange(),
11100                                            computeVerticalScrollOffset(),
11101                                            computeVerticalScrollExtent(), true);
11102                    switch (mVerticalScrollbarPosition) {
11103                        default:
11104                        case SCROLLBAR_POSITION_DEFAULT:
11105                        case SCROLLBAR_POSITION_RIGHT:
11106                            left = scrollX + width - size - (mUserPaddingRight & inside);
11107                            break;
11108                        case SCROLLBAR_POSITION_LEFT:
11109                            left = scrollX + (mUserPaddingLeft & inside);
11110                            break;
11111                    }
11112                    top = scrollY + (mPaddingTop & inside);
11113                    right = left + size;
11114                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11115                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11116                    if (invalidate) {
11117                        invalidate(left, top, right, bottom);
11118                    }
11119                }
11120            }
11121        }
11122    }
11123
11124    /**
11125     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11126     * FastScroller is visible.
11127     * @return whether to temporarily hide the vertical scrollbar
11128     * @hide
11129     */
11130    protected boolean isVerticalScrollBarHidden() {
11131        return false;
11132    }
11133
11134    /**
11135     * <p>Draw the horizontal scrollbar if
11136     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11137     *
11138     * @param canvas the canvas on which to draw the scrollbar
11139     * @param scrollBar the scrollbar's drawable
11140     *
11141     * @see #isHorizontalScrollBarEnabled()
11142     * @see #computeHorizontalScrollRange()
11143     * @see #computeHorizontalScrollExtent()
11144     * @see #computeHorizontalScrollOffset()
11145     * @see android.widget.ScrollBarDrawable
11146     * @hide
11147     */
11148    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11149            int l, int t, int r, int b) {
11150        scrollBar.setBounds(l, t, r, b);
11151        scrollBar.draw(canvas);
11152    }
11153
11154    /**
11155     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11156     * returns true.</p>
11157     *
11158     * @param canvas the canvas on which to draw the scrollbar
11159     * @param scrollBar the scrollbar's drawable
11160     *
11161     * @see #isVerticalScrollBarEnabled()
11162     * @see #computeVerticalScrollRange()
11163     * @see #computeVerticalScrollExtent()
11164     * @see #computeVerticalScrollOffset()
11165     * @see android.widget.ScrollBarDrawable
11166     * @hide
11167     */
11168    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11169            int l, int t, int r, int b) {
11170        scrollBar.setBounds(l, t, r, b);
11171        scrollBar.draw(canvas);
11172    }
11173
11174    /**
11175     * Implement this to do your drawing.
11176     *
11177     * @param canvas the canvas on which the background will be drawn
11178     */
11179    protected void onDraw(Canvas canvas) {
11180    }
11181
11182    /*
11183     * Caller is responsible for calling requestLayout if necessary.
11184     * (This allows addViewInLayout to not request a new layout.)
11185     */
11186    void assignParent(ViewParent parent) {
11187        if (mParent == null) {
11188            mParent = parent;
11189        } else if (parent == null) {
11190            mParent = null;
11191        } else {
11192            throw new RuntimeException("view " + this + " being added, but"
11193                    + " it already has a parent");
11194        }
11195    }
11196
11197    /**
11198     * This is called when the view is attached to a window.  At this point it
11199     * has a Surface and will start drawing.  Note that this function is
11200     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11201     * however it may be called any time before the first onDraw -- including
11202     * before or after {@link #onMeasure(int, int)}.
11203     *
11204     * @see #onDetachedFromWindow()
11205     */
11206    protected void onAttachedToWindow() {
11207        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11208            mParent.requestTransparentRegion(this);
11209        }
11210
11211        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11212            initialAwakenScrollBars();
11213            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11214        }
11215
11216        jumpDrawablesToCurrentState();
11217
11218        // Order is important here: LayoutDirection MUST be resolved before Padding
11219        // and TextDirection
11220        resolveLayoutDirection();
11221        resolvePadding();
11222        resolveTextDirection();
11223        resolveTextAlignment();
11224
11225        clearAccessibilityFocus();
11226        if (isFocused()) {
11227            InputMethodManager imm = InputMethodManager.peekInstance();
11228            imm.focusIn(this);
11229        }
11230
11231        if (mAttachInfo != null && mDisplayList != null) {
11232            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11233        }
11234    }
11235
11236    /**
11237     * @see #onScreenStateChanged(int)
11238     */
11239    void dispatchScreenStateChanged(int screenState) {
11240        onScreenStateChanged(screenState);
11241    }
11242
11243    /**
11244     * This method is called whenever the state of the screen this view is
11245     * attached to changes. A state change will usually occurs when the screen
11246     * turns on or off (whether it happens automatically or the user does it
11247     * manually.)
11248     *
11249     * @param screenState The new state of the screen. Can be either
11250     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11251     */
11252    public void onScreenStateChanged(int screenState) {
11253    }
11254
11255    /**
11256     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11257     */
11258    private boolean hasRtlSupport() {
11259        return mContext.getApplicationInfo().hasRtlSupport();
11260    }
11261
11262    /**
11263     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11264     * that the parent directionality can and will be resolved before its children.
11265     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11266     * @hide
11267     */
11268    public void resolveLayoutDirection() {
11269        // Clear any previous layout direction resolution
11270        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11271
11272        if (hasRtlSupport()) {
11273            // Set resolved depending on layout direction
11274            switch (getLayoutDirection()) {
11275                case LAYOUT_DIRECTION_INHERIT:
11276                    // If this is root view, no need to look at parent's layout dir.
11277                    if (canResolveLayoutDirection()) {
11278                        ViewGroup viewGroup = ((ViewGroup) mParent);
11279
11280                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11281                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11282                        }
11283                    } else {
11284                        // Nothing to do, LTR by default
11285                    }
11286                    break;
11287                case LAYOUT_DIRECTION_RTL:
11288                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11289                    break;
11290                case LAYOUT_DIRECTION_LOCALE:
11291                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11292                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11293                    }
11294                    break;
11295                default:
11296                    // Nothing to do, LTR by default
11297            }
11298        }
11299
11300        // Set to resolved
11301        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11302        onResolvedLayoutDirectionChanged();
11303        // Resolve padding
11304        resolvePadding();
11305    }
11306
11307    /**
11308     * Called when layout direction has been resolved.
11309     *
11310     * The default implementation does nothing.
11311     * @hide
11312     */
11313    public void onResolvedLayoutDirectionChanged() {
11314    }
11315
11316    /**
11317     * Resolve padding depending on layout direction.
11318     * @hide
11319     */
11320    public void resolvePadding() {
11321        // If the user specified the absolute padding (either with android:padding or
11322        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11323        // use the default padding or the padding from the background drawable
11324        // (stored at this point in mPadding*)
11325        int resolvedLayoutDirection = getResolvedLayoutDirection();
11326        switch (resolvedLayoutDirection) {
11327            case LAYOUT_DIRECTION_RTL:
11328                // Start user padding override Right user padding. Otherwise, if Right user
11329                // padding is not defined, use the default Right padding. If Right user padding
11330                // is defined, just use it.
11331                if (mUserPaddingStart >= 0) {
11332                    mUserPaddingRight = mUserPaddingStart;
11333                } else if (mUserPaddingRight < 0) {
11334                    mUserPaddingRight = mPaddingRight;
11335                }
11336                if (mUserPaddingEnd >= 0) {
11337                    mUserPaddingLeft = mUserPaddingEnd;
11338                } else if (mUserPaddingLeft < 0) {
11339                    mUserPaddingLeft = mPaddingLeft;
11340                }
11341                break;
11342            case LAYOUT_DIRECTION_LTR:
11343            default:
11344                // Start user padding override Left user padding. Otherwise, if Left user
11345                // padding is not defined, use the default left padding. If Left user padding
11346                // is defined, just use it.
11347                if (mUserPaddingStart >= 0) {
11348                    mUserPaddingLeft = mUserPaddingStart;
11349                } else if (mUserPaddingLeft < 0) {
11350                    mUserPaddingLeft = mPaddingLeft;
11351                }
11352                if (mUserPaddingEnd >= 0) {
11353                    mUserPaddingRight = mUserPaddingEnd;
11354                } else if (mUserPaddingRight < 0) {
11355                    mUserPaddingRight = mPaddingRight;
11356                }
11357        }
11358
11359        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11360
11361        if(isPaddingRelative()) {
11362            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11363        } else {
11364            recomputePadding();
11365        }
11366        onPaddingChanged(resolvedLayoutDirection);
11367    }
11368
11369    /**
11370     * Resolve padding depending on the layout direction. Subclasses that care about
11371     * padding resolution should override this method. The default implementation does
11372     * nothing.
11373     *
11374     * @param layoutDirection the direction of the layout
11375     *
11376     * @see {@link #LAYOUT_DIRECTION_LTR}
11377     * @see {@link #LAYOUT_DIRECTION_RTL}
11378     * @hide
11379     */
11380    public void onPaddingChanged(int layoutDirection) {
11381    }
11382
11383    /**
11384     * Check if layout direction resolution can be done.
11385     *
11386     * @return true if layout direction resolution can be done otherwise return false.
11387     * @hide
11388     */
11389    public boolean canResolveLayoutDirection() {
11390        switch (getLayoutDirection()) {
11391            case LAYOUT_DIRECTION_INHERIT:
11392                return (mParent != null) && (mParent instanceof ViewGroup);
11393            default:
11394                return true;
11395        }
11396    }
11397
11398    /**
11399     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11400     * when reset is done.
11401     * @hide
11402     */
11403    public void resetResolvedLayoutDirection() {
11404        // Reset the current resolved bits
11405        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11406        onResolvedLayoutDirectionReset();
11407        // Reset also the text direction
11408        resetResolvedTextDirection();
11409    }
11410
11411    /**
11412     * Called during reset of resolved layout direction.
11413     *
11414     * Subclasses need to override this method to clear cached information that depends on the
11415     * resolved layout direction, or to inform child views that inherit their layout direction.
11416     *
11417     * The default implementation does nothing.
11418     * @hide
11419     */
11420    public void onResolvedLayoutDirectionReset() {
11421    }
11422
11423    /**
11424     * Check if a Locale uses an RTL script.
11425     *
11426     * @param locale Locale to check
11427     * @return true if the Locale uses an RTL script.
11428     * @hide
11429     */
11430    protected static boolean isLayoutDirectionRtl(Locale locale) {
11431        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11432    }
11433
11434    /**
11435     * This is called when the view is detached from a window.  At this point it
11436     * no longer has a surface for drawing.
11437     *
11438     * @see #onAttachedToWindow()
11439     */
11440    protected void onDetachedFromWindow() {
11441        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11442
11443        removeUnsetPressCallback();
11444        removeLongPressCallback();
11445        removePerformClickCallback();
11446        removeSendViewScrolledAccessibilityEventCallback();
11447
11448        destroyDrawingCache();
11449
11450        destroyLayer(false);
11451
11452        if (mAttachInfo != null) {
11453            if (mDisplayList != null) {
11454                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11455            }
11456            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11457        } else {
11458            if (mDisplayList != null) {
11459                // Should never happen
11460                mDisplayList.invalidate();
11461            }
11462        }
11463
11464        mCurrentAnimation = null;
11465
11466        resetResolvedLayoutDirection();
11467        resetResolvedTextAlignment();
11468        resetAccessibilityStateChanged();
11469    }
11470
11471    /**
11472     * @return The number of times this view has been attached to a window
11473     */
11474    protected int getWindowAttachCount() {
11475        return mWindowAttachCount;
11476    }
11477
11478    /**
11479     * Retrieve a unique token identifying the window this view is attached to.
11480     * @return Return the window's token for use in
11481     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11482     */
11483    public IBinder getWindowToken() {
11484        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11485    }
11486
11487    /**
11488     * Retrieve a unique token identifying the top-level "real" window of
11489     * the window that this view is attached to.  That is, this is like
11490     * {@link #getWindowToken}, except if the window this view in is a panel
11491     * window (attached to another containing window), then the token of
11492     * the containing window is returned instead.
11493     *
11494     * @return Returns the associated window token, either
11495     * {@link #getWindowToken()} or the containing window's token.
11496     */
11497    public IBinder getApplicationWindowToken() {
11498        AttachInfo ai = mAttachInfo;
11499        if (ai != null) {
11500            IBinder appWindowToken = ai.mPanelParentWindowToken;
11501            if (appWindowToken == null) {
11502                appWindowToken = ai.mWindowToken;
11503            }
11504            return appWindowToken;
11505        }
11506        return null;
11507    }
11508
11509    /**
11510     * Retrieve private session object this view hierarchy is using to
11511     * communicate with the window manager.
11512     * @return the session object to communicate with the window manager
11513     */
11514    /*package*/ IWindowSession getWindowSession() {
11515        return mAttachInfo != null ? mAttachInfo.mSession : null;
11516    }
11517
11518    /**
11519     * @param info the {@link android.view.View.AttachInfo} to associated with
11520     *        this view
11521     */
11522    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11523        //System.out.println("Attached! " + this);
11524        mAttachInfo = info;
11525        mWindowAttachCount++;
11526        // We will need to evaluate the drawable state at least once.
11527        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11528        if (mFloatingTreeObserver != null) {
11529            info.mTreeObserver.merge(mFloatingTreeObserver);
11530            mFloatingTreeObserver = null;
11531        }
11532        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11533            mAttachInfo.mScrollContainers.add(this);
11534            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11535        }
11536        performCollectViewAttributes(mAttachInfo, visibility);
11537        onAttachedToWindow();
11538
11539        ListenerInfo li = mListenerInfo;
11540        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11541                li != null ? li.mOnAttachStateChangeListeners : null;
11542        if (listeners != null && listeners.size() > 0) {
11543            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11544            // perform the dispatching. The iterator is a safe guard against listeners that
11545            // could mutate the list by calling the various add/remove methods. This prevents
11546            // the array from being modified while we iterate it.
11547            for (OnAttachStateChangeListener listener : listeners) {
11548                listener.onViewAttachedToWindow(this);
11549            }
11550        }
11551
11552        int vis = info.mWindowVisibility;
11553        if (vis != GONE) {
11554            onWindowVisibilityChanged(vis);
11555        }
11556        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11557            // If nobody has evaluated the drawable state yet, then do it now.
11558            refreshDrawableState();
11559        }
11560    }
11561
11562    void dispatchDetachedFromWindow() {
11563        AttachInfo info = mAttachInfo;
11564        if (info != null) {
11565            int vis = info.mWindowVisibility;
11566            if (vis != GONE) {
11567                onWindowVisibilityChanged(GONE);
11568            }
11569        }
11570
11571        onDetachedFromWindow();
11572
11573        ListenerInfo li = mListenerInfo;
11574        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11575                li != null ? li.mOnAttachStateChangeListeners : null;
11576        if (listeners != null && listeners.size() > 0) {
11577            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11578            // perform the dispatching. The iterator is a safe guard against listeners that
11579            // could mutate the list by calling the various add/remove methods. This prevents
11580            // the array from being modified while we iterate it.
11581            for (OnAttachStateChangeListener listener : listeners) {
11582                listener.onViewDetachedFromWindow(this);
11583            }
11584        }
11585
11586        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11587            mAttachInfo.mScrollContainers.remove(this);
11588            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11589        }
11590
11591        mAttachInfo = null;
11592    }
11593
11594    /**
11595     * Store this view hierarchy's frozen state into the given container.
11596     *
11597     * @param container The SparseArray in which to save the view's state.
11598     *
11599     * @see #restoreHierarchyState(android.util.SparseArray)
11600     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11601     * @see #onSaveInstanceState()
11602     */
11603    public void saveHierarchyState(SparseArray<Parcelable> container) {
11604        dispatchSaveInstanceState(container);
11605    }
11606
11607    /**
11608     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11609     * this view and its children. May be overridden to modify how freezing happens to a
11610     * view's children; for example, some views may want to not store state for their children.
11611     *
11612     * @param container The SparseArray in which to save the view's state.
11613     *
11614     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11615     * @see #saveHierarchyState(android.util.SparseArray)
11616     * @see #onSaveInstanceState()
11617     */
11618    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11619        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11620            mPrivateFlags &= ~SAVE_STATE_CALLED;
11621            Parcelable state = onSaveInstanceState();
11622            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11623                throw new IllegalStateException(
11624                        "Derived class did not call super.onSaveInstanceState()");
11625            }
11626            if (state != null) {
11627                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11628                // + ": " + state);
11629                container.put(mID, state);
11630            }
11631        }
11632    }
11633
11634    /**
11635     * Hook allowing a view to generate a representation of its internal state
11636     * that can later be used to create a new instance with that same state.
11637     * This state should only contain information that is not persistent or can
11638     * not be reconstructed later. For example, you will never store your
11639     * current position on screen because that will be computed again when a
11640     * new instance of the view is placed in its view hierarchy.
11641     * <p>
11642     * Some examples of things you may store here: the current cursor position
11643     * in a text view (but usually not the text itself since that is stored in a
11644     * content provider or other persistent storage), the currently selected
11645     * item in a list view.
11646     *
11647     * @return Returns a Parcelable object containing the view's current dynamic
11648     *         state, or null if there is nothing interesting to save. The
11649     *         default implementation returns null.
11650     * @see #onRestoreInstanceState(android.os.Parcelable)
11651     * @see #saveHierarchyState(android.util.SparseArray)
11652     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11653     * @see #setSaveEnabled(boolean)
11654     */
11655    protected Parcelable onSaveInstanceState() {
11656        mPrivateFlags |= SAVE_STATE_CALLED;
11657        return BaseSavedState.EMPTY_STATE;
11658    }
11659
11660    /**
11661     * Restore this view hierarchy's frozen state from the given container.
11662     *
11663     * @param container The SparseArray which holds previously frozen states.
11664     *
11665     * @see #saveHierarchyState(android.util.SparseArray)
11666     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11667     * @see #onRestoreInstanceState(android.os.Parcelable)
11668     */
11669    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11670        dispatchRestoreInstanceState(container);
11671    }
11672
11673    /**
11674     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11675     * state for this view and its children. May be overridden to modify how restoring
11676     * happens to a view's children; for example, some views may want to not store state
11677     * for their children.
11678     *
11679     * @param container The SparseArray which holds previously saved state.
11680     *
11681     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11682     * @see #restoreHierarchyState(android.util.SparseArray)
11683     * @see #onRestoreInstanceState(android.os.Parcelable)
11684     */
11685    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11686        if (mID != NO_ID) {
11687            Parcelable state = container.get(mID);
11688            if (state != null) {
11689                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11690                // + ": " + state);
11691                mPrivateFlags &= ~SAVE_STATE_CALLED;
11692                onRestoreInstanceState(state);
11693                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11694                    throw new IllegalStateException(
11695                            "Derived class did not call super.onRestoreInstanceState()");
11696                }
11697            }
11698        }
11699    }
11700
11701    /**
11702     * Hook allowing a view to re-apply a representation of its internal state that had previously
11703     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11704     * null state.
11705     *
11706     * @param state The frozen state that had previously been returned by
11707     *        {@link #onSaveInstanceState}.
11708     *
11709     * @see #onSaveInstanceState()
11710     * @see #restoreHierarchyState(android.util.SparseArray)
11711     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11712     */
11713    protected void onRestoreInstanceState(Parcelable state) {
11714        mPrivateFlags |= SAVE_STATE_CALLED;
11715        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11716            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11717                    + "received " + state.getClass().toString() + " instead. This usually happens "
11718                    + "when two views of different type have the same id in the same hierarchy. "
11719                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11720                    + "other views do not use the same id.");
11721        }
11722    }
11723
11724    /**
11725     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11726     *
11727     * @return the drawing start time in milliseconds
11728     */
11729    public long getDrawingTime() {
11730        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11731    }
11732
11733    /**
11734     * <p>Enables or disables the duplication of the parent's state into this view. When
11735     * duplication is enabled, this view gets its drawable state from its parent rather
11736     * than from its own internal properties.</p>
11737     *
11738     * <p>Note: in the current implementation, setting this property to true after the
11739     * view was added to a ViewGroup might have no effect at all. This property should
11740     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11741     *
11742     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11743     * property is enabled, an exception will be thrown.</p>
11744     *
11745     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11746     * parent, these states should not be affected by this method.</p>
11747     *
11748     * @param enabled True to enable duplication of the parent's drawable state, false
11749     *                to disable it.
11750     *
11751     * @see #getDrawableState()
11752     * @see #isDuplicateParentStateEnabled()
11753     */
11754    public void setDuplicateParentStateEnabled(boolean enabled) {
11755        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11756    }
11757
11758    /**
11759     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11760     *
11761     * @return True if this view's drawable state is duplicated from the parent,
11762     *         false otherwise
11763     *
11764     * @see #getDrawableState()
11765     * @see #setDuplicateParentStateEnabled(boolean)
11766     */
11767    public boolean isDuplicateParentStateEnabled() {
11768        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11769    }
11770
11771    /**
11772     * <p>Specifies the type of layer backing this view. The layer can be
11773     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11774     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11775     *
11776     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11777     * instance that controls how the layer is composed on screen. The following
11778     * properties of the paint are taken into account when composing the layer:</p>
11779     * <ul>
11780     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11781     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11782     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11783     * </ul>
11784     *
11785     * <p>If this view has an alpha value set to < 1.0 by calling
11786     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11787     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11788     * equivalent to setting a hardware layer on this view and providing a paint with
11789     * the desired alpha value.<p>
11790     *
11791     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11792     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11793     * for more information on when and how to use layers.</p>
11794     *
11795     * @param layerType The ype of layer to use with this view, must be one of
11796     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11797     *        {@link #LAYER_TYPE_HARDWARE}
11798     * @param paint The paint used to compose the layer. This argument is optional
11799     *        and can be null. It is ignored when the layer type is
11800     *        {@link #LAYER_TYPE_NONE}
11801     *
11802     * @see #getLayerType()
11803     * @see #LAYER_TYPE_NONE
11804     * @see #LAYER_TYPE_SOFTWARE
11805     * @see #LAYER_TYPE_HARDWARE
11806     * @see #setAlpha(float)
11807     *
11808     * @attr ref android.R.styleable#View_layerType
11809     */
11810    public void setLayerType(int layerType, Paint paint) {
11811        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11812            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11813                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11814        }
11815
11816        if (layerType == mLayerType) {
11817            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11818                mLayerPaint = paint == null ? new Paint() : paint;
11819                invalidateParentCaches();
11820                invalidate(true);
11821            }
11822            return;
11823        }
11824
11825        // Destroy any previous software drawing cache if needed
11826        switch (mLayerType) {
11827            case LAYER_TYPE_HARDWARE:
11828                destroyLayer(false);
11829                // fall through - non-accelerated views may use software layer mechanism instead
11830            case LAYER_TYPE_SOFTWARE:
11831                destroyDrawingCache();
11832                break;
11833            default:
11834                break;
11835        }
11836
11837        mLayerType = layerType;
11838        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11839        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11840        mLocalDirtyRect = layerDisabled ? null : new Rect();
11841
11842        invalidateParentCaches();
11843        invalidate(true);
11844    }
11845
11846    /**
11847     * Indicates whether this view has a static layer. A view with layer type
11848     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11849     * dynamic.
11850     */
11851    boolean hasStaticLayer() {
11852        return true;
11853    }
11854
11855    /**
11856     * Indicates what type of layer is currently associated with this view. By default
11857     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11858     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11859     * for more information on the different types of layers.
11860     *
11861     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11862     *         {@link #LAYER_TYPE_HARDWARE}
11863     *
11864     * @see #setLayerType(int, android.graphics.Paint)
11865     * @see #buildLayer()
11866     * @see #LAYER_TYPE_NONE
11867     * @see #LAYER_TYPE_SOFTWARE
11868     * @see #LAYER_TYPE_HARDWARE
11869     */
11870    public int getLayerType() {
11871        return mLayerType;
11872    }
11873
11874    /**
11875     * Forces this view's layer to be created and this view to be rendered
11876     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11877     * invoking this method will have no effect.
11878     *
11879     * This method can for instance be used to render a view into its layer before
11880     * starting an animation. If this view is complex, rendering into the layer
11881     * before starting the animation will avoid skipping frames.
11882     *
11883     * @throws IllegalStateException If this view is not attached to a window
11884     *
11885     * @see #setLayerType(int, android.graphics.Paint)
11886     */
11887    public void buildLayer() {
11888        if (mLayerType == LAYER_TYPE_NONE) return;
11889
11890        if (mAttachInfo == null) {
11891            throw new IllegalStateException("This view must be attached to a window first");
11892        }
11893
11894        switch (mLayerType) {
11895            case LAYER_TYPE_HARDWARE:
11896                if (mAttachInfo.mHardwareRenderer != null &&
11897                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11898                        mAttachInfo.mHardwareRenderer.validate()) {
11899                    getHardwareLayer();
11900                }
11901                break;
11902            case LAYER_TYPE_SOFTWARE:
11903                buildDrawingCache(true);
11904                break;
11905        }
11906    }
11907
11908    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11909    void flushLayer() {
11910        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11911            mHardwareLayer.flush();
11912        }
11913    }
11914
11915    /**
11916     * <p>Returns a hardware layer that can be used to draw this view again
11917     * without executing its draw method.</p>
11918     *
11919     * @return A HardwareLayer ready to render, or null if an error occurred.
11920     */
11921    HardwareLayer getHardwareLayer() {
11922        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11923                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11924            return null;
11925        }
11926
11927        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11928
11929        final int width = mRight - mLeft;
11930        final int height = mBottom - mTop;
11931
11932        if (width == 0 || height == 0) {
11933            return null;
11934        }
11935
11936        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11937            if (mHardwareLayer == null) {
11938                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11939                        width, height, isOpaque());
11940                mLocalDirtyRect.set(0, 0, width, height);
11941            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11942                mHardwareLayer.resize(width, height);
11943                mLocalDirtyRect.set(0, 0, width, height);
11944            }
11945
11946            // The layer is not valid if the underlying GPU resources cannot be allocated
11947            if (!mHardwareLayer.isValid()) {
11948                return null;
11949            }
11950
11951            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11952            mLocalDirtyRect.setEmpty();
11953        }
11954
11955        return mHardwareLayer;
11956    }
11957
11958    /**
11959     * Destroys this View's hardware layer if possible.
11960     *
11961     * @return True if the layer was destroyed, false otherwise.
11962     *
11963     * @see #setLayerType(int, android.graphics.Paint)
11964     * @see #LAYER_TYPE_HARDWARE
11965     */
11966    boolean destroyLayer(boolean valid) {
11967        if (mHardwareLayer != null) {
11968            AttachInfo info = mAttachInfo;
11969            if (info != null && info.mHardwareRenderer != null &&
11970                    info.mHardwareRenderer.isEnabled() &&
11971                    (valid || info.mHardwareRenderer.validate())) {
11972                mHardwareLayer.destroy();
11973                mHardwareLayer = null;
11974
11975                invalidate(true);
11976                invalidateParentCaches();
11977            }
11978            return true;
11979        }
11980        return false;
11981    }
11982
11983    /**
11984     * Destroys all hardware rendering resources. This method is invoked
11985     * when the system needs to reclaim resources. Upon execution of this
11986     * method, you should free any OpenGL resources created by the view.
11987     *
11988     * Note: you <strong>must</strong> call
11989     * <code>super.destroyHardwareResources()</code> when overriding
11990     * this method.
11991     *
11992     * @hide
11993     */
11994    protected void destroyHardwareResources() {
11995        destroyLayer(true);
11996    }
11997
11998    /**
11999     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12000     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12001     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12002     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12003     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12004     * null.</p>
12005     *
12006     * <p>Enabling the drawing cache is similar to
12007     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12008     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12009     * drawing cache has no effect on rendering because the system uses a different mechanism
12010     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12011     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12012     * for information on how to enable software and hardware layers.</p>
12013     *
12014     * <p>This API can be used to manually generate
12015     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12016     * {@link #getDrawingCache()}.</p>
12017     *
12018     * @param enabled true to enable the drawing cache, false otherwise
12019     *
12020     * @see #isDrawingCacheEnabled()
12021     * @see #getDrawingCache()
12022     * @see #buildDrawingCache()
12023     * @see #setLayerType(int, android.graphics.Paint)
12024     */
12025    public void setDrawingCacheEnabled(boolean enabled) {
12026        mCachingFailed = false;
12027        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12028    }
12029
12030    /**
12031     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12032     *
12033     * @return true if the drawing cache is enabled
12034     *
12035     * @see #setDrawingCacheEnabled(boolean)
12036     * @see #getDrawingCache()
12037     */
12038    @ViewDebug.ExportedProperty(category = "drawing")
12039    public boolean isDrawingCacheEnabled() {
12040        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12041    }
12042
12043    /**
12044     * Debugging utility which recursively outputs the dirty state of a view and its
12045     * descendants.
12046     *
12047     * @hide
12048     */
12049    @SuppressWarnings({"UnusedDeclaration"})
12050    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12051        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12052                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12053                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12054                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12055        if (clear) {
12056            mPrivateFlags &= clearMask;
12057        }
12058        if (this instanceof ViewGroup) {
12059            ViewGroup parent = (ViewGroup) this;
12060            final int count = parent.getChildCount();
12061            for (int i = 0; i < count; i++) {
12062                final View child = parent.getChildAt(i);
12063                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12064            }
12065        }
12066    }
12067
12068    /**
12069     * This method is used by ViewGroup to cause its children to restore or recreate their
12070     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12071     * to recreate its own display list, which would happen if it went through the normal
12072     * draw/dispatchDraw mechanisms.
12073     *
12074     * @hide
12075     */
12076    protected void dispatchGetDisplayList() {}
12077
12078    /**
12079     * A view that is not attached or hardware accelerated cannot create a display list.
12080     * This method checks these conditions and returns the appropriate result.
12081     *
12082     * @return true if view has the ability to create a display list, false otherwise.
12083     *
12084     * @hide
12085     */
12086    public boolean canHaveDisplayList() {
12087        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12088    }
12089
12090    /**
12091     * @return The HardwareRenderer associated with that view or null if hardware rendering
12092     * is not supported or this this has not been attached to a window.
12093     *
12094     * @hide
12095     */
12096    public HardwareRenderer getHardwareRenderer() {
12097        if (mAttachInfo != null) {
12098            return mAttachInfo.mHardwareRenderer;
12099        }
12100        return null;
12101    }
12102
12103    /**
12104     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12105     * Otherwise, the same display list will be returned (after having been rendered into
12106     * along the way, depending on the invalidation state of the view).
12107     *
12108     * @param displayList The previous version of this displayList, could be null.
12109     * @param isLayer Whether the requester of the display list is a layer. If so,
12110     * the view will avoid creating a layer inside the resulting display list.
12111     * @return A new or reused DisplayList object.
12112     */
12113    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12114        if (!canHaveDisplayList()) {
12115            return null;
12116        }
12117
12118        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12119                displayList == null || !displayList.isValid() ||
12120                (!isLayer && mRecreateDisplayList))) {
12121            // Don't need to recreate the display list, just need to tell our
12122            // children to restore/recreate theirs
12123            if (displayList != null && displayList.isValid() &&
12124                    !isLayer && !mRecreateDisplayList) {
12125                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12126                mPrivateFlags &= ~DIRTY_MASK;
12127                dispatchGetDisplayList();
12128
12129                return displayList;
12130            }
12131
12132            if (!isLayer) {
12133                // If we got here, we're recreating it. Mark it as such to ensure that
12134                // we copy in child display lists into ours in drawChild()
12135                mRecreateDisplayList = true;
12136            }
12137            if (displayList == null) {
12138                final String name = getClass().getSimpleName();
12139                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12140                // If we're creating a new display list, make sure our parent gets invalidated
12141                // since they will need to recreate their display list to account for this
12142                // new child display list.
12143                invalidateParentCaches();
12144            }
12145
12146            boolean caching = false;
12147            final HardwareCanvas canvas = displayList.start();
12148            int width = mRight - mLeft;
12149            int height = mBottom - mTop;
12150
12151            try {
12152                canvas.setViewport(width, height);
12153                // The dirty rect should always be null for a display list
12154                canvas.onPreDraw(null);
12155                int layerType = (
12156                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12157                        getLayerType() : LAYER_TYPE_NONE;
12158                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12159                    if (layerType == LAYER_TYPE_HARDWARE) {
12160                        final HardwareLayer layer = getHardwareLayer();
12161                        if (layer != null && layer.isValid()) {
12162                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12163                        } else {
12164                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12165                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12166                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12167                        }
12168                        caching = true;
12169                    } else {
12170                        buildDrawingCache(true);
12171                        Bitmap cache = getDrawingCache(true);
12172                        if (cache != null) {
12173                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12174                            caching = true;
12175                        }
12176                    }
12177                } else {
12178
12179                    computeScroll();
12180
12181                    canvas.translate(-mScrollX, -mScrollY);
12182                    if (!isLayer) {
12183                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12184                        mPrivateFlags &= ~DIRTY_MASK;
12185                    }
12186
12187                    // Fast path for layouts with no backgrounds
12188                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12189                        dispatchDraw(canvas);
12190                    } else {
12191                        draw(canvas);
12192                    }
12193                }
12194            } finally {
12195                canvas.onPostDraw();
12196
12197                displayList.end();
12198                displayList.setCaching(caching);
12199                if (isLayer) {
12200                    displayList.setLeftTopRightBottom(0, 0, width, height);
12201                } else {
12202                    setDisplayListProperties(displayList);
12203                }
12204            }
12205        } else if (!isLayer) {
12206            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12207            mPrivateFlags &= ~DIRTY_MASK;
12208        }
12209
12210        return displayList;
12211    }
12212
12213    /**
12214     * Get the DisplayList for the HardwareLayer
12215     *
12216     * @param layer The HardwareLayer whose DisplayList we want
12217     * @return A DisplayList fopr the specified HardwareLayer
12218     */
12219    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12220        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12221        layer.setDisplayList(displayList);
12222        return displayList;
12223    }
12224
12225
12226    /**
12227     * <p>Returns a display list that can be used to draw this view again
12228     * without executing its draw method.</p>
12229     *
12230     * @return A DisplayList ready to replay, or null if caching is not enabled.
12231     *
12232     * @hide
12233     */
12234    public DisplayList getDisplayList() {
12235        mDisplayList = getDisplayList(mDisplayList, false);
12236        return mDisplayList;
12237    }
12238
12239    /**
12240     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12241     *
12242     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12243     *
12244     * @see #getDrawingCache(boolean)
12245     */
12246    public Bitmap getDrawingCache() {
12247        return getDrawingCache(false);
12248    }
12249
12250    /**
12251     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12252     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12253     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12254     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12255     * request the drawing cache by calling this method and draw it on screen if the
12256     * returned bitmap is not null.</p>
12257     *
12258     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12259     * this method will create a bitmap of the same size as this view. Because this bitmap
12260     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12261     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12262     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12263     * size than the view. This implies that your application must be able to handle this
12264     * size.</p>
12265     *
12266     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12267     *        the current density of the screen when the application is in compatibility
12268     *        mode.
12269     *
12270     * @return A bitmap representing this view or null if cache is disabled.
12271     *
12272     * @see #setDrawingCacheEnabled(boolean)
12273     * @see #isDrawingCacheEnabled()
12274     * @see #buildDrawingCache(boolean)
12275     * @see #destroyDrawingCache()
12276     */
12277    public Bitmap getDrawingCache(boolean autoScale) {
12278        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12279            return null;
12280        }
12281        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12282            buildDrawingCache(autoScale);
12283        }
12284        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12285    }
12286
12287    /**
12288     * <p>Frees the resources used by the drawing cache. If you call
12289     * {@link #buildDrawingCache()} manually without calling
12290     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12291     * should cleanup the cache with this method afterwards.</p>
12292     *
12293     * @see #setDrawingCacheEnabled(boolean)
12294     * @see #buildDrawingCache()
12295     * @see #getDrawingCache()
12296     */
12297    public void destroyDrawingCache() {
12298        if (mDrawingCache != null) {
12299            mDrawingCache.recycle();
12300            mDrawingCache = null;
12301        }
12302        if (mUnscaledDrawingCache != null) {
12303            mUnscaledDrawingCache.recycle();
12304            mUnscaledDrawingCache = null;
12305        }
12306    }
12307
12308    /**
12309     * Setting a solid background color for the drawing cache's bitmaps will improve
12310     * performance and memory usage. Note, though that this should only be used if this
12311     * view will always be drawn on top of a solid color.
12312     *
12313     * @param color The background color to use for the drawing cache's bitmap
12314     *
12315     * @see #setDrawingCacheEnabled(boolean)
12316     * @see #buildDrawingCache()
12317     * @see #getDrawingCache()
12318     */
12319    public void setDrawingCacheBackgroundColor(int color) {
12320        if (color != mDrawingCacheBackgroundColor) {
12321            mDrawingCacheBackgroundColor = color;
12322            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12323        }
12324    }
12325
12326    /**
12327     * @see #setDrawingCacheBackgroundColor(int)
12328     *
12329     * @return The background color to used for the drawing cache's bitmap
12330     */
12331    public int getDrawingCacheBackgroundColor() {
12332        return mDrawingCacheBackgroundColor;
12333    }
12334
12335    /**
12336     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12337     *
12338     * @see #buildDrawingCache(boolean)
12339     */
12340    public void buildDrawingCache() {
12341        buildDrawingCache(false);
12342    }
12343
12344    /**
12345     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12346     *
12347     * <p>If you call {@link #buildDrawingCache()} manually without calling
12348     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12349     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12350     *
12351     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12352     * this method will create a bitmap of the same size as this view. Because this bitmap
12353     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12354     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12355     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12356     * size than the view. This implies that your application must be able to handle this
12357     * size.</p>
12358     *
12359     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12360     * you do not need the drawing cache bitmap, calling this method will increase memory
12361     * usage and cause the view to be rendered in software once, thus negatively impacting
12362     * performance.</p>
12363     *
12364     * @see #getDrawingCache()
12365     * @see #destroyDrawingCache()
12366     */
12367    public void buildDrawingCache(boolean autoScale) {
12368        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12369                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12370            mCachingFailed = false;
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                mPrivateFlags &= ~DIRTY_MASK;
12492                dispatchDraw(canvas);
12493            } else {
12494                draw(canvas);
12495            }
12496
12497            canvas.restoreToCount(restoreCount);
12498            canvas.setBitmap(null);
12499
12500            if (attachInfo != null) {
12501                // Restore the cached Canvas for our siblings
12502                attachInfo.mCanvas = canvas;
12503            }
12504        }
12505    }
12506
12507    /**
12508     * Create a snapshot of the view into a bitmap.  We should probably make
12509     * some form of this public, but should think about the API.
12510     */
12511    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12512        int width = mRight - mLeft;
12513        int height = mBottom - mTop;
12514
12515        final AttachInfo attachInfo = mAttachInfo;
12516        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12517        width = (int) ((width * scale) + 0.5f);
12518        height = (int) ((height * scale) + 0.5f);
12519
12520        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12521        if (bitmap == null) {
12522            throw new OutOfMemoryError();
12523        }
12524
12525        Resources resources = getResources();
12526        if (resources != null) {
12527            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12528        }
12529
12530        Canvas canvas;
12531        if (attachInfo != null) {
12532            canvas = attachInfo.mCanvas;
12533            if (canvas == null) {
12534                canvas = new Canvas();
12535            }
12536            canvas.setBitmap(bitmap);
12537            // Temporarily clobber the cached Canvas in case one of our children
12538            // is also using a drawing cache. Without this, the children would
12539            // steal the canvas by attaching their own bitmap to it and bad, bad
12540            // things would happen (invisible views, corrupted drawings, etc.)
12541            attachInfo.mCanvas = null;
12542        } else {
12543            // This case should hopefully never or seldom happen
12544            canvas = new Canvas(bitmap);
12545        }
12546
12547        if ((backgroundColor & 0xff000000) != 0) {
12548            bitmap.eraseColor(backgroundColor);
12549        }
12550
12551        computeScroll();
12552        final int restoreCount = canvas.save();
12553        canvas.scale(scale, scale);
12554        canvas.translate(-mScrollX, -mScrollY);
12555
12556        // Temporarily remove the dirty mask
12557        int flags = mPrivateFlags;
12558        mPrivateFlags &= ~DIRTY_MASK;
12559
12560        // Fast path for layouts with no backgrounds
12561        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12562            dispatchDraw(canvas);
12563        } else {
12564            draw(canvas);
12565        }
12566
12567        mPrivateFlags = flags;
12568
12569        canvas.restoreToCount(restoreCount);
12570        canvas.setBitmap(null);
12571
12572        if (attachInfo != null) {
12573            // Restore the cached Canvas for our siblings
12574            attachInfo.mCanvas = canvas;
12575        }
12576
12577        return bitmap;
12578    }
12579
12580    /**
12581     * Indicates whether this View is currently in edit mode. A View is usually
12582     * in edit mode when displayed within a developer tool. For instance, if
12583     * this View is being drawn by a visual user interface builder, this method
12584     * should return true.
12585     *
12586     * Subclasses should check the return value of this method to provide
12587     * different behaviors if their normal behavior might interfere with the
12588     * host environment. For instance: the class spawns a thread in its
12589     * constructor, the drawing code relies on device-specific features, etc.
12590     *
12591     * This method is usually checked in the drawing code of custom widgets.
12592     *
12593     * @return True if this View is in edit mode, false otherwise.
12594     */
12595    public boolean isInEditMode() {
12596        return false;
12597    }
12598
12599    /**
12600     * If the View draws content inside its padding and enables fading edges,
12601     * it needs to support padding offsets. Padding offsets are added to the
12602     * fading edges to extend the length of the fade so that it covers pixels
12603     * drawn inside the padding.
12604     *
12605     * Subclasses of this class should override this method if they need
12606     * to draw content inside the padding.
12607     *
12608     * @return True if padding offset must be applied, false otherwise.
12609     *
12610     * @see #getLeftPaddingOffset()
12611     * @see #getRightPaddingOffset()
12612     * @see #getTopPaddingOffset()
12613     * @see #getBottomPaddingOffset()
12614     *
12615     * @since CURRENT
12616     */
12617    protected boolean isPaddingOffsetRequired() {
12618        return false;
12619    }
12620
12621    /**
12622     * Amount by which to extend the left fading region. Called only when
12623     * {@link #isPaddingOffsetRequired()} returns true.
12624     *
12625     * @return The left padding offset in pixels.
12626     *
12627     * @see #isPaddingOffsetRequired()
12628     *
12629     * @since CURRENT
12630     */
12631    protected int getLeftPaddingOffset() {
12632        return 0;
12633    }
12634
12635    /**
12636     * Amount by which to extend the right fading region. Called only when
12637     * {@link #isPaddingOffsetRequired()} returns true.
12638     *
12639     * @return The right padding offset in pixels.
12640     *
12641     * @see #isPaddingOffsetRequired()
12642     *
12643     * @since CURRENT
12644     */
12645    protected int getRightPaddingOffset() {
12646        return 0;
12647    }
12648
12649    /**
12650     * Amount by which to extend the top fading region. Called only when
12651     * {@link #isPaddingOffsetRequired()} returns true.
12652     *
12653     * @return The top padding offset in pixels.
12654     *
12655     * @see #isPaddingOffsetRequired()
12656     *
12657     * @since CURRENT
12658     */
12659    protected int getTopPaddingOffset() {
12660        return 0;
12661    }
12662
12663    /**
12664     * Amount by which to extend the bottom fading region. Called only when
12665     * {@link #isPaddingOffsetRequired()} returns true.
12666     *
12667     * @return The bottom padding offset in pixels.
12668     *
12669     * @see #isPaddingOffsetRequired()
12670     *
12671     * @since CURRENT
12672     */
12673    protected int getBottomPaddingOffset() {
12674        return 0;
12675    }
12676
12677    /**
12678     * @hide
12679     * @param offsetRequired
12680     */
12681    protected int getFadeTop(boolean offsetRequired) {
12682        int top = mPaddingTop;
12683        if (offsetRequired) top += getTopPaddingOffset();
12684        return top;
12685    }
12686
12687    /**
12688     * @hide
12689     * @param offsetRequired
12690     */
12691    protected int getFadeHeight(boolean offsetRequired) {
12692        int padding = mPaddingTop;
12693        if (offsetRequired) padding += getTopPaddingOffset();
12694        return mBottom - mTop - mPaddingBottom - padding;
12695    }
12696
12697    /**
12698     * <p>Indicates whether this view is attached to a hardware accelerated
12699     * window or not.</p>
12700     *
12701     * <p>Even if this method returns true, it does not mean that every call
12702     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12703     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12704     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12705     * window is hardware accelerated,
12706     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12707     * return false, and this method will return true.</p>
12708     *
12709     * @return True if the view is attached to a window and the window is
12710     *         hardware accelerated; false in any other case.
12711     */
12712    public boolean isHardwareAccelerated() {
12713        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12714    }
12715
12716    /**
12717     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12718     * case of an active Animation being run on the view.
12719     */
12720    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12721            Animation a, boolean scalingRequired) {
12722        Transformation invalidationTransform;
12723        final int flags = parent.mGroupFlags;
12724        final boolean initialized = a.isInitialized();
12725        if (!initialized) {
12726            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12727            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12728            onAnimationStart();
12729        }
12730
12731        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12732        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12733            if (parent.mInvalidationTransformation == null) {
12734                parent.mInvalidationTransformation = new Transformation();
12735            }
12736            invalidationTransform = parent.mInvalidationTransformation;
12737            a.getTransformation(drawingTime, invalidationTransform, 1f);
12738        } else {
12739            invalidationTransform = parent.mChildTransformation;
12740        }
12741        if (more) {
12742            if (!a.willChangeBounds()) {
12743                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12744                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12745                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12746                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12747                    // The child need to draw an animation, potentially offscreen, so
12748                    // make sure we do not cancel invalidate requests
12749                    parent.mPrivateFlags |= DRAW_ANIMATION;
12750                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12751                }
12752            } else {
12753                if (parent.mInvalidateRegion == null) {
12754                    parent.mInvalidateRegion = new RectF();
12755                }
12756                final RectF region = parent.mInvalidateRegion;
12757                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12758                        invalidationTransform);
12759
12760                // The child need to draw an animation, potentially offscreen, so
12761                // make sure we do not cancel invalidate requests
12762                parent.mPrivateFlags |= DRAW_ANIMATION;
12763
12764                final int left = mLeft + (int) region.left;
12765                final int top = mTop + (int) region.top;
12766                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12767                        top + (int) (region.height() + .5f));
12768            }
12769        }
12770        return more;
12771    }
12772
12773    /**
12774     * This method is called by getDisplayList() when a display list is created or re-rendered.
12775     * It sets or resets the current value of all properties on that display list (resetting is
12776     * necessary when a display list is being re-created, because we need to make sure that
12777     * previously-set transform values
12778     */
12779    void setDisplayListProperties(DisplayList displayList) {
12780        if (displayList != null) {
12781            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12782            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12783            if (mParent instanceof ViewGroup) {
12784                displayList.setClipChildren(
12785                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12786            }
12787            float alpha = 1;
12788            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12789                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12790                ViewGroup parentVG = (ViewGroup) mParent;
12791                final boolean hasTransform =
12792                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12793                if (hasTransform) {
12794                    Transformation transform = parentVG.mChildTransformation;
12795                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12796                    if (transformType != Transformation.TYPE_IDENTITY) {
12797                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12798                            alpha = transform.getAlpha();
12799                        }
12800                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12801                            displayList.setStaticMatrix(transform.getMatrix());
12802                        }
12803                    }
12804                }
12805            }
12806            if (mTransformationInfo != null) {
12807                alpha *= mTransformationInfo.mAlpha;
12808                if (alpha < 1) {
12809                    final int multipliedAlpha = (int) (255 * alpha);
12810                    if (onSetAlpha(multipliedAlpha)) {
12811                        alpha = 1;
12812                    }
12813                }
12814                displayList.setTransformationInfo(alpha,
12815                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12816                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12817                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12818                        mTransformationInfo.mScaleY);
12819                if (mTransformationInfo.mCamera == null) {
12820                    mTransformationInfo.mCamera = new Camera();
12821                    mTransformationInfo.matrix3D = new Matrix();
12822                }
12823                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12824                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12825                    displayList.setPivotX(getPivotX());
12826                    displayList.setPivotY(getPivotY());
12827                }
12828            } else if (alpha < 1) {
12829                displayList.setAlpha(alpha);
12830            }
12831        }
12832    }
12833
12834    /**
12835     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12836     * This draw() method is an implementation detail and is not intended to be overridden or
12837     * to be called from anywhere else other than ViewGroup.drawChild().
12838     */
12839    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12840        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12841        boolean more = false;
12842        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12843        final int flags = parent.mGroupFlags;
12844
12845        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12846            parent.mChildTransformation.clear();
12847            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12848        }
12849
12850        Transformation transformToApply = null;
12851        boolean concatMatrix = false;
12852
12853        boolean scalingRequired = false;
12854        boolean caching;
12855        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12856
12857        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12858        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12859                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12860            caching = true;
12861            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12862            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12863        } else {
12864            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12865        }
12866
12867        final Animation a = getAnimation();
12868        if (a != null) {
12869            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12870            concatMatrix = a.willChangeTransformationMatrix();
12871            if (concatMatrix) {
12872                mPrivateFlags2 |= VIEW_IS_ANIMATING_TRANSFORM;
12873            }
12874            transformToApply = parent.mChildTransformation;
12875        } else {
12876            if ((mPrivateFlags2 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
12877                    mDisplayList != null) {
12878                // No longer animating: clear out old animation matrix
12879                mDisplayList.setAnimationMatrix(null);
12880                mPrivateFlags2 &= ~VIEW_IS_ANIMATING_TRANSFORM;
12881            }
12882            if (!useDisplayListProperties &&
12883                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12884                final boolean hasTransform =
12885                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
12886                if (hasTransform) {
12887                    final int transformType = parent.mChildTransformation.getTransformationType();
12888                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12889                            parent.mChildTransformation : null;
12890                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12891                }
12892            }
12893        }
12894
12895        concatMatrix |= !childHasIdentityMatrix;
12896
12897        // Sets the flag as early as possible to allow draw() implementations
12898        // to call invalidate() successfully when doing animations
12899        mPrivateFlags |= DRAWN;
12900
12901        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12902                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12903            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
12904            return more;
12905        }
12906        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
12907
12908        if (hardwareAccelerated) {
12909            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12910            // retain the flag's value temporarily in the mRecreateDisplayList flag
12911            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12912            mPrivateFlags &= ~INVALIDATED;
12913        }
12914
12915        computeScroll();
12916
12917        final int sx = mScrollX;
12918        final int sy = mScrollY;
12919
12920        DisplayList displayList = null;
12921        Bitmap cache = null;
12922        boolean hasDisplayList = false;
12923        if (caching) {
12924            if (!hardwareAccelerated) {
12925                if (layerType != LAYER_TYPE_NONE) {
12926                    layerType = LAYER_TYPE_SOFTWARE;
12927                    buildDrawingCache(true);
12928                }
12929                cache = getDrawingCache(true);
12930            } else {
12931                switch (layerType) {
12932                    case LAYER_TYPE_SOFTWARE:
12933                        if (useDisplayListProperties) {
12934                            hasDisplayList = canHaveDisplayList();
12935                        } else {
12936                            buildDrawingCache(true);
12937                            cache = getDrawingCache(true);
12938                        }
12939                        break;
12940                    case LAYER_TYPE_HARDWARE:
12941                        if (useDisplayListProperties) {
12942                            hasDisplayList = canHaveDisplayList();
12943                        }
12944                        break;
12945                    case LAYER_TYPE_NONE:
12946                        // Delay getting the display list until animation-driven alpha values are
12947                        // set up and possibly passed on to the view
12948                        hasDisplayList = canHaveDisplayList();
12949                        break;
12950                }
12951            }
12952        }
12953        useDisplayListProperties &= hasDisplayList;
12954        if (useDisplayListProperties) {
12955            displayList = getDisplayList();
12956            if (!displayList.isValid()) {
12957                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12958                // to getDisplayList(), the display list will be marked invalid and we should not
12959                // try to use it again.
12960                displayList = null;
12961                hasDisplayList = false;
12962                useDisplayListProperties = false;
12963            }
12964        }
12965
12966        final boolean hasNoCache = cache == null || hasDisplayList;
12967        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12968                layerType != LAYER_TYPE_HARDWARE;
12969
12970        int restoreTo = -1;
12971        if (!useDisplayListProperties || transformToApply != null) {
12972            restoreTo = canvas.save();
12973        }
12974        if (offsetForScroll) {
12975            canvas.translate(mLeft - sx, mTop - sy);
12976        } else {
12977            if (!useDisplayListProperties) {
12978                canvas.translate(mLeft, mTop);
12979            }
12980            if (scalingRequired) {
12981                if (useDisplayListProperties) {
12982                    // TODO: Might not need this if we put everything inside the DL
12983                    restoreTo = canvas.save();
12984                }
12985                // mAttachInfo cannot be null, otherwise scalingRequired == false
12986                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12987                canvas.scale(scale, scale);
12988            }
12989        }
12990
12991        float alpha = useDisplayListProperties ? 1 : getAlpha();
12992        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12993            if (transformToApply != null || !childHasIdentityMatrix) {
12994                int transX = 0;
12995                int transY = 0;
12996
12997                if (offsetForScroll) {
12998                    transX = -sx;
12999                    transY = -sy;
13000                }
13001
13002                if (transformToApply != null) {
13003                    if (concatMatrix) {
13004                        if (useDisplayListProperties) {
13005                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13006                        } else {
13007                            // Undo the scroll translation, apply the transformation matrix,
13008                            // then redo the scroll translate to get the correct result.
13009                            canvas.translate(-transX, -transY);
13010                            canvas.concat(transformToApply.getMatrix());
13011                            canvas.translate(transX, transY);
13012                        }
13013                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13014                    }
13015
13016                    float transformAlpha = transformToApply.getAlpha();
13017                    if (transformAlpha < 1) {
13018                        alpha *= transformToApply.getAlpha();
13019                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13020                    }
13021                }
13022
13023                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13024                    canvas.translate(-transX, -transY);
13025                    canvas.concat(getMatrix());
13026                    canvas.translate(transX, transY);
13027                }
13028            }
13029
13030            if (alpha < 1) {
13031                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13032                if (hasNoCache) {
13033                    final int multipliedAlpha = (int) (255 * alpha);
13034                    if (!onSetAlpha(multipliedAlpha)) {
13035                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13036                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13037                                layerType != LAYER_TYPE_NONE) {
13038                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13039                        }
13040                        if (useDisplayListProperties) {
13041                            displayList.setAlpha(alpha * getAlpha());
13042                        } else  if (layerType == LAYER_TYPE_NONE) {
13043                            final int scrollX = hasDisplayList ? 0 : sx;
13044                            final int scrollY = hasDisplayList ? 0 : sy;
13045                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13046                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13047                        }
13048                    } else {
13049                        // Alpha is handled by the child directly, clobber the layer's alpha
13050                        mPrivateFlags |= ALPHA_SET;
13051                    }
13052                }
13053            }
13054        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13055            onSetAlpha(255);
13056            mPrivateFlags &= ~ALPHA_SET;
13057        }
13058
13059        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13060                !useDisplayListProperties) {
13061            if (offsetForScroll) {
13062                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13063            } else {
13064                if (!scalingRequired || cache == null) {
13065                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13066                } else {
13067                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13068                }
13069            }
13070        }
13071
13072        if (!useDisplayListProperties && hasDisplayList) {
13073            displayList = getDisplayList();
13074            if (!displayList.isValid()) {
13075                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13076                // to getDisplayList(), the display list will be marked invalid and we should not
13077                // try to use it again.
13078                displayList = null;
13079                hasDisplayList = false;
13080            }
13081        }
13082
13083        if (hasNoCache) {
13084            boolean layerRendered = false;
13085            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13086                final HardwareLayer layer = getHardwareLayer();
13087                if (layer != null && layer.isValid()) {
13088                    mLayerPaint.setAlpha((int) (alpha * 255));
13089                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13090                    layerRendered = true;
13091                } else {
13092                    final int scrollX = hasDisplayList ? 0 : sx;
13093                    final int scrollY = hasDisplayList ? 0 : sy;
13094                    canvas.saveLayer(scrollX, scrollY,
13095                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13096                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13097                }
13098            }
13099
13100            if (!layerRendered) {
13101                if (!hasDisplayList) {
13102                    // Fast path for layouts with no backgrounds
13103                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13104                        mPrivateFlags &= ~DIRTY_MASK;
13105                        dispatchDraw(canvas);
13106                    } else {
13107                        draw(canvas);
13108                    }
13109                } else {
13110                    mPrivateFlags &= ~DIRTY_MASK;
13111                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13112                }
13113            }
13114        } else if (cache != null) {
13115            mPrivateFlags &= ~DIRTY_MASK;
13116            Paint cachePaint;
13117
13118            if (layerType == LAYER_TYPE_NONE) {
13119                cachePaint = parent.mCachePaint;
13120                if (cachePaint == null) {
13121                    cachePaint = new Paint();
13122                    cachePaint.setDither(false);
13123                    parent.mCachePaint = cachePaint;
13124                }
13125                if (alpha < 1) {
13126                    cachePaint.setAlpha((int) (alpha * 255));
13127                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13128                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13129                    cachePaint.setAlpha(255);
13130                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13131                }
13132            } else {
13133                cachePaint = mLayerPaint;
13134                cachePaint.setAlpha((int) (alpha * 255));
13135            }
13136            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13137        }
13138
13139        if (restoreTo >= 0) {
13140            canvas.restoreToCount(restoreTo);
13141        }
13142
13143        if (a != null && !more) {
13144            if (!hardwareAccelerated && !a.getFillAfter()) {
13145                onSetAlpha(255);
13146            }
13147            parent.finishAnimatingView(this, a);
13148        }
13149
13150        if (more && hardwareAccelerated) {
13151            // invalidation is the trigger to recreate display lists, so if we're using
13152            // display lists to render, force an invalidate to allow the animation to
13153            // continue drawing another frame
13154            parent.invalidate(true);
13155            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13156                // alpha animations should cause the child to recreate its display list
13157                invalidate(true);
13158            }
13159        }
13160
13161        mRecreateDisplayList = false;
13162
13163        return more;
13164    }
13165
13166    /**
13167     * Manually render this view (and all of its children) to the given Canvas.
13168     * The view must have already done a full layout before this function is
13169     * called.  When implementing a view, implement
13170     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13171     * If you do need to override this method, call the superclass version.
13172     *
13173     * @param canvas The Canvas to which the View is rendered.
13174     */
13175    public void draw(Canvas canvas) {
13176        final int privateFlags = mPrivateFlags;
13177        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13178                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13179        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13180
13181        /*
13182         * Draw traversal performs several drawing steps which must be executed
13183         * in the appropriate order:
13184         *
13185         *      1. Draw the background
13186         *      2. If necessary, save the canvas' layers to prepare for fading
13187         *      3. Draw view's content
13188         *      4. Draw children
13189         *      5. If necessary, draw the fading edges and restore layers
13190         *      6. Draw decorations (scrollbars for instance)
13191         */
13192
13193        // Step 1, draw the background, if needed
13194        int saveCount;
13195
13196        if (!dirtyOpaque) {
13197            final Drawable background = mBackground;
13198            if (background != null) {
13199                final int scrollX = mScrollX;
13200                final int scrollY = mScrollY;
13201
13202                if (mBackgroundSizeChanged) {
13203                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13204                    mBackgroundSizeChanged = false;
13205                }
13206
13207                if ((scrollX | scrollY) == 0) {
13208                    background.draw(canvas);
13209                } else {
13210                    canvas.translate(scrollX, scrollY);
13211                    background.draw(canvas);
13212                    canvas.translate(-scrollX, -scrollY);
13213                }
13214            }
13215        }
13216
13217        // skip step 2 & 5 if possible (common case)
13218        final int viewFlags = mViewFlags;
13219        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13220        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13221        if (!verticalEdges && !horizontalEdges) {
13222            // Step 3, draw the content
13223            if (!dirtyOpaque) onDraw(canvas);
13224
13225            // Step 4, draw the children
13226            dispatchDraw(canvas);
13227
13228            // Step 6, draw decorations (scrollbars)
13229            onDrawScrollBars(canvas);
13230
13231            // we're done...
13232            return;
13233        }
13234
13235        /*
13236         * Here we do the full fledged routine...
13237         * (this is an uncommon case where speed matters less,
13238         * this is why we repeat some of the tests that have been
13239         * done above)
13240         */
13241
13242        boolean drawTop = false;
13243        boolean drawBottom = false;
13244        boolean drawLeft = false;
13245        boolean drawRight = false;
13246
13247        float topFadeStrength = 0.0f;
13248        float bottomFadeStrength = 0.0f;
13249        float leftFadeStrength = 0.0f;
13250        float rightFadeStrength = 0.0f;
13251
13252        // Step 2, save the canvas' layers
13253        int paddingLeft = mPaddingLeft;
13254
13255        final boolean offsetRequired = isPaddingOffsetRequired();
13256        if (offsetRequired) {
13257            paddingLeft += getLeftPaddingOffset();
13258        }
13259
13260        int left = mScrollX + paddingLeft;
13261        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13262        int top = mScrollY + getFadeTop(offsetRequired);
13263        int bottom = top + getFadeHeight(offsetRequired);
13264
13265        if (offsetRequired) {
13266            right += getRightPaddingOffset();
13267            bottom += getBottomPaddingOffset();
13268        }
13269
13270        final ScrollabilityCache scrollabilityCache = mScrollCache;
13271        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13272        int length = (int) fadeHeight;
13273
13274        // clip the fade length if top and bottom fades overlap
13275        // overlapping fades produce odd-looking artifacts
13276        if (verticalEdges && (top + length > bottom - length)) {
13277            length = (bottom - top) / 2;
13278        }
13279
13280        // also clip horizontal fades if necessary
13281        if (horizontalEdges && (left + length > right - length)) {
13282            length = (right - left) / 2;
13283        }
13284
13285        if (verticalEdges) {
13286            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13287            drawTop = topFadeStrength * fadeHeight > 1.0f;
13288            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13289            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13290        }
13291
13292        if (horizontalEdges) {
13293            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13294            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13295            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13296            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13297        }
13298
13299        saveCount = canvas.getSaveCount();
13300
13301        int solidColor = getSolidColor();
13302        if (solidColor == 0) {
13303            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13304
13305            if (drawTop) {
13306                canvas.saveLayer(left, top, right, top + length, null, flags);
13307            }
13308
13309            if (drawBottom) {
13310                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13311            }
13312
13313            if (drawLeft) {
13314                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13315            }
13316
13317            if (drawRight) {
13318                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13319            }
13320        } else {
13321            scrollabilityCache.setFadeColor(solidColor);
13322        }
13323
13324        // Step 3, draw the content
13325        if (!dirtyOpaque) onDraw(canvas);
13326
13327        // Step 4, draw the children
13328        dispatchDraw(canvas);
13329
13330        // Step 5, draw the fade effect and restore layers
13331        final Paint p = scrollabilityCache.paint;
13332        final Matrix matrix = scrollabilityCache.matrix;
13333        final Shader fade = scrollabilityCache.shader;
13334
13335        if (drawTop) {
13336            matrix.setScale(1, fadeHeight * topFadeStrength);
13337            matrix.postTranslate(left, top);
13338            fade.setLocalMatrix(matrix);
13339            canvas.drawRect(left, top, right, top + length, p);
13340        }
13341
13342        if (drawBottom) {
13343            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13344            matrix.postRotate(180);
13345            matrix.postTranslate(left, bottom);
13346            fade.setLocalMatrix(matrix);
13347            canvas.drawRect(left, bottom - length, right, bottom, p);
13348        }
13349
13350        if (drawLeft) {
13351            matrix.setScale(1, fadeHeight * leftFadeStrength);
13352            matrix.postRotate(-90);
13353            matrix.postTranslate(left, top);
13354            fade.setLocalMatrix(matrix);
13355            canvas.drawRect(left, top, left + length, bottom, p);
13356        }
13357
13358        if (drawRight) {
13359            matrix.setScale(1, fadeHeight * rightFadeStrength);
13360            matrix.postRotate(90);
13361            matrix.postTranslate(right, top);
13362            fade.setLocalMatrix(matrix);
13363            canvas.drawRect(right - length, top, right, bottom, p);
13364        }
13365
13366        canvas.restoreToCount(saveCount);
13367
13368        // Step 6, draw decorations (scrollbars)
13369        onDrawScrollBars(canvas);
13370    }
13371
13372    /**
13373     * Override this if your view is known to always be drawn on top of a solid color background,
13374     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13375     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13376     * should be set to 0xFF.
13377     *
13378     * @see #setVerticalFadingEdgeEnabled(boolean)
13379     * @see #setHorizontalFadingEdgeEnabled(boolean)
13380     *
13381     * @return The known solid color background for this view, or 0 if the color may vary
13382     */
13383    @ViewDebug.ExportedProperty(category = "drawing")
13384    public int getSolidColor() {
13385        return 0;
13386    }
13387
13388    /**
13389     * Build a human readable string representation of the specified view flags.
13390     *
13391     * @param flags the view flags to convert to a string
13392     * @return a String representing the supplied flags
13393     */
13394    private static String printFlags(int flags) {
13395        String output = "";
13396        int numFlags = 0;
13397        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13398            output += "TAKES_FOCUS";
13399            numFlags++;
13400        }
13401
13402        switch (flags & VISIBILITY_MASK) {
13403        case INVISIBLE:
13404            if (numFlags > 0) {
13405                output += " ";
13406            }
13407            output += "INVISIBLE";
13408            // USELESS HERE numFlags++;
13409            break;
13410        case GONE:
13411            if (numFlags > 0) {
13412                output += " ";
13413            }
13414            output += "GONE";
13415            // USELESS HERE numFlags++;
13416            break;
13417        default:
13418            break;
13419        }
13420        return output;
13421    }
13422
13423    /**
13424     * Build a human readable string representation of the specified private
13425     * view flags.
13426     *
13427     * @param privateFlags the private view flags to convert to a string
13428     * @return a String representing the supplied flags
13429     */
13430    private static String printPrivateFlags(int privateFlags) {
13431        String output = "";
13432        int numFlags = 0;
13433
13434        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13435            output += "WANTS_FOCUS";
13436            numFlags++;
13437        }
13438
13439        if ((privateFlags & FOCUSED) == FOCUSED) {
13440            if (numFlags > 0) {
13441                output += " ";
13442            }
13443            output += "FOCUSED";
13444            numFlags++;
13445        }
13446
13447        if ((privateFlags & SELECTED) == SELECTED) {
13448            if (numFlags > 0) {
13449                output += " ";
13450            }
13451            output += "SELECTED";
13452            numFlags++;
13453        }
13454
13455        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13456            if (numFlags > 0) {
13457                output += " ";
13458            }
13459            output += "IS_ROOT_NAMESPACE";
13460            numFlags++;
13461        }
13462
13463        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13464            if (numFlags > 0) {
13465                output += " ";
13466            }
13467            output += "HAS_BOUNDS";
13468            numFlags++;
13469        }
13470
13471        if ((privateFlags & DRAWN) == DRAWN) {
13472            if (numFlags > 0) {
13473                output += " ";
13474            }
13475            output += "DRAWN";
13476            // USELESS HERE numFlags++;
13477        }
13478        return output;
13479    }
13480
13481    /**
13482     * <p>Indicates whether or not this view's layout will be requested during
13483     * the next hierarchy layout pass.</p>
13484     *
13485     * @return true if the layout will be forced during next layout pass
13486     */
13487    public boolean isLayoutRequested() {
13488        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13489    }
13490
13491    /**
13492     * Assign a size and position to a view and all of its
13493     * descendants
13494     *
13495     * <p>This is the second phase of the layout mechanism.
13496     * (The first is measuring). In this phase, each parent calls
13497     * layout on all of its children to position them.
13498     * This is typically done using the child measurements
13499     * that were stored in the measure pass().</p>
13500     *
13501     * <p>Derived classes should not override this method.
13502     * Derived classes with children should override
13503     * onLayout. In that method, they should
13504     * call layout on each of their children.</p>
13505     *
13506     * @param l Left position, relative to parent
13507     * @param t Top position, relative to parent
13508     * @param r Right position, relative to parent
13509     * @param b Bottom position, relative to parent
13510     */
13511    @SuppressWarnings({"unchecked"})
13512    public void layout(int l, int t, int r, int b) {
13513        int oldL = mLeft;
13514        int oldT = mTop;
13515        int oldB = mBottom;
13516        int oldR = mRight;
13517        boolean changed = setFrame(l, t, r, b);
13518        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13519            onLayout(changed, l, t, r, b);
13520            mPrivateFlags &= ~LAYOUT_REQUIRED;
13521
13522            ListenerInfo li = mListenerInfo;
13523            if (li != null && li.mOnLayoutChangeListeners != null) {
13524                ArrayList<OnLayoutChangeListener> listenersCopy =
13525                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13526                int numListeners = listenersCopy.size();
13527                for (int i = 0; i < numListeners; ++i) {
13528                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13529                }
13530            }
13531        }
13532        mPrivateFlags &= ~FORCE_LAYOUT;
13533    }
13534
13535    /**
13536     * Called from layout when this view should
13537     * assign a size and position to each of its children.
13538     *
13539     * Derived classes with children should override
13540     * this method and call layout on each of
13541     * their children.
13542     * @param changed This is a new size or position for this view
13543     * @param left Left position, relative to parent
13544     * @param top Top position, relative to parent
13545     * @param right Right position, relative to parent
13546     * @param bottom Bottom position, relative to parent
13547     */
13548    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13549    }
13550
13551    /**
13552     * Assign a size and position to this view.
13553     *
13554     * This is called from layout.
13555     *
13556     * @param left Left position, relative to parent
13557     * @param top Top position, relative to parent
13558     * @param right Right position, relative to parent
13559     * @param bottom Bottom position, relative to parent
13560     * @return true if the new size and position are different than the
13561     *         previous ones
13562     * {@hide}
13563     */
13564    protected boolean setFrame(int left, int top, int right, int bottom) {
13565        boolean changed = false;
13566
13567        if (DBG) {
13568            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13569                    + right + "," + bottom + ")");
13570        }
13571
13572        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13573            changed = true;
13574
13575            // Remember our drawn bit
13576            int drawn = mPrivateFlags & DRAWN;
13577
13578            int oldWidth = mRight - mLeft;
13579            int oldHeight = mBottom - mTop;
13580            int newWidth = right - left;
13581            int newHeight = bottom - top;
13582            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13583
13584            // Invalidate our old position
13585            invalidate(sizeChanged);
13586
13587            mLeft = left;
13588            mTop = top;
13589            mRight = right;
13590            mBottom = bottom;
13591            if (mDisplayList != null) {
13592                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13593            }
13594
13595            mPrivateFlags |= HAS_BOUNDS;
13596
13597
13598            if (sizeChanged) {
13599                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13600                    // A change in dimension means an auto-centered pivot point changes, too
13601                    if (mTransformationInfo != null) {
13602                        mTransformationInfo.mMatrixDirty = true;
13603                    }
13604                }
13605                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13606            }
13607
13608            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13609                // If we are visible, force the DRAWN bit to on so that
13610                // this invalidate will go through (at least to our parent).
13611                // This is because someone may have invalidated this view
13612                // before this call to setFrame came in, thereby clearing
13613                // the DRAWN bit.
13614                mPrivateFlags |= DRAWN;
13615                invalidate(sizeChanged);
13616                // parent display list may need to be recreated based on a change in the bounds
13617                // of any child
13618                invalidateParentCaches();
13619            }
13620
13621            // Reset drawn bit to original value (invalidate turns it off)
13622            mPrivateFlags |= drawn;
13623
13624            mBackgroundSizeChanged = true;
13625        }
13626        return changed;
13627    }
13628
13629    /**
13630     * Finalize inflating a view from XML.  This is called as the last phase
13631     * of inflation, after all child views have been added.
13632     *
13633     * <p>Even if the subclass overrides onFinishInflate, they should always be
13634     * sure to call the super method, so that we get called.
13635     */
13636    protected void onFinishInflate() {
13637    }
13638
13639    /**
13640     * Returns the resources associated with this view.
13641     *
13642     * @return Resources object.
13643     */
13644    public Resources getResources() {
13645        return mResources;
13646    }
13647
13648    /**
13649     * Invalidates the specified Drawable.
13650     *
13651     * @param drawable the drawable to invalidate
13652     */
13653    public void invalidateDrawable(Drawable drawable) {
13654        if (verifyDrawable(drawable)) {
13655            final Rect dirty = drawable.getBounds();
13656            final int scrollX = mScrollX;
13657            final int scrollY = mScrollY;
13658
13659            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13660                    dirty.right + scrollX, dirty.bottom + scrollY);
13661        }
13662    }
13663
13664    /**
13665     * Schedules an action on a drawable to occur at a specified time.
13666     *
13667     * @param who the recipient of the action
13668     * @param what the action to run on the drawable
13669     * @param when the time at which the action must occur. Uses the
13670     *        {@link SystemClock#uptimeMillis} timebase.
13671     */
13672    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13673        if (verifyDrawable(who) && what != null) {
13674            final long delay = when - SystemClock.uptimeMillis();
13675            if (mAttachInfo != null) {
13676                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13677                        Choreographer.CALLBACK_ANIMATION, what, who,
13678                        Choreographer.subtractFrameDelay(delay));
13679            } else {
13680                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13681            }
13682        }
13683    }
13684
13685    /**
13686     * Cancels a scheduled action on a drawable.
13687     *
13688     * @param who the recipient of the action
13689     * @param what the action to cancel
13690     */
13691    public void unscheduleDrawable(Drawable who, Runnable what) {
13692        if (verifyDrawable(who) && what != null) {
13693            if (mAttachInfo != null) {
13694                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13695                        Choreographer.CALLBACK_ANIMATION, what, who);
13696            } else {
13697                ViewRootImpl.getRunQueue().removeCallbacks(what);
13698            }
13699        }
13700    }
13701
13702    /**
13703     * Unschedule any events associated with the given Drawable.  This can be
13704     * used when selecting a new Drawable into a view, so that the previous
13705     * one is completely unscheduled.
13706     *
13707     * @param who The Drawable to unschedule.
13708     *
13709     * @see #drawableStateChanged
13710     */
13711    public void unscheduleDrawable(Drawable who) {
13712        if (mAttachInfo != null && who != null) {
13713            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13714                    Choreographer.CALLBACK_ANIMATION, null, who);
13715        }
13716    }
13717
13718    /**
13719    * Return the layout direction of a given Drawable.
13720    *
13721    * @param who the Drawable to query
13722    * @hide
13723    */
13724    public int getResolvedLayoutDirection(Drawable who) {
13725        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13726    }
13727
13728    /**
13729     * If your view subclass is displaying its own Drawable objects, it should
13730     * override this function and return true for any Drawable it is
13731     * displaying.  This allows animations for those drawables to be
13732     * scheduled.
13733     *
13734     * <p>Be sure to call through to the super class when overriding this
13735     * function.
13736     *
13737     * @param who The Drawable to verify.  Return true if it is one you are
13738     *            displaying, else return the result of calling through to the
13739     *            super class.
13740     *
13741     * @return boolean If true than the Drawable is being displayed in the
13742     *         view; else false and it is not allowed to animate.
13743     *
13744     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13745     * @see #drawableStateChanged()
13746     */
13747    protected boolean verifyDrawable(Drawable who) {
13748        return who == mBackground;
13749    }
13750
13751    /**
13752     * This function is called whenever the state of the view changes in such
13753     * a way that it impacts the state of drawables being shown.
13754     *
13755     * <p>Be sure to call through to the superclass when overriding this
13756     * function.
13757     *
13758     * @see Drawable#setState(int[])
13759     */
13760    protected void drawableStateChanged() {
13761        Drawable d = mBackground;
13762        if (d != null && d.isStateful()) {
13763            d.setState(getDrawableState());
13764        }
13765    }
13766
13767    /**
13768     * Call this to force a view to update its drawable state. This will cause
13769     * drawableStateChanged to be called on this view. Views that are interested
13770     * in the new state should call getDrawableState.
13771     *
13772     * @see #drawableStateChanged
13773     * @see #getDrawableState
13774     */
13775    public void refreshDrawableState() {
13776        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13777        drawableStateChanged();
13778
13779        ViewParent parent = mParent;
13780        if (parent != null) {
13781            parent.childDrawableStateChanged(this);
13782        }
13783    }
13784
13785    /**
13786     * Return an array of resource IDs of the drawable states representing the
13787     * current state of the view.
13788     *
13789     * @return The current drawable state
13790     *
13791     * @see Drawable#setState(int[])
13792     * @see #drawableStateChanged()
13793     * @see #onCreateDrawableState(int)
13794     */
13795    public final int[] getDrawableState() {
13796        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13797            return mDrawableState;
13798        } else {
13799            mDrawableState = onCreateDrawableState(0);
13800            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13801            return mDrawableState;
13802        }
13803    }
13804
13805    /**
13806     * Generate the new {@link android.graphics.drawable.Drawable} state for
13807     * this view. This is called by the view
13808     * system when the cached Drawable state is determined to be invalid.  To
13809     * retrieve the current state, you should use {@link #getDrawableState}.
13810     *
13811     * @param extraSpace if non-zero, this is the number of extra entries you
13812     * would like in the returned array in which you can place your own
13813     * states.
13814     *
13815     * @return Returns an array holding the current {@link Drawable} state of
13816     * the view.
13817     *
13818     * @see #mergeDrawableStates(int[], int[])
13819     */
13820    protected int[] onCreateDrawableState(int extraSpace) {
13821        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13822                mParent instanceof View) {
13823            return ((View) mParent).onCreateDrawableState(extraSpace);
13824        }
13825
13826        int[] drawableState;
13827
13828        int privateFlags = mPrivateFlags;
13829
13830        int viewStateIndex = 0;
13831        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13832        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13833        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13834        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13835        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13836        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13837        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13838                HardwareRenderer.isAvailable()) {
13839            // This is set if HW acceleration is requested, even if the current
13840            // process doesn't allow it.  This is just to allow app preview
13841            // windows to better match their app.
13842            viewStateIndex |= VIEW_STATE_ACCELERATED;
13843        }
13844        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13845
13846        final int privateFlags2 = mPrivateFlags2;
13847        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13848        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13849
13850        drawableState = VIEW_STATE_SETS[viewStateIndex];
13851
13852        //noinspection ConstantIfStatement
13853        if (false) {
13854            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13855            Log.i("View", toString()
13856                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13857                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13858                    + " fo=" + hasFocus()
13859                    + " sl=" + ((privateFlags & SELECTED) != 0)
13860                    + " wf=" + hasWindowFocus()
13861                    + ": " + Arrays.toString(drawableState));
13862        }
13863
13864        if (extraSpace == 0) {
13865            return drawableState;
13866        }
13867
13868        final int[] fullState;
13869        if (drawableState != null) {
13870            fullState = new int[drawableState.length + extraSpace];
13871            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13872        } else {
13873            fullState = new int[extraSpace];
13874        }
13875
13876        return fullState;
13877    }
13878
13879    /**
13880     * Merge your own state values in <var>additionalState</var> into the base
13881     * state values <var>baseState</var> that were returned by
13882     * {@link #onCreateDrawableState(int)}.
13883     *
13884     * @param baseState The base state values returned by
13885     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13886     * own additional state values.
13887     *
13888     * @param additionalState The additional state values you would like
13889     * added to <var>baseState</var>; this array is not modified.
13890     *
13891     * @return As a convenience, the <var>baseState</var> array you originally
13892     * passed into the function is returned.
13893     *
13894     * @see #onCreateDrawableState(int)
13895     */
13896    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13897        final int N = baseState.length;
13898        int i = N - 1;
13899        while (i >= 0 && baseState[i] == 0) {
13900            i--;
13901        }
13902        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13903        return baseState;
13904    }
13905
13906    /**
13907     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13908     * on all Drawable objects associated with this view.
13909     */
13910    public void jumpDrawablesToCurrentState() {
13911        if (mBackground != null) {
13912            mBackground.jumpToCurrentState();
13913        }
13914    }
13915
13916    /**
13917     * Sets the background color for this view.
13918     * @param color the color of the background
13919     */
13920    @RemotableViewMethod
13921    public void setBackgroundColor(int color) {
13922        if (mBackground instanceof ColorDrawable) {
13923            ((ColorDrawable) mBackground).setColor(color);
13924        } else {
13925            setBackground(new ColorDrawable(color));
13926        }
13927    }
13928
13929    /**
13930     * Set the background to a given resource. The resource should refer to
13931     * a Drawable object or 0 to remove the background.
13932     * @param resid The identifier of the resource.
13933     *
13934     * @attr ref android.R.styleable#View_background
13935     */
13936    @RemotableViewMethod
13937    public void setBackgroundResource(int resid) {
13938        if (resid != 0 && resid == mBackgroundResource) {
13939            return;
13940        }
13941
13942        Drawable d= null;
13943        if (resid != 0) {
13944            d = mResources.getDrawable(resid);
13945        }
13946        setBackground(d);
13947
13948        mBackgroundResource = resid;
13949    }
13950
13951    /**
13952     * Set the background to a given Drawable, or remove the background. If the
13953     * background has padding, this View's padding is set to the background's
13954     * padding. However, when a background is removed, this View's padding isn't
13955     * touched. If setting the padding is desired, please use
13956     * {@link #setPadding(int, int, int, int)}.
13957     *
13958     * @param background The Drawable to use as the background, or null to remove the
13959     *        background
13960     */
13961    public void setBackground(Drawable background) {
13962        //noinspection deprecation
13963        setBackgroundDrawable(background);
13964    }
13965
13966    /**
13967     * @deprecated use {@link #setBackground(Drawable)} instead
13968     */
13969    @Deprecated
13970    public void setBackgroundDrawable(Drawable background) {
13971        if (background == mBackground) {
13972            return;
13973        }
13974
13975        boolean requestLayout = false;
13976
13977        mBackgroundResource = 0;
13978
13979        /*
13980         * Regardless of whether we're setting a new background or not, we want
13981         * to clear the previous drawable.
13982         */
13983        if (mBackground != null) {
13984            mBackground.setCallback(null);
13985            unscheduleDrawable(mBackground);
13986        }
13987
13988        if (background != null) {
13989            Rect padding = sThreadLocal.get();
13990            if (padding == null) {
13991                padding = new Rect();
13992                sThreadLocal.set(padding);
13993            }
13994            if (background.getPadding(padding)) {
13995                switch (background.getResolvedLayoutDirectionSelf()) {
13996                    case LAYOUT_DIRECTION_RTL:
13997                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13998                        break;
13999                    case LAYOUT_DIRECTION_LTR:
14000                    default:
14001                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14002                }
14003            }
14004
14005            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14006            // if it has a different minimum size, we should layout again
14007            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14008                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14009                requestLayout = true;
14010            }
14011
14012            background.setCallback(this);
14013            if (background.isStateful()) {
14014                background.setState(getDrawableState());
14015            }
14016            background.setVisible(getVisibility() == VISIBLE, false);
14017            mBackground = background;
14018
14019            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14020                mPrivateFlags &= ~SKIP_DRAW;
14021                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14022                requestLayout = true;
14023            }
14024        } else {
14025            /* Remove the background */
14026            mBackground = null;
14027
14028            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14029                /*
14030                 * This view ONLY drew the background before and we're removing
14031                 * the background, so now it won't draw anything
14032                 * (hence we SKIP_DRAW)
14033                 */
14034                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14035                mPrivateFlags |= SKIP_DRAW;
14036            }
14037
14038            /*
14039             * When the background is set, we try to apply its padding to this
14040             * View. When the background is removed, we don't touch this View's
14041             * padding. This is noted in the Javadocs. Hence, we don't need to
14042             * requestLayout(), the invalidate() below is sufficient.
14043             */
14044
14045            // The old background's minimum size could have affected this
14046            // View's layout, so let's requestLayout
14047            requestLayout = true;
14048        }
14049
14050        computeOpaqueFlags();
14051
14052        if (requestLayout) {
14053            requestLayout();
14054        }
14055
14056        mBackgroundSizeChanged = true;
14057        invalidate(true);
14058    }
14059
14060    /**
14061     * Gets the background drawable
14062     *
14063     * @return The drawable used as the background for this view, if any.
14064     *
14065     * @see #setBackground(Drawable)
14066     *
14067     * @attr ref android.R.styleable#View_background
14068     */
14069    public Drawable getBackground() {
14070        return mBackground;
14071    }
14072
14073    /**
14074     * Sets the padding. The view may add on the space required to display
14075     * the scrollbars, depending on the style and visibility of the scrollbars.
14076     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14077     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14078     * from the values set in this call.
14079     *
14080     * @attr ref android.R.styleable#View_padding
14081     * @attr ref android.R.styleable#View_paddingBottom
14082     * @attr ref android.R.styleable#View_paddingLeft
14083     * @attr ref android.R.styleable#View_paddingRight
14084     * @attr ref android.R.styleable#View_paddingTop
14085     * @param left the left padding in pixels
14086     * @param top the top padding in pixels
14087     * @param right the right padding in pixels
14088     * @param bottom the bottom padding in pixels
14089     */
14090    public void setPadding(int left, int top, int right, int bottom) {
14091        mUserPaddingStart = -1;
14092        mUserPaddingEnd = -1;
14093        mUserPaddingRelative = false;
14094
14095        internalSetPadding(left, top, right, bottom);
14096    }
14097
14098    private void internalSetPadding(int left, int top, int right, int bottom) {
14099        mUserPaddingLeft = left;
14100        mUserPaddingRight = right;
14101        mUserPaddingBottom = bottom;
14102
14103        final int viewFlags = mViewFlags;
14104        boolean changed = false;
14105
14106        // Common case is there are no scroll bars.
14107        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14108            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14109                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14110                        ? 0 : getVerticalScrollbarWidth();
14111                switch (mVerticalScrollbarPosition) {
14112                    case SCROLLBAR_POSITION_DEFAULT:
14113                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14114                            left += offset;
14115                        } else {
14116                            right += offset;
14117                        }
14118                        break;
14119                    case SCROLLBAR_POSITION_RIGHT:
14120                        right += offset;
14121                        break;
14122                    case SCROLLBAR_POSITION_LEFT:
14123                        left += offset;
14124                        break;
14125                }
14126            }
14127            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14128                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14129                        ? 0 : getHorizontalScrollbarHeight();
14130            }
14131        }
14132
14133        if (mPaddingLeft != left) {
14134            changed = true;
14135            mPaddingLeft = left;
14136        }
14137        if (mPaddingTop != top) {
14138            changed = true;
14139            mPaddingTop = top;
14140        }
14141        if (mPaddingRight != right) {
14142            changed = true;
14143            mPaddingRight = right;
14144        }
14145        if (mPaddingBottom != bottom) {
14146            changed = true;
14147            mPaddingBottom = bottom;
14148        }
14149
14150        if (changed) {
14151            requestLayout();
14152        }
14153    }
14154
14155    /**
14156     * Sets the relative padding. The view may add on the space required to display
14157     * the scrollbars, depending on the style and visibility of the scrollbars.
14158     * from the values set in this call.
14159     *
14160     * @param start the start padding in pixels
14161     * @param top the top padding in pixels
14162     * @param end the end padding in pixels
14163     * @param bottom the bottom padding in pixels
14164     * @hide
14165     */
14166    public void setPaddingRelative(int start, int top, int end, int bottom) {
14167        mUserPaddingStart = start;
14168        mUserPaddingEnd = end;
14169        mUserPaddingRelative = true;
14170
14171        switch(getResolvedLayoutDirection()) {
14172            case LAYOUT_DIRECTION_RTL:
14173                internalSetPadding(end, top, start, bottom);
14174                break;
14175            case LAYOUT_DIRECTION_LTR:
14176            default:
14177                internalSetPadding(start, top, end, bottom);
14178        }
14179    }
14180
14181    /**
14182     * Returns the top padding of this view.
14183     *
14184     * @return the top padding in pixels
14185     */
14186    public int getPaddingTop() {
14187        return mPaddingTop;
14188    }
14189
14190    /**
14191     * Returns the bottom padding of this view. If there are inset and enabled
14192     * scrollbars, this value may include the space required to display the
14193     * scrollbars as well.
14194     *
14195     * @return the bottom padding in pixels
14196     */
14197    public int getPaddingBottom() {
14198        return mPaddingBottom;
14199    }
14200
14201    /**
14202     * Returns the left padding of this view. If there are inset and enabled
14203     * scrollbars, this value may include the space required to display the
14204     * scrollbars as well.
14205     *
14206     * @return the left padding in pixels
14207     */
14208    public int getPaddingLeft() {
14209        return mPaddingLeft;
14210    }
14211
14212    /**
14213     * Returns the start padding of this view depending on its resolved layout direction.
14214     * If there are inset and enabled scrollbars, this value may include the space
14215     * required to display the scrollbars as well.
14216     *
14217     * @return the start padding in pixels
14218     * @hide
14219     */
14220    public int getPaddingStart() {
14221        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14222                mPaddingRight : mPaddingLeft;
14223    }
14224
14225    /**
14226     * Returns the right padding of this view. If there are inset and enabled
14227     * scrollbars, this value may include the space required to display the
14228     * scrollbars as well.
14229     *
14230     * @return the right padding in pixels
14231     */
14232    public int getPaddingRight() {
14233        return mPaddingRight;
14234    }
14235
14236    /**
14237     * Returns the end padding of this view depending on its resolved layout direction.
14238     * If there are inset and enabled scrollbars, this value may include the space
14239     * required to display the scrollbars as well.
14240     *
14241     * @return the end padding in pixels
14242     * @hide
14243     */
14244    public int getPaddingEnd() {
14245        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14246                mPaddingLeft : mPaddingRight;
14247    }
14248
14249    /**
14250     * Return if the padding as been set thru relative values
14251     * {@link #setPaddingRelative(int, int, int, int)}
14252     *
14253     * @return true if the padding is relative or false if it is not.
14254     * @hide
14255     */
14256    public boolean isPaddingRelative() {
14257        return mUserPaddingRelative;
14258    }
14259
14260    /**
14261     * @hide
14262     */
14263    public Insets getOpticalInsets() {
14264        if (mLayoutInsets == null) {
14265            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14266        }
14267        return mLayoutInsets;
14268    }
14269
14270    /**
14271     * @hide
14272     */
14273    public void setLayoutInsets(Insets layoutInsets) {
14274        mLayoutInsets = layoutInsets;
14275    }
14276
14277    /**
14278     * Changes the selection state of this view. A view can be selected or not.
14279     * Note that selection is not the same as focus. Views are typically
14280     * selected in the context of an AdapterView like ListView or GridView;
14281     * the selected view is the view that is highlighted.
14282     *
14283     * @param selected true if the view must be selected, false otherwise
14284     */
14285    public void setSelected(boolean selected) {
14286        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14287            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14288            if (!selected) resetPressedState();
14289            invalidate(true);
14290            refreshDrawableState();
14291            dispatchSetSelected(selected);
14292            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14293                notifyAccessibilityStateChanged();
14294            }
14295        }
14296    }
14297
14298    /**
14299     * Dispatch setSelected to all of this View's children.
14300     *
14301     * @see #setSelected(boolean)
14302     *
14303     * @param selected The new selected state
14304     */
14305    protected void dispatchSetSelected(boolean selected) {
14306    }
14307
14308    /**
14309     * Indicates the selection state of this view.
14310     *
14311     * @return true if the view is selected, false otherwise
14312     */
14313    @ViewDebug.ExportedProperty
14314    public boolean isSelected() {
14315        return (mPrivateFlags & SELECTED) != 0;
14316    }
14317
14318    /**
14319     * Changes the activated state of this view. A view can be activated or not.
14320     * Note that activation is not the same as selection.  Selection is
14321     * a transient property, representing the view (hierarchy) the user is
14322     * currently interacting with.  Activation is a longer-term state that the
14323     * user can move views in and out of.  For example, in a list view with
14324     * single or multiple selection enabled, the views in the current selection
14325     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14326     * here.)  The activated state is propagated down to children of the view it
14327     * is set on.
14328     *
14329     * @param activated true if the view must be activated, false otherwise
14330     */
14331    public void setActivated(boolean activated) {
14332        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14333            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14334            invalidate(true);
14335            refreshDrawableState();
14336            dispatchSetActivated(activated);
14337        }
14338    }
14339
14340    /**
14341     * Dispatch setActivated to all of this View's children.
14342     *
14343     * @see #setActivated(boolean)
14344     *
14345     * @param activated The new activated state
14346     */
14347    protected void dispatchSetActivated(boolean activated) {
14348    }
14349
14350    /**
14351     * Indicates the activation state of this view.
14352     *
14353     * @return true if the view is activated, false otherwise
14354     */
14355    @ViewDebug.ExportedProperty
14356    public boolean isActivated() {
14357        return (mPrivateFlags & ACTIVATED) != 0;
14358    }
14359
14360    /**
14361     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14362     * observer can be used to get notifications when global events, like
14363     * layout, happen.
14364     *
14365     * The returned ViewTreeObserver observer is not guaranteed to remain
14366     * valid for the lifetime of this View. If the caller of this method keeps
14367     * a long-lived reference to ViewTreeObserver, it should always check for
14368     * the return value of {@link ViewTreeObserver#isAlive()}.
14369     *
14370     * @return The ViewTreeObserver for this view's hierarchy.
14371     */
14372    public ViewTreeObserver getViewTreeObserver() {
14373        if (mAttachInfo != null) {
14374            return mAttachInfo.mTreeObserver;
14375        }
14376        if (mFloatingTreeObserver == null) {
14377            mFloatingTreeObserver = new ViewTreeObserver();
14378        }
14379        return mFloatingTreeObserver;
14380    }
14381
14382    /**
14383     * <p>Finds the topmost view in the current view hierarchy.</p>
14384     *
14385     * @return the topmost view containing this view
14386     */
14387    public View getRootView() {
14388        if (mAttachInfo != null) {
14389            final View v = mAttachInfo.mRootView;
14390            if (v != null) {
14391                return v;
14392            }
14393        }
14394
14395        View parent = this;
14396
14397        while (parent.mParent != null && parent.mParent instanceof View) {
14398            parent = (View) parent.mParent;
14399        }
14400
14401        return parent;
14402    }
14403
14404    /**
14405     * <p>Computes the coordinates of this view on the screen. The argument
14406     * must be an array of two integers. After the method returns, the array
14407     * contains the x and y location in that order.</p>
14408     *
14409     * @param location an array of two integers in which to hold the coordinates
14410     */
14411    public void getLocationOnScreen(int[] location) {
14412        getLocationInWindow(location);
14413
14414        final AttachInfo info = mAttachInfo;
14415        if (info != null) {
14416            location[0] += info.mWindowLeft;
14417            location[1] += info.mWindowTop;
14418        }
14419    }
14420
14421    /**
14422     * <p>Computes the coordinates of this view in its window. The argument
14423     * must be an array of two integers. After the method returns, the array
14424     * contains the x and y location in that order.</p>
14425     *
14426     * @param location an array of two integers in which to hold the coordinates
14427     */
14428    public void getLocationInWindow(int[] location) {
14429        if (location == null || location.length < 2) {
14430            throw new IllegalArgumentException("location must be an array of two integers");
14431        }
14432
14433        if (mAttachInfo == null) {
14434            // When the view is not attached to a window, this method does not make sense
14435            location[0] = location[1] = 0;
14436            return;
14437        }
14438
14439        float[] position = mAttachInfo.mTmpTransformLocation;
14440        position[0] = position[1] = 0.0f;
14441
14442        if (!hasIdentityMatrix()) {
14443            getMatrix().mapPoints(position);
14444        }
14445
14446        position[0] += mLeft;
14447        position[1] += mTop;
14448
14449        ViewParent viewParent = mParent;
14450        while (viewParent instanceof View) {
14451            final View view = (View) viewParent;
14452
14453            position[0] -= view.mScrollX;
14454            position[1] -= view.mScrollY;
14455
14456            if (!view.hasIdentityMatrix()) {
14457                view.getMatrix().mapPoints(position);
14458            }
14459
14460            position[0] += view.mLeft;
14461            position[1] += view.mTop;
14462
14463            viewParent = view.mParent;
14464         }
14465
14466        if (viewParent instanceof ViewRootImpl) {
14467            // *cough*
14468            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14469            position[1] -= vr.mCurScrollY;
14470        }
14471
14472        location[0] = (int) (position[0] + 0.5f);
14473        location[1] = (int) (position[1] + 0.5f);
14474    }
14475
14476    /**
14477     * {@hide}
14478     * @param id the id of the view to be found
14479     * @return the view of the specified id, null if cannot be found
14480     */
14481    protected View findViewTraversal(int id) {
14482        if (id == mID) {
14483            return this;
14484        }
14485        return null;
14486    }
14487
14488    /**
14489     * {@hide}
14490     * @param tag the tag of the view to be found
14491     * @return the view of specified tag, null if cannot be found
14492     */
14493    protected View findViewWithTagTraversal(Object tag) {
14494        if (tag != null && tag.equals(mTag)) {
14495            return this;
14496        }
14497        return null;
14498    }
14499
14500    /**
14501     * {@hide}
14502     * @param predicate The predicate to evaluate.
14503     * @param childToSkip If not null, ignores this child during the recursive traversal.
14504     * @return The first view that matches the predicate or null.
14505     */
14506    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14507        if (predicate.apply(this)) {
14508            return this;
14509        }
14510        return null;
14511    }
14512
14513    /**
14514     * Look for a child view with the given id.  If this view has the given
14515     * id, return this view.
14516     *
14517     * @param id The id to search for.
14518     * @return The view that has the given id in the hierarchy or null
14519     */
14520    public final View findViewById(int id) {
14521        if (id < 0) {
14522            return null;
14523        }
14524        return findViewTraversal(id);
14525    }
14526
14527    /**
14528     * Finds a view by its unuque and stable accessibility id.
14529     *
14530     * @param accessibilityId The searched accessibility id.
14531     * @return The found view.
14532     */
14533    final View findViewByAccessibilityId(int accessibilityId) {
14534        if (accessibilityId < 0) {
14535            return null;
14536        }
14537        return findViewByAccessibilityIdTraversal(accessibilityId);
14538    }
14539
14540    /**
14541     * Performs the traversal to find a view by its unuque and stable accessibility id.
14542     *
14543     * <strong>Note:</strong>This method does not stop at the root namespace
14544     * boundary since the user can touch the screen at an arbitrary location
14545     * potentially crossing the root namespace bounday which will send an
14546     * accessibility event to accessibility services and they should be able
14547     * to obtain the event source. Also accessibility ids are guaranteed to be
14548     * unique in the window.
14549     *
14550     * @param accessibilityId The accessibility id.
14551     * @return The found view.
14552     */
14553    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14554        if (getAccessibilityViewId() == accessibilityId) {
14555            return this;
14556        }
14557        return null;
14558    }
14559
14560    /**
14561     * Look for a child view with the given tag.  If this view has the given
14562     * tag, return this view.
14563     *
14564     * @param tag The tag to search for, using "tag.equals(getTag())".
14565     * @return The View that has the given tag in the hierarchy or null
14566     */
14567    public final View findViewWithTag(Object tag) {
14568        if (tag == null) {
14569            return null;
14570        }
14571        return findViewWithTagTraversal(tag);
14572    }
14573
14574    /**
14575     * {@hide}
14576     * Look for a child view that matches the specified predicate.
14577     * If this view matches the predicate, return this view.
14578     *
14579     * @param predicate The predicate to evaluate.
14580     * @return The first view that matches the predicate or null.
14581     */
14582    public final View findViewByPredicate(Predicate<View> predicate) {
14583        return findViewByPredicateTraversal(predicate, null);
14584    }
14585
14586    /**
14587     * {@hide}
14588     * Look for a child view that matches the specified predicate,
14589     * starting with the specified view and its descendents and then
14590     * recusively searching the ancestors and siblings of that view
14591     * until this view is reached.
14592     *
14593     * This method is useful in cases where the predicate does not match
14594     * a single unique view (perhaps multiple views use the same id)
14595     * and we are trying to find the view that is "closest" in scope to the
14596     * starting view.
14597     *
14598     * @param start The view to start from.
14599     * @param predicate The predicate to evaluate.
14600     * @return The first view that matches the predicate or null.
14601     */
14602    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14603        View childToSkip = null;
14604        for (;;) {
14605            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14606            if (view != null || start == this) {
14607                return view;
14608            }
14609
14610            ViewParent parent = start.getParent();
14611            if (parent == null || !(parent instanceof View)) {
14612                return null;
14613            }
14614
14615            childToSkip = start;
14616            start = (View) parent;
14617        }
14618    }
14619
14620    /**
14621     * Sets the identifier for this view. The identifier does not have to be
14622     * unique in this view's hierarchy. The identifier should be a positive
14623     * number.
14624     *
14625     * @see #NO_ID
14626     * @see #getId()
14627     * @see #findViewById(int)
14628     *
14629     * @param id a number used to identify the view
14630     *
14631     * @attr ref android.R.styleable#View_id
14632     */
14633    public void setId(int id) {
14634        mID = id;
14635    }
14636
14637    /**
14638     * {@hide}
14639     *
14640     * @param isRoot true if the view belongs to the root namespace, false
14641     *        otherwise
14642     */
14643    public void setIsRootNamespace(boolean isRoot) {
14644        if (isRoot) {
14645            mPrivateFlags |= IS_ROOT_NAMESPACE;
14646        } else {
14647            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14648        }
14649    }
14650
14651    /**
14652     * {@hide}
14653     *
14654     * @return true if the view belongs to the root namespace, false otherwise
14655     */
14656    public boolean isRootNamespace() {
14657        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14658    }
14659
14660    /**
14661     * Returns this view's identifier.
14662     *
14663     * @return a positive integer used to identify the view or {@link #NO_ID}
14664     *         if the view has no ID
14665     *
14666     * @see #setId(int)
14667     * @see #findViewById(int)
14668     * @attr ref android.R.styleable#View_id
14669     */
14670    @ViewDebug.CapturedViewProperty
14671    public int getId() {
14672        return mID;
14673    }
14674
14675    /**
14676     * Returns this view's tag.
14677     *
14678     * @return the Object stored in this view as a tag
14679     *
14680     * @see #setTag(Object)
14681     * @see #getTag(int)
14682     */
14683    @ViewDebug.ExportedProperty
14684    public Object getTag() {
14685        return mTag;
14686    }
14687
14688    /**
14689     * Sets the tag associated with this view. A tag can be used to mark
14690     * a view in its hierarchy and does not have to be unique within the
14691     * hierarchy. Tags can also be used to store data within a view without
14692     * resorting to another data structure.
14693     *
14694     * @param tag an Object to tag the view with
14695     *
14696     * @see #getTag()
14697     * @see #setTag(int, Object)
14698     */
14699    public void setTag(final Object tag) {
14700        mTag = tag;
14701    }
14702
14703    /**
14704     * Returns the tag associated with this view and the specified key.
14705     *
14706     * @param key The key identifying the tag
14707     *
14708     * @return the Object stored in this view as a tag
14709     *
14710     * @see #setTag(int, Object)
14711     * @see #getTag()
14712     */
14713    public Object getTag(int key) {
14714        if (mKeyedTags != null) return mKeyedTags.get(key);
14715        return null;
14716    }
14717
14718    /**
14719     * Sets a tag associated with this view and a key. A tag can be used
14720     * to mark a view in its hierarchy and does not have to be unique within
14721     * the hierarchy. Tags can also be used to store data within a view
14722     * without resorting to another data structure.
14723     *
14724     * The specified key should be an id declared in the resources of the
14725     * application to ensure it is unique (see the <a
14726     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14727     * Keys identified as belonging to
14728     * the Android framework or not associated with any package will cause
14729     * an {@link IllegalArgumentException} to be thrown.
14730     *
14731     * @param key The key identifying the tag
14732     * @param tag An Object to tag the view with
14733     *
14734     * @throws IllegalArgumentException If they specified key is not valid
14735     *
14736     * @see #setTag(Object)
14737     * @see #getTag(int)
14738     */
14739    public void setTag(int key, final Object tag) {
14740        // If the package id is 0x00 or 0x01, it's either an undefined package
14741        // or a framework id
14742        if ((key >>> 24) < 2) {
14743            throw new IllegalArgumentException("The key must be an application-specific "
14744                    + "resource id.");
14745        }
14746
14747        setKeyedTag(key, tag);
14748    }
14749
14750    /**
14751     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14752     * framework id.
14753     *
14754     * @hide
14755     */
14756    public void setTagInternal(int key, Object tag) {
14757        if ((key >>> 24) != 0x1) {
14758            throw new IllegalArgumentException("The key must be a framework-specific "
14759                    + "resource id.");
14760        }
14761
14762        setKeyedTag(key, tag);
14763    }
14764
14765    private void setKeyedTag(int key, Object tag) {
14766        if (mKeyedTags == null) {
14767            mKeyedTags = new SparseArray<Object>();
14768        }
14769
14770        mKeyedTags.put(key, tag);
14771    }
14772
14773    /**
14774     * Prints information about this view in the log output, with the tag
14775     * {@link #VIEW_LOG_TAG}.
14776     *
14777     * @hide
14778     */
14779    public void debug() {
14780        debug(0);
14781    }
14782
14783    /**
14784     * Prints information about this view in the log output, with the tag
14785     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14786     * indentation defined by the <code>depth</code>.
14787     *
14788     * @param depth the indentation level
14789     *
14790     * @hide
14791     */
14792    protected void debug(int depth) {
14793        String output = debugIndent(depth - 1);
14794
14795        output += "+ " + this;
14796        int id = getId();
14797        if (id != -1) {
14798            output += " (id=" + id + ")";
14799        }
14800        Object tag = getTag();
14801        if (tag != null) {
14802            output += " (tag=" + tag + ")";
14803        }
14804        Log.d(VIEW_LOG_TAG, output);
14805
14806        if ((mPrivateFlags & FOCUSED) != 0) {
14807            output = debugIndent(depth) + " FOCUSED";
14808            Log.d(VIEW_LOG_TAG, output);
14809        }
14810
14811        output = debugIndent(depth);
14812        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14813                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14814                + "} ";
14815        Log.d(VIEW_LOG_TAG, output);
14816
14817        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14818                || mPaddingBottom != 0) {
14819            output = debugIndent(depth);
14820            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14821                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14822            Log.d(VIEW_LOG_TAG, output);
14823        }
14824
14825        output = debugIndent(depth);
14826        output += "mMeasureWidth=" + mMeasuredWidth +
14827                " mMeasureHeight=" + mMeasuredHeight;
14828        Log.d(VIEW_LOG_TAG, output);
14829
14830        output = debugIndent(depth);
14831        if (mLayoutParams == null) {
14832            output += "BAD! no layout params";
14833        } else {
14834            output = mLayoutParams.debug(output);
14835        }
14836        Log.d(VIEW_LOG_TAG, output);
14837
14838        output = debugIndent(depth);
14839        output += "flags={";
14840        output += View.printFlags(mViewFlags);
14841        output += "}";
14842        Log.d(VIEW_LOG_TAG, output);
14843
14844        output = debugIndent(depth);
14845        output += "privateFlags={";
14846        output += View.printPrivateFlags(mPrivateFlags);
14847        output += "}";
14848        Log.d(VIEW_LOG_TAG, output);
14849    }
14850
14851    /**
14852     * Creates a string of whitespaces used for indentation.
14853     *
14854     * @param depth the indentation level
14855     * @return a String containing (depth * 2 + 3) * 2 white spaces
14856     *
14857     * @hide
14858     */
14859    protected static String debugIndent(int depth) {
14860        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14861        for (int i = 0; i < (depth * 2) + 3; i++) {
14862            spaces.append(' ').append(' ');
14863        }
14864        return spaces.toString();
14865    }
14866
14867    /**
14868     * <p>Return the offset of the widget's text baseline from the widget's top
14869     * boundary. If this widget does not support baseline alignment, this
14870     * method returns -1. </p>
14871     *
14872     * @return the offset of the baseline within the widget's bounds or -1
14873     *         if baseline alignment is not supported
14874     */
14875    @ViewDebug.ExportedProperty(category = "layout")
14876    public int getBaseline() {
14877        return -1;
14878    }
14879
14880    /**
14881     * Call this when something has changed which has invalidated the
14882     * layout of this view. This will schedule a layout pass of the view
14883     * tree.
14884     */
14885    public void requestLayout() {
14886        mPrivateFlags |= FORCE_LAYOUT;
14887        mPrivateFlags |= INVALIDATED;
14888
14889        if (mLayoutParams != null) {
14890            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14891        }
14892
14893        if (mParent != null && !mParent.isLayoutRequested()) {
14894            mParent.requestLayout();
14895        }
14896    }
14897
14898    /**
14899     * Forces this view to be laid out during the next layout pass.
14900     * This method does not call requestLayout() or forceLayout()
14901     * on the parent.
14902     */
14903    public void forceLayout() {
14904        mPrivateFlags |= FORCE_LAYOUT;
14905        mPrivateFlags |= INVALIDATED;
14906    }
14907
14908    /**
14909     * <p>
14910     * This is called to find out how big a view should be. The parent
14911     * supplies constraint information in the width and height parameters.
14912     * </p>
14913     *
14914     * <p>
14915     * The actual measurement work of a view is performed in
14916     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14917     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14918     * </p>
14919     *
14920     *
14921     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14922     *        parent
14923     * @param heightMeasureSpec Vertical space requirements as imposed by the
14924     *        parent
14925     *
14926     * @see #onMeasure(int, int)
14927     */
14928    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14929        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14930                widthMeasureSpec != mOldWidthMeasureSpec ||
14931                heightMeasureSpec != mOldHeightMeasureSpec) {
14932
14933            // first clears the measured dimension flag
14934            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14935
14936            // measure ourselves, this should set the measured dimension flag back
14937            onMeasure(widthMeasureSpec, heightMeasureSpec);
14938
14939            // flag not set, setMeasuredDimension() was not invoked, we raise
14940            // an exception to warn the developer
14941            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14942                throw new IllegalStateException("onMeasure() did not set the"
14943                        + " measured dimension by calling"
14944                        + " setMeasuredDimension()");
14945            }
14946
14947            mPrivateFlags |= LAYOUT_REQUIRED;
14948        }
14949
14950        mOldWidthMeasureSpec = widthMeasureSpec;
14951        mOldHeightMeasureSpec = heightMeasureSpec;
14952    }
14953
14954    /**
14955     * <p>
14956     * Measure the view and its content to determine the measured width and the
14957     * measured height. This method is invoked by {@link #measure(int, int)} and
14958     * should be overriden by subclasses to provide accurate and efficient
14959     * measurement of their contents.
14960     * </p>
14961     *
14962     * <p>
14963     * <strong>CONTRACT:</strong> When overriding this method, you
14964     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14965     * measured width and height of this view. Failure to do so will trigger an
14966     * <code>IllegalStateException</code>, thrown by
14967     * {@link #measure(int, int)}. Calling the superclass'
14968     * {@link #onMeasure(int, int)} is a valid use.
14969     * </p>
14970     *
14971     * <p>
14972     * The base class implementation of measure defaults to the background size,
14973     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14974     * override {@link #onMeasure(int, int)} to provide better measurements of
14975     * their content.
14976     * </p>
14977     *
14978     * <p>
14979     * If this method is overridden, it is the subclass's responsibility to make
14980     * sure the measured height and width are at least the view's minimum height
14981     * and width ({@link #getSuggestedMinimumHeight()} and
14982     * {@link #getSuggestedMinimumWidth()}).
14983     * </p>
14984     *
14985     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14986     *                         The requirements are encoded with
14987     *                         {@link android.view.View.MeasureSpec}.
14988     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14989     *                         The requirements are encoded with
14990     *                         {@link android.view.View.MeasureSpec}.
14991     *
14992     * @see #getMeasuredWidth()
14993     * @see #getMeasuredHeight()
14994     * @see #setMeasuredDimension(int, int)
14995     * @see #getSuggestedMinimumHeight()
14996     * @see #getSuggestedMinimumWidth()
14997     * @see android.view.View.MeasureSpec#getMode(int)
14998     * @see android.view.View.MeasureSpec#getSize(int)
14999     */
15000    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15001        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15002                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15003    }
15004
15005    /**
15006     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15007     * measured width and measured height. Failing to do so will trigger an
15008     * exception at measurement time.</p>
15009     *
15010     * @param measuredWidth The measured width of this view.  May be a complex
15011     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15012     * {@link #MEASURED_STATE_TOO_SMALL}.
15013     * @param measuredHeight The measured height of this view.  May be a complex
15014     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15015     * {@link #MEASURED_STATE_TOO_SMALL}.
15016     */
15017    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15018        mMeasuredWidth = measuredWidth;
15019        mMeasuredHeight = measuredHeight;
15020
15021        mPrivateFlags |= MEASURED_DIMENSION_SET;
15022    }
15023
15024    /**
15025     * Merge two states as returned by {@link #getMeasuredState()}.
15026     * @param curState The current state as returned from a view or the result
15027     * of combining multiple views.
15028     * @param newState The new view state to combine.
15029     * @return Returns a new integer reflecting the combination of the two
15030     * states.
15031     */
15032    public static int combineMeasuredStates(int curState, int newState) {
15033        return curState | newState;
15034    }
15035
15036    /**
15037     * Version of {@link #resolveSizeAndState(int, int, int)}
15038     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15039     */
15040    public static int resolveSize(int size, int measureSpec) {
15041        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15042    }
15043
15044    /**
15045     * Utility to reconcile a desired size and state, with constraints imposed
15046     * by a MeasureSpec.  Will take the desired size, unless a different size
15047     * is imposed by the constraints.  The returned value is a compound integer,
15048     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15049     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15050     * size is smaller than the size the view wants to be.
15051     *
15052     * @param size How big the view wants to be
15053     * @param measureSpec Constraints imposed by the parent
15054     * @return Size information bit mask as defined by
15055     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15056     */
15057    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15058        int result = size;
15059        int specMode = MeasureSpec.getMode(measureSpec);
15060        int specSize =  MeasureSpec.getSize(measureSpec);
15061        switch (specMode) {
15062        case MeasureSpec.UNSPECIFIED:
15063            result = size;
15064            break;
15065        case MeasureSpec.AT_MOST:
15066            if (specSize < size) {
15067                result = specSize | MEASURED_STATE_TOO_SMALL;
15068            } else {
15069                result = size;
15070            }
15071            break;
15072        case MeasureSpec.EXACTLY:
15073            result = specSize;
15074            break;
15075        }
15076        return result | (childMeasuredState&MEASURED_STATE_MASK);
15077    }
15078
15079    /**
15080     * Utility to return a default size. Uses the supplied size if the
15081     * MeasureSpec imposed no constraints. Will get larger if allowed
15082     * by the MeasureSpec.
15083     *
15084     * @param size Default size for this view
15085     * @param measureSpec Constraints imposed by the parent
15086     * @return The size this view should be.
15087     */
15088    public static int getDefaultSize(int size, int measureSpec) {
15089        int result = size;
15090        int specMode = MeasureSpec.getMode(measureSpec);
15091        int specSize = MeasureSpec.getSize(measureSpec);
15092
15093        switch (specMode) {
15094        case MeasureSpec.UNSPECIFIED:
15095            result = size;
15096            break;
15097        case MeasureSpec.AT_MOST:
15098        case MeasureSpec.EXACTLY:
15099            result = specSize;
15100            break;
15101        }
15102        return result;
15103    }
15104
15105    /**
15106     * Returns the suggested minimum height that the view should use. This
15107     * returns the maximum of the view's minimum height
15108     * and the background's minimum height
15109     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15110     * <p>
15111     * When being used in {@link #onMeasure(int, int)}, the caller should still
15112     * ensure the returned height is within the requirements of the parent.
15113     *
15114     * @return The suggested minimum height of the view.
15115     */
15116    protected int getSuggestedMinimumHeight() {
15117        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15118
15119    }
15120
15121    /**
15122     * Returns the suggested minimum width that the view should use. This
15123     * returns the maximum of the view's minimum width)
15124     * and the background's minimum width
15125     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15126     * <p>
15127     * When being used in {@link #onMeasure(int, int)}, the caller should still
15128     * ensure the returned width is within the requirements of the parent.
15129     *
15130     * @return The suggested minimum width of the view.
15131     */
15132    protected int getSuggestedMinimumWidth() {
15133        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15134    }
15135
15136    /**
15137     * Returns the minimum height of the view.
15138     *
15139     * @return the minimum height the view will try to be.
15140     *
15141     * @see #setMinimumHeight(int)
15142     *
15143     * @attr ref android.R.styleable#View_minHeight
15144     */
15145    public int getMinimumHeight() {
15146        return mMinHeight;
15147    }
15148
15149    /**
15150     * Sets the minimum height of the view. It is not guaranteed the view will
15151     * be able to achieve this minimum height (for example, if its parent layout
15152     * constrains it with less available height).
15153     *
15154     * @param minHeight The minimum height the view will try to be.
15155     *
15156     * @see #getMinimumHeight()
15157     *
15158     * @attr ref android.R.styleable#View_minHeight
15159     */
15160    public void setMinimumHeight(int minHeight) {
15161        mMinHeight = minHeight;
15162        requestLayout();
15163    }
15164
15165    /**
15166     * Returns the minimum width of the view.
15167     *
15168     * @return the minimum width the view will try to be.
15169     *
15170     * @see #setMinimumWidth(int)
15171     *
15172     * @attr ref android.R.styleable#View_minWidth
15173     */
15174    public int getMinimumWidth() {
15175        return mMinWidth;
15176    }
15177
15178    /**
15179     * Sets the minimum width of the view. It is not guaranteed the view will
15180     * be able to achieve this minimum width (for example, if its parent layout
15181     * constrains it with less available width).
15182     *
15183     * @param minWidth The minimum width the view will try to be.
15184     *
15185     * @see #getMinimumWidth()
15186     *
15187     * @attr ref android.R.styleable#View_minWidth
15188     */
15189    public void setMinimumWidth(int minWidth) {
15190        mMinWidth = minWidth;
15191        requestLayout();
15192
15193    }
15194
15195    /**
15196     * Get the animation currently associated with this view.
15197     *
15198     * @return The animation that is currently playing or
15199     *         scheduled to play for this view.
15200     */
15201    public Animation getAnimation() {
15202        return mCurrentAnimation;
15203    }
15204
15205    /**
15206     * Start the specified animation now.
15207     *
15208     * @param animation the animation to start now
15209     */
15210    public void startAnimation(Animation animation) {
15211        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15212        setAnimation(animation);
15213        invalidateParentCaches();
15214        invalidate(true);
15215    }
15216
15217    /**
15218     * Cancels any animations for this view.
15219     */
15220    public void clearAnimation() {
15221        if (mCurrentAnimation != null) {
15222            mCurrentAnimation.detach();
15223        }
15224        mCurrentAnimation = null;
15225        invalidateParentIfNeeded();
15226    }
15227
15228    /**
15229     * Sets the next animation to play for this view.
15230     * If you want the animation to play immediately, use
15231     * {@link #startAnimation(android.view.animation.Animation)} instead.
15232     * This method provides allows fine-grained
15233     * control over the start time and invalidation, but you
15234     * must make sure that 1) the animation has a start time set, and
15235     * 2) the view's parent (which controls animations on its children)
15236     * will be invalidated when the animation is supposed to
15237     * start.
15238     *
15239     * @param animation The next animation, or null.
15240     */
15241    public void setAnimation(Animation animation) {
15242        mCurrentAnimation = animation;
15243
15244        if (animation != null) {
15245            // If the screen is off assume the animation start time is now instead of
15246            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15247            // would cause the animation to start when the screen turns back on
15248            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15249                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15250                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15251            }
15252            animation.reset();
15253        }
15254    }
15255
15256    /**
15257     * Invoked by a parent ViewGroup to notify the start of the animation
15258     * currently associated with this view. If you override this method,
15259     * always call super.onAnimationStart();
15260     *
15261     * @see #setAnimation(android.view.animation.Animation)
15262     * @see #getAnimation()
15263     */
15264    protected void onAnimationStart() {
15265        mPrivateFlags |= ANIMATION_STARTED;
15266    }
15267
15268    /**
15269     * Invoked by a parent ViewGroup to notify the end of the animation
15270     * currently associated with this view. If you override this method,
15271     * always call super.onAnimationEnd();
15272     *
15273     * @see #setAnimation(android.view.animation.Animation)
15274     * @see #getAnimation()
15275     */
15276    protected void onAnimationEnd() {
15277        mPrivateFlags &= ~ANIMATION_STARTED;
15278    }
15279
15280    /**
15281     * Invoked if there is a Transform that involves alpha. Subclass that can
15282     * draw themselves with the specified alpha should return true, and then
15283     * respect that alpha when their onDraw() is called. If this returns false
15284     * then the view may be redirected to draw into an offscreen buffer to
15285     * fulfill the request, which will look fine, but may be slower than if the
15286     * subclass handles it internally. The default implementation returns false.
15287     *
15288     * @param alpha The alpha (0..255) to apply to the view's drawing
15289     * @return true if the view can draw with the specified alpha.
15290     */
15291    protected boolean onSetAlpha(int alpha) {
15292        return false;
15293    }
15294
15295    /**
15296     * This is used by the RootView to perform an optimization when
15297     * the view hierarchy contains one or several SurfaceView.
15298     * SurfaceView is always considered transparent, but its children are not,
15299     * therefore all View objects remove themselves from the global transparent
15300     * region (passed as a parameter to this function).
15301     *
15302     * @param region The transparent region for this ViewAncestor (window).
15303     *
15304     * @return Returns true if the effective visibility of the view at this
15305     * point is opaque, regardless of the transparent region; returns false
15306     * if it is possible for underlying windows to be seen behind the view.
15307     *
15308     * {@hide}
15309     */
15310    public boolean gatherTransparentRegion(Region region) {
15311        final AttachInfo attachInfo = mAttachInfo;
15312        if (region != null && attachInfo != null) {
15313            final int pflags = mPrivateFlags;
15314            if ((pflags & SKIP_DRAW) == 0) {
15315                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15316                // remove it from the transparent region.
15317                final int[] location = attachInfo.mTransparentLocation;
15318                getLocationInWindow(location);
15319                region.op(location[0], location[1], location[0] + mRight - mLeft,
15320                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15321            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15322                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15323                // exists, so we remove the background drawable's non-transparent
15324                // parts from this transparent region.
15325                applyDrawableToTransparentRegion(mBackground, region);
15326            }
15327        }
15328        return true;
15329    }
15330
15331    /**
15332     * Play a sound effect for this view.
15333     *
15334     * <p>The framework will play sound effects for some built in actions, such as
15335     * clicking, but you may wish to play these effects in your widget,
15336     * for instance, for internal navigation.
15337     *
15338     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15339     * {@link #isSoundEffectsEnabled()} is true.
15340     *
15341     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15342     */
15343    public void playSoundEffect(int soundConstant) {
15344        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15345            return;
15346        }
15347        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15348    }
15349
15350    /**
15351     * BZZZTT!!1!
15352     *
15353     * <p>Provide haptic feedback to the user for this view.
15354     *
15355     * <p>The framework will provide haptic feedback for some built in actions,
15356     * such as long presses, but you may wish to provide feedback for your
15357     * own widget.
15358     *
15359     * <p>The feedback will only be performed if
15360     * {@link #isHapticFeedbackEnabled()} is true.
15361     *
15362     * @param feedbackConstant One of the constants defined in
15363     * {@link HapticFeedbackConstants}
15364     */
15365    public boolean performHapticFeedback(int feedbackConstant) {
15366        return performHapticFeedback(feedbackConstant, 0);
15367    }
15368
15369    /**
15370     * BZZZTT!!1!
15371     *
15372     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15373     *
15374     * @param feedbackConstant One of the constants defined in
15375     * {@link HapticFeedbackConstants}
15376     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15377     */
15378    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15379        if (mAttachInfo == null) {
15380            return false;
15381        }
15382        //noinspection SimplifiableIfStatement
15383        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15384                && !isHapticFeedbackEnabled()) {
15385            return false;
15386        }
15387        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15388                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15389    }
15390
15391    /**
15392     * Request that the visibility of the status bar or other screen/window
15393     * decorations be changed.
15394     *
15395     * <p>This method is used to put the over device UI into temporary modes
15396     * where the user's attention is focused more on the application content,
15397     * by dimming or hiding surrounding system affordances.  This is typically
15398     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15399     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15400     * to be placed behind the action bar (and with these flags other system
15401     * affordances) so that smooth transitions between hiding and showing them
15402     * can be done.
15403     *
15404     * <p>Two representative examples of the use of system UI visibility is
15405     * implementing a content browsing application (like a magazine reader)
15406     * and a video playing application.
15407     *
15408     * <p>The first code shows a typical implementation of a View in a content
15409     * browsing application.  In this implementation, the application goes
15410     * into a content-oriented mode by hiding the status bar and action bar,
15411     * and putting the navigation elements into lights out mode.  The user can
15412     * then interact with content while in this mode.  Such an application should
15413     * provide an easy way for the user to toggle out of the mode (such as to
15414     * check information in the status bar or access notifications).  In the
15415     * implementation here, this is done simply by tapping on the content.
15416     *
15417     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15418     *      content}
15419     *
15420     * <p>This second code sample shows a typical implementation of a View
15421     * in a video playing application.  In this situation, while the video is
15422     * playing the application would like to go into a complete full-screen mode,
15423     * to use as much of the display as possible for the video.  When in this state
15424     * the user can not interact with the application; the system intercepts
15425     * touching on the screen to pop the UI out of full screen mode.  See
15426     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15427     *
15428     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15429     *      content}
15430     *
15431     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15432     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15433     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15434     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15435     */
15436    public void setSystemUiVisibility(int visibility) {
15437        if (visibility != mSystemUiVisibility) {
15438            mSystemUiVisibility = visibility;
15439            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15440                mParent.recomputeViewAttributes(this);
15441            }
15442        }
15443    }
15444
15445    /**
15446     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15447     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15448     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15449     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15450     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15451     */
15452    public int getSystemUiVisibility() {
15453        return mSystemUiVisibility;
15454    }
15455
15456    /**
15457     * Returns the current system UI visibility that is currently set for
15458     * the entire window.  This is the combination of the
15459     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15460     * views in the window.
15461     */
15462    public int getWindowSystemUiVisibility() {
15463        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15464    }
15465
15466    /**
15467     * Override to find out when the window's requested system UI visibility
15468     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15469     * This is different from the callbacks recieved through
15470     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15471     * in that this is only telling you about the local request of the window,
15472     * not the actual values applied by the system.
15473     */
15474    public void onWindowSystemUiVisibilityChanged(int visible) {
15475    }
15476
15477    /**
15478     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15479     * the view hierarchy.
15480     */
15481    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15482        onWindowSystemUiVisibilityChanged(visible);
15483    }
15484
15485    /**
15486     * Set a listener to receive callbacks when the visibility of the system bar changes.
15487     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15488     */
15489    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15490        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15491        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15492            mParent.recomputeViewAttributes(this);
15493        }
15494    }
15495
15496    /**
15497     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15498     * the view hierarchy.
15499     */
15500    public void dispatchSystemUiVisibilityChanged(int visibility) {
15501        ListenerInfo li = mListenerInfo;
15502        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15503            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15504                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15505        }
15506    }
15507
15508    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15509        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15510        if (val != mSystemUiVisibility) {
15511            setSystemUiVisibility(val);
15512            return true;
15513        }
15514        return false;
15515    }
15516
15517    /** @hide */
15518    public void setDisabledSystemUiVisibility(int flags) {
15519        if (mAttachInfo != null) {
15520            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15521                mAttachInfo.mDisabledSystemUiVisibility = flags;
15522                if (mParent != null) {
15523                    mParent.recomputeViewAttributes(this);
15524                }
15525            }
15526        }
15527    }
15528
15529    /**
15530     * Creates an image that the system displays during the drag and drop
15531     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15532     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15533     * appearance as the given View. The default also positions the center of the drag shadow
15534     * directly under the touch point. If no View is provided (the constructor with no parameters
15535     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15536     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15537     * default is an invisible drag shadow.
15538     * <p>
15539     * You are not required to use the View you provide to the constructor as the basis of the
15540     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15541     * anything you want as the drag shadow.
15542     * </p>
15543     * <p>
15544     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15545     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15546     *  size and position of the drag shadow. It uses this data to construct a
15547     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15548     *  so that your application can draw the shadow image in the Canvas.
15549     * </p>
15550     *
15551     * <div class="special reference">
15552     * <h3>Developer Guides</h3>
15553     * <p>For a guide to implementing drag and drop features, read the
15554     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15555     * </div>
15556     */
15557    public static class DragShadowBuilder {
15558        private final WeakReference<View> mView;
15559
15560        /**
15561         * Constructs a shadow image builder based on a View. By default, the resulting drag
15562         * shadow will have the same appearance and dimensions as the View, with the touch point
15563         * over the center of the View.
15564         * @param view A View. Any View in scope can be used.
15565         */
15566        public DragShadowBuilder(View view) {
15567            mView = new WeakReference<View>(view);
15568        }
15569
15570        /**
15571         * Construct a shadow builder object with no associated View.  This
15572         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15573         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15574         * to supply the drag shadow's dimensions and appearance without
15575         * reference to any View object. If they are not overridden, then the result is an
15576         * invisible drag shadow.
15577         */
15578        public DragShadowBuilder() {
15579            mView = new WeakReference<View>(null);
15580        }
15581
15582        /**
15583         * Returns the View object that had been passed to the
15584         * {@link #View.DragShadowBuilder(View)}
15585         * constructor.  If that View parameter was {@code null} or if the
15586         * {@link #View.DragShadowBuilder()}
15587         * constructor was used to instantiate the builder object, this method will return
15588         * null.
15589         *
15590         * @return The View object associate with this builder object.
15591         */
15592        @SuppressWarnings({"JavadocReference"})
15593        final public View getView() {
15594            return mView.get();
15595        }
15596
15597        /**
15598         * Provides the metrics for the shadow image. These include the dimensions of
15599         * the shadow image, and the point within that shadow that should
15600         * be centered under the touch location while dragging.
15601         * <p>
15602         * The default implementation sets the dimensions of the shadow to be the
15603         * same as the dimensions of the View itself and centers the shadow under
15604         * the touch point.
15605         * </p>
15606         *
15607         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15608         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15609         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15610         * image.
15611         *
15612         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15613         * shadow image that should be underneath the touch point during the drag and drop
15614         * operation. Your application must set {@link android.graphics.Point#x} to the
15615         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15616         */
15617        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15618            final View view = mView.get();
15619            if (view != null) {
15620                shadowSize.set(view.getWidth(), view.getHeight());
15621                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15622            } else {
15623                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15624            }
15625        }
15626
15627        /**
15628         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15629         * based on the dimensions it received from the
15630         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15631         *
15632         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15633         */
15634        public void onDrawShadow(Canvas canvas) {
15635            final View view = mView.get();
15636            if (view != null) {
15637                view.draw(canvas);
15638            } else {
15639                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15640            }
15641        }
15642    }
15643
15644    /**
15645     * Starts a drag and drop operation. When your application calls this method, it passes a
15646     * {@link android.view.View.DragShadowBuilder} object to the system. The
15647     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15648     * to get metrics for the drag shadow, and then calls the object's
15649     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15650     * <p>
15651     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15652     *  drag events to all the View objects in your application that are currently visible. It does
15653     *  this either by calling the View object's drag listener (an implementation of
15654     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15655     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15656     *  Both are passed a {@link android.view.DragEvent} object that has a
15657     *  {@link android.view.DragEvent#getAction()} value of
15658     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15659     * </p>
15660     * <p>
15661     * Your application can invoke startDrag() on any attached View object. The View object does not
15662     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15663     * be related to the View the user selected for dragging.
15664     * </p>
15665     * @param data A {@link android.content.ClipData} object pointing to the data to be
15666     * transferred by the drag and drop operation.
15667     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15668     * drag shadow.
15669     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15670     * drop operation. This Object is put into every DragEvent object sent by the system during the
15671     * current drag.
15672     * <p>
15673     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15674     * to the target Views. For example, it can contain flags that differentiate between a
15675     * a copy operation and a move operation.
15676     * </p>
15677     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15678     * so the parameter should be set to 0.
15679     * @return {@code true} if the method completes successfully, or
15680     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15681     * do a drag, and so no drag operation is in progress.
15682     */
15683    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15684            Object myLocalState, int flags) {
15685        if (ViewDebug.DEBUG_DRAG) {
15686            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15687        }
15688        boolean okay = false;
15689
15690        Point shadowSize = new Point();
15691        Point shadowTouchPoint = new Point();
15692        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15693
15694        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15695                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15696            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15697        }
15698
15699        if (ViewDebug.DEBUG_DRAG) {
15700            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15701                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15702        }
15703        Surface surface = new Surface();
15704        try {
15705            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15706                    flags, shadowSize.x, shadowSize.y, surface);
15707            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15708                    + " surface=" + surface);
15709            if (token != null) {
15710                Canvas canvas = surface.lockCanvas(null);
15711                try {
15712                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15713                    shadowBuilder.onDrawShadow(canvas);
15714                } finally {
15715                    surface.unlockCanvasAndPost(canvas);
15716                }
15717
15718                final ViewRootImpl root = getViewRootImpl();
15719
15720                // Cache the local state object for delivery with DragEvents
15721                root.setLocalDragState(myLocalState);
15722
15723                // repurpose 'shadowSize' for the last touch point
15724                root.getLastTouchPoint(shadowSize);
15725
15726                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15727                        shadowSize.x, shadowSize.y,
15728                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15729                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15730
15731                // Off and running!  Release our local surface instance; the drag
15732                // shadow surface is now managed by the system process.
15733                surface.release();
15734            }
15735        } catch (Exception e) {
15736            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15737            surface.destroy();
15738        }
15739
15740        return okay;
15741    }
15742
15743    /**
15744     * Handles drag events sent by the system following a call to
15745     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15746     *<p>
15747     * When the system calls this method, it passes a
15748     * {@link android.view.DragEvent} object. A call to
15749     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15750     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15751     * operation.
15752     * @param event The {@link android.view.DragEvent} sent by the system.
15753     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15754     * in DragEvent, indicating the type of drag event represented by this object.
15755     * @return {@code true} if the method was successful, otherwise {@code false}.
15756     * <p>
15757     *  The method should return {@code true} in response to an action type of
15758     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15759     *  operation.
15760     * </p>
15761     * <p>
15762     *  The method should also return {@code true} in response to an action type of
15763     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15764     *  {@code false} if it didn't.
15765     * </p>
15766     */
15767    public boolean onDragEvent(DragEvent event) {
15768        return false;
15769    }
15770
15771    /**
15772     * Detects if this View is enabled and has a drag event listener.
15773     * If both are true, then it calls the drag event listener with the
15774     * {@link android.view.DragEvent} it received. If the drag event listener returns
15775     * {@code true}, then dispatchDragEvent() returns {@code true}.
15776     * <p>
15777     * For all other cases, the method calls the
15778     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15779     * method and returns its result.
15780     * </p>
15781     * <p>
15782     * This ensures that a drag event is always consumed, even if the View does not have a drag
15783     * event listener. However, if the View has a listener and the listener returns true, then
15784     * onDragEvent() is not called.
15785     * </p>
15786     */
15787    public boolean dispatchDragEvent(DragEvent event) {
15788        //noinspection SimplifiableIfStatement
15789        ListenerInfo li = mListenerInfo;
15790        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15791                && li.mOnDragListener.onDrag(this, event)) {
15792            return true;
15793        }
15794        return onDragEvent(event);
15795    }
15796
15797    boolean canAcceptDrag() {
15798        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15799    }
15800
15801    /**
15802     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15803     * it is ever exposed at all.
15804     * @hide
15805     */
15806    public void onCloseSystemDialogs(String reason) {
15807    }
15808
15809    /**
15810     * Given a Drawable whose bounds have been set to draw into this view,
15811     * update a Region being computed for
15812     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15813     * that any non-transparent parts of the Drawable are removed from the
15814     * given transparent region.
15815     *
15816     * @param dr The Drawable whose transparency is to be applied to the region.
15817     * @param region A Region holding the current transparency information,
15818     * where any parts of the region that are set are considered to be
15819     * transparent.  On return, this region will be modified to have the
15820     * transparency information reduced by the corresponding parts of the
15821     * Drawable that are not transparent.
15822     * {@hide}
15823     */
15824    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15825        if (DBG) {
15826            Log.i("View", "Getting transparent region for: " + this);
15827        }
15828        final Region r = dr.getTransparentRegion();
15829        final Rect db = dr.getBounds();
15830        final AttachInfo attachInfo = mAttachInfo;
15831        if (r != null && attachInfo != null) {
15832            final int w = getRight()-getLeft();
15833            final int h = getBottom()-getTop();
15834            if (db.left > 0) {
15835                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15836                r.op(0, 0, db.left, h, Region.Op.UNION);
15837            }
15838            if (db.right < w) {
15839                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15840                r.op(db.right, 0, w, h, Region.Op.UNION);
15841            }
15842            if (db.top > 0) {
15843                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15844                r.op(0, 0, w, db.top, Region.Op.UNION);
15845            }
15846            if (db.bottom < h) {
15847                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15848                r.op(0, db.bottom, w, h, Region.Op.UNION);
15849            }
15850            final int[] location = attachInfo.mTransparentLocation;
15851            getLocationInWindow(location);
15852            r.translate(location[0], location[1]);
15853            region.op(r, Region.Op.INTERSECT);
15854        } else {
15855            region.op(db, Region.Op.DIFFERENCE);
15856        }
15857    }
15858
15859    private void checkForLongClick(int delayOffset) {
15860        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15861            mHasPerformedLongPress = false;
15862
15863            if (mPendingCheckForLongPress == null) {
15864                mPendingCheckForLongPress = new CheckForLongPress();
15865            }
15866            mPendingCheckForLongPress.rememberWindowAttachCount();
15867            postDelayed(mPendingCheckForLongPress,
15868                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15869        }
15870    }
15871
15872    /**
15873     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15874     * LayoutInflater} class, which provides a full range of options for view inflation.
15875     *
15876     * @param context The Context object for your activity or application.
15877     * @param resource The resource ID to inflate
15878     * @param root A view group that will be the parent.  Used to properly inflate the
15879     * layout_* parameters.
15880     * @see LayoutInflater
15881     */
15882    public static View inflate(Context context, int resource, ViewGroup root) {
15883        LayoutInflater factory = LayoutInflater.from(context);
15884        return factory.inflate(resource, root);
15885    }
15886
15887    /**
15888     * Scroll the view with standard behavior for scrolling beyond the normal
15889     * content boundaries. Views that call this method should override
15890     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15891     * results of an over-scroll operation.
15892     *
15893     * Views can use this method to handle any touch or fling-based scrolling.
15894     *
15895     * @param deltaX Change in X in pixels
15896     * @param deltaY Change in Y in pixels
15897     * @param scrollX Current X scroll value in pixels before applying deltaX
15898     * @param scrollY Current Y scroll value in pixels before applying deltaY
15899     * @param scrollRangeX Maximum content scroll range along the X axis
15900     * @param scrollRangeY Maximum content scroll range along the Y axis
15901     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15902     *          along the X axis.
15903     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15904     *          along the Y axis.
15905     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15906     * @return true if scrolling was clamped to an over-scroll boundary along either
15907     *          axis, false otherwise.
15908     */
15909    @SuppressWarnings({"UnusedParameters"})
15910    protected boolean overScrollBy(int deltaX, int deltaY,
15911            int scrollX, int scrollY,
15912            int scrollRangeX, int scrollRangeY,
15913            int maxOverScrollX, int maxOverScrollY,
15914            boolean isTouchEvent) {
15915        final int overScrollMode = mOverScrollMode;
15916        final boolean canScrollHorizontal =
15917                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15918        final boolean canScrollVertical =
15919                computeVerticalScrollRange() > computeVerticalScrollExtent();
15920        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15921                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15922        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15923                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15924
15925        int newScrollX = scrollX + deltaX;
15926        if (!overScrollHorizontal) {
15927            maxOverScrollX = 0;
15928        }
15929
15930        int newScrollY = scrollY + deltaY;
15931        if (!overScrollVertical) {
15932            maxOverScrollY = 0;
15933        }
15934
15935        // Clamp values if at the limits and record
15936        final int left = -maxOverScrollX;
15937        final int right = maxOverScrollX + scrollRangeX;
15938        final int top = -maxOverScrollY;
15939        final int bottom = maxOverScrollY + scrollRangeY;
15940
15941        boolean clampedX = false;
15942        if (newScrollX > right) {
15943            newScrollX = right;
15944            clampedX = true;
15945        } else if (newScrollX < left) {
15946            newScrollX = left;
15947            clampedX = true;
15948        }
15949
15950        boolean clampedY = false;
15951        if (newScrollY > bottom) {
15952            newScrollY = bottom;
15953            clampedY = true;
15954        } else if (newScrollY < top) {
15955            newScrollY = top;
15956            clampedY = true;
15957        }
15958
15959        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15960
15961        return clampedX || clampedY;
15962    }
15963
15964    /**
15965     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15966     * respond to the results of an over-scroll operation.
15967     *
15968     * @param scrollX New X scroll value in pixels
15969     * @param scrollY New Y scroll value in pixels
15970     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15971     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15972     */
15973    protected void onOverScrolled(int scrollX, int scrollY,
15974            boolean clampedX, boolean clampedY) {
15975        // Intentionally empty.
15976    }
15977
15978    /**
15979     * Returns the over-scroll mode for this view. The result will be
15980     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15981     * (allow over-scrolling only if the view content is larger than the container),
15982     * or {@link #OVER_SCROLL_NEVER}.
15983     *
15984     * @return This view's over-scroll mode.
15985     */
15986    public int getOverScrollMode() {
15987        return mOverScrollMode;
15988    }
15989
15990    /**
15991     * Set the over-scroll mode for this view. Valid over-scroll modes are
15992     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15993     * (allow over-scrolling only if the view content is larger than the container),
15994     * or {@link #OVER_SCROLL_NEVER}.
15995     *
15996     * Setting the over-scroll mode of a view will have an effect only if the
15997     * view is capable of scrolling.
15998     *
15999     * @param overScrollMode The new over-scroll mode for this view.
16000     */
16001    public void setOverScrollMode(int overScrollMode) {
16002        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16003                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16004                overScrollMode != OVER_SCROLL_NEVER) {
16005            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16006        }
16007        mOverScrollMode = overScrollMode;
16008    }
16009
16010    /**
16011     * Gets a scale factor that determines the distance the view should scroll
16012     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16013     * @return The vertical scroll scale factor.
16014     * @hide
16015     */
16016    protected float getVerticalScrollFactor() {
16017        if (mVerticalScrollFactor == 0) {
16018            TypedValue outValue = new TypedValue();
16019            if (!mContext.getTheme().resolveAttribute(
16020                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16021                throw new IllegalStateException(
16022                        "Expected theme to define listPreferredItemHeight.");
16023            }
16024            mVerticalScrollFactor = outValue.getDimension(
16025                    mContext.getResources().getDisplayMetrics());
16026        }
16027        return mVerticalScrollFactor;
16028    }
16029
16030    /**
16031     * Gets a scale factor that determines the distance the view should scroll
16032     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16033     * @return The horizontal scroll scale factor.
16034     * @hide
16035     */
16036    protected float getHorizontalScrollFactor() {
16037        // TODO: Should use something else.
16038        return getVerticalScrollFactor();
16039    }
16040
16041    /**
16042     * Return the value specifying the text direction or policy that was set with
16043     * {@link #setTextDirection(int)}.
16044     *
16045     * @return the defined text direction. It can be one of:
16046     *
16047     * {@link #TEXT_DIRECTION_INHERIT},
16048     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16049     * {@link #TEXT_DIRECTION_ANY_RTL},
16050     * {@link #TEXT_DIRECTION_LTR},
16051     * {@link #TEXT_DIRECTION_RTL},
16052     * {@link #TEXT_DIRECTION_LOCALE}
16053     * @hide
16054     */
16055    @ViewDebug.ExportedProperty(category = "text", mapping = {
16056            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16057            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16058            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16059            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16060            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16061            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16062    })
16063    public int getTextDirection() {
16064        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16065    }
16066
16067    /**
16068     * Set the text direction.
16069     *
16070     * @param textDirection the direction to set. Should be one of:
16071     *
16072     * {@link #TEXT_DIRECTION_INHERIT},
16073     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16074     * {@link #TEXT_DIRECTION_ANY_RTL},
16075     * {@link #TEXT_DIRECTION_LTR},
16076     * {@link #TEXT_DIRECTION_RTL},
16077     * {@link #TEXT_DIRECTION_LOCALE}
16078     * @hide
16079     */
16080    public void setTextDirection(int textDirection) {
16081        if (getTextDirection() != textDirection) {
16082            // Reset the current text direction and the resolved one
16083            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16084            resetResolvedTextDirection();
16085            // Set the new text direction
16086            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16087            // Refresh
16088            requestLayout();
16089            invalidate(true);
16090        }
16091    }
16092
16093    /**
16094     * Return the resolved text direction.
16095     *
16096     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16097     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16098     * up the parent chain of the view. if there is no parent, then it will return the default
16099     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16100     *
16101     * @return the resolved text direction. Returns one of:
16102     *
16103     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16104     * {@link #TEXT_DIRECTION_ANY_RTL},
16105     * {@link #TEXT_DIRECTION_LTR},
16106     * {@link #TEXT_DIRECTION_RTL},
16107     * {@link #TEXT_DIRECTION_LOCALE}
16108     * @hide
16109     */
16110    public int getResolvedTextDirection() {
16111        // The text direction will be resolved only if needed
16112        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16113            resolveTextDirection();
16114        }
16115        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16116    }
16117
16118    /**
16119     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16120     * resolution is done.
16121     * @hide
16122     */
16123    public void resolveTextDirection() {
16124        // Reset any previous text direction resolution
16125        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16126
16127        if (hasRtlSupport()) {
16128            // Set resolved text direction flag depending on text direction flag
16129            final int textDirection = getTextDirection();
16130            switch(textDirection) {
16131                case TEXT_DIRECTION_INHERIT:
16132                    if (canResolveTextDirection()) {
16133                        ViewGroup viewGroup = ((ViewGroup) mParent);
16134
16135                        // Set current resolved direction to the same value as the parent's one
16136                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16137                        switch (parentResolvedDirection) {
16138                            case TEXT_DIRECTION_FIRST_STRONG:
16139                            case TEXT_DIRECTION_ANY_RTL:
16140                            case TEXT_DIRECTION_LTR:
16141                            case TEXT_DIRECTION_RTL:
16142                            case TEXT_DIRECTION_LOCALE:
16143                                mPrivateFlags2 |=
16144                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16145                                break;
16146                            default:
16147                                // Default resolved direction is "first strong" heuristic
16148                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16149                        }
16150                    } else {
16151                        // We cannot do the resolution if there is no parent, so use the default one
16152                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16153                    }
16154                    break;
16155                case TEXT_DIRECTION_FIRST_STRONG:
16156                case TEXT_DIRECTION_ANY_RTL:
16157                case TEXT_DIRECTION_LTR:
16158                case TEXT_DIRECTION_RTL:
16159                case TEXT_DIRECTION_LOCALE:
16160                    // Resolved direction is the same as text direction
16161                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16162                    break;
16163                default:
16164                    // Default resolved direction is "first strong" heuristic
16165                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16166            }
16167        } else {
16168            // Default resolved direction is "first strong" heuristic
16169            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16170        }
16171
16172        // Set to resolved
16173        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16174        onResolvedTextDirectionChanged();
16175    }
16176
16177    /**
16178     * Called when text direction has been resolved. Subclasses that care about text direction
16179     * resolution should override this method.
16180     *
16181     * The default implementation does nothing.
16182     * @hide
16183     */
16184    public void onResolvedTextDirectionChanged() {
16185    }
16186
16187    /**
16188     * Check if text direction resolution can be done.
16189     *
16190     * @return true if text direction resolution can be done otherwise return false.
16191     * @hide
16192     */
16193    public boolean canResolveTextDirection() {
16194        switch (getTextDirection()) {
16195            case TEXT_DIRECTION_INHERIT:
16196                return (mParent != null) && (mParent instanceof ViewGroup);
16197            default:
16198                return true;
16199        }
16200    }
16201
16202    /**
16203     * Reset resolved text direction. Text direction can be resolved with a call to
16204     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16205     * reset is done.
16206     * @hide
16207     */
16208    public void resetResolvedTextDirection() {
16209        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16210        onResolvedTextDirectionReset();
16211    }
16212
16213    /**
16214     * Called when text direction is reset. Subclasses that care about text direction reset should
16215     * override this method and do a reset of the text direction of their children. The default
16216     * implementation does nothing.
16217     * @hide
16218     */
16219    public void onResolvedTextDirectionReset() {
16220    }
16221
16222    /**
16223     * Return the value specifying the text alignment or policy that was set with
16224     * {@link #setTextAlignment(int)}.
16225     *
16226     * @return the defined text alignment. It can be one of:
16227     *
16228     * {@link #TEXT_ALIGNMENT_INHERIT},
16229     * {@link #TEXT_ALIGNMENT_GRAVITY},
16230     * {@link #TEXT_ALIGNMENT_CENTER},
16231     * {@link #TEXT_ALIGNMENT_TEXT_START},
16232     * {@link #TEXT_ALIGNMENT_TEXT_END},
16233     * {@link #TEXT_ALIGNMENT_VIEW_START},
16234     * {@link #TEXT_ALIGNMENT_VIEW_END}
16235     * @hide
16236     */
16237    @ViewDebug.ExportedProperty(category = "text", mapping = {
16238            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16239            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16240            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16241            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16242            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16243            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16244            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16245    })
16246    public int getTextAlignment() {
16247        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16248    }
16249
16250    /**
16251     * Set the text alignment.
16252     *
16253     * @param textAlignment The text alignment to set. Should be one of
16254     *
16255     * {@link #TEXT_ALIGNMENT_INHERIT},
16256     * {@link #TEXT_ALIGNMENT_GRAVITY},
16257     * {@link #TEXT_ALIGNMENT_CENTER},
16258     * {@link #TEXT_ALIGNMENT_TEXT_START},
16259     * {@link #TEXT_ALIGNMENT_TEXT_END},
16260     * {@link #TEXT_ALIGNMENT_VIEW_START},
16261     * {@link #TEXT_ALIGNMENT_VIEW_END}
16262     *
16263     * @attr ref android.R.styleable#View_textAlignment
16264     * @hide
16265     */
16266    public void setTextAlignment(int textAlignment) {
16267        if (textAlignment != getTextAlignment()) {
16268            // Reset the current and resolved text alignment
16269            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16270            resetResolvedTextAlignment();
16271            // Set the new text alignment
16272            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16273            // Refresh
16274            requestLayout();
16275            invalidate(true);
16276        }
16277    }
16278
16279    /**
16280     * Return the resolved text alignment.
16281     *
16282     * The resolved text alignment. This needs resolution if the value is
16283     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16284     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16285     *
16286     * @return the resolved text alignment. Returns one of:
16287     *
16288     * {@link #TEXT_ALIGNMENT_GRAVITY},
16289     * {@link #TEXT_ALIGNMENT_CENTER},
16290     * {@link #TEXT_ALIGNMENT_TEXT_START},
16291     * {@link #TEXT_ALIGNMENT_TEXT_END},
16292     * {@link #TEXT_ALIGNMENT_VIEW_START},
16293     * {@link #TEXT_ALIGNMENT_VIEW_END}
16294     * @hide
16295     */
16296    @ViewDebug.ExportedProperty(category = "text", mapping = {
16297            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16298            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16299            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16300            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16301            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16302            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16303            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16304    })
16305    public int getResolvedTextAlignment() {
16306        // If text alignment is not resolved, then resolve it
16307        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16308            resolveTextAlignment();
16309        }
16310        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16311    }
16312
16313    /**
16314     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16315     * resolution is done.
16316     * @hide
16317     */
16318    public void resolveTextAlignment() {
16319        // Reset any previous text alignment resolution
16320        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16321
16322        if (hasRtlSupport()) {
16323            // Set resolved text alignment flag depending on text alignment flag
16324            final int textAlignment = getTextAlignment();
16325            switch (textAlignment) {
16326                case TEXT_ALIGNMENT_INHERIT:
16327                    // Check if we can resolve the text alignment
16328                    if (canResolveLayoutDirection() && mParent instanceof View) {
16329                        View view = (View) mParent;
16330
16331                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16332                        switch (parentResolvedTextAlignment) {
16333                            case TEXT_ALIGNMENT_GRAVITY:
16334                            case TEXT_ALIGNMENT_TEXT_START:
16335                            case TEXT_ALIGNMENT_TEXT_END:
16336                            case TEXT_ALIGNMENT_CENTER:
16337                            case TEXT_ALIGNMENT_VIEW_START:
16338                            case TEXT_ALIGNMENT_VIEW_END:
16339                                // Resolved text alignment is the same as the parent resolved
16340                                // text alignment
16341                                mPrivateFlags2 |=
16342                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16343                                break;
16344                            default:
16345                                // Use default resolved text alignment
16346                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16347                        }
16348                    }
16349                    else {
16350                        // We cannot do the resolution if there is no parent so use the default
16351                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16352                    }
16353                    break;
16354                case TEXT_ALIGNMENT_GRAVITY:
16355                case TEXT_ALIGNMENT_TEXT_START:
16356                case TEXT_ALIGNMENT_TEXT_END:
16357                case TEXT_ALIGNMENT_CENTER:
16358                case TEXT_ALIGNMENT_VIEW_START:
16359                case TEXT_ALIGNMENT_VIEW_END:
16360                    // Resolved text alignment is the same as text alignment
16361                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16362                    break;
16363                default:
16364                    // Use default resolved text alignment
16365                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16366            }
16367        } else {
16368            // Use default resolved text alignment
16369            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16370        }
16371
16372        // Set the resolved
16373        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16374        onResolvedTextAlignmentChanged();
16375    }
16376
16377    /**
16378     * Check if text alignment resolution can be done.
16379     *
16380     * @return true if text alignment resolution can be done otherwise return false.
16381     * @hide
16382     */
16383    public boolean canResolveTextAlignment() {
16384        switch (getTextAlignment()) {
16385            case TEXT_DIRECTION_INHERIT:
16386                return (mParent != null);
16387            default:
16388                return true;
16389        }
16390    }
16391
16392    /**
16393     * Called when text alignment has been resolved. Subclasses that care about text alignment
16394     * resolution should override this method.
16395     *
16396     * The default implementation does nothing.
16397     * @hide
16398     */
16399    public void onResolvedTextAlignmentChanged() {
16400    }
16401
16402    /**
16403     * Reset resolved text alignment. Text alignment can be resolved with a call to
16404     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16405     * reset is done.
16406     * @hide
16407     */
16408    public void resetResolvedTextAlignment() {
16409        // Reset any previous text alignment resolution
16410        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16411        onResolvedTextAlignmentReset();
16412    }
16413
16414    /**
16415     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16416     * override this method and do a reset of the text alignment of their children. The default
16417     * implementation does nothing.
16418     * @hide
16419     */
16420    public void onResolvedTextAlignmentReset() {
16421    }
16422
16423    //
16424    // Properties
16425    //
16426    /**
16427     * A Property wrapper around the <code>alpha</code> functionality handled by the
16428     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16429     */
16430    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16431        @Override
16432        public void setValue(View object, float value) {
16433            object.setAlpha(value);
16434        }
16435
16436        @Override
16437        public Float get(View object) {
16438            return object.getAlpha();
16439        }
16440    };
16441
16442    /**
16443     * A Property wrapper around the <code>translationX</code> functionality handled by the
16444     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16445     */
16446    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16447        @Override
16448        public void setValue(View object, float value) {
16449            object.setTranslationX(value);
16450        }
16451
16452                @Override
16453        public Float get(View object) {
16454            return object.getTranslationX();
16455        }
16456    };
16457
16458    /**
16459     * A Property wrapper around the <code>translationY</code> functionality handled by the
16460     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16461     */
16462    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16463        @Override
16464        public void setValue(View object, float value) {
16465            object.setTranslationY(value);
16466        }
16467
16468        @Override
16469        public Float get(View object) {
16470            return object.getTranslationY();
16471        }
16472    };
16473
16474    /**
16475     * A Property wrapper around the <code>x</code> functionality handled by the
16476     * {@link View#setX(float)} and {@link View#getX()} methods.
16477     */
16478    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16479        @Override
16480        public void setValue(View object, float value) {
16481            object.setX(value);
16482        }
16483
16484        @Override
16485        public Float get(View object) {
16486            return object.getX();
16487        }
16488    };
16489
16490    /**
16491     * A Property wrapper around the <code>y</code> functionality handled by the
16492     * {@link View#setY(float)} and {@link View#getY()} methods.
16493     */
16494    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16495        @Override
16496        public void setValue(View object, float value) {
16497            object.setY(value);
16498        }
16499
16500        @Override
16501        public Float get(View object) {
16502            return object.getY();
16503        }
16504    };
16505
16506    /**
16507     * A Property wrapper around the <code>rotation</code> functionality handled by the
16508     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16509     */
16510    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16511        @Override
16512        public void setValue(View object, float value) {
16513            object.setRotation(value);
16514        }
16515
16516        @Override
16517        public Float get(View object) {
16518            return object.getRotation();
16519        }
16520    };
16521
16522    /**
16523     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16524     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16525     */
16526    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16527        @Override
16528        public void setValue(View object, float value) {
16529            object.setRotationX(value);
16530        }
16531
16532        @Override
16533        public Float get(View object) {
16534            return object.getRotationX();
16535        }
16536    };
16537
16538    /**
16539     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16540     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16541     */
16542    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16543        @Override
16544        public void setValue(View object, float value) {
16545            object.setRotationY(value);
16546        }
16547
16548        @Override
16549        public Float get(View object) {
16550            return object.getRotationY();
16551        }
16552    };
16553
16554    /**
16555     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16556     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16557     */
16558    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16559        @Override
16560        public void setValue(View object, float value) {
16561            object.setScaleX(value);
16562        }
16563
16564        @Override
16565        public Float get(View object) {
16566            return object.getScaleX();
16567        }
16568    };
16569
16570    /**
16571     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16572     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16573     */
16574    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16575        @Override
16576        public void setValue(View object, float value) {
16577            object.setScaleY(value);
16578        }
16579
16580        @Override
16581        public Float get(View object) {
16582            return object.getScaleY();
16583        }
16584    };
16585
16586    /**
16587     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16588     * Each MeasureSpec represents a requirement for either the width or the height.
16589     * A MeasureSpec is comprised of a size and a mode. There are three possible
16590     * modes:
16591     * <dl>
16592     * <dt>UNSPECIFIED</dt>
16593     * <dd>
16594     * The parent has not imposed any constraint on the child. It can be whatever size
16595     * it wants.
16596     * </dd>
16597     *
16598     * <dt>EXACTLY</dt>
16599     * <dd>
16600     * The parent has determined an exact size for the child. The child is going to be
16601     * given those bounds regardless of how big it wants to be.
16602     * </dd>
16603     *
16604     * <dt>AT_MOST</dt>
16605     * <dd>
16606     * The child can be as large as it wants up to the specified size.
16607     * </dd>
16608     * </dl>
16609     *
16610     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16611     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16612     */
16613    public static class MeasureSpec {
16614        private static final int MODE_SHIFT = 30;
16615        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16616
16617        /**
16618         * Measure specification mode: The parent has not imposed any constraint
16619         * on the child. It can be whatever size it wants.
16620         */
16621        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16622
16623        /**
16624         * Measure specification mode: The parent has determined an exact size
16625         * for the child. The child is going to be given those bounds regardless
16626         * of how big it wants to be.
16627         */
16628        public static final int EXACTLY     = 1 << MODE_SHIFT;
16629
16630        /**
16631         * Measure specification mode: The child can be as large as it wants up
16632         * to the specified size.
16633         */
16634        public static final int AT_MOST     = 2 << MODE_SHIFT;
16635
16636        /**
16637         * Creates a measure specification based on the supplied size and mode.
16638         *
16639         * The mode must always be one of the following:
16640         * <ul>
16641         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16642         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16643         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16644         * </ul>
16645         *
16646         * @param size the size of the measure specification
16647         * @param mode the mode of the measure specification
16648         * @return the measure specification based on size and mode
16649         */
16650        public static int makeMeasureSpec(int size, int mode) {
16651            return size + mode;
16652        }
16653
16654        /**
16655         * Extracts the mode from the supplied measure specification.
16656         *
16657         * @param measureSpec the measure specification to extract the mode from
16658         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16659         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16660         *         {@link android.view.View.MeasureSpec#EXACTLY}
16661         */
16662        public static int getMode(int measureSpec) {
16663            return (measureSpec & MODE_MASK);
16664        }
16665
16666        /**
16667         * Extracts the size from the supplied measure specification.
16668         *
16669         * @param measureSpec the measure specification to extract the size from
16670         * @return the size in pixels defined in the supplied measure specification
16671         */
16672        public static int getSize(int measureSpec) {
16673            return (measureSpec & ~MODE_MASK);
16674        }
16675
16676        /**
16677         * Returns a String representation of the specified measure
16678         * specification.
16679         *
16680         * @param measureSpec the measure specification to convert to a String
16681         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16682         */
16683        public static String toString(int measureSpec) {
16684            int mode = getMode(measureSpec);
16685            int size = getSize(measureSpec);
16686
16687            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16688
16689            if (mode == UNSPECIFIED)
16690                sb.append("UNSPECIFIED ");
16691            else if (mode == EXACTLY)
16692                sb.append("EXACTLY ");
16693            else if (mode == AT_MOST)
16694                sb.append("AT_MOST ");
16695            else
16696                sb.append(mode).append(" ");
16697
16698            sb.append(size);
16699            return sb.toString();
16700        }
16701    }
16702
16703    class CheckForLongPress implements Runnable {
16704
16705        private int mOriginalWindowAttachCount;
16706
16707        public void run() {
16708            if (isPressed() && (mParent != null)
16709                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16710                if (performLongClick()) {
16711                    mHasPerformedLongPress = true;
16712                }
16713            }
16714        }
16715
16716        public void rememberWindowAttachCount() {
16717            mOriginalWindowAttachCount = mWindowAttachCount;
16718        }
16719    }
16720
16721    private final class CheckForTap implements Runnable {
16722        public void run() {
16723            mPrivateFlags &= ~PREPRESSED;
16724            setPressed(true);
16725            checkForLongClick(ViewConfiguration.getTapTimeout());
16726        }
16727    }
16728
16729    private final class PerformClick implements Runnable {
16730        public void run() {
16731            performClick();
16732        }
16733    }
16734
16735    /** @hide */
16736    public void hackTurnOffWindowResizeAnim(boolean off) {
16737        mAttachInfo.mTurnOffWindowResizeAnim = off;
16738    }
16739
16740    /**
16741     * This method returns a ViewPropertyAnimator object, which can be used to animate
16742     * specific properties on this View.
16743     *
16744     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16745     */
16746    public ViewPropertyAnimator animate() {
16747        if (mAnimator == null) {
16748            mAnimator = new ViewPropertyAnimator(this);
16749        }
16750        return mAnimator;
16751    }
16752
16753    /**
16754     * Interface definition for a callback to be invoked when a key event is
16755     * dispatched to this view. The callback will be invoked before the key
16756     * event is given to the view.
16757     */
16758    public interface OnKeyListener {
16759        /**
16760         * Called when a key is dispatched to a view. This allows listeners to
16761         * get a chance to respond before the target view.
16762         *
16763         * @param v The view the key has been dispatched to.
16764         * @param keyCode The code for the physical key that was pressed
16765         * @param event The KeyEvent object containing full information about
16766         *        the event.
16767         * @return True if the listener has consumed the event, false otherwise.
16768         */
16769        boolean onKey(View v, int keyCode, KeyEvent event);
16770    }
16771
16772    /**
16773     * Interface definition for a callback to be invoked when a touch event is
16774     * dispatched to this view. The callback will be invoked before the touch
16775     * event is given to the view.
16776     */
16777    public interface OnTouchListener {
16778        /**
16779         * Called when a touch event is dispatched to a view. This allows listeners to
16780         * get a chance to respond before the target view.
16781         *
16782         * @param v The view the touch event has been dispatched to.
16783         * @param event The MotionEvent object containing full information about
16784         *        the event.
16785         * @return True if the listener has consumed the event, false otherwise.
16786         */
16787        boolean onTouch(View v, MotionEvent event);
16788    }
16789
16790    /**
16791     * Interface definition for a callback to be invoked when a hover event is
16792     * dispatched to this view. The callback will be invoked before the hover
16793     * event is given to the view.
16794     */
16795    public interface OnHoverListener {
16796        /**
16797         * Called when a hover event is dispatched to a view. This allows listeners to
16798         * get a chance to respond before the target view.
16799         *
16800         * @param v The view the hover event has been dispatched to.
16801         * @param event The MotionEvent object containing full information about
16802         *        the event.
16803         * @return True if the listener has consumed the event, false otherwise.
16804         */
16805        boolean onHover(View v, MotionEvent event);
16806    }
16807
16808    /**
16809     * Interface definition for a callback to be invoked when a generic motion event is
16810     * dispatched to this view. The callback will be invoked before the generic motion
16811     * event is given to the view.
16812     */
16813    public interface OnGenericMotionListener {
16814        /**
16815         * Called when a generic motion event is dispatched to a view. This allows listeners to
16816         * get a chance to respond before the target view.
16817         *
16818         * @param v The view the generic motion event has been dispatched to.
16819         * @param event The MotionEvent object containing full information about
16820         *        the event.
16821         * @return True if the listener has consumed the event, false otherwise.
16822         */
16823        boolean onGenericMotion(View v, MotionEvent event);
16824    }
16825
16826    /**
16827     * Interface definition for a callback to be invoked when a view has been clicked and held.
16828     */
16829    public interface OnLongClickListener {
16830        /**
16831         * Called when a view has been clicked and held.
16832         *
16833         * @param v The view that was clicked and held.
16834         *
16835         * @return true if the callback consumed the long click, false otherwise.
16836         */
16837        boolean onLongClick(View v);
16838    }
16839
16840    /**
16841     * Interface definition for a callback to be invoked when a drag is being dispatched
16842     * to this view.  The callback will be invoked before the hosting view's own
16843     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16844     * onDrag(event) behavior, it should return 'false' from this callback.
16845     *
16846     * <div class="special reference">
16847     * <h3>Developer Guides</h3>
16848     * <p>For a guide to implementing drag and drop features, read the
16849     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16850     * </div>
16851     */
16852    public interface OnDragListener {
16853        /**
16854         * Called when a drag event is dispatched to a view. This allows listeners
16855         * to get a chance to override base View behavior.
16856         *
16857         * @param v The View that received the drag event.
16858         * @param event The {@link android.view.DragEvent} object for the drag event.
16859         * @return {@code true} if the drag event was handled successfully, or {@code false}
16860         * if the drag event was not handled. Note that {@code false} will trigger the View
16861         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16862         */
16863        boolean onDrag(View v, DragEvent event);
16864    }
16865
16866    /**
16867     * Interface definition for a callback to be invoked when the focus state of
16868     * a view changed.
16869     */
16870    public interface OnFocusChangeListener {
16871        /**
16872         * Called when the focus state of a view has changed.
16873         *
16874         * @param v The view whose state has changed.
16875         * @param hasFocus The new focus state of v.
16876         */
16877        void onFocusChange(View v, boolean hasFocus);
16878    }
16879
16880    /**
16881     * Interface definition for a callback to be invoked when a view is clicked.
16882     */
16883    public interface OnClickListener {
16884        /**
16885         * Called when a view has been clicked.
16886         *
16887         * @param v The view that was clicked.
16888         */
16889        void onClick(View v);
16890    }
16891
16892    /**
16893     * Interface definition for a callback to be invoked when the context menu
16894     * for this view is being built.
16895     */
16896    public interface OnCreateContextMenuListener {
16897        /**
16898         * Called when the context menu for this view is being built. It is not
16899         * safe to hold onto the menu after this method returns.
16900         *
16901         * @param menu The context menu that is being built
16902         * @param v The view for which the context menu is being built
16903         * @param menuInfo Extra information about the item for which the
16904         *            context menu should be shown. This information will vary
16905         *            depending on the class of v.
16906         */
16907        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16908    }
16909
16910    /**
16911     * Interface definition for a callback to be invoked when the status bar changes
16912     * visibility.  This reports <strong>global</strong> changes to the system UI
16913     * state, not what the application is requesting.
16914     *
16915     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16916     */
16917    public interface OnSystemUiVisibilityChangeListener {
16918        /**
16919         * Called when the status bar changes visibility because of a call to
16920         * {@link View#setSystemUiVisibility(int)}.
16921         *
16922         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16923         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
16924         * This tells you the <strong>global</strong> state of these UI visibility
16925         * flags, not what your app is currently applying.
16926         */
16927        public void onSystemUiVisibilityChange(int visibility);
16928    }
16929
16930    /**
16931     * Interface definition for a callback to be invoked when this view is attached
16932     * or detached from its window.
16933     */
16934    public interface OnAttachStateChangeListener {
16935        /**
16936         * Called when the view is attached to a window.
16937         * @param v The view that was attached
16938         */
16939        public void onViewAttachedToWindow(View v);
16940        /**
16941         * Called when the view is detached from a window.
16942         * @param v The view that was detached
16943         */
16944        public void onViewDetachedFromWindow(View v);
16945    }
16946
16947    private final class UnsetPressedState implements Runnable {
16948        public void run() {
16949            setPressed(false);
16950        }
16951    }
16952
16953    /**
16954     * Base class for derived classes that want to save and restore their own
16955     * state in {@link android.view.View#onSaveInstanceState()}.
16956     */
16957    public static class BaseSavedState extends AbsSavedState {
16958        /**
16959         * Constructor used when reading from a parcel. Reads the state of the superclass.
16960         *
16961         * @param source
16962         */
16963        public BaseSavedState(Parcel source) {
16964            super(source);
16965        }
16966
16967        /**
16968         * Constructor called by derived classes when creating their SavedState objects
16969         *
16970         * @param superState The state of the superclass of this view
16971         */
16972        public BaseSavedState(Parcelable superState) {
16973            super(superState);
16974        }
16975
16976        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16977                new Parcelable.Creator<BaseSavedState>() {
16978            public BaseSavedState createFromParcel(Parcel in) {
16979                return new BaseSavedState(in);
16980            }
16981
16982            public BaseSavedState[] newArray(int size) {
16983                return new BaseSavedState[size];
16984            }
16985        };
16986    }
16987
16988    /**
16989     * A set of information given to a view when it is attached to its parent
16990     * window.
16991     */
16992    static class AttachInfo {
16993        interface Callbacks {
16994            void playSoundEffect(int effectId);
16995            boolean performHapticFeedback(int effectId, boolean always);
16996        }
16997
16998        /**
16999         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17000         * to a Handler. This class contains the target (View) to invalidate and
17001         * the coordinates of the dirty rectangle.
17002         *
17003         * For performance purposes, this class also implements a pool of up to
17004         * POOL_LIMIT objects that get reused. This reduces memory allocations
17005         * whenever possible.
17006         */
17007        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17008            private static final int POOL_LIMIT = 10;
17009            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17010                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17011                        public InvalidateInfo newInstance() {
17012                            return new InvalidateInfo();
17013                        }
17014
17015                        public void onAcquired(InvalidateInfo element) {
17016                        }
17017
17018                        public void onReleased(InvalidateInfo element) {
17019                            element.target = null;
17020                        }
17021                    }, POOL_LIMIT)
17022            );
17023
17024            private InvalidateInfo mNext;
17025            private boolean mIsPooled;
17026
17027            View target;
17028
17029            int left;
17030            int top;
17031            int right;
17032            int bottom;
17033
17034            public void setNextPoolable(InvalidateInfo element) {
17035                mNext = element;
17036            }
17037
17038            public InvalidateInfo getNextPoolable() {
17039                return mNext;
17040            }
17041
17042            static InvalidateInfo acquire() {
17043                return sPool.acquire();
17044            }
17045
17046            void release() {
17047                sPool.release(this);
17048            }
17049
17050            public boolean isPooled() {
17051                return mIsPooled;
17052            }
17053
17054            public void setPooled(boolean isPooled) {
17055                mIsPooled = isPooled;
17056            }
17057        }
17058
17059        final IWindowSession mSession;
17060
17061        final IWindow mWindow;
17062
17063        final IBinder mWindowToken;
17064
17065        final Callbacks mRootCallbacks;
17066
17067        HardwareCanvas mHardwareCanvas;
17068
17069        /**
17070         * The top view of the hierarchy.
17071         */
17072        View mRootView;
17073
17074        IBinder mPanelParentWindowToken;
17075        Surface mSurface;
17076
17077        boolean mHardwareAccelerated;
17078        boolean mHardwareAccelerationRequested;
17079        HardwareRenderer mHardwareRenderer;
17080
17081        boolean mScreenOn;
17082
17083        /**
17084         * Scale factor used by the compatibility mode
17085         */
17086        float mApplicationScale;
17087
17088        /**
17089         * Indicates whether the application is in compatibility mode
17090         */
17091        boolean mScalingRequired;
17092
17093        /**
17094         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17095         */
17096        boolean mTurnOffWindowResizeAnim;
17097
17098        /**
17099         * Left position of this view's window
17100         */
17101        int mWindowLeft;
17102
17103        /**
17104         * Top position of this view's window
17105         */
17106        int mWindowTop;
17107
17108        /**
17109         * Indicates whether views need to use 32-bit drawing caches
17110         */
17111        boolean mUse32BitDrawingCache;
17112
17113        /**
17114         * For windows that are full-screen but using insets to layout inside
17115         * of the screen decorations, these are the current insets for the
17116         * content of the window.
17117         */
17118        final Rect mContentInsets = new Rect();
17119
17120        /**
17121         * For windows that are full-screen but using insets to layout inside
17122         * of the screen decorations, these are the current insets for the
17123         * actual visible parts of the window.
17124         */
17125        final Rect mVisibleInsets = new Rect();
17126
17127        /**
17128         * The internal insets given by this window.  This value is
17129         * supplied by the client (through
17130         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17131         * be given to the window manager when changed to be used in laying
17132         * out windows behind it.
17133         */
17134        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17135                = new ViewTreeObserver.InternalInsetsInfo();
17136
17137        /**
17138         * All views in the window's hierarchy that serve as scroll containers,
17139         * used to determine if the window can be resized or must be panned
17140         * to adjust for a soft input area.
17141         */
17142        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17143
17144        final KeyEvent.DispatcherState mKeyDispatchState
17145                = new KeyEvent.DispatcherState();
17146
17147        /**
17148         * Indicates whether the view's window currently has the focus.
17149         */
17150        boolean mHasWindowFocus;
17151
17152        /**
17153         * The current visibility of the window.
17154         */
17155        int mWindowVisibility;
17156
17157        /**
17158         * Indicates the time at which drawing started to occur.
17159         */
17160        long mDrawingTime;
17161
17162        /**
17163         * Indicates whether or not ignoring the DIRTY_MASK flags.
17164         */
17165        boolean mIgnoreDirtyState;
17166
17167        /**
17168         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17169         * to avoid clearing that flag prematurely.
17170         */
17171        boolean mSetIgnoreDirtyState = false;
17172
17173        /**
17174         * Indicates whether the view's window is currently in touch mode.
17175         */
17176        boolean mInTouchMode;
17177
17178        /**
17179         * Indicates that ViewAncestor should trigger a global layout change
17180         * the next time it performs a traversal
17181         */
17182        boolean mRecomputeGlobalAttributes;
17183
17184        /**
17185         * Always report new attributes at next traversal.
17186         */
17187        boolean mForceReportNewAttributes;
17188
17189        /**
17190         * Set during a traveral if any views want to keep the screen on.
17191         */
17192        boolean mKeepScreenOn;
17193
17194        /**
17195         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17196         */
17197        int mSystemUiVisibility;
17198
17199        /**
17200         * Hack to force certain system UI visibility flags to be cleared.
17201         */
17202        int mDisabledSystemUiVisibility;
17203
17204        /**
17205         * Last global system UI visibility reported by the window manager.
17206         */
17207        int mGlobalSystemUiVisibility;
17208
17209        /**
17210         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17211         * attached.
17212         */
17213        boolean mHasSystemUiListeners;
17214
17215        /**
17216         * Set if the visibility of any views has changed.
17217         */
17218        boolean mViewVisibilityChanged;
17219
17220        /**
17221         * Set to true if a view has been scrolled.
17222         */
17223        boolean mViewScrollChanged;
17224
17225        /**
17226         * Global to the view hierarchy used as a temporary for dealing with
17227         * x/y points in the transparent region computations.
17228         */
17229        final int[] mTransparentLocation = new int[2];
17230
17231        /**
17232         * Global to the view hierarchy used as a temporary for dealing with
17233         * x/y points in the ViewGroup.invalidateChild implementation.
17234         */
17235        final int[] mInvalidateChildLocation = new int[2];
17236
17237
17238        /**
17239         * Global to the view hierarchy used as a temporary for dealing with
17240         * x/y location when view is transformed.
17241         */
17242        final float[] mTmpTransformLocation = new float[2];
17243
17244        /**
17245         * The view tree observer used to dispatch global events like
17246         * layout, pre-draw, touch mode change, etc.
17247         */
17248        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17249
17250        /**
17251         * A Canvas used by the view hierarchy to perform bitmap caching.
17252         */
17253        Canvas mCanvas;
17254
17255        /**
17256         * The view root impl.
17257         */
17258        final ViewRootImpl mViewRootImpl;
17259
17260        /**
17261         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17262         * handler can be used to pump events in the UI events queue.
17263         */
17264        final Handler mHandler;
17265
17266        /**
17267         * Temporary for use in computing invalidate rectangles while
17268         * calling up the hierarchy.
17269         */
17270        final Rect mTmpInvalRect = new Rect();
17271
17272        /**
17273         * Temporary for use in computing hit areas with transformed views
17274         */
17275        final RectF mTmpTransformRect = new RectF();
17276
17277        /**
17278         * Temporary list for use in collecting focusable descendents of a view.
17279         */
17280        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17281
17282        /**
17283         * The id of the window for accessibility purposes.
17284         */
17285        int mAccessibilityWindowId = View.NO_ID;
17286
17287        /**
17288         * Whether to ingore not exposed for accessibility Views when
17289         * reporting the view tree to accessibility services.
17290         */
17291        boolean mIncludeNotImportantViews;
17292
17293        /**
17294         * The drawable for highlighting accessibility focus.
17295         */
17296        Drawable mAccessibilityFocusDrawable;
17297
17298        /**
17299         * Show where the margins, bounds and layout bounds are for each view.
17300         */
17301        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17302
17303        /**
17304         * Point used to compute visible regions.
17305         */
17306        final Point mPoint = new Point();
17307
17308        /**
17309         * Creates a new set of attachment information with the specified
17310         * events handler and thread.
17311         *
17312         * @param handler the events handler the view must use
17313         */
17314        AttachInfo(IWindowSession session, IWindow window,
17315                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17316            mSession = session;
17317            mWindow = window;
17318            mWindowToken = window.asBinder();
17319            mViewRootImpl = viewRootImpl;
17320            mHandler = handler;
17321            mRootCallbacks = effectPlayer;
17322        }
17323    }
17324
17325    /**
17326     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17327     * is supported. This avoids keeping too many unused fields in most
17328     * instances of View.</p>
17329     */
17330    private static class ScrollabilityCache implements Runnable {
17331
17332        /**
17333         * Scrollbars are not visible
17334         */
17335        public static final int OFF = 0;
17336
17337        /**
17338         * Scrollbars are visible
17339         */
17340        public static final int ON = 1;
17341
17342        /**
17343         * Scrollbars are fading away
17344         */
17345        public static final int FADING = 2;
17346
17347        public boolean fadeScrollBars;
17348
17349        public int fadingEdgeLength;
17350        public int scrollBarDefaultDelayBeforeFade;
17351        public int scrollBarFadeDuration;
17352
17353        public int scrollBarSize;
17354        public ScrollBarDrawable scrollBar;
17355        public float[] interpolatorValues;
17356        public View host;
17357
17358        public final Paint paint;
17359        public final Matrix matrix;
17360        public Shader shader;
17361
17362        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17363
17364        private static final float[] OPAQUE = { 255 };
17365        private static final float[] TRANSPARENT = { 0.0f };
17366
17367        /**
17368         * When fading should start. This time moves into the future every time
17369         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17370         */
17371        public long fadeStartTime;
17372
17373
17374        /**
17375         * The current state of the scrollbars: ON, OFF, or FADING
17376         */
17377        public int state = OFF;
17378
17379        private int mLastColor;
17380
17381        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17382            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17383            scrollBarSize = configuration.getScaledScrollBarSize();
17384            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17385            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17386
17387            paint = new Paint();
17388            matrix = new Matrix();
17389            // use use a height of 1, and then wack the matrix each time we
17390            // actually use it.
17391            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17392
17393            paint.setShader(shader);
17394            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17395            this.host = host;
17396        }
17397
17398        public void setFadeColor(int color) {
17399            if (color != 0 && color != mLastColor) {
17400                mLastColor = color;
17401                color |= 0xFF000000;
17402
17403                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17404                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17405
17406                paint.setShader(shader);
17407                // Restore the default transfer mode (src_over)
17408                paint.setXfermode(null);
17409            }
17410        }
17411
17412        public void run() {
17413            long now = AnimationUtils.currentAnimationTimeMillis();
17414            if (now >= fadeStartTime) {
17415
17416                // the animation fades the scrollbars out by changing
17417                // the opacity (alpha) from fully opaque to fully
17418                // transparent
17419                int nextFrame = (int) now;
17420                int framesCount = 0;
17421
17422                Interpolator interpolator = scrollBarInterpolator;
17423
17424                // Start opaque
17425                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17426
17427                // End transparent
17428                nextFrame += scrollBarFadeDuration;
17429                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17430
17431                state = FADING;
17432
17433                // Kick off the fade animation
17434                host.invalidate(true);
17435            }
17436        }
17437    }
17438
17439    /**
17440     * Resuable callback for sending
17441     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17442     */
17443    private class SendViewScrolledAccessibilityEvent implements Runnable {
17444        public volatile boolean mIsPending;
17445
17446        public void run() {
17447            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17448            mIsPending = false;
17449        }
17450    }
17451
17452    /**
17453     * <p>
17454     * This class represents a delegate that can be registered in a {@link View}
17455     * to enhance accessibility support via composition rather via inheritance.
17456     * It is specifically targeted to widget developers that extend basic View
17457     * classes i.e. classes in package android.view, that would like their
17458     * applications to be backwards compatible.
17459     * </p>
17460     * <div class="special reference">
17461     * <h3>Developer Guides</h3>
17462     * <p>For more information about making applications accessible, read the
17463     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17464     * developer guide.</p>
17465     * </div>
17466     * <p>
17467     * A scenario in which a developer would like to use an accessibility delegate
17468     * is overriding a method introduced in a later API version then the minimal API
17469     * version supported by the application. For example, the method
17470     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17471     * in API version 4 when the accessibility APIs were first introduced. If a
17472     * developer would like his application to run on API version 4 devices (assuming
17473     * all other APIs used by the application are version 4 or lower) and take advantage
17474     * of this method, instead of overriding the method which would break the application's
17475     * backwards compatibility, he can override the corresponding method in this
17476     * delegate and register the delegate in the target View if the API version of
17477     * the system is high enough i.e. the API version is same or higher to the API
17478     * version that introduced
17479     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17480     * </p>
17481     * <p>
17482     * Here is an example implementation:
17483     * </p>
17484     * <code><pre><p>
17485     * if (Build.VERSION.SDK_INT >= 14) {
17486     *     // If the API version is equal of higher than the version in
17487     *     // which onInitializeAccessibilityNodeInfo was introduced we
17488     *     // register a delegate with a customized implementation.
17489     *     View view = findViewById(R.id.view_id);
17490     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17491     *         public void onInitializeAccessibilityNodeInfo(View host,
17492     *                 AccessibilityNodeInfo info) {
17493     *             // Let the default implementation populate the info.
17494     *             super.onInitializeAccessibilityNodeInfo(host, info);
17495     *             // Set some other information.
17496     *             info.setEnabled(host.isEnabled());
17497     *         }
17498     *     });
17499     * }
17500     * </code></pre></p>
17501     * <p>
17502     * This delegate contains methods that correspond to the accessibility methods
17503     * in View. If a delegate has been specified the implementation in View hands
17504     * off handling to the corresponding method in this delegate. The default
17505     * implementation the delegate methods behaves exactly as the corresponding
17506     * method in View for the case of no accessibility delegate been set. Hence,
17507     * to customize the behavior of a View method, clients can override only the
17508     * corresponding delegate method without altering the behavior of the rest
17509     * accessibility related methods of the host view.
17510     * </p>
17511     */
17512    public static class AccessibilityDelegate {
17513
17514        /**
17515         * Sends an accessibility event of the given type. If accessibility is not
17516         * enabled this method has no effect.
17517         * <p>
17518         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17519         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17520         * been set.
17521         * </p>
17522         *
17523         * @param host The View hosting the delegate.
17524         * @param eventType The type of the event to send.
17525         *
17526         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17527         */
17528        public void sendAccessibilityEvent(View host, int eventType) {
17529            host.sendAccessibilityEventInternal(eventType);
17530        }
17531
17532        /**
17533         * Performs the specified accessibility action on the view. For
17534         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17535         * <p>
17536         * The default implementation behaves as
17537         * {@link View#performAccessibilityAction(int, Bundle)
17538         *  View#performAccessibilityAction(int, Bundle)} for the case of
17539         *  no accessibility delegate been set.
17540         * </p>
17541         *
17542         * @param action The action to perform.
17543         * @return Whether the action was performed.
17544         *
17545         * @see View#performAccessibilityAction(int, Bundle)
17546         *      View#performAccessibilityAction(int, Bundle)
17547         */
17548        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17549            return host.performAccessibilityActionInternal(action, args);
17550        }
17551
17552        /**
17553         * Sends an accessibility event. This method behaves exactly as
17554         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17555         * empty {@link AccessibilityEvent} and does not perform a check whether
17556         * accessibility is enabled.
17557         * <p>
17558         * The default implementation behaves as
17559         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17560         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17561         * the case of no accessibility delegate been set.
17562         * </p>
17563         *
17564         * @param host The View hosting the delegate.
17565         * @param event The event to send.
17566         *
17567         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17568         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17569         */
17570        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17571            host.sendAccessibilityEventUncheckedInternal(event);
17572        }
17573
17574        /**
17575         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17576         * to its children for adding their text content to the event.
17577         * <p>
17578         * The default implementation behaves as
17579         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17580         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17581         * the case of no accessibility delegate been set.
17582         * </p>
17583         *
17584         * @param host The View hosting the delegate.
17585         * @param event The event.
17586         * @return True if the event population was completed.
17587         *
17588         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17589         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17590         */
17591        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17592            return host.dispatchPopulateAccessibilityEventInternal(event);
17593        }
17594
17595        /**
17596         * Gives a chance to the host View to populate the accessibility event with its
17597         * text content.
17598         * <p>
17599         * The default implementation behaves as
17600         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17601         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17602         * the case of no accessibility delegate been set.
17603         * </p>
17604         *
17605         * @param host The View hosting the delegate.
17606         * @param event The accessibility event which to populate.
17607         *
17608         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17609         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17610         */
17611        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17612            host.onPopulateAccessibilityEventInternal(event);
17613        }
17614
17615        /**
17616         * Initializes an {@link AccessibilityEvent} with information about the
17617         * the host View which is the event source.
17618         * <p>
17619         * The default implementation behaves as
17620         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17621         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17622         * the case of no accessibility delegate been set.
17623         * </p>
17624         *
17625         * @param host The View hosting the delegate.
17626         * @param event The event to initialize.
17627         *
17628         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17629         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17630         */
17631        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17632            host.onInitializeAccessibilityEventInternal(event);
17633        }
17634
17635        /**
17636         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17637         * <p>
17638         * The default implementation behaves as
17639         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17640         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17641         * the case of no accessibility delegate been set.
17642         * </p>
17643         *
17644         * @param host The View hosting the delegate.
17645         * @param info The instance to initialize.
17646         *
17647         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17648         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17649         */
17650        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17651            host.onInitializeAccessibilityNodeInfoInternal(info);
17652        }
17653
17654        /**
17655         * Called when a child of the host View has requested sending an
17656         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17657         * to augment the event.
17658         * <p>
17659         * The default implementation behaves as
17660         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17661         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17662         * the case of no accessibility delegate been set.
17663         * </p>
17664         *
17665         * @param host The View hosting the delegate.
17666         * @param child The child which requests sending the event.
17667         * @param event The event to be sent.
17668         * @return True if the event should be sent
17669         *
17670         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17671         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17672         */
17673        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17674                AccessibilityEvent event) {
17675            return host.onRequestSendAccessibilityEventInternal(child, event);
17676        }
17677
17678        /**
17679         * Gets the provider for managing a virtual view hierarchy rooted at this View
17680         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17681         * that explore the window content.
17682         * <p>
17683         * The default implementation behaves as
17684         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17685         * the case of no accessibility delegate been set.
17686         * </p>
17687         *
17688         * @return The provider.
17689         *
17690         * @see AccessibilityNodeProvider
17691         */
17692        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17693            return null;
17694        }
17695    }
17696}
17697