View.java revision 7a46dde1ae56a85fcb5cdac91173424b6355bf3c
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.hardware.display.DisplayManagerGlobal;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.IBinder;
46import android.os.Parcel;
47import android.os.Parcelable;
48import android.os.RemoteException;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.text.TextUtils;
52import android.util.AttributeSet;
53import android.util.FloatProperty;
54import android.util.Log;
55import android.util.LongSparseLongArray;
56import android.util.Pools.SynchronizedPool;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.AccessibilityIterators.TextSegmentIterator;
62import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
63import android.view.AccessibilityIterators.WordTextSegmentIterator;
64import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
65import android.view.accessibility.AccessibilityEvent;
66import android.view.accessibility.AccessibilityEventSource;
67import android.view.accessibility.AccessibilityManager;
68import android.view.accessibility.AccessibilityNodeInfo;
69import android.view.accessibility.AccessibilityNodeProvider;
70import android.view.animation.Animation;
71import android.view.animation.AnimationUtils;
72import android.view.animation.Transformation;
73import android.view.inputmethod.EditorInfo;
74import android.view.inputmethod.InputConnection;
75import android.view.inputmethod.InputMethodManager;
76import android.view.transition.Scene;
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;
85import com.google.android.collect.Lists;
86import com.google.android.collect.Maps;
87
88import java.lang.ref.WeakReference;
89import java.lang.reflect.Field;
90import java.lang.reflect.InvocationTargetException;
91import java.lang.reflect.Method;
92import java.lang.reflect.Modifier;
93import java.util.ArrayList;
94import java.util.Arrays;
95import java.util.Collections;
96import java.util.HashMap;
97import java.util.Locale;
98import java.util.concurrent.CopyOnWriteArrayList;
99import java.util.concurrent.atomic.AtomicInteger;
100
101/**
102 * <p>
103 * This class represents the basic building block for user interface components. A View
104 * occupies a rectangular area on the screen and is responsible for drawing and
105 * event handling. View is the base class for <em>widgets</em>, which are
106 * used to create interactive UI components (buttons, text fields, etc.). The
107 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
108 * are invisible containers that hold other Views (or other ViewGroups) and define
109 * their layout properties.
110 * </p>
111 *
112 * <div class="special reference">
113 * <h3>Developer Guides</h3>
114 * <p>For information about using this class to develop your application's user interface,
115 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
116 * </div>
117 *
118 * <a name="Using"></a>
119 * <h3>Using Views</h3>
120 * <p>
121 * All of the views in a window are arranged in a single tree. You can add views
122 * either from code or by specifying a tree of views in one or more XML layout
123 * files. There are many specialized subclasses of views that act as controls or
124 * are capable of displaying text, images, or other content.
125 * </p>
126 * <p>
127 * Once you have created a tree of views, there are typically a few types of
128 * common operations you may wish to perform:
129 * <ul>
130 * <li><strong>Set properties:</strong> for example setting the text of a
131 * {@link android.widget.TextView}. The available properties and the methods
132 * that set them will vary among the different subclasses of views. Note that
133 * properties that are known at build time can be set in the XML layout
134 * files.</li>
135 * <li><strong>Set focus:</strong> The framework will handled moving focus in
136 * response to user input. To force focus to a specific view, call
137 * {@link #requestFocus}.</li>
138 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
139 * that will be notified when something interesting happens to the view. For
140 * example, all views will let you set a listener to be notified when the view
141 * gains or loses focus. You can register such a listener using
142 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
143 * Other view subclasses offer more specialized listeners. For example, a Button
144 * exposes a listener to notify clients when the button is clicked.</li>
145 * <li><strong>Set visibility:</strong> You can hide or show views using
146 * {@link #setVisibility(int)}.</li>
147 * </ul>
148 * </p>
149 * <p><em>
150 * Note: The Android framework is responsible for measuring, laying out and
151 * drawing views. You should not call methods that perform these actions on
152 * views yourself unless you are actually implementing a
153 * {@link android.view.ViewGroup}.
154 * </em></p>
155 *
156 * <a name="Lifecycle"></a>
157 * <h3>Implementing a Custom View</h3>
158 *
159 * <p>
160 * To implement a custom view, you will usually begin by providing overrides for
161 * some of the standard methods that the framework calls on all views. You do
162 * not need to override all of these methods. In fact, you can start by just
163 * overriding {@link #onDraw(android.graphics.Canvas)}.
164 * <table border="2" width="85%" align="center" cellpadding="5">
165 *     <thead>
166 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
167 *     </thead>
168 *
169 *     <tbody>
170 *     <tr>
171 *         <td rowspan="2">Creation</td>
172 *         <td>Constructors</td>
173 *         <td>There is a form of the constructor that are called when the view
174 *         is created from code and a form that is called when the view is
175 *         inflated from a layout file. The second form should parse and apply
176 *         any attributes defined in the layout file.
177 *         </td>
178 *     </tr>
179 *     <tr>
180 *         <td><code>{@link #onFinishInflate()}</code></td>
181 *         <td>Called after a view and all of its children has been inflated
182 *         from XML.</td>
183 *     </tr>
184 *
185 *     <tr>
186 *         <td rowspan="3">Layout</td>
187 *         <td><code>{@link #onMeasure(int, int)}</code></td>
188 *         <td>Called to determine the size requirements for this view and all
189 *         of its children.
190 *         </td>
191 *     </tr>
192 *     <tr>
193 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
194 *         <td>Called when this view should assign a size and position to all
195 *         of its children.
196 *         </td>
197 *     </tr>
198 *     <tr>
199 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
200 *         <td>Called when the size of this view has changed.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td>Drawing</td>
206 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
207 *         <td>Called when the view should render its content.
208 *         </td>
209 *     </tr>
210 *
211 *     <tr>
212 *         <td rowspan="4">Event processing</td>
213 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
214 *         <td>Called when a new hardware key event occurs.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
219 *         <td>Called when a hardware key up event occurs.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
224 *         <td>Called when a trackball motion event occurs.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
229 *         <td>Called when a touch screen motion event occurs.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td rowspan="2">Focus</td>
235 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
236 *         <td>Called when the view gains or loses focus.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
242 *         <td>Called when the window containing the view gains or loses focus.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td rowspan="3">Attaching</td>
248 *         <td><code>{@link #onAttachedToWindow()}</code></td>
249 *         <td>Called when the view is attached to a window.
250 *         </td>
251 *     </tr>
252 *
253 *     <tr>
254 *         <td><code>{@link #onDetachedFromWindow}</code></td>
255 *         <td>Called when the view is detached from its window.
256 *         </td>
257 *     </tr>
258 *
259 *     <tr>
260 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
261 *         <td>Called when the visibility of the window containing the view
262 *         has changed.
263 *         </td>
264 *     </tr>
265 *     </tbody>
266 *
267 * </table>
268 * </p>
269 *
270 * <a name="IDs"></a>
271 * <h3>IDs</h3>
272 * Views may have an integer id associated with them. These ids are typically
273 * assigned in the layout XML files, and are used to find specific views within
274 * the view tree. A common pattern is to:
275 * <ul>
276 * <li>Define a Button in the layout file and assign it a unique ID.
277 * <pre>
278 * &lt;Button
279 *     android:id="@+id/my_button"
280 *     android:layout_width="wrap_content"
281 *     android:layout_height="wrap_content"
282 *     android:text="@string/my_button_text"/&gt;
283 * </pre></li>
284 * <li>From the onCreate method of an Activity, find the Button
285 * <pre class="prettyprint">
286 *      Button myButton = (Button) findViewById(R.id.my_button);
287 * </pre></li>
288 * </ul>
289 * <p>
290 * View IDs need not be unique throughout the tree, but it is good practice to
291 * ensure that they are at least unique within the part of the tree you are
292 * searching.
293 * </p>
294 *
295 * <a name="Position"></a>
296 * <h3>Position</h3>
297 * <p>
298 * The geometry of a view is that of a rectangle. A view has a location,
299 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
300 * two dimensions, expressed as a width and a height. The unit for location
301 * and dimensions is the pixel.
302 * </p>
303 *
304 * <p>
305 * It is possible to retrieve the location of a view by invoking the methods
306 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
307 * coordinate of the rectangle representing the view. The latter returns the
308 * top, or Y, coordinate of the rectangle representing the view. These methods
309 * both return the location of the view relative to its parent. For instance,
310 * when getLeft() returns 20, that means the view is located 20 pixels to the
311 * right of the left edge of its direct parent.
312 * </p>
313 *
314 * <p>
315 * In addition, several convenience methods are offered to avoid unnecessary
316 * computations, namely {@link #getRight()} and {@link #getBottom()}.
317 * These methods return the coordinates of the right and bottom edges of the
318 * rectangle representing the view. For instance, calling {@link #getRight()}
319 * is similar to the following computation: <code>getLeft() + getWidth()</code>
320 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
321 * </p>
322 *
323 * <a name="SizePaddingMargins"></a>
324 * <h3>Size, padding and margins</h3>
325 * <p>
326 * The size of a view is expressed with a width and a height. A view actually
327 * possess two pairs of width and height values.
328 * </p>
329 *
330 * <p>
331 * The first pair is known as <em>measured width</em> and
332 * <em>measured height</em>. These dimensions define how big a view wants to be
333 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
334 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
335 * and {@link #getMeasuredHeight()}.
336 * </p>
337 *
338 * <p>
339 * The second pair is simply known as <em>width</em> and <em>height</em>, or
340 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
341 * dimensions define the actual size of the view on screen, at drawing time and
342 * after layout. These values may, but do not have to, be different from the
343 * measured width and height. The width and height can be obtained by calling
344 * {@link #getWidth()} and {@link #getHeight()}.
345 * </p>
346 *
347 * <p>
348 * To measure its dimensions, a view takes into account its padding. The padding
349 * is expressed in pixels for the left, top, right and bottom parts of the view.
350 * Padding can be used to offset the content of the view by a specific amount of
351 * pixels. For instance, a left padding of 2 will push the view's content by
352 * 2 pixels to the right of the left edge. Padding can be set using the
353 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
354 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
355 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
356 * {@link #getPaddingEnd()}.
357 * </p>
358 *
359 * <p>
360 * Even though a view can define a padding, it does not provide any support for
361 * margins. However, view groups provide such a support. Refer to
362 * {@link android.view.ViewGroup} and
363 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
364 * </p>
365 *
366 * <a name="Layout"></a>
367 * <h3>Layout</h3>
368 * <p>
369 * Layout is a two pass process: a measure pass and a layout pass. The measuring
370 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
371 * of the view tree. Each view pushes dimension specifications down the tree
372 * during the recursion. At the end of the measure pass, every view has stored
373 * its measurements. The second pass happens in
374 * {@link #layout(int,int,int,int)} and is also top-down. During
375 * this pass each parent is responsible for positioning all of its children
376 * using the sizes computed in the measure pass.
377 * </p>
378 *
379 * <p>
380 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
381 * {@link #getMeasuredHeight()} values must be set, along with those for all of
382 * that view's descendants. A view's measured width and measured height values
383 * must respect the constraints imposed by the view's parents. This guarantees
384 * that at the end of the measure pass, all parents accept all of their
385 * children's measurements. A parent view may call measure() more than once on
386 * its children. For example, the parent may measure each child once with
387 * unspecified dimensions to find out how big they want to be, then call
388 * measure() on them again with actual numbers if the sum of all the children's
389 * unconstrained sizes is too big or too small.
390 * </p>
391 *
392 * <p>
393 * The measure pass uses two classes to communicate dimensions. The
394 * {@link MeasureSpec} class is used by views to tell their parents how they
395 * want to be measured and positioned. The base LayoutParams class just
396 * describes how big the view wants to be for both width and height. For each
397 * dimension, it can specify one of:
398 * <ul>
399 * <li> an exact number
400 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
401 * (minus padding)
402 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
403 * enclose its content (plus padding).
404 * </ul>
405 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
406 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
407 * an X and Y value.
408 * </p>
409 *
410 * <p>
411 * MeasureSpecs are used to push requirements down the tree from parent to
412 * child. A MeasureSpec can be in one of three modes:
413 * <ul>
414 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
415 * of a child view. For example, a LinearLayout may call measure() on its child
416 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
417 * tall the child view wants to be given a width of 240 pixels.
418 * <li>EXACTLY: This is used by the parent to impose an exact size on the
419 * child. The child must use this size, and guarantee that all of its
420 * descendants will fit within this size.
421 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
422 * child. The child must gurantee that it and all of its descendants will fit
423 * within this size.
424 * </ul>
425 * </p>
426 *
427 * <p>
428 * To intiate a layout, call {@link #requestLayout}. This method is typically
429 * called by a view on itself when it believes that is can no longer fit within
430 * its current bounds.
431 * </p>
432 *
433 * <a name="Drawing"></a>
434 * <h3>Drawing</h3>
435 * <p>
436 * Drawing is handled by walking the tree and rendering each view that
437 * intersects the invalid region. Because the tree is traversed in-order,
438 * this means that parents will draw before (i.e., behind) their children, with
439 * siblings drawn in the order they appear in the tree.
440 * If you set a background drawable for a View, then the View will draw it for you
441 * before calling back to its <code>onDraw()</code> method.
442 * </p>
443 *
444 * <p>
445 * Note that the framework will not draw views that are not in the invalid region.
446 * </p>
447 *
448 * <p>
449 * To force a view to draw, call {@link #invalidate()}.
450 * </p>
451 *
452 * <a name="EventHandlingThreading"></a>
453 * <h3>Event Handling and Threading</h3>
454 * <p>
455 * The basic cycle of a view is as follows:
456 * <ol>
457 * <li>An event comes in and is dispatched to the appropriate view. The view
458 * handles the event and notifies any listeners.</li>
459 * <li>If in the course of processing the event, the view's bounds may need
460 * to be changed, the view will call {@link #requestLayout()}.</li>
461 * <li>Similarly, if in the course of processing the event the view's appearance
462 * may need to be changed, the view will call {@link #invalidate()}.</li>
463 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
464 * the framework will take care of measuring, laying out, and drawing the tree
465 * as appropriate.</li>
466 * </ol>
467 * </p>
468 *
469 * <p><em>Note: The entire view tree is single threaded. You must always be on
470 * the UI thread when calling any method on any view.</em>
471 * If you are doing work on other threads and want to update the state of a view
472 * from that thread, you should use a {@link Handler}.
473 * </p>
474 *
475 * <a name="FocusHandling"></a>
476 * <h3>Focus Handling</h3>
477 * <p>
478 * The framework will handle routine focus movement in response to user input.
479 * This includes changing the focus as views are removed or hidden, or as new
480 * views become available. Views indicate their willingness to take focus
481 * through the {@link #isFocusable} method. To change whether a view can take
482 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
483 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
484 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
485 * </p>
486 * <p>
487 * Focus movement is based on an algorithm which finds the nearest neighbor in a
488 * given direction. In rare cases, the default algorithm may not match the
489 * intended behavior of the developer. In these situations, you can provide
490 * explicit overrides by using these XML attributes in the layout file:
491 * <pre>
492 * nextFocusDown
493 * nextFocusLeft
494 * nextFocusRight
495 * nextFocusUp
496 * </pre>
497 * </p>
498 *
499 *
500 * <p>
501 * To get a particular view to take focus, call {@link #requestFocus()}.
502 * </p>
503 *
504 * <a name="TouchMode"></a>
505 * <h3>Touch Mode</h3>
506 * <p>
507 * When a user is navigating a user interface via directional keys such as a D-pad, it is
508 * necessary to give focus to actionable items such as buttons so the user can see
509 * what will take input.  If the device has touch capabilities, however, and the user
510 * begins interacting with the interface by touching it, it is no longer necessary to
511 * always highlight, or give focus to, a particular view.  This motivates a mode
512 * for interaction named 'touch mode'.
513 * </p>
514 * <p>
515 * For a touch capable device, once the user touches the screen, the device
516 * will enter touch mode.  From this point onward, only views for which
517 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
518 * Other views that are touchable, like buttons, will not take focus when touched; they will
519 * only fire the on click listeners.
520 * </p>
521 * <p>
522 * Any time a user hits a directional key, such as a D-pad direction, the view device will
523 * exit touch mode, and find a view to take focus, so that the user may resume interacting
524 * with the user interface without touching the screen again.
525 * </p>
526 * <p>
527 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
528 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
529 * </p>
530 *
531 * <a name="Scrolling"></a>
532 * <h3>Scrolling</h3>
533 * <p>
534 * The framework provides basic support for views that wish to internally
535 * scroll their content. This includes keeping track of the X and Y scroll
536 * offset as well as mechanisms for drawing scrollbars. See
537 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
538 * {@link #awakenScrollBars()} for more details.
539 * </p>
540 *
541 * <a name="Tags"></a>
542 * <h3>Tags</h3>
543 * <p>
544 * Unlike IDs, tags are not used to identify views. Tags are essentially an
545 * extra piece of information that can be associated with a view. They are most
546 * often used as a convenience to store data related to views in the views
547 * themselves rather than by putting them in a separate structure.
548 * </p>
549 *
550 * <a name="Properties"></a>
551 * <h3>Properties</h3>
552 * <p>
553 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
554 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
555 * available both in the {@link Property} form as well as in similarly-named setter/getter
556 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
557 * be used to set persistent state associated with these rendering-related properties on the view.
558 * The properties and methods can also be used in conjunction with
559 * {@link android.animation.Animator Animator}-based animations, described more in the
560 * <a href="#Animation">Animation</a> section.
561 * </p>
562 *
563 * <a name="Animation"></a>
564 * <h3>Animation</h3>
565 * <p>
566 * Starting with Android 3.0, the preferred way of animating views is to use the
567 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
568 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
569 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
570 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
571 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
572 * makes animating these View properties particularly easy and efficient.
573 * </p>
574 * <p>
575 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
576 * You can attach an {@link Animation} object to a view using
577 * {@link #setAnimation(Animation)} or
578 * {@link #startAnimation(Animation)}. The animation can alter the scale,
579 * rotation, translation and alpha of a view over time. If the animation is
580 * attached to a view that has children, the animation will affect the entire
581 * subtree rooted by that node. When an animation is started, the framework will
582 * take care of redrawing the appropriate views until the animation completes.
583 * </p>
584 *
585 * <a name="Security"></a>
586 * <h3>Security</h3>
587 * <p>
588 * Sometimes it is essential that an application be able to verify that an action
589 * is being performed with the full knowledge and consent of the user, such as
590 * granting a permission request, making a purchase or clicking on an advertisement.
591 * Unfortunately, a malicious application could try to spoof the user into
592 * performing these actions, unaware, by concealing the intended purpose of the view.
593 * As a remedy, the framework offers a touch filtering mechanism that can be used to
594 * improve the security of views that provide access to sensitive functionality.
595 * </p><p>
596 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
597 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
598 * will discard touches that are received whenever the view's window is obscured by
599 * another visible window.  As a result, the view will not receive touches whenever a
600 * toast, dialog or other window appears above the view's window.
601 * </p><p>
602 * For more fine-grained control over security, consider overriding the
603 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
604 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
605 * </p>
606 *
607 * @attr ref android.R.styleable#View_alpha
608 * @attr ref android.R.styleable#View_background
609 * @attr ref android.R.styleable#View_clickable
610 * @attr ref android.R.styleable#View_contentDescription
611 * @attr ref android.R.styleable#View_drawingCacheQuality
612 * @attr ref android.R.styleable#View_duplicateParentState
613 * @attr ref android.R.styleable#View_id
614 * @attr ref android.R.styleable#View_requiresFadingEdge
615 * @attr ref android.R.styleable#View_fadeScrollbars
616 * @attr ref android.R.styleable#View_fadingEdgeLength
617 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
618 * @attr ref android.R.styleable#View_fitsSystemWindows
619 * @attr ref android.R.styleable#View_isScrollContainer
620 * @attr ref android.R.styleable#View_focusable
621 * @attr ref android.R.styleable#View_focusableInTouchMode
622 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
623 * @attr ref android.R.styleable#View_keepScreenOn
624 * @attr ref android.R.styleable#View_layerType
625 * @attr ref android.R.styleable#View_layoutDirection
626 * @attr ref android.R.styleable#View_longClickable
627 * @attr ref android.R.styleable#View_minHeight
628 * @attr ref android.R.styleable#View_minWidth
629 * @attr ref android.R.styleable#View_nextFocusDown
630 * @attr ref android.R.styleable#View_nextFocusLeft
631 * @attr ref android.R.styleable#View_nextFocusRight
632 * @attr ref android.R.styleable#View_nextFocusUp
633 * @attr ref android.R.styleable#View_onClick
634 * @attr ref android.R.styleable#View_padding
635 * @attr ref android.R.styleable#View_paddingBottom
636 * @attr ref android.R.styleable#View_paddingLeft
637 * @attr ref android.R.styleable#View_paddingRight
638 * @attr ref android.R.styleable#View_paddingTop
639 * @attr ref android.R.styleable#View_paddingStart
640 * @attr ref android.R.styleable#View_paddingEnd
641 * @attr ref android.R.styleable#View_saveEnabled
642 * @attr ref android.R.styleable#View_rotation
643 * @attr ref android.R.styleable#View_rotationX
644 * @attr ref android.R.styleable#View_rotationY
645 * @attr ref android.R.styleable#View_scaleX
646 * @attr ref android.R.styleable#View_scaleY
647 * @attr ref android.R.styleable#View_scrollX
648 * @attr ref android.R.styleable#View_scrollY
649 * @attr ref android.R.styleable#View_scrollbarSize
650 * @attr ref android.R.styleable#View_scrollbarStyle
651 * @attr ref android.R.styleable#View_scrollbars
652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
653 * @attr ref android.R.styleable#View_scrollbarFadeDuration
654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbVertical
657 * @attr ref android.R.styleable#View_scrollbarTrackVertical
658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
660 * @attr ref android.R.styleable#View_soundEffectsEnabled
661 * @attr ref android.R.styleable#View_tag
662 * @attr ref android.R.styleable#View_textAlignment
663 * @attr ref android.R.styleable#View_textDirection
664 * @attr ref android.R.styleable#View_transformPivotX
665 * @attr ref android.R.styleable#View_transformPivotY
666 * @attr ref android.R.styleable#View_translationX
667 * @attr ref android.R.styleable#View_translationY
668 * @attr ref android.R.styleable#View_visibility
669 *
670 * @see android.view.ViewGroup
671 */
672public class View implements Drawable.Callback, KeyEvent.Callback,
673        AccessibilityEventSource {
674    private static final boolean DBG = false;
675
676    /**
677     * The logging tag used by this class with android.util.Log.
678     */
679    protected static final String VIEW_LOG_TAG = "View";
680
681    /**
682     * When set to true, apps will draw debugging information about their layouts.
683     *
684     * @hide
685     */
686    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
687
688    /**
689     * Used to mark a View that has no ID.
690     */
691    public static final int NO_ID = -1;
692
693    private static boolean sUseBrokenMakeMeasureSpec = false;
694
695    /**
696     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
697     * calling setFlags.
698     */
699    private static final int NOT_FOCUSABLE = 0x00000000;
700
701    /**
702     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
703     * setFlags.
704     */
705    private static final int FOCUSABLE = 0x00000001;
706
707    /**
708     * Mask for use with setFlags indicating bits used for focus.
709     */
710    private static final int FOCUSABLE_MASK = 0x00000001;
711
712    /**
713     * This view will adjust its padding to fit sytem windows (e.g. status bar)
714     */
715    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
716
717    /**
718     * This view is visible.
719     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
720     * android:visibility}.
721     */
722    public static final int VISIBLE = 0x00000000;
723
724    /**
725     * This view is invisible, but it still takes up space for layout purposes.
726     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
727     * android:visibility}.
728     */
729    public static final int INVISIBLE = 0x00000004;
730
731    /**
732     * This view is invisible, and it doesn't take any space for layout
733     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
734     * android:visibility}.
735     */
736    public static final int GONE = 0x00000008;
737
738    /**
739     * Mask for use with setFlags indicating bits used for visibility.
740     * {@hide}
741     */
742    static final int VISIBILITY_MASK = 0x0000000C;
743
744    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
745
746    /**
747     * This view is enabled. Interpretation varies by subclass.
748     * Use with ENABLED_MASK when calling setFlags.
749     * {@hide}
750     */
751    static final int ENABLED = 0x00000000;
752
753    /**
754     * This view is disabled. Interpretation varies by subclass.
755     * Use with ENABLED_MASK when calling setFlags.
756     * {@hide}
757     */
758    static final int DISABLED = 0x00000020;
759
760   /**
761    * Mask for use with setFlags indicating bits used for indicating whether
762    * this view is enabled
763    * {@hide}
764    */
765    static final int ENABLED_MASK = 0x00000020;
766
767    /**
768     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
769     * called and further optimizations will be performed. It is okay to have
770     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
771     * {@hide}
772     */
773    static final int WILL_NOT_DRAW = 0x00000080;
774
775    /**
776     * Mask for use with setFlags indicating bits used for indicating whether
777     * this view is will draw
778     * {@hide}
779     */
780    static final int DRAW_MASK = 0x00000080;
781
782    /**
783     * <p>This view doesn't show scrollbars.</p>
784     * {@hide}
785     */
786    static final int SCROLLBARS_NONE = 0x00000000;
787
788    /**
789     * <p>This view shows horizontal scrollbars.</p>
790     * {@hide}
791     */
792    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
793
794    /**
795     * <p>This view shows vertical scrollbars.</p>
796     * {@hide}
797     */
798    static final int SCROLLBARS_VERTICAL = 0x00000200;
799
800    /**
801     * <p>Mask for use with setFlags indicating bits used for indicating which
802     * scrollbars are enabled.</p>
803     * {@hide}
804     */
805    static final int SCROLLBARS_MASK = 0x00000300;
806
807    /**
808     * Indicates that the view should filter touches when its window is obscured.
809     * Refer to the class comments for more information about this security feature.
810     * {@hide}
811     */
812    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
813
814    /**
815     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
816     * that they are optional and should be skipped if the window has
817     * requested system UI flags that ignore those insets for layout.
818     */
819    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
820
821    /**
822     * <p>This view doesn't show fading edges.</p>
823     * {@hide}
824     */
825    static final int FADING_EDGE_NONE = 0x00000000;
826
827    /**
828     * <p>This view shows horizontal fading edges.</p>
829     * {@hide}
830     */
831    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
832
833    /**
834     * <p>This view shows vertical fading edges.</p>
835     * {@hide}
836     */
837    static final int FADING_EDGE_VERTICAL = 0x00002000;
838
839    /**
840     * <p>Mask for use with setFlags indicating bits used for indicating which
841     * fading edges are enabled.</p>
842     * {@hide}
843     */
844    static final int FADING_EDGE_MASK = 0x00003000;
845
846    /**
847     * <p>Indicates this view can be clicked. When clickable, a View reacts
848     * to clicks by notifying the OnClickListener.<p>
849     * {@hide}
850     */
851    static final int CLICKABLE = 0x00004000;
852
853    /**
854     * <p>Indicates this view is caching its drawing into a bitmap.</p>
855     * {@hide}
856     */
857    static final int DRAWING_CACHE_ENABLED = 0x00008000;
858
859    /**
860     * <p>Indicates that no icicle should be saved for this view.<p>
861     * {@hide}
862     */
863    static final int SAVE_DISABLED = 0x000010000;
864
865    /**
866     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
867     * property.</p>
868     * {@hide}
869     */
870    static final int SAVE_DISABLED_MASK = 0x000010000;
871
872    /**
873     * <p>Indicates that no drawing cache should ever be created for this view.<p>
874     * {@hide}
875     */
876    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
877
878    /**
879     * <p>Indicates this view can take / keep focus when int touch mode.</p>
880     * {@hide}
881     */
882    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
883
884    /**
885     * <p>Enables low quality mode for the drawing cache.</p>
886     */
887    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
888
889    /**
890     * <p>Enables high quality mode for the drawing cache.</p>
891     */
892    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
893
894    /**
895     * <p>Enables automatic quality mode for the drawing cache.</p>
896     */
897    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
898
899    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
900            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
901    };
902
903    /**
904     * <p>Mask for use with setFlags indicating bits used for the cache
905     * quality property.</p>
906     * {@hide}
907     */
908    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
909
910    /**
911     * <p>
912     * Indicates this view can be long clicked. When long clickable, a View
913     * reacts to long clicks by notifying the OnLongClickListener or showing a
914     * context menu.
915     * </p>
916     * {@hide}
917     */
918    static final int LONG_CLICKABLE = 0x00200000;
919
920    /**
921     * <p>Indicates that this view gets its drawable states from its direct parent
922     * and ignores its original internal states.</p>
923     *
924     * @hide
925     */
926    static final int DUPLICATE_PARENT_STATE = 0x00400000;
927
928    /**
929     * The scrollbar style to display the scrollbars inside the content area,
930     * without increasing the padding. The scrollbars will be overlaid with
931     * translucency on the view's content.
932     */
933    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
934
935    /**
936     * The scrollbar style to display the scrollbars inside the padded area,
937     * increasing the padding of the view. The scrollbars will not overlap the
938     * content area of the view.
939     */
940    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
941
942    /**
943     * The scrollbar style to display the scrollbars at the edge of the view,
944     * without increasing the padding. The scrollbars will be overlaid with
945     * translucency.
946     */
947    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
948
949    /**
950     * The scrollbar style to display the scrollbars at the edge of the view,
951     * increasing the padding of the view. The scrollbars will only overlap the
952     * background, if any.
953     */
954    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
955
956    /**
957     * Mask to check if the scrollbar style is overlay or inset.
958     * {@hide}
959     */
960    static final int SCROLLBARS_INSET_MASK = 0x01000000;
961
962    /**
963     * Mask to check if the scrollbar style is inside or outside.
964     * {@hide}
965     */
966    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
967
968    /**
969     * Mask for scrollbar style.
970     * {@hide}
971     */
972    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
973
974    /**
975     * View flag indicating that the screen should remain on while the
976     * window containing this view is visible to the user.  This effectively
977     * takes care of automatically setting the WindowManager's
978     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
979     */
980    public static final int KEEP_SCREEN_ON = 0x04000000;
981
982    /**
983     * View flag indicating whether this view should have sound effects enabled
984     * for events such as clicking and touching.
985     */
986    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
987
988    /**
989     * View flag indicating whether this view should have haptic feedback
990     * enabled for events such as long presses.
991     */
992    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
993
994    /**
995     * <p>Indicates that the view hierarchy should stop saving state when
996     * it reaches this view.  If state saving is initiated immediately at
997     * the view, it will be allowed.
998     * {@hide}
999     */
1000    static final int PARENT_SAVE_DISABLED = 0x20000000;
1001
1002    /**
1003     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1004     * {@hide}
1005     */
1006    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1007
1008    /**
1009     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1010     * should add all focusable Views regardless if they are focusable in touch mode.
1011     */
1012    public static final int FOCUSABLES_ALL = 0x00000000;
1013
1014    /**
1015     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1016     * should add only Views focusable in touch mode.
1017     */
1018    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1019
1020    /**
1021     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1022     * item.
1023     */
1024    public static final int FOCUS_BACKWARD = 0x00000001;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1028     * item.
1029     */
1030    public static final int FOCUS_FORWARD = 0x00000002;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus to the left.
1034     */
1035    public static final int FOCUS_LEFT = 0x00000011;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus up.
1039     */
1040    public static final int FOCUS_UP = 0x00000021;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus to the right.
1044     */
1045    public static final int FOCUS_RIGHT = 0x00000042;
1046
1047    /**
1048     * Use with {@link #focusSearch(int)}. Move focus down.
1049     */
1050    public static final int FOCUS_DOWN = 0x00000082;
1051
1052    /**
1053     * Bits of {@link #getMeasuredWidthAndState()} and
1054     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1055     */
1056    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1057
1058    /**
1059     * Bits of {@link #getMeasuredWidthAndState()} and
1060     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1061     */
1062    public static final int MEASURED_STATE_MASK = 0xff000000;
1063
1064    /**
1065     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1066     * for functions that combine both width and height into a single int,
1067     * such as {@link #getMeasuredState()} and the childState argument of
1068     * {@link #resolveSizeAndState(int, int, int)}.
1069     */
1070    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1071
1072    /**
1073     * Bit of {@link #getMeasuredWidthAndState()} and
1074     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1075     * is smaller that the space the view would like to have.
1076     */
1077    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1078
1079    /**
1080     * Base View state sets
1081     */
1082    // Singles
1083    /**
1084     * Indicates the view has no states set. States are used with
1085     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1086     * view depending on its state.
1087     *
1088     * @see android.graphics.drawable.Drawable
1089     * @see #getDrawableState()
1090     */
1091    protected static final int[] EMPTY_STATE_SET;
1092    /**
1093     * Indicates the view is enabled. States are used with
1094     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1095     * view depending on its state.
1096     *
1097     * @see android.graphics.drawable.Drawable
1098     * @see #getDrawableState()
1099     */
1100    protected static final int[] ENABLED_STATE_SET;
1101    /**
1102     * Indicates the view is focused. States are used with
1103     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1104     * view depending on its state.
1105     *
1106     * @see android.graphics.drawable.Drawable
1107     * @see #getDrawableState()
1108     */
1109    protected static final int[] FOCUSED_STATE_SET;
1110    /**
1111     * Indicates the view is selected. States are used with
1112     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1113     * view depending on its state.
1114     *
1115     * @see android.graphics.drawable.Drawable
1116     * @see #getDrawableState()
1117     */
1118    protected static final int[] SELECTED_STATE_SET;
1119    /**
1120     * Indicates the view is pressed. States are used with
1121     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1122     * view depending on its state.
1123     *
1124     * @see android.graphics.drawable.Drawable
1125     * @see #getDrawableState()
1126     */
1127    protected static final int[] PRESSED_STATE_SET;
1128    /**
1129     * Indicates the view's window has focus. States are used with
1130     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1131     * view depending on its state.
1132     *
1133     * @see android.graphics.drawable.Drawable
1134     * @see #getDrawableState()
1135     */
1136    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1137    // Doubles
1138    /**
1139     * Indicates the view is enabled and has the focus.
1140     *
1141     * @see #ENABLED_STATE_SET
1142     * @see #FOCUSED_STATE_SET
1143     */
1144    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1145    /**
1146     * Indicates the view is enabled and selected.
1147     *
1148     * @see #ENABLED_STATE_SET
1149     * @see #SELECTED_STATE_SET
1150     */
1151    protected static final int[] ENABLED_SELECTED_STATE_SET;
1152    /**
1153     * Indicates the view is enabled and that its window has focus.
1154     *
1155     * @see #ENABLED_STATE_SET
1156     * @see #WINDOW_FOCUSED_STATE_SET
1157     */
1158    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1159    /**
1160     * Indicates the view is focused and selected.
1161     *
1162     * @see #FOCUSED_STATE_SET
1163     * @see #SELECTED_STATE_SET
1164     */
1165    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1166    /**
1167     * Indicates the view has the focus and that its window has the focus.
1168     *
1169     * @see #FOCUSED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1173    /**
1174     * Indicates the view is selected and that its window has the focus.
1175     *
1176     * @see #SELECTED_STATE_SET
1177     * @see #WINDOW_FOCUSED_STATE_SET
1178     */
1179    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1180    // Triples
1181    /**
1182     * Indicates the view is enabled, focused and selected.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #FOCUSED_STATE_SET
1186     * @see #SELECTED_STATE_SET
1187     */
1188    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1189    /**
1190     * Indicates the view is enabled, focused and its window has the focus.
1191     *
1192     * @see #ENABLED_STATE_SET
1193     * @see #FOCUSED_STATE_SET
1194     * @see #WINDOW_FOCUSED_STATE_SET
1195     */
1196    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1197    /**
1198     * Indicates the view is enabled, selected and its window has the focus.
1199     *
1200     * @see #ENABLED_STATE_SET
1201     * @see #SELECTED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is focused, selected and its window has the focus.
1207     *
1208     * @see #FOCUSED_STATE_SET
1209     * @see #SELECTED_STATE_SET
1210     * @see #WINDOW_FOCUSED_STATE_SET
1211     */
1212    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1213    /**
1214     * Indicates the view is enabled, focused, selected and its window
1215     * has the focus.
1216     *
1217     * @see #ENABLED_STATE_SET
1218     * @see #FOCUSED_STATE_SET
1219     * @see #SELECTED_STATE_SET
1220     * @see #WINDOW_FOCUSED_STATE_SET
1221     */
1222    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed and its window has the focus.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #WINDOW_FOCUSED_STATE_SET
1228     */
1229    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is pressed and selected.
1232     *
1233     * @see #PRESSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     */
1236    protected static final int[] PRESSED_SELECTED_STATE_SET;
1237    /**
1238     * Indicates the view is pressed, selected and its window has the focus.
1239     *
1240     * @see #PRESSED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is pressed and focused.
1247     *
1248     * @see #PRESSED_STATE_SET
1249     * @see #FOCUSED_STATE_SET
1250     */
1251    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1252    /**
1253     * Indicates the view is pressed, focused and its window has the focus.
1254     *
1255     * @see #PRESSED_STATE_SET
1256     * @see #FOCUSED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is pressed, focused and selected.
1262     *
1263     * @see #PRESSED_STATE_SET
1264     * @see #SELECTED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed, focused, selected and its window has the focus.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #FOCUSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed and enabled.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_ENABLED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, enabled and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #ENABLED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, enabled and selected.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #ENABLED_STATE_SET
1297     * @see #SELECTED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, enabled, selected and its window has the
1302     * focus.
1303     *
1304     * @see #PRESSED_STATE_SET
1305     * @see #ENABLED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed, enabled and focused.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #ENABLED_STATE_SET
1315     * @see #FOCUSED_STATE_SET
1316     */
1317    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1318    /**
1319     * Indicates the view is pressed, enabled, focused and its window has the
1320     * focus.
1321     *
1322     * @see #PRESSED_STATE_SET
1323     * @see #ENABLED_STATE_SET
1324     * @see #FOCUSED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled, focused and selected.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, enabled, focused, selected and its window
1339     * has the focus.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #ENABLED_STATE_SET
1343     * @see #SELECTED_STATE_SET
1344     * @see #FOCUSED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1348
1349    /**
1350     * The order here is very important to {@link #getDrawableState()}
1351     */
1352    private static final int[][] VIEW_STATE_SETS;
1353
1354    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1355    static final int VIEW_STATE_SELECTED = 1 << 1;
1356    static final int VIEW_STATE_FOCUSED = 1 << 2;
1357    static final int VIEW_STATE_ENABLED = 1 << 3;
1358    static final int VIEW_STATE_PRESSED = 1 << 4;
1359    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1360    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1361    static final int VIEW_STATE_HOVERED = 1 << 7;
1362    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1363    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1364
1365    static final int[] VIEW_STATE_IDS = new int[] {
1366        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1367        R.attr.state_selected,          VIEW_STATE_SELECTED,
1368        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1369        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1370        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1371        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1372        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1373        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1374        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1375        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1376    };
1377
1378    static {
1379        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1380            throw new IllegalStateException(
1381                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1382        }
1383        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1384        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1385            int viewState = R.styleable.ViewDrawableStates[i];
1386            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1387                if (VIEW_STATE_IDS[j] == viewState) {
1388                    orderedIds[i * 2] = viewState;
1389                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1390                }
1391            }
1392        }
1393        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1394        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1395        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1396            int numBits = Integer.bitCount(i);
1397            int[] set = new int[numBits];
1398            int pos = 0;
1399            for (int j = 0; j < orderedIds.length; j += 2) {
1400                if ((i & orderedIds[j+1]) != 0) {
1401                    set[pos++] = orderedIds[j];
1402                }
1403            }
1404            VIEW_STATE_SETS[i] = set;
1405        }
1406
1407        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1408        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1409        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1410        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1412        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1413        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1415        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1417        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1419                | VIEW_STATE_FOCUSED];
1420        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1421        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1423        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1425        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1427                | VIEW_STATE_ENABLED];
1428        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1430        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1432                | VIEW_STATE_ENABLED];
1433        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1434                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1435                | VIEW_STATE_ENABLED];
1436        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1438                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1439
1440        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1441        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1443        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1445        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1447                | VIEW_STATE_PRESSED];
1448        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1450        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1452                | VIEW_STATE_PRESSED];
1453        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1455                | VIEW_STATE_PRESSED];
1456        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1458                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1459        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1463                | VIEW_STATE_PRESSED];
1464        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1466                | VIEW_STATE_PRESSED];
1467        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1469                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1470        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1472                | VIEW_STATE_PRESSED];
1473        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1475                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1476        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1477                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1478                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1479        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1481                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1482                | VIEW_STATE_PRESSED];
1483    }
1484
1485    /**
1486     * Accessibility event types that are dispatched for text population.
1487     */
1488    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1489            AccessibilityEvent.TYPE_VIEW_CLICKED
1490            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_SELECTED
1492            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1493            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1494            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1496            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1499            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1500
1501    /**
1502     * Temporary Rect currently for use in setBackground().  This will probably
1503     * be extended in the future to hold our own class with more than just
1504     * a Rect. :)
1505     */
1506    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1507
1508    /**
1509     * Map used to store views' tags.
1510     */
1511    private SparseArray<Object> mKeyedTags;
1512
1513    /**
1514     * The next available accessibility id.
1515     */
1516    private static int sNextAccessibilityViewId;
1517
1518    /**
1519     * The animation currently associated with this view.
1520     * @hide
1521     */
1522    protected Animation mCurrentAnimation = null;
1523
1524    /**
1525     * Width as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredWidth;
1530
1531    /**
1532     * Height as measured during measure pass.
1533     * {@hide}
1534     */
1535    @ViewDebug.ExportedProperty(category = "measurement")
1536    int mMeasuredHeight;
1537
1538    /**
1539     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1540     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1541     * its display list. This flag, used only when hw accelerated, allows us to clear the
1542     * flag while retaining this information until it's needed (at getDisplayList() time and
1543     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1544     *
1545     * {@hide}
1546     */
1547    boolean mRecreateDisplayList = false;
1548
1549    /**
1550     * The view's identifier.
1551     * {@hide}
1552     *
1553     * @see #setId(int)
1554     * @see #getId()
1555     */
1556    @ViewDebug.ExportedProperty(resolveId = true)
1557    int mID = NO_ID;
1558
1559    /**
1560     * The stable ID of this view for accessibility purposes.
1561     */
1562    int mAccessibilityViewId = NO_ID;
1563
1564    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1565
1566    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1567
1568    /**
1569     * The view's tag.
1570     * {@hide}
1571     *
1572     * @see #setTag(Object)
1573     * @see #getTag()
1574     */
1575    protected Object mTag;
1576
1577    private Scene mCurrentScene = null;
1578
1579    // for mPrivateFlags:
1580    /** {@hide} */
1581    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1582    /** {@hide} */
1583    static final int PFLAG_FOCUSED                     = 0x00000002;
1584    /** {@hide} */
1585    static final int PFLAG_SELECTED                    = 0x00000004;
1586    /** {@hide} */
1587    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1588    /** {@hide} */
1589    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1590    /** {@hide} */
1591    static final int PFLAG_DRAWN                       = 0x00000020;
1592    /**
1593     * When this flag is set, this view is running an animation on behalf of its
1594     * children and should therefore not cancel invalidate requests, even if they
1595     * lie outside of this view's bounds.
1596     *
1597     * {@hide}
1598     */
1599    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1600    /** {@hide} */
1601    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1602    /** {@hide} */
1603    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1604    /** {@hide} */
1605    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1606    /** {@hide} */
1607    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1608    /** {@hide} */
1609    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1610    /** {@hide} */
1611    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1612    /** {@hide} */
1613    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1614
1615    private static final int PFLAG_PRESSED             = 0x00004000;
1616
1617    /** {@hide} */
1618    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1619    /**
1620     * Flag used to indicate that this view should be drawn once more (and only once
1621     * more) after its animation has completed.
1622     * {@hide}
1623     */
1624    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1625
1626    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1627
1628    /**
1629     * Indicates that the View returned true when onSetAlpha() was called and that
1630     * the alpha must be restored.
1631     * {@hide}
1632     */
1633    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1634
1635    /**
1636     * Set by {@link #setScrollContainer(boolean)}.
1637     */
1638    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1639
1640    /**
1641     * Set by {@link #setScrollContainer(boolean)}.
1642     */
1643    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1644
1645    /**
1646     * View flag indicating whether this view was invalidated (fully or partially.)
1647     *
1648     * @hide
1649     */
1650    static final int PFLAG_DIRTY                       = 0x00200000;
1651
1652    /**
1653     * View flag indicating whether this view was invalidated by an opaque
1654     * invalidate request.
1655     *
1656     * @hide
1657     */
1658    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1659
1660    /**
1661     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1662     *
1663     * @hide
1664     */
1665    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1666
1667    /**
1668     * Indicates whether the background is opaque.
1669     *
1670     * @hide
1671     */
1672    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1673
1674    /**
1675     * Indicates whether the scrollbars are opaque.
1676     *
1677     * @hide
1678     */
1679    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1680
1681    /**
1682     * Indicates whether the view is opaque.
1683     *
1684     * @hide
1685     */
1686    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1687
1688    /**
1689     * Indicates a prepressed state;
1690     * the short time between ACTION_DOWN and recognizing
1691     * a 'real' press. Prepressed is used to recognize quick taps
1692     * even when they are shorter than ViewConfiguration.getTapTimeout().
1693     *
1694     * @hide
1695     */
1696    private static final int PFLAG_PREPRESSED          = 0x02000000;
1697
1698    /**
1699     * Indicates whether the view is temporarily detached.
1700     *
1701     * @hide
1702     */
1703    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1704
1705    /**
1706     * Indicates that we should awaken scroll bars once attached
1707     *
1708     * @hide
1709     */
1710    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1711
1712    /**
1713     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1714     * @hide
1715     */
1716    private static final int PFLAG_HOVERED             = 0x10000000;
1717
1718    /**
1719     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1720     * for transform operations
1721     *
1722     * @hide
1723     */
1724    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1725
1726    /** {@hide} */
1727    static final int PFLAG_ACTIVATED                   = 0x40000000;
1728
1729    /**
1730     * Indicates that this view was specifically invalidated, not just dirtied because some
1731     * child view was invalidated. The flag is used to determine when we need to recreate
1732     * a view's display list (as opposed to just returning a reference to its existing
1733     * display list).
1734     *
1735     * @hide
1736     */
1737    static final int PFLAG_INVALIDATED                 = 0x80000000;
1738
1739    /**
1740     * Masks for mPrivateFlags2, as generated by dumpFlags():
1741     *
1742     * -------|-------|-------|-------|
1743     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1744     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1745     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1746     *                               1  PFLAG2_DRAG_HOVERED
1747     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1748     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1749     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1750     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1751     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1752     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1753     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1754     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1755     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1756     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1757     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1758     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1759     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1760     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1761     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1762     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1763     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1764     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1765     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1766     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1767     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1768     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1769     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1770     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1771     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1772     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1773     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1774     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1775     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1776     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1777     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1778     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1779     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1780     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1781     *   1                              PFLAG2_PADDING_RESOLVED
1782     * -------|-------|-------|-------|
1783     */
1784
1785    /**
1786     * Indicates that this view has reported that it can accept the current drag's content.
1787     * Cleared when the drag operation concludes.
1788     * @hide
1789     */
1790    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1791
1792    /**
1793     * Indicates that this view is currently directly under the drag location in a
1794     * drag-and-drop operation involving content that it can accept.  Cleared when
1795     * the drag exits the view, or when the drag operation concludes.
1796     * @hide
1797     */
1798    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1799
1800    /**
1801     * Horizontal layout direction of this view is from Left to Right.
1802     * Use with {@link #setLayoutDirection}.
1803     */
1804    public static final int LAYOUT_DIRECTION_LTR = 0;
1805
1806    /**
1807     * Horizontal layout direction of this view is from Right to Left.
1808     * Use with {@link #setLayoutDirection}.
1809     */
1810    public static final int LAYOUT_DIRECTION_RTL = 1;
1811
1812    /**
1813     * Horizontal layout direction of this view is inherited from its parent.
1814     * Use with {@link #setLayoutDirection}.
1815     */
1816    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1817
1818    /**
1819     * Horizontal layout direction of this view is from deduced from the default language
1820     * script for the locale. Use with {@link #setLayoutDirection}.
1821     */
1822    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1823
1824    /**
1825     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1826     * @hide
1827     */
1828    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1829
1830    /**
1831     * Mask for use with private flags indicating bits used for horizontal layout direction.
1832     * @hide
1833     */
1834    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1835
1836    /**
1837     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1838     * right-to-left direction.
1839     * @hide
1840     */
1841    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1842
1843    /**
1844     * Indicates whether the view horizontal layout direction has been resolved.
1845     * @hide
1846     */
1847    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1848
1849    /**
1850     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1851     * @hide
1852     */
1853    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1854            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1855
1856    /*
1857     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1858     * flag value.
1859     * @hide
1860     */
1861    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1862            LAYOUT_DIRECTION_LTR,
1863            LAYOUT_DIRECTION_RTL,
1864            LAYOUT_DIRECTION_INHERIT,
1865            LAYOUT_DIRECTION_LOCALE
1866    };
1867
1868    /**
1869     * Default horizontal layout direction.
1870     */
1871    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1872
1873    /**
1874     * Default horizontal layout direction.
1875     * @hide
1876     */
1877    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1878
1879    /**
1880     * Indicates that the view is tracking some sort of transient state
1881     * that the app should not need to be aware of, but that the framework
1882     * should take special care to preserve.
1883     *
1884     * @hide
1885     */
1886    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1887
1888    /**
1889     * Text direction is inherited thru {@link ViewGroup}
1890     */
1891    public static final int TEXT_DIRECTION_INHERIT = 0;
1892
1893    /**
1894     * Text direction is using "first strong algorithm". The first strong directional character
1895     * determines the paragraph direction. If there is no strong directional character, the
1896     * paragraph direction is the view's resolved layout direction.
1897     */
1898    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1899
1900    /**
1901     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1902     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1903     * If there are neither, the paragraph direction is the view's resolved layout direction.
1904     */
1905    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1906
1907    /**
1908     * Text direction is forced to LTR.
1909     */
1910    public static final int TEXT_DIRECTION_LTR = 3;
1911
1912    /**
1913     * Text direction is forced to RTL.
1914     */
1915    public static final int TEXT_DIRECTION_RTL = 4;
1916
1917    /**
1918     * Text direction is coming from the system Locale.
1919     */
1920    public static final int TEXT_DIRECTION_LOCALE = 5;
1921
1922    /**
1923     * Default text direction is inherited
1924     */
1925    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1926
1927    /**
1928     * Default resolved text direction
1929     * @hide
1930     */
1931    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1932
1933    /**
1934     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1935     * @hide
1936     */
1937    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1938
1939    /**
1940     * Mask for use with private flags indicating bits used for text direction.
1941     * @hide
1942     */
1943    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1944            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1945
1946    /**
1947     * Array of text direction flags for mapping attribute "textDirection" to correct
1948     * flag value.
1949     * @hide
1950     */
1951    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1952            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1957            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1958    };
1959
1960    /**
1961     * Indicates whether the view text direction has been resolved.
1962     * @hide
1963     */
1964    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1965            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1966
1967    /**
1968     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1969     * @hide
1970     */
1971    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1972
1973    /**
1974     * Mask for use with private flags indicating bits used for resolved text direction.
1975     * @hide
1976     */
1977    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1978            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1979
1980    /**
1981     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1982     * @hide
1983     */
1984    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1985            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1986
1987    /*
1988     * Default text alignment. The text alignment of this View is inherited from its parent.
1989     * Use with {@link #setTextAlignment(int)}
1990     */
1991    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1992
1993    /**
1994     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1995     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1996     *
1997     * Use with {@link #setTextAlignment(int)}
1998     */
1999    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2000
2001    /**
2002     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2003     *
2004     * Use with {@link #setTextAlignment(int)}
2005     */
2006    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2007
2008    /**
2009     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2010     *
2011     * Use with {@link #setTextAlignment(int)}
2012     */
2013    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2014
2015    /**
2016     * Center the paragraph, e.g. ALIGN_CENTER.
2017     *
2018     * Use with {@link #setTextAlignment(int)}
2019     */
2020    public static final int TEXT_ALIGNMENT_CENTER = 4;
2021
2022    /**
2023     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2024     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2025     *
2026     * Use with {@link #setTextAlignment(int)}
2027     */
2028    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2029
2030    /**
2031     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2032     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2033     *
2034     * Use with {@link #setTextAlignment(int)}
2035     */
2036    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2037
2038    /**
2039     * Default text alignment is inherited
2040     */
2041    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2042
2043    /**
2044     * Default resolved text alignment
2045     * @hide
2046     */
2047    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2048
2049    /**
2050      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2051      * @hide
2052      */
2053    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2054
2055    /**
2056      * Mask for use with private flags indicating bits used for text alignment.
2057      * @hide
2058      */
2059    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2060
2061    /**
2062     * Array of text direction flags for mapping attribute "textAlignment" to correct
2063     * flag value.
2064     * @hide
2065     */
2066    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2067            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2073            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2074    };
2075
2076    /**
2077     * Indicates whether the view text alignment has been resolved.
2078     * @hide
2079     */
2080    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2081
2082    /**
2083     * Bit shift to get the resolved text alignment.
2084     * @hide
2085     */
2086    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2087
2088    /**
2089     * Mask for use with private flags indicating bits used for text alignment.
2090     * @hide
2091     */
2092    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2093            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2094
2095    /**
2096     * Indicates whether if the view text alignment has been resolved to gravity
2097     */
2098    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2099            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2100
2101    // Accessiblity constants for mPrivateFlags2
2102
2103    /**
2104     * Shift for the bits in {@link #mPrivateFlags2} related to the
2105     * "importantForAccessibility" attribute.
2106     */
2107    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2108
2109    /**
2110     * Automatically determine whether a view is important for accessibility.
2111     */
2112    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2113
2114    /**
2115     * The view is important for accessibility.
2116     */
2117    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2118
2119    /**
2120     * The view is not important for accessibility.
2121     */
2122    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2123
2124    /**
2125     * The default whether the view is important for accessibility.
2126     */
2127    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2128
2129    /**
2130     * Mask for obtainig the bits which specify how to determine
2131     * whether a view is important for accessibility.
2132     */
2133    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2134        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2135        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2136
2137    /**
2138     * Flag indicating whether a view has accessibility focus.
2139     */
2140    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2141
2142    /**
2143     * Flag whether the accessibility state of the subtree rooted at this view changed.
2144     */
2145    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2146
2147    /**
2148     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2149     * is used to check whether later changes to the view's transform should invalidate the
2150     * view to force the quickReject test to run again.
2151     */
2152    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2153
2154    /**
2155     * Flag indicating that start/end padding has been resolved into left/right padding
2156     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2157     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2158     * during measurement. In some special cases this is required such as when an adapter-based
2159     * view measures prospective children without attaching them to a window.
2160     */
2161    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2162
2163    /**
2164     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2165     */
2166    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2167
2168    /**
2169     * Group of bits indicating that RTL properties resolution is done.
2170     */
2171    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2172            PFLAG2_TEXT_DIRECTION_RESOLVED |
2173            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2174            PFLAG2_PADDING_RESOLVED |
2175            PFLAG2_DRAWABLE_RESOLVED;
2176
2177    // There are a couple of flags left in mPrivateFlags2
2178
2179    /* End of masks for mPrivateFlags2 */
2180
2181    /* Masks for mPrivateFlags3 */
2182
2183    /**
2184     * Flag indicating that view has a transform animation set on it. This is used to track whether
2185     * an animation is cleared between successive frames, in order to tell the associated
2186     * DisplayList to clear its animation matrix.
2187     */
2188    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2189
2190    /**
2191     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2192     * animation is cleared between successive frames, in order to tell the associated
2193     * DisplayList to restore its alpha value.
2194     */
2195    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2196
2197    /**
2198     * Flag indicating that the view has been through at least one layout since it
2199     * was last attached to a window.
2200     */
2201    static final int PFLAG3_IS_LAID_OUT = 0x4;
2202
2203    /**
2204     * Flag indicating that a call to measure() was skipped and should be done
2205     * instead when layout() is invoked.
2206     */
2207    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2208
2209
2210    /* End of masks for mPrivateFlags3 */
2211
2212    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2213
2214    /**
2215     * Always allow a user to over-scroll this view, provided it is a
2216     * view that can scroll.
2217     *
2218     * @see #getOverScrollMode()
2219     * @see #setOverScrollMode(int)
2220     */
2221    public static final int OVER_SCROLL_ALWAYS = 0;
2222
2223    /**
2224     * Allow a user to over-scroll this view only if the content is large
2225     * enough to meaningfully scroll, provided it is a view that can scroll.
2226     *
2227     * @see #getOverScrollMode()
2228     * @see #setOverScrollMode(int)
2229     */
2230    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2231
2232    /**
2233     * Never allow a user to over-scroll this view.
2234     *
2235     * @see #getOverScrollMode()
2236     * @see #setOverScrollMode(int)
2237     */
2238    public static final int OVER_SCROLL_NEVER = 2;
2239
2240    /**
2241     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2242     * requested the system UI (status bar) to be visible (the default).
2243     *
2244     * @see #setSystemUiVisibility(int)
2245     */
2246    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2247
2248    /**
2249     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2250     * system UI to enter an unobtrusive "low profile" mode.
2251     *
2252     * <p>This is for use in games, book readers, video players, or any other
2253     * "immersive" application where the usual system chrome is deemed too distracting.
2254     *
2255     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2256     *
2257     * @see #setSystemUiVisibility(int)
2258     */
2259    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2260
2261    /**
2262     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2263     * system navigation be temporarily hidden.
2264     *
2265     * <p>This is an even less obtrusive state than that called for by
2266     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2267     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2268     * those to disappear. This is useful (in conjunction with the
2269     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2270     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2271     * window flags) for displaying content using every last pixel on the display.
2272     *
2273     * <p>There is a limitation: because navigation controls are so important, the least user
2274     * interaction will cause them to reappear immediately.  When this happens, both
2275     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2276     * so that both elements reappear at the same time.
2277     *
2278     * @see #setSystemUiVisibility(int)
2279     */
2280    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2281
2282    /**
2283     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2284     * into the normal fullscreen mode so that its content can take over the screen
2285     * while still allowing the user to interact with the application.
2286     *
2287     * <p>This has the same visual effect as
2288     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2289     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2290     * meaning that non-critical screen decorations (such as the status bar) will be
2291     * hidden while the user is in the View's window, focusing the experience on
2292     * that content.  Unlike the window flag, if you are using ActionBar in
2293     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2294     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2295     * hide the action bar.
2296     *
2297     * <p>This approach to going fullscreen is best used over the window flag when
2298     * it is a transient state -- that is, the application does this at certain
2299     * points in its user interaction where it wants to allow the user to focus
2300     * on content, but not as a continuous state.  For situations where the application
2301     * would like to simply stay full screen the entire time (such as a game that
2302     * wants to take over the screen), the
2303     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2304     * is usually a better approach.  The state set here will be removed by the system
2305     * in various situations (such as the user moving to another application) like
2306     * the other system UI states.
2307     *
2308     * <p>When using this flag, the application should provide some easy facility
2309     * for the user to go out of it.  A common example would be in an e-book
2310     * reader, where tapping on the screen brings back whatever screen and UI
2311     * decorations that had been hidden while the user was immersed in reading
2312     * the book.
2313     *
2314     * @see #setSystemUiVisibility(int)
2315     */
2316    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2317
2318    /**
2319     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2320     * flags, we would like a stable view of the content insets given to
2321     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2322     * will always represent the worst case that the application can expect
2323     * as a continuous state.  In the stock Android UI this is the space for
2324     * the system bar, nav bar, and status bar, but not more transient elements
2325     * such as an input method.
2326     *
2327     * The stable layout your UI sees is based on the system UI modes you can
2328     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2329     * then you will get a stable layout for changes of the
2330     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2331     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2332     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2333     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2334     * with a stable layout.  (Note that you should avoid using
2335     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2336     *
2337     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2338     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2339     * then a hidden status bar will be considered a "stable" state for purposes
2340     * here.  This allows your UI to continually hide the status bar, while still
2341     * using the system UI flags to hide the action bar while still retaining
2342     * a stable layout.  Note that changing the window fullscreen flag will never
2343     * provide a stable layout for a clean transition.
2344     *
2345     * <p>If you are using ActionBar in
2346     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2347     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2348     * insets it adds to those given to the application.
2349     */
2350    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2351
2352    /**
2353     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2354     * to be layed out as if it has requested
2355     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2356     * allows it to avoid artifacts when switching in and out of that mode, at
2357     * the expense that some of its user interface may be covered by screen
2358     * decorations when they are shown.  You can perform layout of your inner
2359     * UI elements to account for the navigation system UI through the
2360     * {@link #fitSystemWindows(Rect)} method.
2361     */
2362    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2363
2364    /**
2365     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2366     * to be layed out as if it has requested
2367     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2368     * allows it to avoid artifacts when switching in and out of that mode, at
2369     * the expense that some of its user interface may be covered by screen
2370     * decorations when they are shown.  You can perform layout of your inner
2371     * UI elements to account for non-fullscreen system UI through the
2372     * {@link #fitSystemWindows(Rect)} method.
2373     */
2374    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2375
2376    /**
2377     * Flag for {@link #setSystemUiVisibility(int)}: View would like to receive touch events
2378     * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the
2379     * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system
2380     * clear these flags upon interaction.  The system may compensate by temporarily overlaying
2381     * transparent system ui while also delivering the event.
2382     */
2383    public static final int SYSTEM_UI_FLAG_ALLOW_OVERLAY = 0x00000800;
2384
2385    /**
2386     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2387     */
2388    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2389
2390    /**
2391     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2392     */
2393    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2394
2395    /**
2396     * @hide
2397     *
2398     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2399     * out of the public fields to keep the undefined bits out of the developer's way.
2400     *
2401     * Flag to make the status bar not expandable.  Unless you also
2402     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2403     */
2404    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2405
2406    /**
2407     * @hide
2408     *
2409     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2410     * out of the public fields to keep the undefined bits out of the developer's way.
2411     *
2412     * Flag to hide notification icons and scrolling ticker text.
2413     */
2414    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2415
2416    /**
2417     * @hide
2418     *
2419     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2420     * out of the public fields to keep the undefined bits out of the developer's way.
2421     *
2422     * Flag to disable incoming notification alerts.  This will not block
2423     * icons, but it will block sound, vibrating and other visual or aural notifications.
2424     */
2425    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2426
2427    /**
2428     * @hide
2429     *
2430     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2431     * out of the public fields to keep the undefined bits out of the developer's way.
2432     *
2433     * Flag to hide only the scrolling ticker.  Note that
2434     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2435     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2436     */
2437    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2438
2439    /**
2440     * @hide
2441     *
2442     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2443     * out of the public fields to keep the undefined bits out of the developer's way.
2444     *
2445     * Flag to hide the center system info area.
2446     */
2447    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2448
2449    /**
2450     * @hide
2451     *
2452     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2453     * out of the public fields to keep the undefined bits out of the developer's way.
2454     *
2455     * Flag to hide only the home button.  Don't use this
2456     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2457     */
2458    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2459
2460    /**
2461     * @hide
2462     *
2463     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2464     * out of the public fields to keep the undefined bits out of the developer's way.
2465     *
2466     * Flag to hide only the back button. Don't use this
2467     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2468     */
2469    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2470
2471    /**
2472     * @hide
2473     *
2474     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2475     * out of the public fields to keep the undefined bits out of the developer's way.
2476     *
2477     * Flag to hide only the clock.  You might use this if your activity has
2478     * its own clock making the status bar's clock redundant.
2479     */
2480    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2481
2482    /**
2483     * @hide
2484     *
2485     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2486     * out of the public fields to keep the undefined bits out of the developer's way.
2487     *
2488     * Flag to hide only the recent apps button. Don't use this
2489     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2490     */
2491    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2492
2493    /**
2494     * @hide
2495     *
2496     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2497     * out of the public fields to keep the undefined bits out of the developer's way.
2498     *
2499     * Flag to disable the global search gesture. Don't use this
2500     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2501     */
2502    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2503
2504    /**
2505     * @hide
2506     *
2507     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2508     * out of the public fields to keep the undefined bits out of the developer's way.
2509     *
2510     * Flag to specify that the status bar should temporarily overlay underlying content
2511     * that is otherwise assuming the status bar is hidden.  The status bar may
2512     * have some degree of transparency while in this temporary overlay mode.
2513     */
2514    public static final int STATUS_BAR_OVERLAY = 0x04000000;
2515
2516    /**
2517     * @hide
2518     *
2519     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2520     * out of the public fields to keep the undefined bits out of the developer's way.
2521     *
2522     * Flag to specify that the navigation bar should temporarily overlay underlying content
2523     * that is otherwise assuming the navigation bar is hidden.  The navigation bar mayu
2524     * have some degree of transparency while in this temporary overlay mode.
2525     */
2526    public static final int NAVIGATION_BAR_OVERLAY = 0x08000000;
2527
2528    /**
2529     * @hide
2530     */
2531    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2532
2533    /**
2534     * These are the system UI flags that can be cleared by events outside
2535     * of an application.  Currently this is just the ability to tap on the
2536     * screen while hiding the navigation bar to have it return.
2537     * @hide
2538     */
2539    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2540            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2541            | SYSTEM_UI_FLAG_FULLSCREEN;
2542
2543    /**
2544     * Flags that can impact the layout in relation to system UI.
2545     */
2546    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2547            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2548            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2549
2550    /**
2551     * Find views that render the specified text.
2552     *
2553     * @see #findViewsWithText(ArrayList, CharSequence, int)
2554     */
2555    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2556
2557    /**
2558     * Find find views that contain the specified content description.
2559     *
2560     * @see #findViewsWithText(ArrayList, CharSequence, int)
2561     */
2562    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2563
2564    /**
2565     * Find views that contain {@link AccessibilityNodeProvider}. Such
2566     * a View is a root of virtual view hierarchy and may contain the searched
2567     * text. If this flag is set Views with providers are automatically
2568     * added and it is a responsibility of the client to call the APIs of
2569     * the provider to determine whether the virtual tree rooted at this View
2570     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2571     * represeting the virtual views with this text.
2572     *
2573     * @see #findViewsWithText(ArrayList, CharSequence, int)
2574     *
2575     * @hide
2576     */
2577    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2578
2579    /**
2580     * The undefined cursor position.
2581     *
2582     * @hide
2583     */
2584    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2585
2586    /**
2587     * Indicates that the screen has changed state and is now off.
2588     *
2589     * @see #onScreenStateChanged(int)
2590     */
2591    public static final int SCREEN_STATE_OFF = 0x0;
2592
2593    /**
2594     * Indicates that the screen has changed state and is now on.
2595     *
2596     * @see #onScreenStateChanged(int)
2597     */
2598    public static final int SCREEN_STATE_ON = 0x1;
2599
2600    /**
2601     * Controls the over-scroll mode for this view.
2602     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2603     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2604     * and {@link #OVER_SCROLL_NEVER}.
2605     */
2606    private int mOverScrollMode;
2607
2608    /**
2609     * The parent this view is attached to.
2610     * {@hide}
2611     *
2612     * @see #getParent()
2613     */
2614    protected ViewParent mParent;
2615
2616    /**
2617     * {@hide}
2618     */
2619    AttachInfo mAttachInfo;
2620
2621    /**
2622     * {@hide}
2623     */
2624    @ViewDebug.ExportedProperty(flagMapping = {
2625        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2626                name = "FORCE_LAYOUT"),
2627        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2628                name = "LAYOUT_REQUIRED"),
2629        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2630            name = "DRAWING_CACHE_INVALID", outputIf = false),
2631        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2632        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2633        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2634        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2635    })
2636    int mPrivateFlags;
2637    int mPrivateFlags2;
2638    int mPrivateFlags3;
2639
2640    /**
2641     * This view's request for the visibility of the status bar.
2642     * @hide
2643     */
2644    @ViewDebug.ExportedProperty(flagMapping = {
2645        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2646                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2647                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2648        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2649                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2650                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2651        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2652                                equals = SYSTEM_UI_FLAG_VISIBLE,
2653                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2654    })
2655    int mSystemUiVisibility;
2656
2657    /**
2658     * Reference count for transient state.
2659     * @see #setHasTransientState(boolean)
2660     */
2661    int mTransientStateCount = 0;
2662
2663    /**
2664     * Count of how many windows this view has been attached to.
2665     */
2666    int mWindowAttachCount;
2667
2668    /**
2669     * The layout parameters associated with this view and used by the parent
2670     * {@link android.view.ViewGroup} to determine how this view should be
2671     * laid out.
2672     * {@hide}
2673     */
2674    protected ViewGroup.LayoutParams mLayoutParams;
2675
2676    /**
2677     * The view flags hold various views states.
2678     * {@hide}
2679     */
2680    @ViewDebug.ExportedProperty
2681    int mViewFlags;
2682
2683    static class TransformationInfo {
2684        /**
2685         * The transform matrix for the View. This transform is calculated internally
2686         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2687         * is used by default. Do *not* use this variable directly; instead call
2688         * getMatrix(), which will automatically recalculate the matrix if necessary
2689         * to get the correct matrix based on the latest rotation and scale properties.
2690         */
2691        private final Matrix mMatrix = new Matrix();
2692
2693        /**
2694         * The transform matrix for the View. This transform is calculated internally
2695         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2696         * is used by default. Do *not* use this variable directly; instead call
2697         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2698         * to get the correct matrix based on the latest rotation and scale properties.
2699         */
2700        private Matrix mInverseMatrix;
2701
2702        /**
2703         * An internal variable that tracks whether we need to recalculate the
2704         * transform matrix, based on whether the rotation or scaleX/Y properties
2705         * have changed since the matrix was last calculated.
2706         */
2707        boolean mMatrixDirty = false;
2708
2709        /**
2710         * An internal variable that tracks whether we need to recalculate the
2711         * transform matrix, based on whether the rotation or scaleX/Y properties
2712         * have changed since the matrix was last calculated.
2713         */
2714        private boolean mInverseMatrixDirty = true;
2715
2716        /**
2717         * A variable that tracks whether we need to recalculate the
2718         * transform matrix, based on whether the rotation or scaleX/Y properties
2719         * have changed since the matrix was last calculated. This variable
2720         * is only valid after a call to updateMatrix() or to a function that
2721         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2722         */
2723        private boolean mMatrixIsIdentity = true;
2724
2725        /**
2726         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2727         */
2728        private Camera mCamera = null;
2729
2730        /**
2731         * This matrix is used when computing the matrix for 3D rotations.
2732         */
2733        private Matrix matrix3D = null;
2734
2735        /**
2736         * These prev values are used to recalculate a centered pivot point when necessary. The
2737         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2738         * set), so thes values are only used then as well.
2739         */
2740        private int mPrevWidth = -1;
2741        private int mPrevHeight = -1;
2742
2743        /**
2744         * The degrees rotation around the vertical axis through the pivot point.
2745         */
2746        @ViewDebug.ExportedProperty
2747        float mRotationY = 0f;
2748
2749        /**
2750         * The degrees rotation around the horizontal axis through the pivot point.
2751         */
2752        @ViewDebug.ExportedProperty
2753        float mRotationX = 0f;
2754
2755        /**
2756         * The degrees rotation around the pivot point.
2757         */
2758        @ViewDebug.ExportedProperty
2759        float mRotation = 0f;
2760
2761        /**
2762         * The amount of translation of the object away from its left property (post-layout).
2763         */
2764        @ViewDebug.ExportedProperty
2765        float mTranslationX = 0f;
2766
2767        /**
2768         * The amount of translation of the object away from its top property (post-layout).
2769         */
2770        @ViewDebug.ExportedProperty
2771        float mTranslationY = 0f;
2772
2773        /**
2774         * The amount of scale in the x direction around the pivot point. A
2775         * value of 1 means no scaling is applied.
2776         */
2777        @ViewDebug.ExportedProperty
2778        float mScaleX = 1f;
2779
2780        /**
2781         * The amount of scale in the y direction around the pivot point. A
2782         * value of 1 means no scaling is applied.
2783         */
2784        @ViewDebug.ExportedProperty
2785        float mScaleY = 1f;
2786
2787        /**
2788         * The x location of the point around which the view is rotated and scaled.
2789         */
2790        @ViewDebug.ExportedProperty
2791        float mPivotX = 0f;
2792
2793        /**
2794         * The y location of the point around which the view is rotated and scaled.
2795         */
2796        @ViewDebug.ExportedProperty
2797        float mPivotY = 0f;
2798
2799        /**
2800         * The opacity of the View. This is a value from 0 to 1, where 0 means
2801         * completely transparent and 1 means completely opaque.
2802         */
2803        @ViewDebug.ExportedProperty
2804        float mAlpha = 1f;
2805    }
2806
2807    TransformationInfo mTransformationInfo;
2808
2809    /**
2810     * Current clip bounds. to which all drawing of this view are constrained.
2811     */
2812    private Rect mClipBounds = null;
2813
2814    private boolean mLastIsOpaque;
2815
2816    /**
2817     * Convenience value to check for float values that are close enough to zero to be considered
2818     * zero.
2819     */
2820    private static final float NONZERO_EPSILON = .001f;
2821
2822    /**
2823     * The distance in pixels from the left edge of this view's parent
2824     * to the left edge of this view.
2825     * {@hide}
2826     */
2827    @ViewDebug.ExportedProperty(category = "layout")
2828    protected int mLeft;
2829    /**
2830     * The distance in pixels from the left edge of this view's parent
2831     * to the right edge of this view.
2832     * {@hide}
2833     */
2834    @ViewDebug.ExportedProperty(category = "layout")
2835    protected int mRight;
2836    /**
2837     * The distance in pixels from the top edge of this view's parent
2838     * to the top edge of this view.
2839     * {@hide}
2840     */
2841    @ViewDebug.ExportedProperty(category = "layout")
2842    protected int mTop;
2843    /**
2844     * The distance in pixels from the top edge of this view's parent
2845     * to the bottom edge of this view.
2846     * {@hide}
2847     */
2848    @ViewDebug.ExportedProperty(category = "layout")
2849    protected int mBottom;
2850
2851    /**
2852     * The offset, in pixels, by which the content of this view is scrolled
2853     * horizontally.
2854     * {@hide}
2855     */
2856    @ViewDebug.ExportedProperty(category = "scrolling")
2857    protected int mScrollX;
2858    /**
2859     * The offset, in pixels, by which the content of this view is scrolled
2860     * vertically.
2861     * {@hide}
2862     */
2863    @ViewDebug.ExportedProperty(category = "scrolling")
2864    protected int mScrollY;
2865
2866    /**
2867     * The left padding in pixels, that is the distance in pixels between the
2868     * left edge of this view and the left edge of its content.
2869     * {@hide}
2870     */
2871    @ViewDebug.ExportedProperty(category = "padding")
2872    protected int mPaddingLeft = 0;
2873    /**
2874     * The right padding in pixels, that is the distance in pixels between the
2875     * right edge of this view and the right edge of its content.
2876     * {@hide}
2877     */
2878    @ViewDebug.ExportedProperty(category = "padding")
2879    protected int mPaddingRight = 0;
2880    /**
2881     * The top padding in pixels, that is the distance in pixels between the
2882     * top edge of this view and the top edge of its content.
2883     * {@hide}
2884     */
2885    @ViewDebug.ExportedProperty(category = "padding")
2886    protected int mPaddingTop;
2887    /**
2888     * The bottom padding in pixels, that is the distance in pixels between the
2889     * bottom edge of this view and the bottom edge of its content.
2890     * {@hide}
2891     */
2892    @ViewDebug.ExportedProperty(category = "padding")
2893    protected int mPaddingBottom;
2894
2895    /**
2896     * The layout insets in pixels, that is the distance in pixels between the
2897     * visible edges of this view its bounds.
2898     */
2899    private Insets mLayoutInsets;
2900
2901    /**
2902     * Briefly describes the view and is primarily used for accessibility support.
2903     */
2904    private CharSequence mContentDescription;
2905
2906    /**
2907     * Specifies the id of a view for which this view serves as a label for
2908     * accessibility purposes.
2909     */
2910    private int mLabelForId = View.NO_ID;
2911
2912    /**
2913     * Predicate for matching labeled view id with its label for
2914     * accessibility purposes.
2915     */
2916    private MatchLabelForPredicate mMatchLabelForPredicate;
2917
2918    /**
2919     * Predicate for matching a view by its id.
2920     */
2921    private MatchIdPredicate mMatchIdPredicate;
2922
2923    /**
2924     * Cache the paddingRight set by the user to append to the scrollbar's size.
2925     *
2926     * @hide
2927     */
2928    @ViewDebug.ExportedProperty(category = "padding")
2929    protected int mUserPaddingRight;
2930
2931    /**
2932     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2933     *
2934     * @hide
2935     */
2936    @ViewDebug.ExportedProperty(category = "padding")
2937    protected int mUserPaddingBottom;
2938
2939    /**
2940     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2941     *
2942     * @hide
2943     */
2944    @ViewDebug.ExportedProperty(category = "padding")
2945    protected int mUserPaddingLeft;
2946
2947    /**
2948     * Cache the paddingStart set by the user to append to the scrollbar's size.
2949     *
2950     */
2951    @ViewDebug.ExportedProperty(category = "padding")
2952    int mUserPaddingStart;
2953
2954    /**
2955     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2956     *
2957     */
2958    @ViewDebug.ExportedProperty(category = "padding")
2959    int mUserPaddingEnd;
2960
2961    /**
2962     * Cache initial left padding.
2963     *
2964     * @hide
2965     */
2966    int mUserPaddingLeftInitial;
2967
2968    /**
2969     * Cache initial right padding.
2970     *
2971     * @hide
2972     */
2973    int mUserPaddingRightInitial;
2974
2975    /**
2976     * Default undefined padding
2977     */
2978    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2979
2980    /**
2981     * @hide
2982     */
2983    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2984    /**
2985     * @hide
2986     */
2987    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2988
2989    private LongSparseLongArray mMeasureCache;
2990
2991    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2992    private Drawable mBackground;
2993
2994    private int mBackgroundResource;
2995    private boolean mBackgroundSizeChanged;
2996
2997    static class ListenerInfo {
2998        /**
2999         * Listener used to dispatch focus change events.
3000         * This field should be made private, so it is hidden from the SDK.
3001         * {@hide}
3002         */
3003        protected OnFocusChangeListener mOnFocusChangeListener;
3004
3005        /**
3006         * Listeners for layout change events.
3007         */
3008        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3009
3010        /**
3011         * Listeners for attach events.
3012         */
3013        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3014
3015        /**
3016         * Listener used to dispatch click events.
3017         * This field should be made private, so it is hidden from the SDK.
3018         * {@hide}
3019         */
3020        public OnClickListener mOnClickListener;
3021
3022        /**
3023         * Listener used to dispatch long click events.
3024         * This field should be made private, so it is hidden from the SDK.
3025         * {@hide}
3026         */
3027        protected OnLongClickListener mOnLongClickListener;
3028
3029        /**
3030         * Listener used to build the context menu.
3031         * This field should be made private, so it is hidden from the SDK.
3032         * {@hide}
3033         */
3034        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3035
3036        private OnKeyListener mOnKeyListener;
3037
3038        private OnTouchListener mOnTouchListener;
3039
3040        private OnHoverListener mOnHoverListener;
3041
3042        private OnGenericMotionListener mOnGenericMotionListener;
3043
3044        private OnDragListener mOnDragListener;
3045
3046        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3047    }
3048
3049    ListenerInfo mListenerInfo;
3050
3051    /**
3052     * The application environment this view lives in.
3053     * This field should be made private, so it is hidden from the SDK.
3054     * {@hide}
3055     */
3056    protected Context mContext;
3057
3058    private final Resources mResources;
3059
3060    private ScrollabilityCache mScrollCache;
3061
3062    private int[] mDrawableState = null;
3063
3064    /**
3065     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3066     * the user may specify which view to go to next.
3067     */
3068    private int mNextFocusLeftId = View.NO_ID;
3069
3070    /**
3071     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3072     * the user may specify which view to go to next.
3073     */
3074    private int mNextFocusRightId = View.NO_ID;
3075
3076    /**
3077     * When this view has focus and the next focus is {@link #FOCUS_UP},
3078     * the user may specify which view to go to next.
3079     */
3080    private int mNextFocusUpId = View.NO_ID;
3081
3082    /**
3083     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3084     * the user may specify which view to go to next.
3085     */
3086    private int mNextFocusDownId = View.NO_ID;
3087
3088    /**
3089     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3090     * the user may specify which view to go to next.
3091     */
3092    int mNextFocusForwardId = View.NO_ID;
3093
3094    private CheckForLongPress mPendingCheckForLongPress;
3095    private CheckForTap mPendingCheckForTap = null;
3096    private PerformClick mPerformClick;
3097    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3098
3099    private UnsetPressedState mUnsetPressedState;
3100
3101    /**
3102     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3103     * up event while a long press is invoked as soon as the long press duration is reached, so
3104     * a long press could be performed before the tap is checked, in which case the tap's action
3105     * should not be invoked.
3106     */
3107    private boolean mHasPerformedLongPress;
3108
3109    /**
3110     * The minimum height of the view. We'll try our best to have the height
3111     * of this view to at least this amount.
3112     */
3113    @ViewDebug.ExportedProperty(category = "measurement")
3114    private int mMinHeight;
3115
3116    /**
3117     * The minimum width of the view. We'll try our best to have the width
3118     * of this view to at least this amount.
3119     */
3120    @ViewDebug.ExportedProperty(category = "measurement")
3121    private int mMinWidth;
3122
3123    /**
3124     * The delegate to handle touch events that are physically in this view
3125     * but should be handled by another view.
3126     */
3127    private TouchDelegate mTouchDelegate = null;
3128
3129    /**
3130     * Solid color to use as a background when creating the drawing cache. Enables
3131     * the cache to use 16 bit bitmaps instead of 32 bit.
3132     */
3133    private int mDrawingCacheBackgroundColor = 0;
3134
3135    /**
3136     * Special tree observer used when mAttachInfo is null.
3137     */
3138    private ViewTreeObserver mFloatingTreeObserver;
3139
3140    /**
3141     * Cache the touch slop from the context that created the view.
3142     */
3143    private int mTouchSlop;
3144
3145    /**
3146     * Object that handles automatic animation of view properties.
3147     */
3148    private ViewPropertyAnimator mAnimator = null;
3149
3150    /**
3151     * Flag indicating that a drag can cross window boundaries.  When
3152     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3153     * with this flag set, all visible applications will be able to participate
3154     * in the drag operation and receive the dragged content.
3155     *
3156     * @hide
3157     */
3158    public static final int DRAG_FLAG_GLOBAL = 1;
3159
3160    /**
3161     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3162     */
3163    private float mVerticalScrollFactor;
3164
3165    /**
3166     * Position of the vertical scroll bar.
3167     */
3168    private int mVerticalScrollbarPosition;
3169
3170    /**
3171     * Position the scroll bar at the default position as determined by the system.
3172     */
3173    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3174
3175    /**
3176     * Position the scroll bar along the left edge.
3177     */
3178    public static final int SCROLLBAR_POSITION_LEFT = 1;
3179
3180    /**
3181     * Position the scroll bar along the right edge.
3182     */
3183    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3184
3185    /**
3186     * Indicates that the view does not have a layer.
3187     *
3188     * @see #getLayerType()
3189     * @see #setLayerType(int, android.graphics.Paint)
3190     * @see #LAYER_TYPE_SOFTWARE
3191     * @see #LAYER_TYPE_HARDWARE
3192     */
3193    public static final int LAYER_TYPE_NONE = 0;
3194
3195    /**
3196     * <p>Indicates that the view has a software layer. A software layer is backed
3197     * by a bitmap and causes the view to be rendered using Android's software
3198     * rendering pipeline, even if hardware acceleration is enabled.</p>
3199     *
3200     * <p>Software layers have various usages:</p>
3201     * <p>When the application is not using hardware acceleration, a software layer
3202     * is useful to apply a specific color filter and/or blending mode and/or
3203     * translucency to a view and all its children.</p>
3204     * <p>When the application is using hardware acceleration, a software layer
3205     * is useful to render drawing primitives not supported by the hardware
3206     * accelerated pipeline. It can also be used to cache a complex view tree
3207     * into a texture and reduce the complexity of drawing operations. For instance,
3208     * when animating a complex view tree with a translation, a software layer can
3209     * be used to render the view tree only once.</p>
3210     * <p>Software layers should be avoided when the affected view tree updates
3211     * often. Every update will require to re-render the software layer, which can
3212     * potentially be slow (particularly when hardware acceleration is turned on
3213     * since the layer will have to be uploaded into a hardware texture after every
3214     * update.)</p>
3215     *
3216     * @see #getLayerType()
3217     * @see #setLayerType(int, android.graphics.Paint)
3218     * @see #LAYER_TYPE_NONE
3219     * @see #LAYER_TYPE_HARDWARE
3220     */
3221    public static final int LAYER_TYPE_SOFTWARE = 1;
3222
3223    /**
3224     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3225     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3226     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3227     * rendering pipeline, but only if hardware acceleration is turned on for the
3228     * view hierarchy. When hardware acceleration is turned off, hardware layers
3229     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3230     *
3231     * <p>A hardware layer is useful to apply a specific color filter and/or
3232     * blending mode and/or translucency to a view and all its children.</p>
3233     * <p>A hardware layer can be used to cache a complex view tree into a
3234     * texture and reduce the complexity of drawing operations. For instance,
3235     * when animating a complex view tree with a translation, a hardware layer can
3236     * be used to render the view tree only once.</p>
3237     * <p>A hardware layer can also be used to increase the rendering quality when
3238     * rotation transformations are applied on a view. It can also be used to
3239     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3240     *
3241     * @see #getLayerType()
3242     * @see #setLayerType(int, android.graphics.Paint)
3243     * @see #LAYER_TYPE_NONE
3244     * @see #LAYER_TYPE_SOFTWARE
3245     */
3246    public static final int LAYER_TYPE_HARDWARE = 2;
3247
3248    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3249            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3250            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3251            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3252    })
3253    int mLayerType = LAYER_TYPE_NONE;
3254    Paint mLayerPaint;
3255    Rect mLocalDirtyRect;
3256    private HardwareLayer mHardwareLayer;
3257
3258    /**
3259     * Set to true when drawing cache is enabled and cannot be created.
3260     *
3261     * @hide
3262     */
3263    public boolean mCachingFailed;
3264    private Bitmap mDrawingCache;
3265    private Bitmap mUnscaledDrawingCache;
3266
3267    DisplayList mDisplayList;
3268
3269    /**
3270     * Set to true when the view is sending hover accessibility events because it
3271     * is the innermost hovered view.
3272     */
3273    private boolean mSendingHoverAccessibilityEvents;
3274
3275    /**
3276     * Delegate for injecting accessibility functionality.
3277     */
3278    AccessibilityDelegate mAccessibilityDelegate;
3279
3280    /**
3281     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3282     * and add/remove objects to/from the overlay directly through the Overlay methods.
3283     */
3284    ViewOverlay mOverlay;
3285
3286    /**
3287     * Consistency verifier for debugging purposes.
3288     * @hide
3289     */
3290    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3291            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3292                    new InputEventConsistencyVerifier(this, 0) : null;
3293
3294    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3295
3296    /**
3297     * Simple constructor to use when creating a view from code.
3298     *
3299     * @param context The Context the view is running in, through which it can
3300     *        access the current theme, resources, etc.
3301     */
3302    public View(Context context) {
3303        mContext = context;
3304        mResources = context != null ? context.getResources() : null;
3305        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3306        // Set some flags defaults
3307        mPrivateFlags2 =
3308                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3309                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3310                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3311                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3312                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3313                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3314        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3315        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3316        mUserPaddingStart = UNDEFINED_PADDING;
3317        mUserPaddingEnd = UNDEFINED_PADDING;
3318
3319        if (!sUseBrokenMakeMeasureSpec && context != null &&
3320                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3321            // Older apps may need this compatibility hack for measurement.
3322            sUseBrokenMakeMeasureSpec = true;
3323        }
3324    }
3325
3326    /**
3327     * Constructor that is called when inflating a view from XML. This is called
3328     * when a view is being constructed from an XML file, supplying attributes
3329     * that were specified in the XML file. This version uses a default style of
3330     * 0, so the only attribute values applied are those in the Context's Theme
3331     * and the given AttributeSet.
3332     *
3333     * <p>
3334     * The method onFinishInflate() will be called after all children have been
3335     * added.
3336     *
3337     * @param context The Context the view is running in, through which it can
3338     *        access the current theme, resources, etc.
3339     * @param attrs The attributes of the XML tag that is inflating the view.
3340     * @see #View(Context, AttributeSet, int)
3341     */
3342    public View(Context context, AttributeSet attrs) {
3343        this(context, attrs, 0);
3344    }
3345
3346    /**
3347     * Perform inflation from XML and apply a class-specific base style. This
3348     * constructor of View allows subclasses to use their own base style when
3349     * they are inflating. For example, a Button class's constructor would call
3350     * this version of the super class constructor and supply
3351     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3352     * the theme's button style to modify all of the base view attributes (in
3353     * particular its background) as well as the Button class's attributes.
3354     *
3355     * @param context The Context the view is running in, through which it can
3356     *        access the current theme, resources, etc.
3357     * @param attrs The attributes of the XML tag that is inflating the view.
3358     * @param defStyle The default style to apply to this view. If 0, no style
3359     *        will be applied (beyond what is included in the theme). This may
3360     *        either be an attribute resource, whose value will be retrieved
3361     *        from the current theme, or an explicit style resource.
3362     * @see #View(Context, AttributeSet)
3363     */
3364    public View(Context context, AttributeSet attrs, int defStyle) {
3365        this(context);
3366
3367        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3368                defStyle, 0);
3369
3370        Drawable background = null;
3371
3372        int leftPadding = -1;
3373        int topPadding = -1;
3374        int rightPadding = -1;
3375        int bottomPadding = -1;
3376        int startPadding = UNDEFINED_PADDING;
3377        int endPadding = UNDEFINED_PADDING;
3378
3379        int padding = -1;
3380
3381        int viewFlagValues = 0;
3382        int viewFlagMasks = 0;
3383
3384        boolean setScrollContainer = false;
3385
3386        int x = 0;
3387        int y = 0;
3388
3389        float tx = 0;
3390        float ty = 0;
3391        float rotation = 0;
3392        float rotationX = 0;
3393        float rotationY = 0;
3394        float sx = 1f;
3395        float sy = 1f;
3396        boolean transformSet = false;
3397
3398        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3399        int overScrollMode = mOverScrollMode;
3400        boolean initializeScrollbars = false;
3401
3402        boolean leftPaddingDefined = false;
3403        boolean rightPaddingDefined = false;
3404        boolean startPaddingDefined = false;
3405        boolean endPaddingDefined = false;
3406
3407        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3408
3409        final int N = a.getIndexCount();
3410        for (int i = 0; i < N; i++) {
3411            int attr = a.getIndex(i);
3412            switch (attr) {
3413                case com.android.internal.R.styleable.View_background:
3414                    background = a.getDrawable(attr);
3415                    break;
3416                case com.android.internal.R.styleable.View_padding:
3417                    padding = a.getDimensionPixelSize(attr, -1);
3418                    mUserPaddingLeftInitial = padding;
3419                    mUserPaddingRightInitial = padding;
3420                    leftPaddingDefined = true;
3421                    rightPaddingDefined = true;
3422                    break;
3423                 case com.android.internal.R.styleable.View_paddingLeft:
3424                    leftPadding = a.getDimensionPixelSize(attr, -1);
3425                    mUserPaddingLeftInitial = leftPadding;
3426                    leftPaddingDefined = true;
3427                    break;
3428                case com.android.internal.R.styleable.View_paddingTop:
3429                    topPadding = a.getDimensionPixelSize(attr, -1);
3430                    break;
3431                case com.android.internal.R.styleable.View_paddingRight:
3432                    rightPadding = a.getDimensionPixelSize(attr, -1);
3433                    mUserPaddingRightInitial = rightPadding;
3434                    rightPaddingDefined = true;
3435                    break;
3436                case com.android.internal.R.styleable.View_paddingBottom:
3437                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3438                    break;
3439                case com.android.internal.R.styleable.View_paddingStart:
3440                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3441                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3442                    break;
3443                case com.android.internal.R.styleable.View_paddingEnd:
3444                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3445                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3446                    break;
3447                case com.android.internal.R.styleable.View_scrollX:
3448                    x = a.getDimensionPixelOffset(attr, 0);
3449                    break;
3450                case com.android.internal.R.styleable.View_scrollY:
3451                    y = a.getDimensionPixelOffset(attr, 0);
3452                    break;
3453                case com.android.internal.R.styleable.View_alpha:
3454                    setAlpha(a.getFloat(attr, 1f));
3455                    break;
3456                case com.android.internal.R.styleable.View_transformPivotX:
3457                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3458                    break;
3459                case com.android.internal.R.styleable.View_transformPivotY:
3460                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3461                    break;
3462                case com.android.internal.R.styleable.View_translationX:
3463                    tx = a.getDimensionPixelOffset(attr, 0);
3464                    transformSet = true;
3465                    break;
3466                case com.android.internal.R.styleable.View_translationY:
3467                    ty = a.getDimensionPixelOffset(attr, 0);
3468                    transformSet = true;
3469                    break;
3470                case com.android.internal.R.styleable.View_rotation:
3471                    rotation = a.getFloat(attr, 0);
3472                    transformSet = true;
3473                    break;
3474                case com.android.internal.R.styleable.View_rotationX:
3475                    rotationX = a.getFloat(attr, 0);
3476                    transformSet = true;
3477                    break;
3478                case com.android.internal.R.styleable.View_rotationY:
3479                    rotationY = a.getFloat(attr, 0);
3480                    transformSet = true;
3481                    break;
3482                case com.android.internal.R.styleable.View_scaleX:
3483                    sx = a.getFloat(attr, 1f);
3484                    transformSet = true;
3485                    break;
3486                case com.android.internal.R.styleable.View_scaleY:
3487                    sy = a.getFloat(attr, 1f);
3488                    transformSet = true;
3489                    break;
3490                case com.android.internal.R.styleable.View_id:
3491                    mID = a.getResourceId(attr, NO_ID);
3492                    break;
3493                case com.android.internal.R.styleable.View_tag:
3494                    mTag = a.getText(attr);
3495                    break;
3496                case com.android.internal.R.styleable.View_fitsSystemWindows:
3497                    if (a.getBoolean(attr, false)) {
3498                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3499                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3500                    }
3501                    break;
3502                case com.android.internal.R.styleable.View_focusable:
3503                    if (a.getBoolean(attr, false)) {
3504                        viewFlagValues |= FOCUSABLE;
3505                        viewFlagMasks |= FOCUSABLE_MASK;
3506                    }
3507                    break;
3508                case com.android.internal.R.styleable.View_focusableInTouchMode:
3509                    if (a.getBoolean(attr, false)) {
3510                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3511                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3512                    }
3513                    break;
3514                case com.android.internal.R.styleable.View_clickable:
3515                    if (a.getBoolean(attr, false)) {
3516                        viewFlagValues |= CLICKABLE;
3517                        viewFlagMasks |= CLICKABLE;
3518                    }
3519                    break;
3520                case com.android.internal.R.styleable.View_longClickable:
3521                    if (a.getBoolean(attr, false)) {
3522                        viewFlagValues |= LONG_CLICKABLE;
3523                        viewFlagMasks |= LONG_CLICKABLE;
3524                    }
3525                    break;
3526                case com.android.internal.R.styleable.View_saveEnabled:
3527                    if (!a.getBoolean(attr, true)) {
3528                        viewFlagValues |= SAVE_DISABLED;
3529                        viewFlagMasks |= SAVE_DISABLED_MASK;
3530                    }
3531                    break;
3532                case com.android.internal.R.styleable.View_duplicateParentState:
3533                    if (a.getBoolean(attr, false)) {
3534                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3535                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3536                    }
3537                    break;
3538                case com.android.internal.R.styleable.View_visibility:
3539                    final int visibility = a.getInt(attr, 0);
3540                    if (visibility != 0) {
3541                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3542                        viewFlagMasks |= VISIBILITY_MASK;
3543                    }
3544                    break;
3545                case com.android.internal.R.styleable.View_layoutDirection:
3546                    // Clear any layout direction flags (included resolved bits) already set
3547                    mPrivateFlags2 &=
3548                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3549                    // Set the layout direction flags depending on the value of the attribute
3550                    final int layoutDirection = a.getInt(attr, -1);
3551                    final int value = (layoutDirection != -1) ?
3552                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3553                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3554                    break;
3555                case com.android.internal.R.styleable.View_drawingCacheQuality:
3556                    final int cacheQuality = a.getInt(attr, 0);
3557                    if (cacheQuality != 0) {
3558                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3559                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3560                    }
3561                    break;
3562                case com.android.internal.R.styleable.View_contentDescription:
3563                    setContentDescription(a.getString(attr));
3564                    break;
3565                case com.android.internal.R.styleable.View_labelFor:
3566                    setLabelFor(a.getResourceId(attr, NO_ID));
3567                    break;
3568                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3569                    if (!a.getBoolean(attr, true)) {
3570                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3571                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3572                    }
3573                    break;
3574                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3575                    if (!a.getBoolean(attr, true)) {
3576                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3577                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3578                    }
3579                    break;
3580                case R.styleable.View_scrollbars:
3581                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3582                    if (scrollbars != SCROLLBARS_NONE) {
3583                        viewFlagValues |= scrollbars;
3584                        viewFlagMasks |= SCROLLBARS_MASK;
3585                        initializeScrollbars = true;
3586                    }
3587                    break;
3588                //noinspection deprecation
3589                case R.styleable.View_fadingEdge:
3590                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3591                        // Ignore the attribute starting with ICS
3592                        break;
3593                    }
3594                    // With builds < ICS, fall through and apply fading edges
3595                case R.styleable.View_requiresFadingEdge:
3596                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3597                    if (fadingEdge != FADING_EDGE_NONE) {
3598                        viewFlagValues |= fadingEdge;
3599                        viewFlagMasks |= FADING_EDGE_MASK;
3600                        initializeFadingEdge(a);
3601                    }
3602                    break;
3603                case R.styleable.View_scrollbarStyle:
3604                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3605                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3606                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3607                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3608                    }
3609                    break;
3610                case R.styleable.View_isScrollContainer:
3611                    setScrollContainer = true;
3612                    if (a.getBoolean(attr, false)) {
3613                        setScrollContainer(true);
3614                    }
3615                    break;
3616                case com.android.internal.R.styleable.View_keepScreenOn:
3617                    if (a.getBoolean(attr, false)) {
3618                        viewFlagValues |= KEEP_SCREEN_ON;
3619                        viewFlagMasks |= KEEP_SCREEN_ON;
3620                    }
3621                    break;
3622                case R.styleable.View_filterTouchesWhenObscured:
3623                    if (a.getBoolean(attr, false)) {
3624                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3625                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3626                    }
3627                    break;
3628                case R.styleable.View_nextFocusLeft:
3629                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3630                    break;
3631                case R.styleable.View_nextFocusRight:
3632                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3633                    break;
3634                case R.styleable.View_nextFocusUp:
3635                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3636                    break;
3637                case R.styleable.View_nextFocusDown:
3638                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3639                    break;
3640                case R.styleable.View_nextFocusForward:
3641                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3642                    break;
3643                case R.styleable.View_minWidth:
3644                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3645                    break;
3646                case R.styleable.View_minHeight:
3647                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3648                    break;
3649                case R.styleable.View_onClick:
3650                    if (context.isRestricted()) {
3651                        throw new IllegalStateException("The android:onClick attribute cannot "
3652                                + "be used within a restricted context");
3653                    }
3654
3655                    final String handlerName = a.getString(attr);
3656                    if (handlerName != null) {
3657                        setOnClickListener(new OnClickListener() {
3658                            private Method mHandler;
3659
3660                            public void onClick(View v) {
3661                                if (mHandler == null) {
3662                                    try {
3663                                        mHandler = getContext().getClass().getMethod(handlerName,
3664                                                View.class);
3665                                    } catch (NoSuchMethodException e) {
3666                                        int id = getId();
3667                                        String idText = id == NO_ID ? "" : " with id '"
3668                                                + getContext().getResources().getResourceEntryName(
3669                                                    id) + "'";
3670                                        throw new IllegalStateException("Could not find a method " +
3671                                                handlerName + "(View) in the activity "
3672                                                + getContext().getClass() + " for onClick handler"
3673                                                + " on view " + View.this.getClass() + idText, e);
3674                                    }
3675                                }
3676
3677                                try {
3678                                    mHandler.invoke(getContext(), View.this);
3679                                } catch (IllegalAccessException e) {
3680                                    throw new IllegalStateException("Could not execute non "
3681                                            + "public method of the activity", e);
3682                                } catch (InvocationTargetException e) {
3683                                    throw new IllegalStateException("Could not execute "
3684                                            + "method of the activity", e);
3685                                }
3686                            }
3687                        });
3688                    }
3689                    break;
3690                case R.styleable.View_overScrollMode:
3691                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3692                    break;
3693                case R.styleable.View_verticalScrollbarPosition:
3694                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3695                    break;
3696                case R.styleable.View_layerType:
3697                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3698                    break;
3699                case R.styleable.View_textDirection:
3700                    // Clear any text direction flag already set
3701                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3702                    // Set the text direction flags depending on the value of the attribute
3703                    final int textDirection = a.getInt(attr, -1);
3704                    if (textDirection != -1) {
3705                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3706                    }
3707                    break;
3708                case R.styleable.View_textAlignment:
3709                    // Clear any text alignment flag already set
3710                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3711                    // Set the text alignment flag depending on the value of the attribute
3712                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3713                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3714                    break;
3715                case R.styleable.View_importantForAccessibility:
3716                    setImportantForAccessibility(a.getInt(attr,
3717                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3718                    break;
3719            }
3720        }
3721
3722        setOverScrollMode(overScrollMode);
3723
3724        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3725        // the resolved layout direction). Those cached values will be used later during padding
3726        // resolution.
3727        mUserPaddingStart = startPadding;
3728        mUserPaddingEnd = endPadding;
3729
3730        if (background != null) {
3731            setBackground(background);
3732        }
3733
3734        if (padding >= 0) {
3735            leftPadding = padding;
3736            topPadding = padding;
3737            rightPadding = padding;
3738            bottomPadding = padding;
3739            mUserPaddingLeftInitial = padding;
3740            mUserPaddingRightInitial = padding;
3741        }
3742
3743        if (isRtlCompatibilityMode()) {
3744            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3745            // left / right padding are used if defined (meaning here nothing to do). If they are not
3746            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3747            // start / end and resolve them as left / right (layout direction is not taken into account).
3748            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3749            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3750            // defined.
3751            if (!leftPaddingDefined && startPaddingDefined) {
3752                leftPadding = startPadding;
3753            }
3754            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3755            if (!rightPaddingDefined && endPaddingDefined) {
3756                rightPadding = endPadding;
3757            }
3758            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3759        } else {
3760            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3761            // values defined. Otherwise, left /right values are used.
3762            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3763            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3764            // defined.
3765            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3766
3767            if (leftPaddingDefined && !hasRelativePadding) {
3768                mUserPaddingLeftInitial = leftPadding;
3769            }
3770            if (rightPaddingDefined && !hasRelativePadding) {
3771                mUserPaddingRightInitial = rightPadding;
3772            }
3773        }
3774
3775        internalSetPadding(
3776                mUserPaddingLeftInitial,
3777                topPadding >= 0 ? topPadding : mPaddingTop,
3778                mUserPaddingRightInitial,
3779                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3780
3781        if (viewFlagMasks != 0) {
3782            setFlags(viewFlagValues, viewFlagMasks);
3783        }
3784
3785        if (initializeScrollbars) {
3786            initializeScrollbars(a);
3787        }
3788
3789        a.recycle();
3790
3791        // Needs to be called after mViewFlags is set
3792        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3793            recomputePadding();
3794        }
3795
3796        if (x != 0 || y != 0) {
3797            scrollTo(x, y);
3798        }
3799
3800        if (transformSet) {
3801            setTranslationX(tx);
3802            setTranslationY(ty);
3803            setRotation(rotation);
3804            setRotationX(rotationX);
3805            setRotationY(rotationY);
3806            setScaleX(sx);
3807            setScaleY(sy);
3808        }
3809
3810        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3811            setScrollContainer(true);
3812        }
3813
3814        computeOpaqueFlags();
3815    }
3816
3817    /**
3818     * Non-public constructor for use in testing
3819     */
3820    View() {
3821        mResources = null;
3822    }
3823
3824    public String toString() {
3825        StringBuilder out = new StringBuilder(128);
3826        out.append(getClass().getName());
3827        out.append('{');
3828        out.append(Integer.toHexString(System.identityHashCode(this)));
3829        out.append(' ');
3830        switch (mViewFlags&VISIBILITY_MASK) {
3831            case VISIBLE: out.append('V'); break;
3832            case INVISIBLE: out.append('I'); break;
3833            case GONE: out.append('G'); break;
3834            default: out.append('.'); break;
3835        }
3836        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3837        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3838        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3839        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3840        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3841        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3842        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3843        out.append(' ');
3844        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3845        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3846        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3847        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3848            out.append('p');
3849        } else {
3850            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3851        }
3852        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3853        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3854        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3855        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3856        out.append(' ');
3857        out.append(mLeft);
3858        out.append(',');
3859        out.append(mTop);
3860        out.append('-');
3861        out.append(mRight);
3862        out.append(',');
3863        out.append(mBottom);
3864        final int id = getId();
3865        if (id != NO_ID) {
3866            out.append(" #");
3867            out.append(Integer.toHexString(id));
3868            final Resources r = mResources;
3869            if (id != 0 && r != null) {
3870                try {
3871                    String pkgname;
3872                    switch (id&0xff000000) {
3873                        case 0x7f000000:
3874                            pkgname="app";
3875                            break;
3876                        case 0x01000000:
3877                            pkgname="android";
3878                            break;
3879                        default:
3880                            pkgname = r.getResourcePackageName(id);
3881                            break;
3882                    }
3883                    String typename = r.getResourceTypeName(id);
3884                    String entryname = r.getResourceEntryName(id);
3885                    out.append(" ");
3886                    out.append(pkgname);
3887                    out.append(":");
3888                    out.append(typename);
3889                    out.append("/");
3890                    out.append(entryname);
3891                } catch (Resources.NotFoundException e) {
3892                }
3893            }
3894        }
3895        out.append("}");
3896        return out.toString();
3897    }
3898
3899    /**
3900     * <p>
3901     * Initializes the fading edges from a given set of styled attributes. This
3902     * method should be called by subclasses that need fading edges and when an
3903     * instance of these subclasses is created programmatically rather than
3904     * being inflated from XML. This method is automatically called when the XML
3905     * is inflated.
3906     * </p>
3907     *
3908     * @param a the styled attributes set to initialize the fading edges from
3909     */
3910    protected void initializeFadingEdge(TypedArray a) {
3911        initScrollCache();
3912
3913        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3914                R.styleable.View_fadingEdgeLength,
3915                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3916    }
3917
3918    /**
3919     * Returns the size of the vertical faded edges used to indicate that more
3920     * content in this view is visible.
3921     *
3922     * @return The size in pixels of the vertical faded edge or 0 if vertical
3923     *         faded edges are not enabled for this view.
3924     * @attr ref android.R.styleable#View_fadingEdgeLength
3925     */
3926    public int getVerticalFadingEdgeLength() {
3927        if (isVerticalFadingEdgeEnabled()) {
3928            ScrollabilityCache cache = mScrollCache;
3929            if (cache != null) {
3930                return cache.fadingEdgeLength;
3931            }
3932        }
3933        return 0;
3934    }
3935
3936    /**
3937     * Set the size of the faded edge used to indicate that more content in this
3938     * view is available.  Will not change whether the fading edge is enabled; use
3939     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3940     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3941     * for the vertical or horizontal fading edges.
3942     *
3943     * @param length The size in pixels of the faded edge used to indicate that more
3944     *        content in this view is visible.
3945     */
3946    public void setFadingEdgeLength(int length) {
3947        initScrollCache();
3948        mScrollCache.fadingEdgeLength = length;
3949    }
3950
3951    /**
3952     * Returns the size of the horizontal faded edges used to indicate that more
3953     * content in this view is visible.
3954     *
3955     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3956     *         faded edges are not enabled for this view.
3957     * @attr ref android.R.styleable#View_fadingEdgeLength
3958     */
3959    public int getHorizontalFadingEdgeLength() {
3960        if (isHorizontalFadingEdgeEnabled()) {
3961            ScrollabilityCache cache = mScrollCache;
3962            if (cache != null) {
3963                return cache.fadingEdgeLength;
3964            }
3965        }
3966        return 0;
3967    }
3968
3969    /**
3970     * Returns the width of the vertical scrollbar.
3971     *
3972     * @return The width in pixels of the vertical scrollbar or 0 if there
3973     *         is no vertical scrollbar.
3974     */
3975    public int getVerticalScrollbarWidth() {
3976        ScrollabilityCache cache = mScrollCache;
3977        if (cache != null) {
3978            ScrollBarDrawable scrollBar = cache.scrollBar;
3979            if (scrollBar != null) {
3980                int size = scrollBar.getSize(true);
3981                if (size <= 0) {
3982                    size = cache.scrollBarSize;
3983                }
3984                return size;
3985            }
3986            return 0;
3987        }
3988        return 0;
3989    }
3990
3991    /**
3992     * Returns the height of the horizontal scrollbar.
3993     *
3994     * @return The height in pixels of the horizontal scrollbar or 0 if
3995     *         there is no horizontal scrollbar.
3996     */
3997    protected int getHorizontalScrollbarHeight() {
3998        ScrollabilityCache cache = mScrollCache;
3999        if (cache != null) {
4000            ScrollBarDrawable scrollBar = cache.scrollBar;
4001            if (scrollBar != null) {
4002                int size = scrollBar.getSize(false);
4003                if (size <= 0) {
4004                    size = cache.scrollBarSize;
4005                }
4006                return size;
4007            }
4008            return 0;
4009        }
4010        return 0;
4011    }
4012
4013    /**
4014     * <p>
4015     * Initializes the scrollbars from a given set of styled attributes. This
4016     * method should be called by subclasses that need scrollbars and when an
4017     * instance of these subclasses is created programmatically rather than
4018     * being inflated from XML. This method is automatically called when the XML
4019     * is inflated.
4020     * </p>
4021     *
4022     * @param a the styled attributes set to initialize the scrollbars from
4023     */
4024    protected void initializeScrollbars(TypedArray a) {
4025        initScrollCache();
4026
4027        final ScrollabilityCache scrollabilityCache = mScrollCache;
4028
4029        if (scrollabilityCache.scrollBar == null) {
4030            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4031        }
4032
4033        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4034
4035        if (!fadeScrollbars) {
4036            scrollabilityCache.state = ScrollabilityCache.ON;
4037        }
4038        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4039
4040
4041        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4042                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4043                        .getScrollBarFadeDuration());
4044        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4045                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4046                ViewConfiguration.getScrollDefaultDelay());
4047
4048
4049        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4050                com.android.internal.R.styleable.View_scrollbarSize,
4051                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4052
4053        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4054        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4055
4056        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4057        if (thumb != null) {
4058            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4059        }
4060
4061        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4062                false);
4063        if (alwaysDraw) {
4064            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4065        }
4066
4067        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4068        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4069
4070        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4071        if (thumb != null) {
4072            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4073        }
4074
4075        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4076                false);
4077        if (alwaysDraw) {
4078            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4079        }
4080
4081        // Apply layout direction to the new Drawables if needed
4082        final int layoutDirection = getLayoutDirection();
4083        if (track != null) {
4084            track.setLayoutDirection(layoutDirection);
4085        }
4086        if (thumb != null) {
4087            thumb.setLayoutDirection(layoutDirection);
4088        }
4089
4090        // Re-apply user/background padding so that scrollbar(s) get added
4091        resolvePadding();
4092    }
4093
4094    /**
4095     * <p>
4096     * Initalizes the scrollability cache if necessary.
4097     * </p>
4098     */
4099    private void initScrollCache() {
4100        if (mScrollCache == null) {
4101            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4102        }
4103    }
4104
4105    private ScrollabilityCache getScrollCache() {
4106        initScrollCache();
4107        return mScrollCache;
4108    }
4109
4110    /**
4111     * Set the position of the vertical scroll bar. Should be one of
4112     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4113     * {@link #SCROLLBAR_POSITION_RIGHT}.
4114     *
4115     * @param position Where the vertical scroll bar should be positioned.
4116     */
4117    public void setVerticalScrollbarPosition(int position) {
4118        if (mVerticalScrollbarPosition != position) {
4119            mVerticalScrollbarPosition = position;
4120            computeOpaqueFlags();
4121            resolvePadding();
4122        }
4123    }
4124
4125    /**
4126     * @return The position where the vertical scroll bar will show, if applicable.
4127     * @see #setVerticalScrollbarPosition(int)
4128     */
4129    public int getVerticalScrollbarPosition() {
4130        return mVerticalScrollbarPosition;
4131    }
4132
4133    ListenerInfo getListenerInfo() {
4134        if (mListenerInfo != null) {
4135            return mListenerInfo;
4136        }
4137        mListenerInfo = new ListenerInfo();
4138        return mListenerInfo;
4139    }
4140
4141    /**
4142     * Register a callback to be invoked when focus of this view changed.
4143     *
4144     * @param l The callback that will run.
4145     */
4146    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4147        getListenerInfo().mOnFocusChangeListener = l;
4148    }
4149
4150    /**
4151     * Add a listener that will be called when the bounds of the view change due to
4152     * layout processing.
4153     *
4154     * @param listener The listener that will be called when layout bounds change.
4155     */
4156    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4157        ListenerInfo li = getListenerInfo();
4158        if (li.mOnLayoutChangeListeners == null) {
4159            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4160        }
4161        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4162            li.mOnLayoutChangeListeners.add(listener);
4163        }
4164    }
4165
4166    /**
4167     * Remove a listener for layout changes.
4168     *
4169     * @param listener The listener for layout bounds change.
4170     */
4171    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4172        ListenerInfo li = mListenerInfo;
4173        if (li == null || li.mOnLayoutChangeListeners == null) {
4174            return;
4175        }
4176        li.mOnLayoutChangeListeners.remove(listener);
4177    }
4178
4179    /**
4180     * Add a listener for attach state changes.
4181     *
4182     * This listener will be called whenever this view is attached or detached
4183     * from a window. Remove the listener using
4184     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4185     *
4186     * @param listener Listener to attach
4187     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4188     */
4189    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4190        ListenerInfo li = getListenerInfo();
4191        if (li.mOnAttachStateChangeListeners == null) {
4192            li.mOnAttachStateChangeListeners
4193                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4194        }
4195        li.mOnAttachStateChangeListeners.add(listener);
4196    }
4197
4198    /**
4199     * Remove a listener for attach state changes. The listener will receive no further
4200     * notification of window attach/detach events.
4201     *
4202     * @param listener Listener to remove
4203     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4204     */
4205    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4206        ListenerInfo li = mListenerInfo;
4207        if (li == null || li.mOnAttachStateChangeListeners == null) {
4208            return;
4209        }
4210        li.mOnAttachStateChangeListeners.remove(listener);
4211    }
4212
4213    /**
4214     * Returns the focus-change callback registered for this view.
4215     *
4216     * @return The callback, or null if one is not registered.
4217     */
4218    public OnFocusChangeListener getOnFocusChangeListener() {
4219        ListenerInfo li = mListenerInfo;
4220        return li != null ? li.mOnFocusChangeListener : null;
4221    }
4222
4223    /**
4224     * Register a callback to be invoked when this view is clicked. If this view is not
4225     * clickable, it becomes clickable.
4226     *
4227     * @param l The callback that will run
4228     *
4229     * @see #setClickable(boolean)
4230     */
4231    public void setOnClickListener(OnClickListener l) {
4232        if (!isClickable()) {
4233            setClickable(true);
4234        }
4235        getListenerInfo().mOnClickListener = l;
4236    }
4237
4238    /**
4239     * Return whether this view has an attached OnClickListener.  Returns
4240     * true if there is a listener, false if there is none.
4241     */
4242    public boolean hasOnClickListeners() {
4243        ListenerInfo li = mListenerInfo;
4244        return (li != null && li.mOnClickListener != null);
4245    }
4246
4247    /**
4248     * Register a callback to be invoked when this view is clicked and held. If this view is not
4249     * long clickable, it becomes long clickable.
4250     *
4251     * @param l The callback that will run
4252     *
4253     * @see #setLongClickable(boolean)
4254     */
4255    public void setOnLongClickListener(OnLongClickListener l) {
4256        if (!isLongClickable()) {
4257            setLongClickable(true);
4258        }
4259        getListenerInfo().mOnLongClickListener = l;
4260    }
4261
4262    /**
4263     * Register a callback to be invoked when the context menu for this view is
4264     * being built. If this view is not long clickable, it becomes long clickable.
4265     *
4266     * @param l The callback that will run
4267     *
4268     */
4269    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4270        if (!isLongClickable()) {
4271            setLongClickable(true);
4272        }
4273        getListenerInfo().mOnCreateContextMenuListener = l;
4274    }
4275
4276    /**
4277     * Call this view's OnClickListener, if it is defined.  Performs all normal
4278     * actions associated with clicking: reporting accessibility event, playing
4279     * a sound, etc.
4280     *
4281     * @return True there was an assigned OnClickListener that was called, false
4282     *         otherwise is returned.
4283     */
4284    public boolean performClick() {
4285        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4286
4287        ListenerInfo li = mListenerInfo;
4288        if (li != null && li.mOnClickListener != null) {
4289            playSoundEffect(SoundEffectConstants.CLICK);
4290            li.mOnClickListener.onClick(this);
4291            return true;
4292        }
4293
4294        return false;
4295    }
4296
4297    /**
4298     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4299     * this only calls the listener, and does not do any associated clicking
4300     * actions like reporting an accessibility event.
4301     *
4302     * @return True there was an assigned OnClickListener that was called, false
4303     *         otherwise is returned.
4304     */
4305    public boolean callOnClick() {
4306        ListenerInfo li = mListenerInfo;
4307        if (li != null && li.mOnClickListener != null) {
4308            li.mOnClickListener.onClick(this);
4309            return true;
4310        }
4311        return false;
4312    }
4313
4314    /**
4315     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4316     * OnLongClickListener did not consume the event.
4317     *
4318     * @return True if one of the above receivers consumed the event, false otherwise.
4319     */
4320    public boolean performLongClick() {
4321        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4322
4323        boolean handled = false;
4324        ListenerInfo li = mListenerInfo;
4325        if (li != null && li.mOnLongClickListener != null) {
4326            handled = li.mOnLongClickListener.onLongClick(View.this);
4327        }
4328        if (!handled) {
4329            handled = showContextMenu();
4330        }
4331        if (handled) {
4332            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4333        }
4334        return handled;
4335    }
4336
4337    /**
4338     * Performs button-related actions during a touch down event.
4339     *
4340     * @param event The event.
4341     * @return True if the down was consumed.
4342     *
4343     * @hide
4344     */
4345    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4346        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4347            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4348                return true;
4349            }
4350        }
4351        return false;
4352    }
4353
4354    /**
4355     * Bring up the context menu for this view.
4356     *
4357     * @return Whether a context menu was displayed.
4358     */
4359    public boolean showContextMenu() {
4360        return getParent().showContextMenuForChild(this);
4361    }
4362
4363    /**
4364     * Bring up the context menu for this view, referring to the item under the specified point.
4365     *
4366     * @param x The referenced x coordinate.
4367     * @param y The referenced y coordinate.
4368     * @param metaState The keyboard modifiers that were pressed.
4369     * @return Whether a context menu was displayed.
4370     *
4371     * @hide
4372     */
4373    public boolean showContextMenu(float x, float y, int metaState) {
4374        return showContextMenu();
4375    }
4376
4377    /**
4378     * Start an action mode.
4379     *
4380     * @param callback Callback that will control the lifecycle of the action mode
4381     * @return The new action mode if it is started, null otherwise
4382     *
4383     * @see ActionMode
4384     */
4385    public ActionMode startActionMode(ActionMode.Callback callback) {
4386        ViewParent parent = getParent();
4387        if (parent == null) return null;
4388        return parent.startActionModeForChild(this, callback);
4389    }
4390
4391    /**
4392     * Register a callback to be invoked when a hardware key is pressed in this view.
4393     * Key presses in software input methods will generally not trigger the methods of
4394     * this listener.
4395     * @param l the key listener to attach to this view
4396     */
4397    public void setOnKeyListener(OnKeyListener l) {
4398        getListenerInfo().mOnKeyListener = l;
4399    }
4400
4401    /**
4402     * Register a callback to be invoked when a touch event is sent to this view.
4403     * @param l the touch listener to attach to this view
4404     */
4405    public void setOnTouchListener(OnTouchListener l) {
4406        getListenerInfo().mOnTouchListener = l;
4407    }
4408
4409    /**
4410     * Register a callback to be invoked when a generic motion event is sent to this view.
4411     * @param l the generic motion listener to attach to this view
4412     */
4413    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4414        getListenerInfo().mOnGenericMotionListener = l;
4415    }
4416
4417    /**
4418     * Register a callback to be invoked when a hover event is sent to this view.
4419     * @param l the hover listener to attach to this view
4420     */
4421    public void setOnHoverListener(OnHoverListener l) {
4422        getListenerInfo().mOnHoverListener = l;
4423    }
4424
4425    /**
4426     * Register a drag event listener callback object for this View. The parameter is
4427     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4428     * View, the system calls the
4429     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4430     * @param l An implementation of {@link android.view.View.OnDragListener}.
4431     */
4432    public void setOnDragListener(OnDragListener l) {
4433        getListenerInfo().mOnDragListener = l;
4434    }
4435
4436    /**
4437     * Give this view focus. This will cause
4438     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4439     *
4440     * Note: this does not check whether this {@link View} should get focus, it just
4441     * gives it focus no matter what.  It should only be called internally by framework
4442     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4443     *
4444     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4445     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4446     *        focus moved when requestFocus() is called. It may not always
4447     *        apply, in which case use the default View.FOCUS_DOWN.
4448     * @param previouslyFocusedRect The rectangle of the view that had focus
4449     *        prior in this View's coordinate system.
4450     */
4451    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4452        if (DBG) {
4453            System.out.println(this + " requestFocus()");
4454        }
4455
4456        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4457            mPrivateFlags |= PFLAG_FOCUSED;
4458
4459            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4460
4461            if (mParent != null) {
4462                mParent.requestChildFocus(this, this);
4463            }
4464
4465            if (mAttachInfo != null) {
4466                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4467            }
4468
4469            onFocusChanged(true, direction, previouslyFocusedRect);
4470            refreshDrawableState();
4471        }
4472    }
4473
4474    /**
4475     * Request that a rectangle of this view be visible on the screen,
4476     * scrolling if necessary just enough.
4477     *
4478     * <p>A View should call this if it maintains some notion of which part
4479     * of its content is interesting.  For example, a text editing view
4480     * should call this when its cursor moves.
4481     *
4482     * @param rectangle The rectangle.
4483     * @return Whether any parent scrolled.
4484     */
4485    public boolean requestRectangleOnScreen(Rect rectangle) {
4486        return requestRectangleOnScreen(rectangle, false);
4487    }
4488
4489    /**
4490     * Request that a rectangle of this view be visible on the screen,
4491     * scrolling if necessary just enough.
4492     *
4493     * <p>A View should call this if it maintains some notion of which part
4494     * of its content is interesting.  For example, a text editing view
4495     * should call this when its cursor moves.
4496     *
4497     * <p>When <code>immediate</code> is set to true, scrolling will not be
4498     * animated.
4499     *
4500     * @param rectangle The rectangle.
4501     * @param immediate True to forbid animated scrolling, false otherwise
4502     * @return Whether any parent scrolled.
4503     */
4504    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4505        if (mParent == null) {
4506            return false;
4507        }
4508
4509        View child = this;
4510
4511        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4512        position.set(rectangle);
4513
4514        ViewParent parent = mParent;
4515        boolean scrolled = false;
4516        while (parent != null) {
4517            rectangle.set((int) position.left, (int) position.top,
4518                    (int) position.right, (int) position.bottom);
4519
4520            scrolled |= parent.requestChildRectangleOnScreen(child,
4521                    rectangle, immediate);
4522
4523            if (!child.hasIdentityMatrix()) {
4524                child.getMatrix().mapRect(position);
4525            }
4526
4527            position.offset(child.mLeft, child.mTop);
4528
4529            if (!(parent instanceof View)) {
4530                break;
4531            }
4532
4533            View parentView = (View) parent;
4534
4535            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4536
4537            child = parentView;
4538            parent = child.getParent();
4539        }
4540
4541        return scrolled;
4542    }
4543
4544    /**
4545     * Called when this view wants to give up focus. If focus is cleared
4546     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4547     * <p>
4548     * <strong>Note:</strong> When a View clears focus the framework is trying
4549     * to give focus to the first focusable View from the top. Hence, if this
4550     * View is the first from the top that can take focus, then all callbacks
4551     * related to clearing focus will be invoked after wich the framework will
4552     * give focus to this view.
4553     * </p>
4554     */
4555    public void clearFocus() {
4556        if (DBG) {
4557            System.out.println(this + " clearFocus()");
4558        }
4559
4560        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4561            mPrivateFlags &= ~PFLAG_FOCUSED;
4562
4563            if (mParent != null) {
4564                mParent.clearChildFocus(this);
4565            }
4566
4567            onFocusChanged(false, 0, null);
4568
4569            refreshDrawableState();
4570
4571            if (!rootViewRequestFocus()) {
4572                notifyGlobalFocusCleared(this);
4573            }
4574        }
4575    }
4576
4577    void notifyGlobalFocusCleared(View oldFocus) {
4578        if (oldFocus != null && mAttachInfo != null) {
4579            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4580        }
4581    }
4582
4583    boolean rootViewRequestFocus() {
4584        final View root = getRootView();
4585        return root != null && root.requestFocus();
4586    }
4587
4588    /**
4589     * Called internally by the view system when a new view is getting focus.
4590     * This is what clears the old focus.
4591     */
4592    void unFocus() {
4593        if (DBG) {
4594            System.out.println(this + " unFocus()");
4595        }
4596
4597        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4598            mPrivateFlags &= ~PFLAG_FOCUSED;
4599
4600            onFocusChanged(false, 0, null);
4601            refreshDrawableState();
4602        }
4603    }
4604
4605    /**
4606     * Returns true if this view has focus iteself, or is the ancestor of the
4607     * view that has focus.
4608     *
4609     * @return True if this view has or contains focus, false otherwise.
4610     */
4611    @ViewDebug.ExportedProperty(category = "focus")
4612    public boolean hasFocus() {
4613        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4614    }
4615
4616    /**
4617     * Returns true if this view is focusable or if it contains a reachable View
4618     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4619     * is a View whose parents do not block descendants focus.
4620     *
4621     * Only {@link #VISIBLE} views are considered focusable.
4622     *
4623     * @return True if the view is focusable or if the view contains a focusable
4624     *         View, false otherwise.
4625     *
4626     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4627     */
4628    public boolean hasFocusable() {
4629        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4630    }
4631
4632    /**
4633     * Called by the view system when the focus state of this view changes.
4634     * When the focus change event is caused by directional navigation, direction
4635     * and previouslyFocusedRect provide insight into where the focus is coming from.
4636     * When overriding, be sure to call up through to the super class so that
4637     * the standard focus handling will occur.
4638     *
4639     * @param gainFocus True if the View has focus; false otherwise.
4640     * @param direction The direction focus has moved when requestFocus()
4641     *                  is called to give this view focus. Values are
4642     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4643     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4644     *                  It may not always apply, in which case use the default.
4645     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4646     *        system, of the previously focused view.  If applicable, this will be
4647     *        passed in as finer grained information about where the focus is coming
4648     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4649     */
4650    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4651        if (gainFocus) {
4652            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4653        } else {
4654            notifyViewAccessibilityStateChangedIfNeeded();
4655        }
4656
4657        InputMethodManager imm = InputMethodManager.peekInstance();
4658        if (!gainFocus) {
4659            if (isPressed()) {
4660                setPressed(false);
4661            }
4662            if (imm != null && mAttachInfo != null
4663                    && mAttachInfo.mHasWindowFocus) {
4664                imm.focusOut(this);
4665            }
4666            onFocusLost();
4667        } else if (imm != null && mAttachInfo != null
4668                && mAttachInfo.mHasWindowFocus) {
4669            imm.focusIn(this);
4670        }
4671
4672        invalidate(true);
4673        ListenerInfo li = mListenerInfo;
4674        if (li != null && li.mOnFocusChangeListener != null) {
4675            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4676        }
4677
4678        if (mAttachInfo != null) {
4679            mAttachInfo.mKeyDispatchState.reset(this);
4680        }
4681    }
4682
4683    /**
4684     * Sends an accessibility event of the given type. If accessibility is
4685     * not enabled this method has no effect. The default implementation calls
4686     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4687     * to populate information about the event source (this View), then calls
4688     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4689     * populate the text content of the event source including its descendants,
4690     * and last calls
4691     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4692     * on its parent to resuest sending of the event to interested parties.
4693     * <p>
4694     * If an {@link AccessibilityDelegate} has been specified via calling
4695     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4696     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4697     * responsible for handling this call.
4698     * </p>
4699     *
4700     * @param eventType The type of the event to send, as defined by several types from
4701     * {@link android.view.accessibility.AccessibilityEvent}, such as
4702     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4703     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4704     *
4705     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4706     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4707     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4708     * @see AccessibilityDelegate
4709     */
4710    public void sendAccessibilityEvent(int eventType) {
4711        // Excluded views do not send accessibility events.
4712        if (!includeForAccessibility()) {
4713            return;
4714        }
4715        if (mAccessibilityDelegate != null) {
4716            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4717        } else {
4718            sendAccessibilityEventInternal(eventType);
4719        }
4720    }
4721
4722    /**
4723     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4724     * {@link AccessibilityEvent} to make an announcement which is related to some
4725     * sort of a context change for which none of the events representing UI transitions
4726     * is a good fit. For example, announcing a new page in a book. If accessibility
4727     * is not enabled this method does nothing.
4728     *
4729     * @param text The announcement text.
4730     */
4731    public void announceForAccessibility(CharSequence text) {
4732        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4733            AccessibilityEvent event = AccessibilityEvent.obtain(
4734                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4735            onInitializeAccessibilityEvent(event);
4736            event.getText().add(text);
4737            event.setContentDescription(null);
4738            mParent.requestSendAccessibilityEvent(this, event);
4739        }
4740    }
4741
4742    /**
4743     * @see #sendAccessibilityEvent(int)
4744     *
4745     * Note: Called from the default {@link AccessibilityDelegate}.
4746     */
4747    void sendAccessibilityEventInternal(int eventType) {
4748        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4749            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4750        }
4751    }
4752
4753    /**
4754     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4755     * takes as an argument an empty {@link AccessibilityEvent} and does not
4756     * perform a check whether accessibility is enabled.
4757     * <p>
4758     * If an {@link AccessibilityDelegate} has been specified via calling
4759     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4760     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4761     * is responsible for handling this call.
4762     * </p>
4763     *
4764     * @param event The event to send.
4765     *
4766     * @see #sendAccessibilityEvent(int)
4767     */
4768    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4769        if (mAccessibilityDelegate != null) {
4770            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4771        } else {
4772            sendAccessibilityEventUncheckedInternal(event);
4773        }
4774    }
4775
4776    /**
4777     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4778     *
4779     * Note: Called from the default {@link AccessibilityDelegate}.
4780     */
4781    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4782        if (!isShown()) {
4783            return;
4784        }
4785        onInitializeAccessibilityEvent(event);
4786        // Only a subset of accessibility events populates text content.
4787        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4788            dispatchPopulateAccessibilityEvent(event);
4789        }
4790        // In the beginning we called #isShown(), so we know that getParent() is not null.
4791        getParent().requestSendAccessibilityEvent(this, event);
4792    }
4793
4794    /**
4795     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4796     * to its children for adding their text content to the event. Note that the
4797     * event text is populated in a separate dispatch path since we add to the
4798     * event not only the text of the source but also the text of all its descendants.
4799     * A typical implementation will call
4800     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4801     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4802     * on each child. Override this method if custom population of the event text
4803     * content is required.
4804     * <p>
4805     * If an {@link AccessibilityDelegate} has been specified via calling
4806     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4807     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4808     * is responsible for handling this call.
4809     * </p>
4810     * <p>
4811     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4812     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4813     * </p>
4814     *
4815     * @param event The event.
4816     *
4817     * @return True if the event population was completed.
4818     */
4819    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4820        if (mAccessibilityDelegate != null) {
4821            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4822        } else {
4823            return dispatchPopulateAccessibilityEventInternal(event);
4824        }
4825    }
4826
4827    /**
4828     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4829     *
4830     * Note: Called from the default {@link AccessibilityDelegate}.
4831     */
4832    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4833        onPopulateAccessibilityEvent(event);
4834        return false;
4835    }
4836
4837    /**
4838     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4839     * giving a chance to this View to populate the accessibility event with its
4840     * text content. While this method is free to modify event
4841     * attributes other than text content, doing so should normally be performed in
4842     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4843     * <p>
4844     * Example: Adding formatted date string to an accessibility event in addition
4845     *          to the text added by the super implementation:
4846     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4847     *     super.onPopulateAccessibilityEvent(event);
4848     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4849     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4850     *         mCurrentDate.getTimeInMillis(), flags);
4851     *     event.getText().add(selectedDateUtterance);
4852     * }</pre>
4853     * <p>
4854     * If an {@link AccessibilityDelegate} has been specified via calling
4855     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4856     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4857     * is responsible for handling this call.
4858     * </p>
4859     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4860     * information to the event, in case the default implementation has basic information to add.
4861     * </p>
4862     *
4863     * @param event The accessibility event which to populate.
4864     *
4865     * @see #sendAccessibilityEvent(int)
4866     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4867     */
4868    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4869        if (mAccessibilityDelegate != null) {
4870            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4871        } else {
4872            onPopulateAccessibilityEventInternal(event);
4873        }
4874    }
4875
4876    /**
4877     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4878     *
4879     * Note: Called from the default {@link AccessibilityDelegate}.
4880     */
4881    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4882    }
4883
4884    /**
4885     * Initializes an {@link AccessibilityEvent} with information about
4886     * this View which is the event source. In other words, the source of
4887     * an accessibility event is the view whose state change triggered firing
4888     * the event.
4889     * <p>
4890     * Example: Setting the password property of an event in addition
4891     *          to properties set by the super implementation:
4892     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4893     *     super.onInitializeAccessibilityEvent(event);
4894     *     event.setPassword(true);
4895     * }</pre>
4896     * <p>
4897     * If an {@link AccessibilityDelegate} has been specified via calling
4898     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4899     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4900     * is responsible for handling this call.
4901     * </p>
4902     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4903     * information to the event, in case the default implementation has basic information to add.
4904     * </p>
4905     * @param event The event to initialize.
4906     *
4907     * @see #sendAccessibilityEvent(int)
4908     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4909     */
4910    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4911        if (mAccessibilityDelegate != null) {
4912            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4913        } else {
4914            onInitializeAccessibilityEventInternal(event);
4915        }
4916    }
4917
4918    /**
4919     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4920     *
4921     * Note: Called from the default {@link AccessibilityDelegate}.
4922     */
4923    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4924        event.setSource(this);
4925        event.setClassName(View.class.getName());
4926        event.setPackageName(getContext().getPackageName());
4927        event.setEnabled(isEnabled());
4928        event.setContentDescription(mContentDescription);
4929
4930        switch (event.getEventType()) {
4931            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4932                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4933                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4934                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4935                event.setItemCount(focusablesTempList.size());
4936                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4937                if (mAttachInfo != null) {
4938                    focusablesTempList.clear();
4939                }
4940            } break;
4941            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4942                CharSequence text = getIterableTextForAccessibility();
4943                if (text != null && text.length() > 0) {
4944                    event.setFromIndex(getAccessibilitySelectionStart());
4945                    event.setToIndex(getAccessibilitySelectionEnd());
4946                    event.setItemCount(text.length());
4947                }
4948            } break;
4949        }
4950    }
4951
4952    /**
4953     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4954     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4955     * This method is responsible for obtaining an accessibility node info from a
4956     * pool of reusable instances and calling
4957     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4958     * initialize the former.
4959     * <p>
4960     * Note: The client is responsible for recycling the obtained instance by calling
4961     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4962     * </p>
4963     *
4964     * @return A populated {@link AccessibilityNodeInfo}.
4965     *
4966     * @see AccessibilityNodeInfo
4967     */
4968    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4969        if (mAccessibilityDelegate != null) {
4970            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
4971        } else {
4972            return createAccessibilityNodeInfoInternal();
4973        }
4974    }
4975
4976    /**
4977     * @see #createAccessibilityNodeInfo()
4978     */
4979    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
4980        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4981        if (provider != null) {
4982            return provider.createAccessibilityNodeInfo(View.NO_ID);
4983        } else {
4984            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4985            onInitializeAccessibilityNodeInfo(info);
4986            return info;
4987        }
4988    }
4989
4990    /**
4991     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4992     * The base implementation sets:
4993     * <ul>
4994     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4995     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4996     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4997     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4998     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4999     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5000     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5001     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5002     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5003     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5004     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5005     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5006     * </ul>
5007     * <p>
5008     * Subclasses should override this method, call the super implementation,
5009     * and set additional attributes.
5010     * </p>
5011     * <p>
5012     * If an {@link AccessibilityDelegate} has been specified via calling
5013     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5014     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5015     * is responsible for handling this call.
5016     * </p>
5017     *
5018     * @param info The instance to initialize.
5019     */
5020    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5021        if (mAccessibilityDelegate != null) {
5022            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5023        } else {
5024            onInitializeAccessibilityNodeInfoInternal(info);
5025        }
5026    }
5027
5028    /**
5029     * Gets the location of this view in screen coordintates.
5030     *
5031     * @param outRect The output location
5032     */
5033    void getBoundsOnScreen(Rect outRect) {
5034        if (mAttachInfo == null) {
5035            return;
5036        }
5037
5038        RectF position = mAttachInfo.mTmpTransformRect;
5039        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5040
5041        if (!hasIdentityMatrix()) {
5042            getMatrix().mapRect(position);
5043        }
5044
5045        position.offset(mLeft, mTop);
5046
5047        ViewParent parent = mParent;
5048        while (parent instanceof View) {
5049            View parentView = (View) parent;
5050
5051            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5052
5053            if (!parentView.hasIdentityMatrix()) {
5054                parentView.getMatrix().mapRect(position);
5055            }
5056
5057            position.offset(parentView.mLeft, parentView.mTop);
5058
5059            parent = parentView.mParent;
5060        }
5061
5062        if (parent instanceof ViewRootImpl) {
5063            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5064            position.offset(0, -viewRootImpl.mCurScrollY);
5065        }
5066
5067        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5068
5069        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5070                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5071    }
5072
5073    /**
5074     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5075     *
5076     * Note: Called from the default {@link AccessibilityDelegate}.
5077     */
5078    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5079        Rect bounds = mAttachInfo.mTmpInvalRect;
5080
5081        getDrawingRect(bounds);
5082        info.setBoundsInParent(bounds);
5083
5084        getBoundsOnScreen(bounds);
5085        info.setBoundsInScreen(bounds);
5086
5087        ViewParent parent = getParentForAccessibility();
5088        if (parent instanceof View) {
5089            info.setParent((View) parent);
5090        }
5091
5092        if (mID != View.NO_ID) {
5093            View rootView = getRootView();
5094            if (rootView == null) {
5095                rootView = this;
5096            }
5097            View label = rootView.findLabelForView(this, mID);
5098            if (label != null) {
5099                info.setLabeledBy(label);
5100            }
5101
5102            if ((mAttachInfo.mAccessibilityFetchFlags
5103                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5104                    && Resources.resourceHasPackage(mID)) {
5105                try {
5106                    String viewId = getResources().getResourceName(mID);
5107                    info.setViewIdResourceName(viewId);
5108                } catch (Resources.NotFoundException nfe) {
5109                    /* ignore */
5110                }
5111            }
5112        }
5113
5114        if (mLabelForId != View.NO_ID) {
5115            View rootView = getRootView();
5116            if (rootView == null) {
5117                rootView = this;
5118            }
5119            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5120            if (labeled != null) {
5121                info.setLabelFor(labeled);
5122            }
5123        }
5124
5125        info.setVisibleToUser(isVisibleToUser());
5126
5127        info.setPackageName(mContext.getPackageName());
5128        info.setClassName(View.class.getName());
5129        info.setContentDescription(getContentDescription());
5130
5131        info.setEnabled(isEnabled());
5132        info.setClickable(isClickable());
5133        info.setFocusable(isFocusable());
5134        info.setFocused(isFocused());
5135        info.setAccessibilityFocused(isAccessibilityFocused());
5136        info.setSelected(isSelected());
5137        info.setLongClickable(isLongClickable());
5138
5139        // TODO: These make sense only if we are in an AdapterView but all
5140        // views can be selected. Maybe from accessibility perspective
5141        // we should report as selectable view in an AdapterView.
5142        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5143        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5144
5145        if (isFocusable()) {
5146            if (isFocused()) {
5147                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5148            } else {
5149                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5150            }
5151        }
5152
5153        if (!isAccessibilityFocused()) {
5154            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5155        } else {
5156            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5157        }
5158
5159        if (isClickable() && isEnabled()) {
5160            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5161        }
5162
5163        if (isLongClickable() && isEnabled()) {
5164            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5165        }
5166
5167        CharSequence text = getIterableTextForAccessibility();
5168        if (text != null && text.length() > 0) {
5169            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5170
5171            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5172            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5173            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5174            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5175                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5176                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5177        }
5178    }
5179
5180    private View findLabelForView(View view, int labeledId) {
5181        if (mMatchLabelForPredicate == null) {
5182            mMatchLabelForPredicate = new MatchLabelForPredicate();
5183        }
5184        mMatchLabelForPredicate.mLabeledId = labeledId;
5185        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5186    }
5187
5188    /**
5189     * Computes whether this view is visible to the user. Such a view is
5190     * attached, visible, all its predecessors are visible, it is not clipped
5191     * entirely by its predecessors, and has an alpha greater than zero.
5192     *
5193     * @return Whether the view is visible on the screen.
5194     *
5195     * @hide
5196     */
5197    protected boolean isVisibleToUser() {
5198        return isVisibleToUser(null);
5199    }
5200
5201    /**
5202     * Computes whether the given portion of this view is visible to the user.
5203     * Such a view is attached, visible, all its predecessors are visible,
5204     * has an alpha greater than zero, and the specified portion is not
5205     * clipped entirely by its predecessors.
5206     *
5207     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5208     *                    <code>null</code>, and the entire view will be tested in this case.
5209     *                    When <code>true</code> is returned by the function, the actual visible
5210     *                    region will be stored in this parameter; that is, if boundInView is fully
5211     *                    contained within the view, no modification will be made, otherwise regions
5212     *                    outside of the visible area of the view will be clipped.
5213     *
5214     * @return Whether the specified portion of the view is visible on the screen.
5215     *
5216     * @hide
5217     */
5218    protected boolean isVisibleToUser(Rect boundInView) {
5219        if (mAttachInfo != null) {
5220            // Attached to invisible window means this view is not visible.
5221            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5222                return false;
5223            }
5224            // An invisible predecessor or one with alpha zero means
5225            // that this view is not visible to the user.
5226            Object current = this;
5227            while (current instanceof View) {
5228                View view = (View) current;
5229                // We have attach info so this view is attached and there is no
5230                // need to check whether we reach to ViewRootImpl on the way up.
5231                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5232                    return false;
5233                }
5234                current = view.mParent;
5235            }
5236            // Check if the view is entirely covered by its predecessors.
5237            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5238            Point offset = mAttachInfo.mPoint;
5239            if (!getGlobalVisibleRect(visibleRect, offset)) {
5240                return false;
5241            }
5242            // Check if the visible portion intersects the rectangle of interest.
5243            if (boundInView != null) {
5244                visibleRect.offset(-offset.x, -offset.y);
5245                return boundInView.intersect(visibleRect);
5246            }
5247            return true;
5248        }
5249        return false;
5250    }
5251
5252    /**
5253     * Returns the delegate for implementing accessibility support via
5254     * composition. For more details see {@link AccessibilityDelegate}.
5255     *
5256     * @return The delegate, or null if none set.
5257     *
5258     * @hide
5259     */
5260    public AccessibilityDelegate getAccessibilityDelegate() {
5261        return mAccessibilityDelegate;
5262    }
5263
5264    /**
5265     * Sets a delegate for implementing accessibility support via composition as
5266     * opposed to inheritance. The delegate's primary use is for implementing
5267     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5268     *
5269     * @param delegate The delegate instance.
5270     *
5271     * @see AccessibilityDelegate
5272     */
5273    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5274        mAccessibilityDelegate = delegate;
5275    }
5276
5277    /**
5278     * Gets the provider for managing a virtual view hierarchy rooted at this View
5279     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5280     * that explore the window content.
5281     * <p>
5282     * If this method returns an instance, this instance is responsible for managing
5283     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5284     * View including the one representing the View itself. Similarly the returned
5285     * instance is responsible for performing accessibility actions on any virtual
5286     * view or the root view itself.
5287     * </p>
5288     * <p>
5289     * If an {@link AccessibilityDelegate} has been specified via calling
5290     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5291     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5292     * is responsible for handling this call.
5293     * </p>
5294     *
5295     * @return The provider.
5296     *
5297     * @see AccessibilityNodeProvider
5298     */
5299    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5300        if (mAccessibilityDelegate != null) {
5301            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5302        } else {
5303            return null;
5304        }
5305    }
5306
5307    /**
5308     * Gets the unique identifier of this view on the screen for accessibility purposes.
5309     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5310     *
5311     * @return The view accessibility id.
5312     *
5313     * @hide
5314     */
5315    public int getAccessibilityViewId() {
5316        if (mAccessibilityViewId == NO_ID) {
5317            mAccessibilityViewId = sNextAccessibilityViewId++;
5318        }
5319        return mAccessibilityViewId;
5320    }
5321
5322    /**
5323     * Gets the unique identifier of the window in which this View reseides.
5324     *
5325     * @return The window accessibility id.
5326     *
5327     * @hide
5328     */
5329    public int getAccessibilityWindowId() {
5330        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5331    }
5332
5333    /**
5334     * Gets the {@link View} description. It briefly describes the view and is
5335     * primarily used for accessibility support. Set this property to enable
5336     * better accessibility support for your application. This is especially
5337     * true for views that do not have textual representation (For example,
5338     * ImageButton).
5339     *
5340     * @return The content description.
5341     *
5342     * @attr ref android.R.styleable#View_contentDescription
5343     */
5344    @ViewDebug.ExportedProperty(category = "accessibility")
5345    public CharSequence getContentDescription() {
5346        return mContentDescription;
5347    }
5348
5349    /**
5350     * Sets the {@link View} description. It briefly describes the view and is
5351     * primarily used for accessibility support. Set this property to enable
5352     * better accessibility support for your application. This is especially
5353     * true for views that do not have textual representation (For example,
5354     * ImageButton).
5355     *
5356     * @param contentDescription The content description.
5357     *
5358     * @attr ref android.R.styleable#View_contentDescription
5359     */
5360    @RemotableViewMethod
5361    public void setContentDescription(CharSequence contentDescription) {
5362        if (mContentDescription == null) {
5363            if (contentDescription == null) {
5364                return;
5365            }
5366        } else if (mContentDescription.equals(contentDescription)) {
5367            return;
5368        }
5369        mContentDescription = contentDescription;
5370        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5371        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5372            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5373            notifySubtreeAccessibilityStateChangedIfNeeded();
5374        } else {
5375            notifyViewAccessibilityStateChangedIfNeeded();
5376        }
5377    }
5378
5379    /**
5380     * Gets the id of a view for which this view serves as a label for
5381     * accessibility purposes.
5382     *
5383     * @return The labeled view id.
5384     */
5385    @ViewDebug.ExportedProperty(category = "accessibility")
5386    public int getLabelFor() {
5387        return mLabelForId;
5388    }
5389
5390    /**
5391     * Sets the id of a view for which this view serves as a label for
5392     * accessibility purposes.
5393     *
5394     * @param id The labeled view id.
5395     */
5396    @RemotableViewMethod
5397    public void setLabelFor(int id) {
5398        mLabelForId = id;
5399        if (mLabelForId != View.NO_ID
5400                && mID == View.NO_ID) {
5401            mID = generateViewId();
5402        }
5403    }
5404
5405    /**
5406     * Invoked whenever this view loses focus, either by losing window focus or by losing
5407     * focus within its window. This method can be used to clear any state tied to the
5408     * focus. For instance, if a button is held pressed with the trackball and the window
5409     * loses focus, this method can be used to cancel the press.
5410     *
5411     * Subclasses of View overriding this method should always call super.onFocusLost().
5412     *
5413     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5414     * @see #onWindowFocusChanged(boolean)
5415     *
5416     * @hide pending API council approval
5417     */
5418    protected void onFocusLost() {
5419        resetPressedState();
5420    }
5421
5422    private void resetPressedState() {
5423        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5424            return;
5425        }
5426
5427        if (isPressed()) {
5428            setPressed(false);
5429
5430            if (!mHasPerformedLongPress) {
5431                removeLongPressCallback();
5432            }
5433        }
5434    }
5435
5436    /**
5437     * Returns true if this view has focus
5438     *
5439     * @return True if this view has focus, false otherwise.
5440     */
5441    @ViewDebug.ExportedProperty(category = "focus")
5442    public boolean isFocused() {
5443        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5444    }
5445
5446    /**
5447     * Find the view in the hierarchy rooted at this view that currently has
5448     * focus.
5449     *
5450     * @return The view that currently has focus, or null if no focused view can
5451     *         be found.
5452     */
5453    public View findFocus() {
5454        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5455    }
5456
5457    /**
5458     * Indicates whether this view is one of the set of scrollable containers in
5459     * its window.
5460     *
5461     * @return whether this view is one of the set of scrollable containers in
5462     * its window
5463     *
5464     * @attr ref android.R.styleable#View_isScrollContainer
5465     */
5466    public boolean isScrollContainer() {
5467        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5468    }
5469
5470    /**
5471     * Change whether this view is one of the set of scrollable containers in
5472     * its window.  This will be used to determine whether the window can
5473     * resize or must pan when a soft input area is open -- scrollable
5474     * containers allow the window to use resize mode since the container
5475     * will appropriately shrink.
5476     *
5477     * @attr ref android.R.styleable#View_isScrollContainer
5478     */
5479    public void setScrollContainer(boolean isScrollContainer) {
5480        if (isScrollContainer) {
5481            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5482                mAttachInfo.mScrollContainers.add(this);
5483                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5484            }
5485            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5486        } else {
5487            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5488                mAttachInfo.mScrollContainers.remove(this);
5489            }
5490            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5491        }
5492    }
5493
5494    /**
5495     * Returns the quality of the drawing cache.
5496     *
5497     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5498     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5499     *
5500     * @see #setDrawingCacheQuality(int)
5501     * @see #setDrawingCacheEnabled(boolean)
5502     * @see #isDrawingCacheEnabled()
5503     *
5504     * @attr ref android.R.styleable#View_drawingCacheQuality
5505     */
5506    public int getDrawingCacheQuality() {
5507        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5508    }
5509
5510    /**
5511     * Set the drawing cache quality of this view. This value is used only when the
5512     * drawing cache is enabled
5513     *
5514     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5515     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5516     *
5517     * @see #getDrawingCacheQuality()
5518     * @see #setDrawingCacheEnabled(boolean)
5519     * @see #isDrawingCacheEnabled()
5520     *
5521     * @attr ref android.R.styleable#View_drawingCacheQuality
5522     */
5523    public void setDrawingCacheQuality(int quality) {
5524        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5525    }
5526
5527    /**
5528     * Returns whether the screen should remain on, corresponding to the current
5529     * value of {@link #KEEP_SCREEN_ON}.
5530     *
5531     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5532     *
5533     * @see #setKeepScreenOn(boolean)
5534     *
5535     * @attr ref android.R.styleable#View_keepScreenOn
5536     */
5537    public boolean getKeepScreenOn() {
5538        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5539    }
5540
5541    /**
5542     * Controls whether the screen should remain on, modifying the
5543     * value of {@link #KEEP_SCREEN_ON}.
5544     *
5545     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5546     *
5547     * @see #getKeepScreenOn()
5548     *
5549     * @attr ref android.R.styleable#View_keepScreenOn
5550     */
5551    public void setKeepScreenOn(boolean keepScreenOn) {
5552        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5553    }
5554
5555    /**
5556     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5557     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5558     *
5559     * @attr ref android.R.styleable#View_nextFocusLeft
5560     */
5561    public int getNextFocusLeftId() {
5562        return mNextFocusLeftId;
5563    }
5564
5565    /**
5566     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5567     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5568     * decide automatically.
5569     *
5570     * @attr ref android.R.styleable#View_nextFocusLeft
5571     */
5572    public void setNextFocusLeftId(int nextFocusLeftId) {
5573        mNextFocusLeftId = nextFocusLeftId;
5574    }
5575
5576    /**
5577     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5578     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5579     *
5580     * @attr ref android.R.styleable#View_nextFocusRight
5581     */
5582    public int getNextFocusRightId() {
5583        return mNextFocusRightId;
5584    }
5585
5586    /**
5587     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5588     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5589     * decide automatically.
5590     *
5591     * @attr ref android.R.styleable#View_nextFocusRight
5592     */
5593    public void setNextFocusRightId(int nextFocusRightId) {
5594        mNextFocusRightId = nextFocusRightId;
5595    }
5596
5597    /**
5598     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5599     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5600     *
5601     * @attr ref android.R.styleable#View_nextFocusUp
5602     */
5603    public int getNextFocusUpId() {
5604        return mNextFocusUpId;
5605    }
5606
5607    /**
5608     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5609     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5610     * decide automatically.
5611     *
5612     * @attr ref android.R.styleable#View_nextFocusUp
5613     */
5614    public void setNextFocusUpId(int nextFocusUpId) {
5615        mNextFocusUpId = nextFocusUpId;
5616    }
5617
5618    /**
5619     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5620     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5621     *
5622     * @attr ref android.R.styleable#View_nextFocusDown
5623     */
5624    public int getNextFocusDownId() {
5625        return mNextFocusDownId;
5626    }
5627
5628    /**
5629     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5630     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5631     * decide automatically.
5632     *
5633     * @attr ref android.R.styleable#View_nextFocusDown
5634     */
5635    public void setNextFocusDownId(int nextFocusDownId) {
5636        mNextFocusDownId = nextFocusDownId;
5637    }
5638
5639    /**
5640     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5641     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5642     *
5643     * @attr ref android.R.styleable#View_nextFocusForward
5644     */
5645    public int getNextFocusForwardId() {
5646        return mNextFocusForwardId;
5647    }
5648
5649    /**
5650     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5651     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5652     * decide automatically.
5653     *
5654     * @attr ref android.R.styleable#View_nextFocusForward
5655     */
5656    public void setNextFocusForwardId(int nextFocusForwardId) {
5657        mNextFocusForwardId = nextFocusForwardId;
5658    }
5659
5660    /**
5661     * Returns the visibility of this view and all of its ancestors
5662     *
5663     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5664     */
5665    public boolean isShown() {
5666        View current = this;
5667        //noinspection ConstantConditions
5668        do {
5669            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5670                return false;
5671            }
5672            ViewParent parent = current.mParent;
5673            if (parent == null) {
5674                return false; // We are not attached to the view root
5675            }
5676            if (!(parent instanceof View)) {
5677                return true;
5678            }
5679            current = (View) parent;
5680        } while (current != null);
5681
5682        return false;
5683    }
5684
5685    /**
5686     * Called by the view hierarchy when the content insets for a window have
5687     * changed, to allow it to adjust its content to fit within those windows.
5688     * The content insets tell you the space that the status bar, input method,
5689     * and other system windows infringe on the application's window.
5690     *
5691     * <p>You do not normally need to deal with this function, since the default
5692     * window decoration given to applications takes care of applying it to the
5693     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5694     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5695     * and your content can be placed under those system elements.  You can then
5696     * use this method within your view hierarchy if you have parts of your UI
5697     * which you would like to ensure are not being covered.
5698     *
5699     * <p>The default implementation of this method simply applies the content
5700     * insets to the view's padding, consuming that content (modifying the
5701     * insets to be 0), and returning true.  This behavior is off by default, but can
5702     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5703     *
5704     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5705     * insets object is propagated down the hierarchy, so any changes made to it will
5706     * be seen by all following views (including potentially ones above in
5707     * the hierarchy since this is a depth-first traversal).  The first view
5708     * that returns true will abort the entire traversal.
5709     *
5710     * <p>The default implementation works well for a situation where it is
5711     * used with a container that covers the entire window, allowing it to
5712     * apply the appropriate insets to its content on all edges.  If you need
5713     * a more complicated layout (such as two different views fitting system
5714     * windows, one on the top of the window, and one on the bottom),
5715     * you can override the method and handle the insets however you would like.
5716     * Note that the insets provided by the framework are always relative to the
5717     * far edges of the window, not accounting for the location of the called view
5718     * within that window.  (In fact when this method is called you do not yet know
5719     * where the layout will place the view, as it is done before layout happens.)
5720     *
5721     * <p>Note: unlike many View methods, there is no dispatch phase to this
5722     * call.  If you are overriding it in a ViewGroup and want to allow the
5723     * call to continue to your children, you must be sure to call the super
5724     * implementation.
5725     *
5726     * <p>Here is a sample layout that makes use of fitting system windows
5727     * to have controls for a video view placed inside of the window decorations
5728     * that it hides and shows.  This can be used with code like the second
5729     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5730     *
5731     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5732     *
5733     * @param insets Current content insets of the window.  Prior to
5734     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5735     * the insets or else you and Android will be unhappy.
5736     *
5737     * @return {@code true} if this view applied the insets and it should not
5738     * continue propagating further down the hierarchy, {@code false} otherwise.
5739     * @see #getFitsSystemWindows()
5740     * @see #setFitsSystemWindows(boolean)
5741     * @see #setSystemUiVisibility(int)
5742     */
5743    protected boolean fitSystemWindows(Rect insets) {
5744        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5745            mUserPaddingStart = UNDEFINED_PADDING;
5746            mUserPaddingEnd = UNDEFINED_PADDING;
5747            Rect localInsets = sThreadLocal.get();
5748            if (localInsets == null) {
5749                localInsets = new Rect();
5750                sThreadLocal.set(localInsets);
5751            }
5752            boolean res = computeFitSystemWindows(insets, localInsets);
5753            internalSetPadding(localInsets.left, localInsets.top,
5754                    localInsets.right, localInsets.bottom);
5755            return res;
5756        }
5757        return false;
5758    }
5759
5760    /**
5761     * @hide Compute the insets that should be consumed by this view and the ones
5762     * that should propagate to those under it.
5763     */
5764    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5765        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5766                || mAttachInfo == null
5767                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5768                        && !mAttachInfo.mOverscanRequested)) {
5769            outLocalInsets.set(inoutInsets);
5770            inoutInsets.set(0, 0, 0, 0);
5771            return true;
5772        } else {
5773            // The application wants to take care of fitting system window for
5774            // the content...  however we still need to take care of any overscan here.
5775            final Rect overscan = mAttachInfo.mOverscanInsets;
5776            outLocalInsets.set(overscan);
5777            inoutInsets.left -= overscan.left;
5778            inoutInsets.top -= overscan.top;
5779            inoutInsets.right -= overscan.right;
5780            inoutInsets.bottom -= overscan.bottom;
5781            return false;
5782        }
5783    }
5784
5785    /**
5786     * Sets whether or not this view should account for system screen decorations
5787     * such as the status bar and inset its content; that is, controlling whether
5788     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5789     * executed.  See that method for more details.
5790     *
5791     * <p>Note that if you are providing your own implementation of
5792     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5793     * flag to true -- your implementation will be overriding the default
5794     * implementation that checks this flag.
5795     *
5796     * @param fitSystemWindows If true, then the default implementation of
5797     * {@link #fitSystemWindows(Rect)} will be executed.
5798     *
5799     * @attr ref android.R.styleable#View_fitsSystemWindows
5800     * @see #getFitsSystemWindows()
5801     * @see #fitSystemWindows(Rect)
5802     * @see #setSystemUiVisibility(int)
5803     */
5804    public void setFitsSystemWindows(boolean fitSystemWindows) {
5805        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5806    }
5807
5808    /**
5809     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5810     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5811     * will be executed.
5812     *
5813     * @return {@code true} if the default implementation of
5814     * {@link #fitSystemWindows(Rect)} will be executed.
5815     *
5816     * @attr ref android.R.styleable#View_fitsSystemWindows
5817     * @see #setFitsSystemWindows(boolean)
5818     * @see #fitSystemWindows(Rect)
5819     * @see #setSystemUiVisibility(int)
5820     */
5821    public boolean getFitsSystemWindows() {
5822        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5823    }
5824
5825    /** @hide */
5826    public boolean fitsSystemWindows() {
5827        return getFitsSystemWindows();
5828    }
5829
5830    /**
5831     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5832     */
5833    public void requestFitSystemWindows() {
5834        if (mParent != null) {
5835            mParent.requestFitSystemWindows();
5836        }
5837    }
5838
5839    /**
5840     * For use by PhoneWindow to make its own system window fitting optional.
5841     * @hide
5842     */
5843    public void makeOptionalFitsSystemWindows() {
5844        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5845    }
5846
5847    /**
5848     * Returns the visibility status for this view.
5849     *
5850     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5851     * @attr ref android.R.styleable#View_visibility
5852     */
5853    @ViewDebug.ExportedProperty(mapping = {
5854        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5855        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5856        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5857    })
5858    public int getVisibility() {
5859        return mViewFlags & VISIBILITY_MASK;
5860    }
5861
5862    /**
5863     * Set the enabled state of this view.
5864     *
5865     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5866     * @attr ref android.R.styleable#View_visibility
5867     */
5868    @RemotableViewMethod
5869    public void setVisibility(int visibility) {
5870        setFlags(visibility, VISIBILITY_MASK);
5871        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5872    }
5873
5874    /**
5875     * Returns the enabled status for this view. The interpretation of the
5876     * enabled state varies by subclass.
5877     *
5878     * @return True if this view is enabled, false otherwise.
5879     */
5880    @ViewDebug.ExportedProperty
5881    public boolean isEnabled() {
5882        return (mViewFlags & ENABLED_MASK) == ENABLED;
5883    }
5884
5885    /**
5886     * Set the enabled state of this view. The interpretation of the enabled
5887     * state varies by subclass.
5888     *
5889     * @param enabled True if this view is enabled, false otherwise.
5890     */
5891    @RemotableViewMethod
5892    public void setEnabled(boolean enabled) {
5893        if (enabled == isEnabled()) return;
5894
5895        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5896
5897        /*
5898         * The View most likely has to change its appearance, so refresh
5899         * the drawable state.
5900         */
5901        refreshDrawableState();
5902
5903        // Invalidate too, since the default behavior for views is to be
5904        // be drawn at 50% alpha rather than to change the drawable.
5905        invalidate(true);
5906    }
5907
5908    /**
5909     * Set whether this view can receive the focus.
5910     *
5911     * Setting this to false will also ensure that this view is not focusable
5912     * in touch mode.
5913     *
5914     * @param focusable If true, this view can receive the focus.
5915     *
5916     * @see #setFocusableInTouchMode(boolean)
5917     * @attr ref android.R.styleable#View_focusable
5918     */
5919    public void setFocusable(boolean focusable) {
5920        if (!focusable) {
5921            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5922        }
5923        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5924    }
5925
5926    /**
5927     * Set whether this view can receive focus while in touch mode.
5928     *
5929     * Setting this to true will also ensure that this view is focusable.
5930     *
5931     * @param focusableInTouchMode If true, this view can receive the focus while
5932     *   in touch mode.
5933     *
5934     * @see #setFocusable(boolean)
5935     * @attr ref android.R.styleable#View_focusableInTouchMode
5936     */
5937    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5938        // Focusable in touch mode should always be set before the focusable flag
5939        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5940        // which, in touch mode, will not successfully request focus on this view
5941        // because the focusable in touch mode flag is not set
5942        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5943        if (focusableInTouchMode) {
5944            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5945        }
5946    }
5947
5948    /**
5949     * Set whether this view should have sound effects enabled for events such as
5950     * clicking and touching.
5951     *
5952     * <p>You may wish to disable sound effects for a view if you already play sounds,
5953     * for instance, a dial key that plays dtmf tones.
5954     *
5955     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5956     * @see #isSoundEffectsEnabled()
5957     * @see #playSoundEffect(int)
5958     * @attr ref android.R.styleable#View_soundEffectsEnabled
5959     */
5960    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5961        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5962    }
5963
5964    /**
5965     * @return whether this view should have sound effects enabled for events such as
5966     *     clicking and touching.
5967     *
5968     * @see #setSoundEffectsEnabled(boolean)
5969     * @see #playSoundEffect(int)
5970     * @attr ref android.R.styleable#View_soundEffectsEnabled
5971     */
5972    @ViewDebug.ExportedProperty
5973    public boolean isSoundEffectsEnabled() {
5974        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5975    }
5976
5977    /**
5978     * Set whether this view should have haptic feedback for events such as
5979     * long presses.
5980     *
5981     * <p>You may wish to disable haptic feedback if your view already controls
5982     * its own haptic feedback.
5983     *
5984     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5985     * @see #isHapticFeedbackEnabled()
5986     * @see #performHapticFeedback(int)
5987     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5988     */
5989    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5990        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5991    }
5992
5993    /**
5994     * @return whether this view should have haptic feedback enabled for events
5995     * long presses.
5996     *
5997     * @see #setHapticFeedbackEnabled(boolean)
5998     * @see #performHapticFeedback(int)
5999     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6000     */
6001    @ViewDebug.ExportedProperty
6002    public boolean isHapticFeedbackEnabled() {
6003        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6004    }
6005
6006    /**
6007     * Returns the layout direction for this view.
6008     *
6009     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6010     *   {@link #LAYOUT_DIRECTION_RTL},
6011     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6012     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6013     *
6014     * @attr ref android.R.styleable#View_layoutDirection
6015     *
6016     * @hide
6017     */
6018    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6019        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6020        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6021        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6022        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6023    })
6024    public int getRawLayoutDirection() {
6025        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6026    }
6027
6028    /**
6029     * Set the layout direction for this view. This will propagate a reset of layout direction
6030     * resolution to the view's children and resolve layout direction for this view.
6031     *
6032     * @param layoutDirection the layout direction to set. Should be one of:
6033     *
6034     * {@link #LAYOUT_DIRECTION_LTR},
6035     * {@link #LAYOUT_DIRECTION_RTL},
6036     * {@link #LAYOUT_DIRECTION_INHERIT},
6037     * {@link #LAYOUT_DIRECTION_LOCALE}.
6038     *
6039     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6040     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6041     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6042     *
6043     * @attr ref android.R.styleable#View_layoutDirection
6044     */
6045    @RemotableViewMethod
6046    public void setLayoutDirection(int layoutDirection) {
6047        if (getRawLayoutDirection() != layoutDirection) {
6048            // Reset the current layout direction and the resolved one
6049            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6050            resetRtlProperties();
6051            // Set the new layout direction (filtered)
6052            mPrivateFlags2 |=
6053                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6054            // We need to resolve all RTL properties as they all depend on layout direction
6055            resolveRtlPropertiesIfNeeded();
6056            requestLayout();
6057            invalidate(true);
6058        }
6059    }
6060
6061    /**
6062     * Returns the resolved layout direction for this view.
6063     *
6064     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6065     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6066     *
6067     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6068     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6069     *
6070     * @attr ref android.R.styleable#View_layoutDirection
6071     */
6072    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6073        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6074        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6075    })
6076    public int getLayoutDirection() {
6077        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6078        if (targetSdkVersion < JELLY_BEAN_MR1) {
6079            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6080            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6081        }
6082        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6083                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6084    }
6085
6086    /**
6087     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6088     * layout attribute and/or the inherited value from the parent
6089     *
6090     * @return true if the layout is right-to-left.
6091     *
6092     * @hide
6093     */
6094    @ViewDebug.ExportedProperty(category = "layout")
6095    public boolean isLayoutRtl() {
6096        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6097    }
6098
6099    /**
6100     * Indicates whether the view is currently tracking transient state that the
6101     * app should not need to concern itself with saving and restoring, but that
6102     * the framework should take special note to preserve when possible.
6103     *
6104     * <p>A view with transient state cannot be trivially rebound from an external
6105     * data source, such as an adapter binding item views in a list. This may be
6106     * because the view is performing an animation, tracking user selection
6107     * of content, or similar.</p>
6108     *
6109     * @return true if the view has transient state
6110     */
6111    @ViewDebug.ExportedProperty(category = "layout")
6112    public boolean hasTransientState() {
6113        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6114    }
6115
6116    /**
6117     * Set whether this view is currently tracking transient state that the
6118     * framework should attempt to preserve when possible. This flag is reference counted,
6119     * so every call to setHasTransientState(true) should be paired with a later call
6120     * to setHasTransientState(false).
6121     *
6122     * <p>A view with transient state cannot be trivially rebound from an external
6123     * data source, such as an adapter binding item views in a list. This may be
6124     * because the view is performing an animation, tracking user selection
6125     * of content, or similar.</p>
6126     *
6127     * @param hasTransientState true if this view has transient state
6128     */
6129    public void setHasTransientState(boolean hasTransientState) {
6130        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6131                mTransientStateCount - 1;
6132        if (mTransientStateCount < 0) {
6133            mTransientStateCount = 0;
6134            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6135                    "unmatched pair of setHasTransientState calls");
6136        } else if ((hasTransientState && mTransientStateCount == 1) ||
6137                (!hasTransientState && mTransientStateCount == 0)) {
6138            // update flag if we've just incremented up from 0 or decremented down to 0
6139            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6140                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6141            if (mParent != null) {
6142                try {
6143                    mParent.childHasTransientStateChanged(this, hasTransientState);
6144                } catch (AbstractMethodError e) {
6145                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6146                            " does not fully implement ViewParent", e);
6147                }
6148            }
6149        }
6150    }
6151
6152    /**
6153     * Returns true if this view is currently attached to a window.
6154     */
6155    public boolean isAttachedToWindow() {
6156        return mAttachInfo != null;
6157    }
6158
6159    /**
6160     * Returns true if this view has been through at least one layout since it
6161     * was last attached to or detached from a window.
6162     */
6163    public boolean isLaidOut() {
6164        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6165    }
6166
6167    /**
6168     * If this view doesn't do any drawing on its own, set this flag to
6169     * allow further optimizations. By default, this flag is not set on
6170     * View, but could be set on some View subclasses such as ViewGroup.
6171     *
6172     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6173     * you should clear this flag.
6174     *
6175     * @param willNotDraw whether or not this View draw on its own
6176     */
6177    public void setWillNotDraw(boolean willNotDraw) {
6178        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6179    }
6180
6181    /**
6182     * Returns whether or not this View draws on its own.
6183     *
6184     * @return true if this view has nothing to draw, false otherwise
6185     */
6186    @ViewDebug.ExportedProperty(category = "drawing")
6187    public boolean willNotDraw() {
6188        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6189    }
6190
6191    /**
6192     * When a View's drawing cache is enabled, drawing is redirected to an
6193     * offscreen bitmap. Some views, like an ImageView, must be able to
6194     * bypass this mechanism if they already draw a single bitmap, to avoid
6195     * unnecessary usage of the memory.
6196     *
6197     * @param willNotCacheDrawing true if this view does not cache its
6198     *        drawing, false otherwise
6199     */
6200    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6201        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6202    }
6203
6204    /**
6205     * Returns whether or not this View can cache its drawing or not.
6206     *
6207     * @return true if this view does not cache its drawing, false otherwise
6208     */
6209    @ViewDebug.ExportedProperty(category = "drawing")
6210    public boolean willNotCacheDrawing() {
6211        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6212    }
6213
6214    /**
6215     * Indicates whether this view reacts to click events or not.
6216     *
6217     * @return true if the view is clickable, false otherwise
6218     *
6219     * @see #setClickable(boolean)
6220     * @attr ref android.R.styleable#View_clickable
6221     */
6222    @ViewDebug.ExportedProperty
6223    public boolean isClickable() {
6224        return (mViewFlags & CLICKABLE) == CLICKABLE;
6225    }
6226
6227    /**
6228     * Enables or disables click events for this view. When a view
6229     * is clickable it will change its state to "pressed" on every click.
6230     * Subclasses should set the view clickable to visually react to
6231     * user's clicks.
6232     *
6233     * @param clickable true to make the view clickable, false otherwise
6234     *
6235     * @see #isClickable()
6236     * @attr ref android.R.styleable#View_clickable
6237     */
6238    public void setClickable(boolean clickable) {
6239        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6240    }
6241
6242    /**
6243     * Indicates whether this view reacts to long click events or not.
6244     *
6245     * @return true if the view is long clickable, false otherwise
6246     *
6247     * @see #setLongClickable(boolean)
6248     * @attr ref android.R.styleable#View_longClickable
6249     */
6250    public boolean isLongClickable() {
6251        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6252    }
6253
6254    /**
6255     * Enables or disables long click events for this view. When a view is long
6256     * clickable it reacts to the user holding down the button for a longer
6257     * duration than a tap. This event can either launch the listener or a
6258     * context menu.
6259     *
6260     * @param longClickable true to make the view long clickable, false otherwise
6261     * @see #isLongClickable()
6262     * @attr ref android.R.styleable#View_longClickable
6263     */
6264    public void setLongClickable(boolean longClickable) {
6265        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6266    }
6267
6268    /**
6269     * Sets the pressed state for this view.
6270     *
6271     * @see #isClickable()
6272     * @see #setClickable(boolean)
6273     *
6274     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6275     *        the View's internal state from a previously set "pressed" state.
6276     */
6277    public void setPressed(boolean pressed) {
6278        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6279
6280        if (pressed) {
6281            mPrivateFlags |= PFLAG_PRESSED;
6282        } else {
6283            mPrivateFlags &= ~PFLAG_PRESSED;
6284        }
6285
6286        if (needsRefresh) {
6287            refreshDrawableState();
6288        }
6289        dispatchSetPressed(pressed);
6290    }
6291
6292    /**
6293     * Dispatch setPressed to all of this View's children.
6294     *
6295     * @see #setPressed(boolean)
6296     *
6297     * @param pressed The new pressed state
6298     */
6299    protected void dispatchSetPressed(boolean pressed) {
6300    }
6301
6302    /**
6303     * Indicates whether the view is currently in pressed state. Unless
6304     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6305     * the pressed state.
6306     *
6307     * @see #setPressed(boolean)
6308     * @see #isClickable()
6309     * @see #setClickable(boolean)
6310     *
6311     * @return true if the view is currently pressed, false otherwise
6312     */
6313    public boolean isPressed() {
6314        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6315    }
6316
6317    /**
6318     * Indicates whether this view will save its state (that is,
6319     * whether its {@link #onSaveInstanceState} method will be called).
6320     *
6321     * @return Returns true if the view state saving is enabled, else false.
6322     *
6323     * @see #setSaveEnabled(boolean)
6324     * @attr ref android.R.styleable#View_saveEnabled
6325     */
6326    public boolean isSaveEnabled() {
6327        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6328    }
6329
6330    /**
6331     * Controls whether the saving of this view's state is
6332     * enabled (that is, whether its {@link #onSaveInstanceState} method
6333     * will be called).  Note that even if freezing is enabled, the
6334     * view still must have an id assigned to it (via {@link #setId(int)})
6335     * for its state to be saved.  This flag can only disable the
6336     * saving of this view; any child views may still have their state saved.
6337     *
6338     * @param enabled Set to false to <em>disable</em> state saving, or true
6339     * (the default) to allow it.
6340     *
6341     * @see #isSaveEnabled()
6342     * @see #setId(int)
6343     * @see #onSaveInstanceState()
6344     * @attr ref android.R.styleable#View_saveEnabled
6345     */
6346    public void setSaveEnabled(boolean enabled) {
6347        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6348    }
6349
6350    /**
6351     * Gets whether the framework should discard touches when the view's
6352     * window is obscured by another visible window.
6353     * Refer to the {@link View} security documentation for more details.
6354     *
6355     * @return True if touch filtering is enabled.
6356     *
6357     * @see #setFilterTouchesWhenObscured(boolean)
6358     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6359     */
6360    @ViewDebug.ExportedProperty
6361    public boolean getFilterTouchesWhenObscured() {
6362        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6363    }
6364
6365    /**
6366     * Sets whether the framework should discard touches when the view's
6367     * window is obscured by another visible window.
6368     * Refer to the {@link View} security documentation for more details.
6369     *
6370     * @param enabled True if touch filtering should be enabled.
6371     *
6372     * @see #getFilterTouchesWhenObscured
6373     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6374     */
6375    public void setFilterTouchesWhenObscured(boolean enabled) {
6376        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6377                FILTER_TOUCHES_WHEN_OBSCURED);
6378    }
6379
6380    /**
6381     * Indicates whether the entire hierarchy under this view will save its
6382     * state when a state saving traversal occurs from its parent.  The default
6383     * is true; if false, these views will not be saved unless
6384     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6385     *
6386     * @return Returns true if the view state saving from parent is enabled, else false.
6387     *
6388     * @see #setSaveFromParentEnabled(boolean)
6389     */
6390    public boolean isSaveFromParentEnabled() {
6391        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6392    }
6393
6394    /**
6395     * Controls whether the entire hierarchy under this view will save its
6396     * state when a state saving traversal occurs from its parent.  The default
6397     * is true; if false, these views will not be saved unless
6398     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6399     *
6400     * @param enabled Set to false to <em>disable</em> state saving, or true
6401     * (the default) to allow it.
6402     *
6403     * @see #isSaveFromParentEnabled()
6404     * @see #setId(int)
6405     * @see #onSaveInstanceState()
6406     */
6407    public void setSaveFromParentEnabled(boolean enabled) {
6408        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6409    }
6410
6411
6412    /**
6413     * Returns whether this View is able to take focus.
6414     *
6415     * @return True if this view can take focus, or false otherwise.
6416     * @attr ref android.R.styleable#View_focusable
6417     */
6418    @ViewDebug.ExportedProperty(category = "focus")
6419    public final boolean isFocusable() {
6420        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6421    }
6422
6423    /**
6424     * When a view is focusable, it may not want to take focus when in touch mode.
6425     * For example, a button would like focus when the user is navigating via a D-pad
6426     * so that the user can click on it, but once the user starts touching the screen,
6427     * the button shouldn't take focus
6428     * @return Whether the view is focusable in touch mode.
6429     * @attr ref android.R.styleable#View_focusableInTouchMode
6430     */
6431    @ViewDebug.ExportedProperty
6432    public final boolean isFocusableInTouchMode() {
6433        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6434    }
6435
6436    /**
6437     * Find the nearest view in the specified direction that can take focus.
6438     * This does not actually give focus to that view.
6439     *
6440     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6441     *
6442     * @return The nearest focusable in the specified direction, or null if none
6443     *         can be found.
6444     */
6445    public View focusSearch(int direction) {
6446        if (mParent != null) {
6447            return mParent.focusSearch(this, direction);
6448        } else {
6449            return null;
6450        }
6451    }
6452
6453    /**
6454     * This method is the last chance for the focused view and its ancestors to
6455     * respond to an arrow key. This is called when the focused view did not
6456     * consume the key internally, nor could the view system find a new view in
6457     * the requested direction to give focus to.
6458     *
6459     * @param focused The currently focused view.
6460     * @param direction The direction focus wants to move. One of FOCUS_UP,
6461     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6462     * @return True if the this view consumed this unhandled move.
6463     */
6464    public boolean dispatchUnhandledMove(View focused, int direction) {
6465        return false;
6466    }
6467
6468    /**
6469     * If a user manually specified the next view id for a particular direction,
6470     * use the root to look up the view.
6471     * @param root The root view of the hierarchy containing this view.
6472     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6473     * or FOCUS_BACKWARD.
6474     * @return The user specified next view, or null if there is none.
6475     */
6476    View findUserSetNextFocus(View root, int direction) {
6477        switch (direction) {
6478            case FOCUS_LEFT:
6479                if (mNextFocusLeftId == View.NO_ID) return null;
6480                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6481            case FOCUS_RIGHT:
6482                if (mNextFocusRightId == View.NO_ID) return null;
6483                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6484            case FOCUS_UP:
6485                if (mNextFocusUpId == View.NO_ID) return null;
6486                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6487            case FOCUS_DOWN:
6488                if (mNextFocusDownId == View.NO_ID) return null;
6489                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6490            case FOCUS_FORWARD:
6491                if (mNextFocusForwardId == View.NO_ID) return null;
6492                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6493            case FOCUS_BACKWARD: {
6494                if (mID == View.NO_ID) return null;
6495                final int id = mID;
6496                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6497                    @Override
6498                    public boolean apply(View t) {
6499                        return t.mNextFocusForwardId == id;
6500                    }
6501                });
6502            }
6503        }
6504        return null;
6505    }
6506
6507    private View findViewInsideOutShouldExist(View root, int id) {
6508        if (mMatchIdPredicate == null) {
6509            mMatchIdPredicate = new MatchIdPredicate();
6510        }
6511        mMatchIdPredicate.mId = id;
6512        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6513        if (result == null) {
6514            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6515        }
6516        return result;
6517    }
6518
6519    /**
6520     * Find and return all focusable views that are descendants of this view,
6521     * possibly including this view if it is focusable itself.
6522     *
6523     * @param direction The direction of the focus
6524     * @return A list of focusable views
6525     */
6526    public ArrayList<View> getFocusables(int direction) {
6527        ArrayList<View> result = new ArrayList<View>(24);
6528        addFocusables(result, direction);
6529        return result;
6530    }
6531
6532    /**
6533     * Add any focusable views that are descendants of this view (possibly
6534     * including this view if it is focusable itself) to views.  If we are in touch mode,
6535     * only add views that are also focusable in touch mode.
6536     *
6537     * @param views Focusable views found so far
6538     * @param direction The direction of the focus
6539     */
6540    public void addFocusables(ArrayList<View> views, int direction) {
6541        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6542    }
6543
6544    /**
6545     * Adds any focusable views that are descendants of this view (possibly
6546     * including this view if it is focusable itself) to views. This method
6547     * adds all focusable views regardless if we are in touch mode or
6548     * only views focusable in touch mode if we are in touch mode or
6549     * only views that can take accessibility focus if accessibility is enabeld
6550     * depending on the focusable mode paramater.
6551     *
6552     * @param views Focusable views found so far or null if all we are interested is
6553     *        the number of focusables.
6554     * @param direction The direction of the focus.
6555     * @param focusableMode The type of focusables to be added.
6556     *
6557     * @see #FOCUSABLES_ALL
6558     * @see #FOCUSABLES_TOUCH_MODE
6559     */
6560    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6561        if (views == null) {
6562            return;
6563        }
6564        if (!isFocusable()) {
6565            return;
6566        }
6567        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6568                && isInTouchMode() && !isFocusableInTouchMode()) {
6569            return;
6570        }
6571        views.add(this);
6572    }
6573
6574    /**
6575     * Finds the Views that contain given text. The containment is case insensitive.
6576     * The search is performed by either the text that the View renders or the content
6577     * description that describes the view for accessibility purposes and the view does
6578     * not render or both. Clients can specify how the search is to be performed via
6579     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6580     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6581     *
6582     * @param outViews The output list of matching Views.
6583     * @param searched The text to match against.
6584     *
6585     * @see #FIND_VIEWS_WITH_TEXT
6586     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6587     * @see #setContentDescription(CharSequence)
6588     */
6589    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6590        if (getAccessibilityNodeProvider() != null) {
6591            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6592                outViews.add(this);
6593            }
6594        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6595                && (searched != null && searched.length() > 0)
6596                && (mContentDescription != null && mContentDescription.length() > 0)) {
6597            String searchedLowerCase = searched.toString().toLowerCase();
6598            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6599            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6600                outViews.add(this);
6601            }
6602        }
6603    }
6604
6605    /**
6606     * Find and return all touchable views that are descendants of this view,
6607     * possibly including this view if it is touchable itself.
6608     *
6609     * @return A list of touchable views
6610     */
6611    public ArrayList<View> getTouchables() {
6612        ArrayList<View> result = new ArrayList<View>();
6613        addTouchables(result);
6614        return result;
6615    }
6616
6617    /**
6618     * Add any touchable views that are descendants of this view (possibly
6619     * including this view if it is touchable itself) to views.
6620     *
6621     * @param views Touchable views found so far
6622     */
6623    public void addTouchables(ArrayList<View> views) {
6624        final int viewFlags = mViewFlags;
6625
6626        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6627                && (viewFlags & ENABLED_MASK) == ENABLED) {
6628            views.add(this);
6629        }
6630    }
6631
6632    /**
6633     * Returns whether this View is accessibility focused.
6634     *
6635     * @return True if this View is accessibility focused.
6636     */
6637    boolean isAccessibilityFocused() {
6638        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6639    }
6640
6641    /**
6642     * Call this to try to give accessibility focus to this view.
6643     *
6644     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6645     * returns false or the view is no visible or the view already has accessibility
6646     * focus.
6647     *
6648     * See also {@link #focusSearch(int)}, which is what you call to say that you
6649     * have focus, and you want your parent to look for the next one.
6650     *
6651     * @return Whether this view actually took accessibility focus.
6652     *
6653     * @hide
6654     */
6655    public boolean requestAccessibilityFocus() {
6656        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6657        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6658            return false;
6659        }
6660        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6661            return false;
6662        }
6663        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6664            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6665            ViewRootImpl viewRootImpl = getViewRootImpl();
6666            if (viewRootImpl != null) {
6667                viewRootImpl.setAccessibilityFocus(this, null);
6668            }
6669            invalidate();
6670            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6671            return true;
6672        }
6673        return false;
6674    }
6675
6676    /**
6677     * Call this to try to clear accessibility focus of this view.
6678     *
6679     * See also {@link #focusSearch(int)}, which is what you call to say that you
6680     * have focus, and you want your parent to look for the next one.
6681     *
6682     * @hide
6683     */
6684    public void clearAccessibilityFocus() {
6685        clearAccessibilityFocusNoCallbacks();
6686        // Clear the global reference of accessibility focus if this
6687        // view or any of its descendants had accessibility focus.
6688        ViewRootImpl viewRootImpl = getViewRootImpl();
6689        if (viewRootImpl != null) {
6690            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6691            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6692                viewRootImpl.setAccessibilityFocus(null, null);
6693            }
6694        }
6695    }
6696
6697    private void sendAccessibilityHoverEvent(int eventType) {
6698        // Since we are not delivering to a client accessibility events from not
6699        // important views (unless the clinet request that) we need to fire the
6700        // event from the deepest view exposed to the client. As a consequence if
6701        // the user crosses a not exposed view the client will see enter and exit
6702        // of the exposed predecessor followed by and enter and exit of that same
6703        // predecessor when entering and exiting the not exposed descendant. This
6704        // is fine since the client has a clear idea which view is hovered at the
6705        // price of a couple more events being sent. This is a simple and
6706        // working solution.
6707        View source = this;
6708        while (true) {
6709            if (source.includeForAccessibility()) {
6710                source.sendAccessibilityEvent(eventType);
6711                return;
6712            }
6713            ViewParent parent = source.getParent();
6714            if (parent instanceof View) {
6715                source = (View) parent;
6716            } else {
6717                return;
6718            }
6719        }
6720    }
6721
6722    /**
6723     * Clears accessibility focus without calling any callback methods
6724     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6725     * is used for clearing accessibility focus when giving this focus to
6726     * another view.
6727     */
6728    void clearAccessibilityFocusNoCallbacks() {
6729        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6730            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6731            invalidate();
6732            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6733        }
6734    }
6735
6736    /**
6737     * Call this to try to give focus to a specific view or to one of its
6738     * descendants.
6739     *
6740     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6741     * false), or if it is focusable and it is not focusable in touch mode
6742     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6743     *
6744     * See also {@link #focusSearch(int)}, which is what you call to say that you
6745     * have focus, and you want your parent to look for the next one.
6746     *
6747     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6748     * {@link #FOCUS_DOWN} and <code>null</code>.
6749     *
6750     * @return Whether this view or one of its descendants actually took focus.
6751     */
6752    public final boolean requestFocus() {
6753        return requestFocus(View.FOCUS_DOWN);
6754    }
6755
6756    /**
6757     * Call this to try to give focus to a specific view or to one of its
6758     * descendants and give it a hint about what direction focus is heading.
6759     *
6760     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6761     * false), or if it is focusable and it is not focusable in touch mode
6762     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6763     *
6764     * See also {@link #focusSearch(int)}, which is what you call to say that you
6765     * have focus, and you want your parent to look for the next one.
6766     *
6767     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6768     * <code>null</code> set for the previously focused rectangle.
6769     *
6770     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6771     * @return Whether this view or one of its descendants actually took focus.
6772     */
6773    public final boolean requestFocus(int direction) {
6774        return requestFocus(direction, null);
6775    }
6776
6777    /**
6778     * Call this to try to give focus to a specific view or to one of its descendants
6779     * and give it hints about the direction and a specific rectangle that the focus
6780     * is coming from.  The rectangle can help give larger views a finer grained hint
6781     * about where focus is coming from, and therefore, where to show selection, or
6782     * forward focus change internally.
6783     *
6784     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6785     * false), or if it is focusable and it is not focusable in touch mode
6786     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6787     *
6788     * A View will not take focus if it is not visible.
6789     *
6790     * A View will not take focus if one of its parents has
6791     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6792     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6793     *
6794     * See also {@link #focusSearch(int)}, which is what you call to say that you
6795     * have focus, and you want your parent to look for the next one.
6796     *
6797     * You may wish to override this method if your custom {@link View} has an internal
6798     * {@link View} that it wishes to forward the request to.
6799     *
6800     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6801     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6802     *        to give a finer grained hint about where focus is coming from.  May be null
6803     *        if there is no hint.
6804     * @return Whether this view or one of its descendants actually took focus.
6805     */
6806    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6807        return requestFocusNoSearch(direction, previouslyFocusedRect);
6808    }
6809
6810    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6811        // need to be focusable
6812        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6813                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6814            return false;
6815        }
6816
6817        // need to be focusable in touch mode if in touch mode
6818        if (isInTouchMode() &&
6819            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6820               return false;
6821        }
6822
6823        // need to not have any parents blocking us
6824        if (hasAncestorThatBlocksDescendantFocus()) {
6825            return false;
6826        }
6827
6828        handleFocusGainInternal(direction, previouslyFocusedRect);
6829        return true;
6830    }
6831
6832    /**
6833     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6834     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6835     * touch mode to request focus when they are touched.
6836     *
6837     * @return Whether this view or one of its descendants actually took focus.
6838     *
6839     * @see #isInTouchMode()
6840     *
6841     */
6842    public final boolean requestFocusFromTouch() {
6843        // Leave touch mode if we need to
6844        if (isInTouchMode()) {
6845            ViewRootImpl viewRoot = getViewRootImpl();
6846            if (viewRoot != null) {
6847                viewRoot.ensureTouchMode(false);
6848            }
6849        }
6850        return requestFocus(View.FOCUS_DOWN);
6851    }
6852
6853    /**
6854     * @return Whether any ancestor of this view blocks descendant focus.
6855     */
6856    private boolean hasAncestorThatBlocksDescendantFocus() {
6857        ViewParent ancestor = mParent;
6858        while (ancestor instanceof ViewGroup) {
6859            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6860            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6861                return true;
6862            } else {
6863                ancestor = vgAncestor.getParent();
6864            }
6865        }
6866        return false;
6867    }
6868
6869    /**
6870     * Gets the mode for determining whether this View is important for accessibility
6871     * which is if it fires accessibility events and if it is reported to
6872     * accessibility services that query the screen.
6873     *
6874     * @return The mode for determining whether a View is important for accessibility.
6875     *
6876     * @attr ref android.R.styleable#View_importantForAccessibility
6877     *
6878     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6879     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6880     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6881     */
6882    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6883            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6884            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6885            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6886        })
6887    public int getImportantForAccessibility() {
6888        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6889                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6890    }
6891
6892    /**
6893     * Sets how to determine whether this view is important for accessibility
6894     * which is if it fires accessibility events and if it is reported to
6895     * accessibility services that query the screen.
6896     *
6897     * @param mode How to determine whether this view is important for accessibility.
6898     *
6899     * @attr ref android.R.styleable#View_importantForAccessibility
6900     *
6901     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6902     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6903     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6904     */
6905    public void setImportantForAccessibility(int mode) {
6906        final boolean oldIncludeForAccessibility = includeForAccessibility();
6907        if (mode != getImportantForAccessibility()) {
6908            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6909            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6910                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6911            if (oldIncludeForAccessibility != includeForAccessibility()) {
6912                notifySubtreeAccessibilityStateChangedIfNeeded();
6913            } else {
6914                notifyViewAccessibilityStateChangedIfNeeded();
6915            }
6916        }
6917    }
6918
6919    /**
6920     * Gets whether this view should be exposed for accessibility.
6921     *
6922     * @return Whether the view is exposed for accessibility.
6923     *
6924     * @hide
6925     */
6926    public boolean isImportantForAccessibility() {
6927        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6928                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6929        switch (mode) {
6930            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6931                return true;
6932            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6933                return false;
6934            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6935                return isActionableForAccessibility() || hasListenersForAccessibility()
6936                        || getAccessibilityNodeProvider() != null;
6937            default:
6938                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6939                        + mode);
6940        }
6941    }
6942
6943    /**
6944     * Gets the parent for accessibility purposes. Note that the parent for
6945     * accessibility is not necessary the immediate parent. It is the first
6946     * predecessor that is important for accessibility.
6947     *
6948     * @return The parent for accessibility purposes.
6949     */
6950    public ViewParent getParentForAccessibility() {
6951        if (mParent instanceof View) {
6952            View parentView = (View) mParent;
6953            if (parentView.includeForAccessibility()) {
6954                return mParent;
6955            } else {
6956                return mParent.getParentForAccessibility();
6957            }
6958        }
6959        return null;
6960    }
6961
6962    /**
6963     * Adds the children of a given View for accessibility. Since some Views are
6964     * not important for accessibility the children for accessibility are not
6965     * necessarily direct children of the view, rather they are the first level of
6966     * descendants important for accessibility.
6967     *
6968     * @param children The list of children for accessibility.
6969     */
6970    public void addChildrenForAccessibility(ArrayList<View> children) {
6971        if (includeForAccessibility()) {
6972            children.add(this);
6973        }
6974    }
6975
6976    /**
6977     * Whether to regard this view for accessibility. A view is regarded for
6978     * accessibility if it is important for accessibility or the querying
6979     * accessibility service has explicitly requested that view not
6980     * important for accessibility are regarded.
6981     *
6982     * @return Whether to regard the view for accessibility.
6983     *
6984     * @hide
6985     */
6986    public boolean includeForAccessibility() {
6987        //noinspection SimplifiableIfStatement
6988        if (mAttachInfo != null) {
6989            return (mAttachInfo.mAccessibilityFetchFlags
6990                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6991                    || isImportantForAccessibility();
6992        }
6993        return false;
6994    }
6995
6996    /**
6997     * Returns whether the View is considered actionable from
6998     * accessibility perspective. Such view are important for
6999     * accessibility.
7000     *
7001     * @return True if the view is actionable for accessibility.
7002     *
7003     * @hide
7004     */
7005    public boolean isActionableForAccessibility() {
7006        return (isClickable() || isLongClickable() || isFocusable());
7007    }
7008
7009    /**
7010     * Returns whether the View has registered callbacks wich makes it
7011     * important for accessibility.
7012     *
7013     * @return True if the view is actionable for accessibility.
7014     */
7015    private boolean hasListenersForAccessibility() {
7016        ListenerInfo info = getListenerInfo();
7017        return mTouchDelegate != null || info.mOnKeyListener != null
7018                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7019                || info.mOnHoverListener != null || info.mOnDragListener != null;
7020    }
7021
7022    /**
7023     * Notifies that the accessibility state of this view changed. The change
7024     * is local to this view and does not represent structural changes such
7025     * as children and parent. For example, the view became focusable. The
7026     * notification is at at most once every
7027     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7028     * to avoid unnecessary load to the system. Also once a view has a pending
7029     * notifucation this method is a NOP until the notification has been sent.
7030     *
7031     * @hide
7032     */
7033    public void notifyViewAccessibilityStateChangedIfNeeded() {
7034        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7035            return;
7036        }
7037        if (mSendViewStateChangedAccessibilityEvent == null) {
7038            mSendViewStateChangedAccessibilityEvent =
7039                    new SendViewStateChangedAccessibilityEvent();
7040        }
7041        mSendViewStateChangedAccessibilityEvent.runOrPost();
7042    }
7043
7044    /**
7045     * Notifies that the accessibility state of this view changed. The change
7046     * is *not* local to this view and does represent structural changes such
7047     * as children and parent. For example, the view size changed. The
7048     * notification is at at most once every
7049     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7050     * to avoid unnecessary load to the system. Also once a view has a pending
7051     * notifucation this method is a NOP until the notification has been sent.
7052     *
7053     * @hide
7054     */
7055    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7056        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7057            return;
7058        }
7059        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7060            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7061            if (mParent != null) {
7062                try {
7063                    mParent.childAccessibilityStateChanged(this);
7064                } catch (AbstractMethodError e) {
7065                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7066                            " does not fully implement ViewParent", e);
7067                }
7068            }
7069        }
7070    }
7071
7072    /**
7073     * Reset the flag indicating the accessibility state of the subtree rooted
7074     * at this view changed.
7075     */
7076    void resetSubtreeAccessibilityStateChanged() {
7077        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7078    }
7079
7080    /**
7081     * Performs the specified accessibility action on the view. For
7082     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7083     * <p>
7084     * If an {@link AccessibilityDelegate} has been specified via calling
7085     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7086     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7087     * is responsible for handling this call.
7088     * </p>
7089     *
7090     * @param action The action to perform.
7091     * @param arguments Optional action arguments.
7092     * @return Whether the action was performed.
7093     */
7094    public boolean performAccessibilityAction(int action, Bundle arguments) {
7095      if (mAccessibilityDelegate != null) {
7096          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7097      } else {
7098          return performAccessibilityActionInternal(action, arguments);
7099      }
7100    }
7101
7102   /**
7103    * @see #performAccessibilityAction(int, Bundle)
7104    *
7105    * Note: Called from the default {@link AccessibilityDelegate}.
7106    */
7107    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7108        switch (action) {
7109            case AccessibilityNodeInfo.ACTION_CLICK: {
7110                if (isClickable()) {
7111                    performClick();
7112                    return true;
7113                }
7114            } break;
7115            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7116                if (isLongClickable()) {
7117                    performLongClick();
7118                    return true;
7119                }
7120            } break;
7121            case AccessibilityNodeInfo.ACTION_FOCUS: {
7122                if (!hasFocus()) {
7123                    // Get out of touch mode since accessibility
7124                    // wants to move focus around.
7125                    getViewRootImpl().ensureTouchMode(false);
7126                    return requestFocus();
7127                }
7128            } break;
7129            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7130                if (hasFocus()) {
7131                    clearFocus();
7132                    return !isFocused();
7133                }
7134            } break;
7135            case AccessibilityNodeInfo.ACTION_SELECT: {
7136                if (!isSelected()) {
7137                    setSelected(true);
7138                    return isSelected();
7139                }
7140            } break;
7141            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7142                if (isSelected()) {
7143                    setSelected(false);
7144                    return !isSelected();
7145                }
7146            } break;
7147            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7148                if (!isAccessibilityFocused()) {
7149                    return requestAccessibilityFocus();
7150                }
7151            } break;
7152            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7153                if (isAccessibilityFocused()) {
7154                    clearAccessibilityFocus();
7155                    return true;
7156                }
7157            } break;
7158            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7159                if (arguments != null) {
7160                    final int granularity = arguments.getInt(
7161                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7162                    final boolean extendSelection = arguments.getBoolean(
7163                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7164                    return traverseAtGranularity(granularity, true, extendSelection);
7165                }
7166            } break;
7167            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7168                if (arguments != null) {
7169                    final int granularity = arguments.getInt(
7170                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7171                    final boolean extendSelection = arguments.getBoolean(
7172                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7173                    return traverseAtGranularity(granularity, false, extendSelection);
7174                }
7175            } break;
7176            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7177                CharSequence text = getIterableTextForAccessibility();
7178                if (text == null) {
7179                    return false;
7180                }
7181                final int start = (arguments != null) ? arguments.getInt(
7182                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7183                final int end = (arguments != null) ? arguments.getInt(
7184                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7185                // Only cursor position can be specified (selection length == 0)
7186                if ((getAccessibilitySelectionStart() != start
7187                        || getAccessibilitySelectionEnd() != end)
7188                        && (start == end)) {
7189                    setAccessibilitySelection(start, end);
7190                    notifyViewAccessibilityStateChangedIfNeeded();
7191                    return true;
7192                }
7193            } break;
7194        }
7195        return false;
7196    }
7197
7198    private boolean traverseAtGranularity(int granularity, boolean forward,
7199            boolean extendSelection) {
7200        CharSequence text = getIterableTextForAccessibility();
7201        if (text == null || text.length() == 0) {
7202            return false;
7203        }
7204        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7205        if (iterator == null) {
7206            return false;
7207        }
7208        int current = getAccessibilitySelectionEnd();
7209        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7210            current = forward ? 0 : text.length();
7211        }
7212        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7213        if (range == null) {
7214            return false;
7215        }
7216        final int segmentStart = range[0];
7217        final int segmentEnd = range[1];
7218        int selectionStart;
7219        int selectionEnd;
7220        if (extendSelection && isAccessibilitySelectionExtendable()) {
7221            selectionStart = getAccessibilitySelectionStart();
7222            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7223                selectionStart = forward ? segmentStart : segmentEnd;
7224            }
7225            selectionEnd = forward ? segmentEnd : segmentStart;
7226        } else {
7227            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7228        }
7229        setAccessibilitySelection(selectionStart, selectionEnd);
7230        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7231                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7232        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7233        return true;
7234    }
7235
7236    /**
7237     * Gets the text reported for accessibility purposes.
7238     *
7239     * @return The accessibility text.
7240     *
7241     * @hide
7242     */
7243    public CharSequence getIterableTextForAccessibility() {
7244        return getContentDescription();
7245    }
7246
7247    /**
7248     * Gets whether accessibility selection can be extended.
7249     *
7250     * @return If selection is extensible.
7251     *
7252     * @hide
7253     */
7254    public boolean isAccessibilitySelectionExtendable() {
7255        return false;
7256    }
7257
7258    /**
7259     * @hide
7260     */
7261    public int getAccessibilitySelectionStart() {
7262        return mAccessibilityCursorPosition;
7263    }
7264
7265    /**
7266     * @hide
7267     */
7268    public int getAccessibilitySelectionEnd() {
7269        return getAccessibilitySelectionStart();
7270    }
7271
7272    /**
7273     * @hide
7274     */
7275    public void setAccessibilitySelection(int start, int end) {
7276        if (start ==  end && end == mAccessibilityCursorPosition) {
7277            return;
7278        }
7279        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7280            mAccessibilityCursorPosition = start;
7281        } else {
7282            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7283        }
7284        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7285    }
7286
7287    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7288            int fromIndex, int toIndex) {
7289        if (mParent == null) {
7290            return;
7291        }
7292        AccessibilityEvent event = AccessibilityEvent.obtain(
7293                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7294        onInitializeAccessibilityEvent(event);
7295        onPopulateAccessibilityEvent(event);
7296        event.setFromIndex(fromIndex);
7297        event.setToIndex(toIndex);
7298        event.setAction(action);
7299        event.setMovementGranularity(granularity);
7300        mParent.requestSendAccessibilityEvent(this, event);
7301    }
7302
7303    /**
7304     * @hide
7305     */
7306    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7307        switch (granularity) {
7308            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7309                CharSequence text = getIterableTextForAccessibility();
7310                if (text != null && text.length() > 0) {
7311                    CharacterTextSegmentIterator iterator =
7312                        CharacterTextSegmentIterator.getInstance(
7313                                mContext.getResources().getConfiguration().locale);
7314                    iterator.initialize(text.toString());
7315                    return iterator;
7316                }
7317            } break;
7318            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7319                CharSequence text = getIterableTextForAccessibility();
7320                if (text != null && text.length() > 0) {
7321                    WordTextSegmentIterator iterator =
7322                        WordTextSegmentIterator.getInstance(
7323                                mContext.getResources().getConfiguration().locale);
7324                    iterator.initialize(text.toString());
7325                    return iterator;
7326                }
7327            } break;
7328            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7329                CharSequence text = getIterableTextForAccessibility();
7330                if (text != null && text.length() > 0) {
7331                    ParagraphTextSegmentIterator iterator =
7332                        ParagraphTextSegmentIterator.getInstance();
7333                    iterator.initialize(text.toString());
7334                    return iterator;
7335                }
7336            } break;
7337        }
7338        return null;
7339    }
7340
7341    /**
7342     * @hide
7343     */
7344    public void dispatchStartTemporaryDetach() {
7345        clearAccessibilityFocus();
7346        clearDisplayList();
7347
7348        onStartTemporaryDetach();
7349    }
7350
7351    /**
7352     * This is called when a container is going to temporarily detach a child, with
7353     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7354     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7355     * {@link #onDetachedFromWindow()} when the container is done.
7356     */
7357    public void onStartTemporaryDetach() {
7358        removeUnsetPressCallback();
7359        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7360    }
7361
7362    /**
7363     * @hide
7364     */
7365    public void dispatchFinishTemporaryDetach() {
7366        onFinishTemporaryDetach();
7367    }
7368
7369    /**
7370     * Called after {@link #onStartTemporaryDetach} when the container is done
7371     * changing the view.
7372     */
7373    public void onFinishTemporaryDetach() {
7374    }
7375
7376    /**
7377     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7378     * for this view's window.  Returns null if the view is not currently attached
7379     * to the window.  Normally you will not need to use this directly, but
7380     * just use the standard high-level event callbacks like
7381     * {@link #onKeyDown(int, KeyEvent)}.
7382     */
7383    public KeyEvent.DispatcherState getKeyDispatcherState() {
7384        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7385    }
7386
7387    /**
7388     * Dispatch a key event before it is processed by any input method
7389     * associated with the view hierarchy.  This can be used to intercept
7390     * key events in special situations before the IME consumes them; a
7391     * typical example would be handling the BACK key to update the application's
7392     * UI instead of allowing the IME to see it and close itself.
7393     *
7394     * @param event The key event to be dispatched.
7395     * @return True if the event was handled, false otherwise.
7396     */
7397    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7398        return onKeyPreIme(event.getKeyCode(), event);
7399    }
7400
7401    /**
7402     * Dispatch a key event to the next view on the focus path. This path runs
7403     * from the top of the view tree down to the currently focused view. If this
7404     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7405     * the next node down the focus path. This method also fires any key
7406     * listeners.
7407     *
7408     * @param event The key event to be dispatched.
7409     * @return True if the event was handled, false otherwise.
7410     */
7411    public boolean dispatchKeyEvent(KeyEvent event) {
7412        if (mInputEventConsistencyVerifier != null) {
7413            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7414        }
7415
7416        // Give any attached key listener a first crack at the event.
7417        //noinspection SimplifiableIfStatement
7418        ListenerInfo li = mListenerInfo;
7419        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7420                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7421            return true;
7422        }
7423
7424        if (event.dispatch(this, mAttachInfo != null
7425                ? mAttachInfo.mKeyDispatchState : null, this)) {
7426            return true;
7427        }
7428
7429        if (mInputEventConsistencyVerifier != null) {
7430            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7431        }
7432        return false;
7433    }
7434
7435    /**
7436     * Dispatches a key shortcut event.
7437     *
7438     * @param event The key event to be dispatched.
7439     * @return True if the event was handled by the view, false otherwise.
7440     */
7441    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7442        return onKeyShortcut(event.getKeyCode(), event);
7443    }
7444
7445    /**
7446     * Pass the touch screen motion event down to the target view, or this
7447     * view if it is the target.
7448     *
7449     * @param event The motion event to be dispatched.
7450     * @return True if the event was handled by the view, false otherwise.
7451     */
7452    public boolean dispatchTouchEvent(MotionEvent event) {
7453        if (mInputEventConsistencyVerifier != null) {
7454            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7455        }
7456
7457        if (onFilterTouchEventForSecurity(event)) {
7458            //noinspection SimplifiableIfStatement
7459            ListenerInfo li = mListenerInfo;
7460            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7461                    && li.mOnTouchListener.onTouch(this, event)) {
7462                return true;
7463            }
7464
7465            if (onTouchEvent(event)) {
7466                return true;
7467            }
7468        }
7469
7470        if (mInputEventConsistencyVerifier != null) {
7471            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7472        }
7473        return false;
7474    }
7475
7476    /**
7477     * Filter the touch event to apply security policies.
7478     *
7479     * @param event The motion event to be filtered.
7480     * @return True if the event should be dispatched, false if the event should be dropped.
7481     *
7482     * @see #getFilterTouchesWhenObscured
7483     */
7484    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7485        //noinspection RedundantIfStatement
7486        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7487                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7488            // Window is obscured, drop this touch.
7489            return false;
7490        }
7491        return true;
7492    }
7493
7494    /**
7495     * Pass a trackball motion event down to the focused view.
7496     *
7497     * @param event The motion event to be dispatched.
7498     * @return True if the event was handled by the view, false otherwise.
7499     */
7500    public boolean dispatchTrackballEvent(MotionEvent event) {
7501        if (mInputEventConsistencyVerifier != null) {
7502            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7503        }
7504
7505        return onTrackballEvent(event);
7506    }
7507
7508    /**
7509     * Dispatch a generic motion event.
7510     * <p>
7511     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7512     * are delivered to the view under the pointer.  All other generic motion events are
7513     * delivered to the focused view.  Hover events are handled specially and are delivered
7514     * to {@link #onHoverEvent(MotionEvent)}.
7515     * </p>
7516     *
7517     * @param event The motion event to be dispatched.
7518     * @return True if the event was handled by the view, false otherwise.
7519     */
7520    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7521        if (mInputEventConsistencyVerifier != null) {
7522            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7523        }
7524
7525        final int source = event.getSource();
7526        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7527            final int action = event.getAction();
7528            if (action == MotionEvent.ACTION_HOVER_ENTER
7529                    || action == MotionEvent.ACTION_HOVER_MOVE
7530                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7531                if (dispatchHoverEvent(event)) {
7532                    return true;
7533                }
7534            } else if (dispatchGenericPointerEvent(event)) {
7535                return true;
7536            }
7537        } else if (dispatchGenericFocusedEvent(event)) {
7538            return true;
7539        }
7540
7541        if (dispatchGenericMotionEventInternal(event)) {
7542            return true;
7543        }
7544
7545        if (mInputEventConsistencyVerifier != null) {
7546            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7547        }
7548        return false;
7549    }
7550
7551    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7552        //noinspection SimplifiableIfStatement
7553        ListenerInfo li = mListenerInfo;
7554        if (li != null && li.mOnGenericMotionListener != null
7555                && (mViewFlags & ENABLED_MASK) == ENABLED
7556                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7557            return true;
7558        }
7559
7560        if (onGenericMotionEvent(event)) {
7561            return true;
7562        }
7563
7564        if (mInputEventConsistencyVerifier != null) {
7565            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7566        }
7567        return false;
7568    }
7569
7570    /**
7571     * Dispatch a hover event.
7572     * <p>
7573     * Do not call this method directly.
7574     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7575     * </p>
7576     *
7577     * @param event The motion event to be dispatched.
7578     * @return True if the event was handled by the view, false otherwise.
7579     */
7580    protected boolean dispatchHoverEvent(MotionEvent event) {
7581        ListenerInfo li = mListenerInfo;
7582        //noinspection SimplifiableIfStatement
7583        if (li != null && li.mOnHoverListener != null
7584                && (mViewFlags & ENABLED_MASK) == ENABLED
7585                && li.mOnHoverListener.onHover(this, event)) {
7586            return true;
7587        }
7588
7589        return onHoverEvent(event);
7590    }
7591
7592    /**
7593     * Returns true if the view has a child to which it has recently sent
7594     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7595     * it does not have a hovered child, then it must be the innermost hovered view.
7596     * @hide
7597     */
7598    protected boolean hasHoveredChild() {
7599        return false;
7600    }
7601
7602    /**
7603     * Dispatch a generic motion event to the view under the first pointer.
7604     * <p>
7605     * Do not call this method directly.
7606     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7607     * </p>
7608     *
7609     * @param event The motion event to be dispatched.
7610     * @return True if the event was handled by the view, false otherwise.
7611     */
7612    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7613        return false;
7614    }
7615
7616    /**
7617     * Dispatch a generic motion event to the currently focused view.
7618     * <p>
7619     * Do not call this method directly.
7620     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7621     * </p>
7622     *
7623     * @param event The motion event to be dispatched.
7624     * @return True if the event was handled by the view, false otherwise.
7625     */
7626    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7627        return false;
7628    }
7629
7630    /**
7631     * Dispatch a pointer event.
7632     * <p>
7633     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7634     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7635     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7636     * and should not be expected to handle other pointing device features.
7637     * </p>
7638     *
7639     * @param event The motion event to be dispatched.
7640     * @return True if the event was handled by the view, false otherwise.
7641     * @hide
7642     */
7643    public final boolean dispatchPointerEvent(MotionEvent event) {
7644        if (event.isTouchEvent()) {
7645            return dispatchTouchEvent(event);
7646        } else {
7647            return dispatchGenericMotionEvent(event);
7648        }
7649    }
7650
7651    /**
7652     * Called when the window containing this view gains or loses window focus.
7653     * ViewGroups should override to route to their children.
7654     *
7655     * @param hasFocus True if the window containing this view now has focus,
7656     *        false otherwise.
7657     */
7658    public void dispatchWindowFocusChanged(boolean hasFocus) {
7659        onWindowFocusChanged(hasFocus);
7660    }
7661
7662    /**
7663     * Called when the window containing this view gains or loses focus.  Note
7664     * that this is separate from view focus: to receive key events, both
7665     * your view and its window must have focus.  If a window is displayed
7666     * on top of yours that takes input focus, then your own window will lose
7667     * focus but the view focus will remain unchanged.
7668     *
7669     * @param hasWindowFocus True if the window containing this view now has
7670     *        focus, false otherwise.
7671     */
7672    public void onWindowFocusChanged(boolean hasWindowFocus) {
7673        InputMethodManager imm = InputMethodManager.peekInstance();
7674        if (!hasWindowFocus) {
7675            if (isPressed()) {
7676                setPressed(false);
7677            }
7678            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7679                imm.focusOut(this);
7680            }
7681            removeLongPressCallback();
7682            removeTapCallback();
7683            onFocusLost();
7684        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7685            imm.focusIn(this);
7686        }
7687        refreshDrawableState();
7688    }
7689
7690    /**
7691     * Returns true if this view is in a window that currently has window focus.
7692     * Note that this is not the same as the view itself having focus.
7693     *
7694     * @return True if this view is in a window that currently has window focus.
7695     */
7696    public boolean hasWindowFocus() {
7697        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7698    }
7699
7700    /**
7701     * Dispatch a view visibility change down the view hierarchy.
7702     * ViewGroups should override to route to their children.
7703     * @param changedView The view whose visibility changed. Could be 'this' or
7704     * an ancestor view.
7705     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7706     * {@link #INVISIBLE} or {@link #GONE}.
7707     */
7708    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7709        onVisibilityChanged(changedView, visibility);
7710    }
7711
7712    /**
7713     * Called when the visibility of the view or an ancestor of the view is changed.
7714     * @param changedView The view whose visibility changed. Could be 'this' or
7715     * an ancestor view.
7716     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7717     * {@link #INVISIBLE} or {@link #GONE}.
7718     */
7719    protected void onVisibilityChanged(View changedView, int visibility) {
7720        if (visibility == VISIBLE) {
7721            if (mAttachInfo != null) {
7722                initialAwakenScrollBars();
7723            } else {
7724                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7725            }
7726        }
7727    }
7728
7729    /**
7730     * Dispatch a hint about whether this view is displayed. For instance, when
7731     * a View moves out of the screen, it might receives a display hint indicating
7732     * the view is not displayed. Applications should not <em>rely</em> on this hint
7733     * as there is no guarantee that they will receive one.
7734     *
7735     * @param hint A hint about whether or not this view is displayed:
7736     * {@link #VISIBLE} or {@link #INVISIBLE}.
7737     */
7738    public void dispatchDisplayHint(int hint) {
7739        onDisplayHint(hint);
7740    }
7741
7742    /**
7743     * Gives this view a hint about whether is displayed or not. For instance, when
7744     * a View moves out of the screen, it might receives a display hint indicating
7745     * the view is not displayed. Applications should not <em>rely</em> on this hint
7746     * as there is no guarantee that they will receive one.
7747     *
7748     * @param hint A hint about whether or not this view is displayed:
7749     * {@link #VISIBLE} or {@link #INVISIBLE}.
7750     */
7751    protected void onDisplayHint(int hint) {
7752    }
7753
7754    /**
7755     * Dispatch a window visibility change down the view hierarchy.
7756     * ViewGroups should override to route to their children.
7757     *
7758     * @param visibility The new visibility of the window.
7759     *
7760     * @see #onWindowVisibilityChanged(int)
7761     */
7762    public void dispatchWindowVisibilityChanged(int visibility) {
7763        onWindowVisibilityChanged(visibility);
7764    }
7765
7766    /**
7767     * Called when the window containing has change its visibility
7768     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7769     * that this tells you whether or not your window is being made visible
7770     * to the window manager; this does <em>not</em> tell you whether or not
7771     * your window is obscured by other windows on the screen, even if it
7772     * is itself visible.
7773     *
7774     * @param visibility The new visibility of the window.
7775     */
7776    protected void onWindowVisibilityChanged(int visibility) {
7777        if (visibility == VISIBLE) {
7778            initialAwakenScrollBars();
7779        }
7780    }
7781
7782    /**
7783     * Returns the current visibility of the window this view is attached to
7784     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7785     *
7786     * @return Returns the current visibility of the view's window.
7787     */
7788    public int getWindowVisibility() {
7789        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7790    }
7791
7792    /**
7793     * Retrieve the overall visible display size in which the window this view is
7794     * attached to has been positioned in.  This takes into account screen
7795     * decorations above the window, for both cases where the window itself
7796     * is being position inside of them or the window is being placed under
7797     * then and covered insets are used for the window to position its content
7798     * inside.  In effect, this tells you the available area where content can
7799     * be placed and remain visible to users.
7800     *
7801     * <p>This function requires an IPC back to the window manager to retrieve
7802     * the requested information, so should not be used in performance critical
7803     * code like drawing.
7804     *
7805     * @param outRect Filled in with the visible display frame.  If the view
7806     * is not attached to a window, this is simply the raw display size.
7807     */
7808    public void getWindowVisibleDisplayFrame(Rect outRect) {
7809        if (mAttachInfo != null) {
7810            try {
7811                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7812            } catch (RemoteException e) {
7813                return;
7814            }
7815            // XXX This is really broken, and probably all needs to be done
7816            // in the window manager, and we need to know more about whether
7817            // we want the area behind or in front of the IME.
7818            final Rect insets = mAttachInfo.mVisibleInsets;
7819            outRect.left += insets.left;
7820            outRect.top += insets.top;
7821            outRect.right -= insets.right;
7822            outRect.bottom -= insets.bottom;
7823            return;
7824        }
7825        // The view is not attached to a display so we don't have a context.
7826        // Make a best guess about the display size.
7827        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7828        d.getRectSize(outRect);
7829    }
7830
7831    /**
7832     * Dispatch a notification about a resource configuration change down
7833     * the view hierarchy.
7834     * ViewGroups should override to route to their children.
7835     *
7836     * @param newConfig The new resource configuration.
7837     *
7838     * @see #onConfigurationChanged(android.content.res.Configuration)
7839     */
7840    public void dispatchConfigurationChanged(Configuration newConfig) {
7841        onConfigurationChanged(newConfig);
7842    }
7843
7844    /**
7845     * Called when the current configuration of the resources being used
7846     * by the application have changed.  You can use this to decide when
7847     * to reload resources that can changed based on orientation and other
7848     * configuration characterstics.  You only need to use this if you are
7849     * not relying on the normal {@link android.app.Activity} mechanism of
7850     * recreating the activity instance upon a configuration change.
7851     *
7852     * @param newConfig The new resource configuration.
7853     */
7854    protected void onConfigurationChanged(Configuration newConfig) {
7855    }
7856
7857    /**
7858     * Private function to aggregate all per-view attributes in to the view
7859     * root.
7860     */
7861    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7862        performCollectViewAttributes(attachInfo, visibility);
7863    }
7864
7865    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7866        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7867            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7868                attachInfo.mKeepScreenOn = true;
7869            }
7870            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7871            ListenerInfo li = mListenerInfo;
7872            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7873                attachInfo.mHasSystemUiListeners = true;
7874            }
7875        }
7876    }
7877
7878    void needGlobalAttributesUpdate(boolean force) {
7879        final AttachInfo ai = mAttachInfo;
7880        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7881            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7882                    || ai.mHasSystemUiListeners) {
7883                ai.mRecomputeGlobalAttributes = true;
7884            }
7885        }
7886    }
7887
7888    /**
7889     * Returns whether the device is currently in touch mode.  Touch mode is entered
7890     * once the user begins interacting with the device by touch, and affects various
7891     * things like whether focus is always visible to the user.
7892     *
7893     * @return Whether the device is in touch mode.
7894     */
7895    @ViewDebug.ExportedProperty
7896    public boolean isInTouchMode() {
7897        if (mAttachInfo != null) {
7898            return mAttachInfo.mInTouchMode;
7899        } else {
7900            return ViewRootImpl.isInTouchMode();
7901        }
7902    }
7903
7904    /**
7905     * Returns the context the view is running in, through which it can
7906     * access the current theme, resources, etc.
7907     *
7908     * @return The view's Context.
7909     */
7910    @ViewDebug.CapturedViewProperty
7911    public final Context getContext() {
7912        return mContext;
7913    }
7914
7915    /**
7916     * Handle a key event before it is processed by any input method
7917     * associated with the view hierarchy.  This can be used to intercept
7918     * key events in special situations before the IME consumes them; a
7919     * typical example would be handling the BACK key to update the application's
7920     * UI instead of allowing the IME to see it and close itself.
7921     *
7922     * @param keyCode The value in event.getKeyCode().
7923     * @param event Description of the key event.
7924     * @return If you handled the event, return true. If you want to allow the
7925     *         event to be handled by the next receiver, return false.
7926     */
7927    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7928        return false;
7929    }
7930
7931    /**
7932     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7933     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7934     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7935     * is released, if the view is enabled and clickable.
7936     *
7937     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7938     * although some may elect to do so in some situations. Do not rely on this to
7939     * catch software key presses.
7940     *
7941     * @param keyCode A key code that represents the button pressed, from
7942     *                {@link android.view.KeyEvent}.
7943     * @param event   The KeyEvent object that defines the button action.
7944     */
7945    public boolean onKeyDown(int keyCode, KeyEvent event) {
7946        boolean result = false;
7947
7948        switch (keyCode) {
7949            case KeyEvent.KEYCODE_DPAD_CENTER:
7950            case KeyEvent.KEYCODE_ENTER: {
7951                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7952                    return true;
7953                }
7954                // Long clickable items don't necessarily have to be clickable
7955                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7956                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7957                        (event.getRepeatCount() == 0)) {
7958                    setPressed(true);
7959                    checkForLongClick(0);
7960                    return true;
7961                }
7962                break;
7963            }
7964        }
7965        return result;
7966    }
7967
7968    /**
7969     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7970     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7971     * the event).
7972     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7973     * although some may elect to do so in some situations. Do not rely on this to
7974     * catch software key presses.
7975     */
7976    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7977        return false;
7978    }
7979
7980    /**
7981     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7982     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7983     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7984     * {@link KeyEvent#KEYCODE_ENTER} is released.
7985     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7986     * although some may elect to do so in some situations. Do not rely on this to
7987     * catch software key presses.
7988     *
7989     * @param keyCode A key code that represents the button pressed, from
7990     *                {@link android.view.KeyEvent}.
7991     * @param event   The KeyEvent object that defines the button action.
7992     */
7993    public boolean onKeyUp(int keyCode, KeyEvent event) {
7994        boolean result = false;
7995
7996        switch (keyCode) {
7997            case KeyEvent.KEYCODE_DPAD_CENTER:
7998            case KeyEvent.KEYCODE_ENTER: {
7999                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8000                    return true;
8001                }
8002                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8003                    setPressed(false);
8004
8005                    if (!mHasPerformedLongPress) {
8006                        // This is a tap, so remove the longpress check
8007                        removeLongPressCallback();
8008
8009                        result = performClick();
8010                    }
8011                }
8012                break;
8013            }
8014        }
8015        return result;
8016    }
8017
8018    /**
8019     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8020     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8021     * the event).
8022     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8023     * although some may elect to do so in some situations. Do not rely on this to
8024     * catch software key presses.
8025     *
8026     * @param keyCode     A key code that represents the button pressed, from
8027     *                    {@link android.view.KeyEvent}.
8028     * @param repeatCount The number of times the action was made.
8029     * @param event       The KeyEvent object that defines the button action.
8030     */
8031    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8032        return false;
8033    }
8034
8035    /**
8036     * Called on the focused view when a key shortcut event is not handled.
8037     * Override this method to implement local key shortcuts for the View.
8038     * Key shortcuts can also be implemented by setting the
8039     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8040     *
8041     * @param keyCode The value in event.getKeyCode().
8042     * @param event Description of the key event.
8043     * @return If you handled the event, return true. If you want to allow the
8044     *         event to be handled by the next receiver, return false.
8045     */
8046    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8047        return false;
8048    }
8049
8050    /**
8051     * Check whether the called view is a text editor, in which case it
8052     * would make sense to automatically display a soft input window for
8053     * it.  Subclasses should override this if they implement
8054     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8055     * a call on that method would return a non-null InputConnection, and
8056     * they are really a first-class editor that the user would normally
8057     * start typing on when the go into a window containing your view.
8058     *
8059     * <p>The default implementation always returns false.  This does
8060     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8061     * will not be called or the user can not otherwise perform edits on your
8062     * view; it is just a hint to the system that this is not the primary
8063     * purpose of this view.
8064     *
8065     * @return Returns true if this view is a text editor, else false.
8066     */
8067    public boolean onCheckIsTextEditor() {
8068        return false;
8069    }
8070
8071    /**
8072     * Create a new InputConnection for an InputMethod to interact
8073     * with the view.  The default implementation returns null, since it doesn't
8074     * support input methods.  You can override this to implement such support.
8075     * This is only needed for views that take focus and text input.
8076     *
8077     * <p>When implementing this, you probably also want to implement
8078     * {@link #onCheckIsTextEditor()} to indicate you will return a
8079     * non-null InputConnection.
8080     *
8081     * @param outAttrs Fill in with attribute information about the connection.
8082     */
8083    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8084        return null;
8085    }
8086
8087    /**
8088     * Called by the {@link android.view.inputmethod.InputMethodManager}
8089     * when a view who is not the current
8090     * input connection target is trying to make a call on the manager.  The
8091     * default implementation returns false; you can override this to return
8092     * true for certain views if you are performing InputConnection proxying
8093     * to them.
8094     * @param view The View that is making the InputMethodManager call.
8095     * @return Return true to allow the call, false to reject.
8096     */
8097    public boolean checkInputConnectionProxy(View view) {
8098        return false;
8099    }
8100
8101    /**
8102     * Show the context menu for this view. It is not safe to hold on to the
8103     * menu after returning from this method.
8104     *
8105     * You should normally not overload this method. Overload
8106     * {@link #onCreateContextMenu(ContextMenu)} or define an
8107     * {@link OnCreateContextMenuListener} to add items to the context menu.
8108     *
8109     * @param menu The context menu to populate
8110     */
8111    public void createContextMenu(ContextMenu menu) {
8112        ContextMenuInfo menuInfo = getContextMenuInfo();
8113
8114        // Sets the current menu info so all items added to menu will have
8115        // my extra info set.
8116        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8117
8118        onCreateContextMenu(menu);
8119        ListenerInfo li = mListenerInfo;
8120        if (li != null && li.mOnCreateContextMenuListener != null) {
8121            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8122        }
8123
8124        // Clear the extra information so subsequent items that aren't mine don't
8125        // have my extra info.
8126        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8127
8128        if (mParent != null) {
8129            mParent.createContextMenu(menu);
8130        }
8131    }
8132
8133    /**
8134     * Views should implement this if they have extra information to associate
8135     * with the context menu. The return result is supplied as a parameter to
8136     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8137     * callback.
8138     *
8139     * @return Extra information about the item for which the context menu
8140     *         should be shown. This information will vary across different
8141     *         subclasses of View.
8142     */
8143    protected ContextMenuInfo getContextMenuInfo() {
8144        return null;
8145    }
8146
8147    /**
8148     * Views should implement this if the view itself is going to add items to
8149     * the context menu.
8150     *
8151     * @param menu the context menu to populate
8152     */
8153    protected void onCreateContextMenu(ContextMenu menu) {
8154    }
8155
8156    /**
8157     * Implement this method to handle trackball motion events.  The
8158     * <em>relative</em> movement of the trackball since the last event
8159     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8160     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8161     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8162     * they will often be fractional values, representing the more fine-grained
8163     * movement information available from a trackball).
8164     *
8165     * @param event The motion event.
8166     * @return True if the event was handled, false otherwise.
8167     */
8168    public boolean onTrackballEvent(MotionEvent event) {
8169        return false;
8170    }
8171
8172    /**
8173     * Implement this method to handle generic motion events.
8174     * <p>
8175     * Generic motion events describe joystick movements, mouse hovers, track pad
8176     * touches, scroll wheel movements and other input events.  The
8177     * {@link MotionEvent#getSource() source} of the motion event specifies
8178     * the class of input that was received.  Implementations of this method
8179     * must examine the bits in the source before processing the event.
8180     * The following code example shows how this is done.
8181     * </p><p>
8182     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8183     * are delivered to the view under the pointer.  All other generic motion events are
8184     * delivered to the focused view.
8185     * </p>
8186     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8187     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8188     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8189     *             // process the joystick movement...
8190     *             return true;
8191     *         }
8192     *     }
8193     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8194     *         switch (event.getAction()) {
8195     *             case MotionEvent.ACTION_HOVER_MOVE:
8196     *                 // process the mouse hover movement...
8197     *                 return true;
8198     *             case MotionEvent.ACTION_SCROLL:
8199     *                 // process the scroll wheel movement...
8200     *                 return true;
8201     *         }
8202     *     }
8203     *     return super.onGenericMotionEvent(event);
8204     * }</pre>
8205     *
8206     * @param event The generic motion event being processed.
8207     * @return True if the event was handled, false otherwise.
8208     */
8209    public boolean onGenericMotionEvent(MotionEvent event) {
8210        return false;
8211    }
8212
8213    /**
8214     * Implement this method to handle hover events.
8215     * <p>
8216     * This method is called whenever a pointer is hovering into, over, or out of the
8217     * bounds of a view and the view is not currently being touched.
8218     * Hover events are represented as pointer events with action
8219     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8220     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8221     * </p>
8222     * <ul>
8223     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8224     * when the pointer enters the bounds of the view.</li>
8225     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8226     * when the pointer has already entered the bounds of the view and has moved.</li>
8227     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8228     * when the pointer has exited the bounds of the view or when the pointer is
8229     * about to go down due to a button click, tap, or similar user action that
8230     * causes the view to be touched.</li>
8231     * </ul>
8232     * <p>
8233     * The view should implement this method to return true to indicate that it is
8234     * handling the hover event, such as by changing its drawable state.
8235     * </p><p>
8236     * The default implementation calls {@link #setHovered} to update the hovered state
8237     * of the view when a hover enter or hover exit event is received, if the view
8238     * is enabled and is clickable.  The default implementation also sends hover
8239     * accessibility events.
8240     * </p>
8241     *
8242     * @param event The motion event that describes the hover.
8243     * @return True if the view handled the hover event.
8244     *
8245     * @see #isHovered
8246     * @see #setHovered
8247     * @see #onHoverChanged
8248     */
8249    public boolean onHoverEvent(MotionEvent event) {
8250        // The root view may receive hover (or touch) events that are outside the bounds of
8251        // the window.  This code ensures that we only send accessibility events for
8252        // hovers that are actually within the bounds of the root view.
8253        final int action = event.getActionMasked();
8254        if (!mSendingHoverAccessibilityEvents) {
8255            if ((action == MotionEvent.ACTION_HOVER_ENTER
8256                    || action == MotionEvent.ACTION_HOVER_MOVE)
8257                    && !hasHoveredChild()
8258                    && pointInView(event.getX(), event.getY())) {
8259                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8260                mSendingHoverAccessibilityEvents = true;
8261            }
8262        } else {
8263            if (action == MotionEvent.ACTION_HOVER_EXIT
8264                    || (action == MotionEvent.ACTION_MOVE
8265                            && !pointInView(event.getX(), event.getY()))) {
8266                mSendingHoverAccessibilityEvents = false;
8267                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8268                // If the window does not have input focus we take away accessibility
8269                // focus as soon as the user stop hovering over the view.
8270                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8271                    getViewRootImpl().setAccessibilityFocus(null, null);
8272                }
8273            }
8274        }
8275
8276        if (isHoverable()) {
8277            switch (action) {
8278                case MotionEvent.ACTION_HOVER_ENTER:
8279                    setHovered(true);
8280                    break;
8281                case MotionEvent.ACTION_HOVER_EXIT:
8282                    setHovered(false);
8283                    break;
8284            }
8285
8286            // Dispatch the event to onGenericMotionEvent before returning true.
8287            // This is to provide compatibility with existing applications that
8288            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8289            // break because of the new default handling for hoverable views
8290            // in onHoverEvent.
8291            // Note that onGenericMotionEvent will be called by default when
8292            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8293            dispatchGenericMotionEventInternal(event);
8294            // The event was already handled by calling setHovered(), so always
8295            // return true.
8296            return true;
8297        }
8298
8299        return false;
8300    }
8301
8302    /**
8303     * Returns true if the view should handle {@link #onHoverEvent}
8304     * by calling {@link #setHovered} to change its hovered state.
8305     *
8306     * @return True if the view is hoverable.
8307     */
8308    private boolean isHoverable() {
8309        final int viewFlags = mViewFlags;
8310        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8311            return false;
8312        }
8313
8314        return (viewFlags & CLICKABLE) == CLICKABLE
8315                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8316    }
8317
8318    /**
8319     * Returns true if the view is currently hovered.
8320     *
8321     * @return True if the view is currently hovered.
8322     *
8323     * @see #setHovered
8324     * @see #onHoverChanged
8325     */
8326    @ViewDebug.ExportedProperty
8327    public boolean isHovered() {
8328        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8329    }
8330
8331    /**
8332     * Sets whether the view is currently hovered.
8333     * <p>
8334     * Calling this method also changes the drawable state of the view.  This
8335     * enables the view to react to hover by using different drawable resources
8336     * to change its appearance.
8337     * </p><p>
8338     * The {@link #onHoverChanged} method is called when the hovered state changes.
8339     * </p>
8340     *
8341     * @param hovered True if the view is hovered.
8342     *
8343     * @see #isHovered
8344     * @see #onHoverChanged
8345     */
8346    public void setHovered(boolean hovered) {
8347        if (hovered) {
8348            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8349                mPrivateFlags |= PFLAG_HOVERED;
8350                refreshDrawableState();
8351                onHoverChanged(true);
8352            }
8353        } else {
8354            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8355                mPrivateFlags &= ~PFLAG_HOVERED;
8356                refreshDrawableState();
8357                onHoverChanged(false);
8358            }
8359        }
8360    }
8361
8362    /**
8363     * Implement this method to handle hover state changes.
8364     * <p>
8365     * This method is called whenever the hover state changes as a result of a
8366     * call to {@link #setHovered}.
8367     * </p>
8368     *
8369     * @param hovered The current hover state, as returned by {@link #isHovered}.
8370     *
8371     * @see #isHovered
8372     * @see #setHovered
8373     */
8374    public void onHoverChanged(boolean hovered) {
8375    }
8376
8377    /**
8378     * Implement this method to handle touch screen motion events.
8379     *
8380     * @param event The motion event.
8381     * @return True if the event was handled, false otherwise.
8382     */
8383    public boolean onTouchEvent(MotionEvent event) {
8384        final int viewFlags = mViewFlags;
8385
8386        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8387            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8388                setPressed(false);
8389            }
8390            // A disabled view that is clickable still consumes the touch
8391            // events, it just doesn't respond to them.
8392            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8393                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8394        }
8395
8396        if (mTouchDelegate != null) {
8397            if (mTouchDelegate.onTouchEvent(event)) {
8398                return true;
8399            }
8400        }
8401
8402        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8403                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8404            switch (event.getAction()) {
8405                case MotionEvent.ACTION_UP:
8406                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8407                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8408                        // take focus if we don't have it already and we should in
8409                        // touch mode.
8410                        boolean focusTaken = false;
8411                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8412                            focusTaken = requestFocus();
8413                        }
8414
8415                        if (prepressed) {
8416                            // The button is being released before we actually
8417                            // showed it as pressed.  Make it show the pressed
8418                            // state now (before scheduling the click) to ensure
8419                            // the user sees it.
8420                            setPressed(true);
8421                       }
8422
8423                        if (!mHasPerformedLongPress) {
8424                            // This is a tap, so remove the longpress check
8425                            removeLongPressCallback();
8426
8427                            // Only perform take click actions if we were in the pressed state
8428                            if (!focusTaken) {
8429                                // Use a Runnable and post this rather than calling
8430                                // performClick directly. This lets other visual state
8431                                // of the view update before click actions start.
8432                                if (mPerformClick == null) {
8433                                    mPerformClick = new PerformClick();
8434                                }
8435                                if (!post(mPerformClick)) {
8436                                    performClick();
8437                                }
8438                            }
8439                        }
8440
8441                        if (mUnsetPressedState == null) {
8442                            mUnsetPressedState = new UnsetPressedState();
8443                        }
8444
8445                        if (prepressed) {
8446                            postDelayed(mUnsetPressedState,
8447                                    ViewConfiguration.getPressedStateDuration());
8448                        } else if (!post(mUnsetPressedState)) {
8449                            // If the post failed, unpress right now
8450                            mUnsetPressedState.run();
8451                        }
8452                        removeTapCallback();
8453                    }
8454                    break;
8455
8456                case MotionEvent.ACTION_DOWN:
8457                    mHasPerformedLongPress = false;
8458
8459                    if (performButtonActionOnTouchDown(event)) {
8460                        break;
8461                    }
8462
8463                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8464                    boolean isInScrollingContainer = isInScrollingContainer();
8465
8466                    // For views inside a scrolling container, delay the pressed feedback for
8467                    // a short period in case this is a scroll.
8468                    if (isInScrollingContainer) {
8469                        mPrivateFlags |= PFLAG_PREPRESSED;
8470                        if (mPendingCheckForTap == null) {
8471                            mPendingCheckForTap = new CheckForTap();
8472                        }
8473                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8474                    } else {
8475                        // Not inside a scrolling container, so show the feedback right away
8476                        setPressed(true);
8477                        checkForLongClick(0);
8478                    }
8479                    break;
8480
8481                case MotionEvent.ACTION_CANCEL:
8482                    setPressed(false);
8483                    removeTapCallback();
8484                    removeLongPressCallback();
8485                    break;
8486
8487                case MotionEvent.ACTION_MOVE:
8488                    final int x = (int) event.getX();
8489                    final int y = (int) event.getY();
8490
8491                    // Be lenient about moving outside of buttons
8492                    if (!pointInView(x, y, mTouchSlop)) {
8493                        // Outside button
8494                        removeTapCallback();
8495                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8496                            // Remove any future long press/tap checks
8497                            removeLongPressCallback();
8498
8499                            setPressed(false);
8500                        }
8501                    }
8502                    break;
8503            }
8504            return true;
8505        }
8506
8507        return false;
8508    }
8509
8510    /**
8511     * @hide
8512     */
8513    public boolean isInScrollingContainer() {
8514        ViewParent p = getParent();
8515        while (p != null && p instanceof ViewGroup) {
8516            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8517                return true;
8518            }
8519            p = p.getParent();
8520        }
8521        return false;
8522    }
8523
8524    /**
8525     * Remove the longpress detection timer.
8526     */
8527    private void removeLongPressCallback() {
8528        if (mPendingCheckForLongPress != null) {
8529          removeCallbacks(mPendingCheckForLongPress);
8530        }
8531    }
8532
8533    /**
8534     * Remove the pending click action
8535     */
8536    private void removePerformClickCallback() {
8537        if (mPerformClick != null) {
8538            removeCallbacks(mPerformClick);
8539        }
8540    }
8541
8542    /**
8543     * Remove the prepress detection timer.
8544     */
8545    private void removeUnsetPressCallback() {
8546        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8547            setPressed(false);
8548            removeCallbacks(mUnsetPressedState);
8549        }
8550    }
8551
8552    /**
8553     * Remove the tap detection timer.
8554     */
8555    private void removeTapCallback() {
8556        if (mPendingCheckForTap != null) {
8557            mPrivateFlags &= ~PFLAG_PREPRESSED;
8558            removeCallbacks(mPendingCheckForTap);
8559        }
8560    }
8561
8562    /**
8563     * Cancels a pending long press.  Your subclass can use this if you
8564     * want the context menu to come up if the user presses and holds
8565     * at the same place, but you don't want it to come up if they press
8566     * and then move around enough to cause scrolling.
8567     */
8568    public void cancelLongPress() {
8569        removeLongPressCallback();
8570
8571        /*
8572         * The prepressed state handled by the tap callback is a display
8573         * construct, but the tap callback will post a long press callback
8574         * less its own timeout. Remove it here.
8575         */
8576        removeTapCallback();
8577    }
8578
8579    /**
8580     * Remove the pending callback for sending a
8581     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8582     */
8583    private void removeSendViewScrolledAccessibilityEventCallback() {
8584        if (mSendViewScrolledAccessibilityEvent != null) {
8585            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8586            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8587        }
8588    }
8589
8590    /**
8591     * Sets the TouchDelegate for this View.
8592     */
8593    public void setTouchDelegate(TouchDelegate delegate) {
8594        mTouchDelegate = delegate;
8595    }
8596
8597    /**
8598     * Gets the TouchDelegate for this View.
8599     */
8600    public TouchDelegate getTouchDelegate() {
8601        return mTouchDelegate;
8602    }
8603
8604    /**
8605     * Set flags controlling behavior of this view.
8606     *
8607     * @param flags Constant indicating the value which should be set
8608     * @param mask Constant indicating the bit range that should be changed
8609     */
8610    void setFlags(int flags, int mask) {
8611        final boolean accessibilityEnabled =
8612                AccessibilityManager.getInstance(mContext).isEnabled();
8613        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8614
8615        int old = mViewFlags;
8616        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8617
8618        int changed = mViewFlags ^ old;
8619        if (changed == 0) {
8620            return;
8621        }
8622        int privateFlags = mPrivateFlags;
8623
8624        /* Check if the FOCUSABLE bit has changed */
8625        if (((changed & FOCUSABLE_MASK) != 0) &&
8626                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8627            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8628                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8629                /* Give up focus if we are no longer focusable */
8630                clearFocus();
8631            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8632                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8633                /*
8634                 * Tell the view system that we are now available to take focus
8635                 * if no one else already has it.
8636                 */
8637                if (mParent != null) mParent.focusableViewAvailable(this);
8638            }
8639        }
8640
8641        final int newVisibility = flags & VISIBILITY_MASK;
8642        if (newVisibility == VISIBLE) {
8643            if ((changed & VISIBILITY_MASK) != 0) {
8644                /*
8645                 * If this view is becoming visible, invalidate it in case it changed while
8646                 * it was not visible. Marking it drawn ensures that the invalidation will
8647                 * go through.
8648                 */
8649                mPrivateFlags |= PFLAG_DRAWN;
8650                invalidate(true);
8651
8652                needGlobalAttributesUpdate(true);
8653
8654                // a view becoming visible is worth notifying the parent
8655                // about in case nothing has focus.  even if this specific view
8656                // isn't focusable, it may contain something that is, so let
8657                // the root view try to give this focus if nothing else does.
8658                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8659                    mParent.focusableViewAvailable(this);
8660                }
8661            }
8662        }
8663
8664        /* Check if the GONE bit has changed */
8665        if ((changed & GONE) != 0) {
8666            needGlobalAttributesUpdate(false);
8667            requestLayout();
8668
8669            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8670                if (hasFocus()) clearFocus();
8671                clearAccessibilityFocus();
8672                destroyDrawingCache();
8673                if (mParent instanceof View) {
8674                    // GONE views noop invalidation, so invalidate the parent
8675                    ((View) mParent).invalidate(true);
8676                }
8677                // Mark the view drawn to ensure that it gets invalidated properly the next
8678                // time it is visible and gets invalidated
8679                mPrivateFlags |= PFLAG_DRAWN;
8680            }
8681            if (mAttachInfo != null) {
8682                mAttachInfo.mViewVisibilityChanged = true;
8683            }
8684        }
8685
8686        /* Check if the VISIBLE bit has changed */
8687        if ((changed & INVISIBLE) != 0) {
8688            needGlobalAttributesUpdate(false);
8689            /*
8690             * If this view is becoming invisible, set the DRAWN flag so that
8691             * the next invalidate() will not be skipped.
8692             */
8693            mPrivateFlags |= PFLAG_DRAWN;
8694
8695            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8696                // root view becoming invisible shouldn't clear focus and accessibility focus
8697                if (getRootView() != this) {
8698                    clearFocus();
8699                    clearAccessibilityFocus();
8700                }
8701            }
8702            if (mAttachInfo != null) {
8703                mAttachInfo.mViewVisibilityChanged = true;
8704            }
8705        }
8706
8707        if ((changed & VISIBILITY_MASK) != 0) {
8708            // If the view is invisible, cleanup its display list to free up resources
8709            if (newVisibility != VISIBLE) {
8710                cleanupDraw();
8711            }
8712
8713            if (mParent instanceof ViewGroup) {
8714                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8715                        (changed & VISIBILITY_MASK), newVisibility);
8716                ((View) mParent).invalidate(true);
8717            } else if (mParent != null) {
8718                mParent.invalidateChild(this, null);
8719            }
8720            dispatchVisibilityChanged(this, newVisibility);
8721        }
8722
8723        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8724            destroyDrawingCache();
8725        }
8726
8727        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8728            destroyDrawingCache();
8729            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8730            invalidateParentCaches();
8731        }
8732
8733        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8734            destroyDrawingCache();
8735            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8736        }
8737
8738        if ((changed & DRAW_MASK) != 0) {
8739            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8740                if (mBackground != null) {
8741                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8742                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8743                } else {
8744                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8745                }
8746            } else {
8747                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8748            }
8749            requestLayout();
8750            invalidate(true);
8751        }
8752
8753        if ((changed & KEEP_SCREEN_ON) != 0) {
8754            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8755                mParent.recomputeViewAttributes(this);
8756            }
8757        }
8758
8759        if (accessibilityEnabled) {
8760            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8761                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8762                if (oldIncludeForAccessibility != includeForAccessibility()) {
8763                    notifySubtreeAccessibilityStateChangedIfNeeded();
8764                } else {
8765                    notifyViewAccessibilityStateChangedIfNeeded();
8766                }
8767            }
8768            if ((changed & ENABLED_MASK) != 0) {
8769                notifyViewAccessibilityStateChangedIfNeeded();
8770            }
8771        }
8772    }
8773
8774    /**
8775     * Change the view's z order in the tree, so it's on top of other sibling
8776     * views. This ordering change may affect layout, if the parent container
8777     * uses an order-dependent layout scheme (e.g., LinearLayout). This
8778     * method should be followed by calls to {@link #requestLayout()} and
8779     * {@link View#invalidate()} on the parent.
8780     *
8781     * @see ViewGroup#bringChildToFront(View)
8782     */
8783    public void bringToFront() {
8784        if (mParent != null) {
8785            mParent.bringChildToFront(this);
8786        }
8787    }
8788
8789    /**
8790     * This is called in response to an internal scroll in this view (i.e., the
8791     * view scrolled its own contents). This is typically as a result of
8792     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8793     * called.
8794     *
8795     * @param l Current horizontal scroll origin.
8796     * @param t Current vertical scroll origin.
8797     * @param oldl Previous horizontal scroll origin.
8798     * @param oldt Previous vertical scroll origin.
8799     */
8800    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8801        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8802            postSendViewScrolledAccessibilityEventCallback();
8803        }
8804
8805        mBackgroundSizeChanged = true;
8806
8807        final AttachInfo ai = mAttachInfo;
8808        if (ai != null) {
8809            ai.mViewScrollChanged = true;
8810        }
8811    }
8812
8813    /**
8814     * Interface definition for a callback to be invoked when the layout bounds of a view
8815     * changes due to layout processing.
8816     */
8817    public interface OnLayoutChangeListener {
8818        /**
8819         * Called when the focus state of a view has changed.
8820         *
8821         * @param v The view whose state has changed.
8822         * @param left The new value of the view's left property.
8823         * @param top The new value of the view's top property.
8824         * @param right The new value of the view's right property.
8825         * @param bottom The new value of the view's bottom property.
8826         * @param oldLeft The previous value of the view's left property.
8827         * @param oldTop The previous value of the view's top property.
8828         * @param oldRight The previous value of the view's right property.
8829         * @param oldBottom The previous value of the view's bottom property.
8830         */
8831        void onLayoutChange(View v, int left, int top, int right, int bottom,
8832            int oldLeft, int oldTop, int oldRight, int oldBottom);
8833    }
8834
8835    /**
8836     * This is called during layout when the size of this view has changed. If
8837     * you were just added to the view hierarchy, you're called with the old
8838     * values of 0.
8839     *
8840     * @param w Current width of this view.
8841     * @param h Current height of this view.
8842     * @param oldw Old width of this view.
8843     * @param oldh Old height of this view.
8844     */
8845    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8846    }
8847
8848    /**
8849     * Called by draw to draw the child views. This may be overridden
8850     * by derived classes to gain control just before its children are drawn
8851     * (but after its own view has been drawn).
8852     * @param canvas the canvas on which to draw the view
8853     */
8854    protected void dispatchDraw(Canvas canvas) {
8855
8856    }
8857
8858    /**
8859     * Gets the parent of this view. Note that the parent is a
8860     * ViewParent and not necessarily a View.
8861     *
8862     * @return Parent of this view.
8863     */
8864    public final ViewParent getParent() {
8865        return mParent;
8866    }
8867
8868    /**
8869     * Set the horizontal scrolled position of your view. This will cause a call to
8870     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8871     * invalidated.
8872     * @param value the x position to scroll to
8873     */
8874    public void setScrollX(int value) {
8875        scrollTo(value, mScrollY);
8876    }
8877
8878    /**
8879     * Set the vertical scrolled position of your view. This will cause a call to
8880     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8881     * invalidated.
8882     * @param value the y position to scroll to
8883     */
8884    public void setScrollY(int value) {
8885        scrollTo(mScrollX, value);
8886    }
8887
8888    /**
8889     * Return the scrolled left position of this view. This is the left edge of
8890     * the displayed part of your view. You do not need to draw any pixels
8891     * farther left, since those are outside of the frame of your view on
8892     * screen.
8893     *
8894     * @return The left edge of the displayed part of your view, in pixels.
8895     */
8896    public final int getScrollX() {
8897        return mScrollX;
8898    }
8899
8900    /**
8901     * Return the scrolled top position of this view. This is the top edge of
8902     * the displayed part of your view. You do not need to draw any pixels above
8903     * it, since those are outside of the frame of your view on screen.
8904     *
8905     * @return The top edge of the displayed part of your view, in pixels.
8906     */
8907    public final int getScrollY() {
8908        return mScrollY;
8909    }
8910
8911    /**
8912     * Return the width of the your view.
8913     *
8914     * @return The width of your view, in pixels.
8915     */
8916    @ViewDebug.ExportedProperty(category = "layout")
8917    public final int getWidth() {
8918        return mRight - mLeft;
8919    }
8920
8921    /**
8922     * Return the height of your view.
8923     *
8924     * @return The height of your view, in pixels.
8925     */
8926    @ViewDebug.ExportedProperty(category = "layout")
8927    public final int getHeight() {
8928        return mBottom - mTop;
8929    }
8930
8931    /**
8932     * Return the visible drawing bounds of your view. Fills in the output
8933     * rectangle with the values from getScrollX(), getScrollY(),
8934     * getWidth(), and getHeight(). These bounds do not account for any
8935     * transformation properties currently set on the view, such as
8936     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8937     *
8938     * @param outRect The (scrolled) drawing bounds of the view.
8939     */
8940    public void getDrawingRect(Rect outRect) {
8941        outRect.left = mScrollX;
8942        outRect.top = mScrollY;
8943        outRect.right = mScrollX + (mRight - mLeft);
8944        outRect.bottom = mScrollY + (mBottom - mTop);
8945    }
8946
8947    /**
8948     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8949     * raw width component (that is the result is masked by
8950     * {@link #MEASURED_SIZE_MASK}).
8951     *
8952     * @return The raw measured width of this view.
8953     */
8954    public final int getMeasuredWidth() {
8955        return mMeasuredWidth & MEASURED_SIZE_MASK;
8956    }
8957
8958    /**
8959     * Return the full width measurement information for this view as computed
8960     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8961     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8962     * This should be used during measurement and layout calculations only. Use
8963     * {@link #getWidth()} to see how wide a view is after layout.
8964     *
8965     * @return The measured width of this view as a bit mask.
8966     */
8967    public final int getMeasuredWidthAndState() {
8968        return mMeasuredWidth;
8969    }
8970
8971    /**
8972     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8973     * raw width component (that is the result is masked by
8974     * {@link #MEASURED_SIZE_MASK}).
8975     *
8976     * @return The raw measured height of this view.
8977     */
8978    public final int getMeasuredHeight() {
8979        return mMeasuredHeight & MEASURED_SIZE_MASK;
8980    }
8981
8982    /**
8983     * Return the full height measurement information for this view as computed
8984     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8985     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8986     * This should be used during measurement and layout calculations only. Use
8987     * {@link #getHeight()} to see how wide a view is after layout.
8988     *
8989     * @return The measured width of this view as a bit mask.
8990     */
8991    public final int getMeasuredHeightAndState() {
8992        return mMeasuredHeight;
8993    }
8994
8995    /**
8996     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8997     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8998     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8999     * and the height component is at the shifted bits
9000     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9001     */
9002    public final int getMeasuredState() {
9003        return (mMeasuredWidth&MEASURED_STATE_MASK)
9004                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9005                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9006    }
9007
9008    /**
9009     * The transform matrix of this view, which is calculated based on the current
9010     * roation, scale, and pivot properties.
9011     *
9012     * @see #getRotation()
9013     * @see #getScaleX()
9014     * @see #getScaleY()
9015     * @see #getPivotX()
9016     * @see #getPivotY()
9017     * @return The current transform matrix for the view
9018     */
9019    public Matrix getMatrix() {
9020        if (mTransformationInfo != null) {
9021            updateMatrix();
9022            return mTransformationInfo.mMatrix;
9023        }
9024        return Matrix.IDENTITY_MATRIX;
9025    }
9026
9027    /**
9028     * Utility function to determine if the value is far enough away from zero to be
9029     * considered non-zero.
9030     * @param value A floating point value to check for zero-ness
9031     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9032     */
9033    private static boolean nonzero(float value) {
9034        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9035    }
9036
9037    /**
9038     * Returns true if the transform matrix is the identity matrix.
9039     * Recomputes the matrix if necessary.
9040     *
9041     * @return True if the transform matrix is the identity matrix, false otherwise.
9042     */
9043    final boolean hasIdentityMatrix() {
9044        if (mTransformationInfo != null) {
9045            updateMatrix();
9046            return mTransformationInfo.mMatrixIsIdentity;
9047        }
9048        return true;
9049    }
9050
9051    void ensureTransformationInfo() {
9052        if (mTransformationInfo == null) {
9053            mTransformationInfo = new TransformationInfo();
9054        }
9055    }
9056
9057    /**
9058     * Recomputes the transform matrix if necessary.
9059     */
9060    private void updateMatrix() {
9061        final TransformationInfo info = mTransformationInfo;
9062        if (info == null) {
9063            return;
9064        }
9065        if (info.mMatrixDirty) {
9066            // transform-related properties have changed since the last time someone
9067            // asked for the matrix; recalculate it with the current values
9068
9069            // Figure out if we need to update the pivot point
9070            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9071                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9072                    info.mPrevWidth = mRight - mLeft;
9073                    info.mPrevHeight = mBottom - mTop;
9074                    info.mPivotX = info.mPrevWidth / 2f;
9075                    info.mPivotY = info.mPrevHeight / 2f;
9076                }
9077            }
9078            info.mMatrix.reset();
9079            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9080                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9081                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9082                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9083            } else {
9084                if (info.mCamera == null) {
9085                    info.mCamera = new Camera();
9086                    info.matrix3D = new Matrix();
9087                }
9088                info.mCamera.save();
9089                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9090                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9091                info.mCamera.getMatrix(info.matrix3D);
9092                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9093                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9094                        info.mPivotY + info.mTranslationY);
9095                info.mMatrix.postConcat(info.matrix3D);
9096                info.mCamera.restore();
9097            }
9098            info.mMatrixDirty = false;
9099            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9100            info.mInverseMatrixDirty = true;
9101        }
9102    }
9103
9104   /**
9105     * Utility method to retrieve the inverse of the current mMatrix property.
9106     * We cache the matrix to avoid recalculating it when transform properties
9107     * have not changed.
9108     *
9109     * @return The inverse of the current matrix of this view.
9110     */
9111    final Matrix getInverseMatrix() {
9112        final TransformationInfo info = mTransformationInfo;
9113        if (info != null) {
9114            updateMatrix();
9115            if (info.mInverseMatrixDirty) {
9116                if (info.mInverseMatrix == null) {
9117                    info.mInverseMatrix = new Matrix();
9118                }
9119                info.mMatrix.invert(info.mInverseMatrix);
9120                info.mInverseMatrixDirty = false;
9121            }
9122            return info.mInverseMatrix;
9123        }
9124        return Matrix.IDENTITY_MATRIX;
9125    }
9126
9127    /**
9128     * Gets the distance along the Z axis from the camera to this view.
9129     *
9130     * @see #setCameraDistance(float)
9131     *
9132     * @return The distance along the Z axis.
9133     */
9134    public float getCameraDistance() {
9135        ensureTransformationInfo();
9136        final float dpi = mResources.getDisplayMetrics().densityDpi;
9137        final TransformationInfo info = mTransformationInfo;
9138        if (info.mCamera == null) {
9139            info.mCamera = new Camera();
9140            info.matrix3D = new Matrix();
9141        }
9142        return -(info.mCamera.getLocationZ() * dpi);
9143    }
9144
9145    /**
9146     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9147     * views are drawn) from the camera to this view. The camera's distance
9148     * affects 3D transformations, for instance rotations around the X and Y
9149     * axis. If the rotationX or rotationY properties are changed and this view is
9150     * large (more than half the size of the screen), it is recommended to always
9151     * use a camera distance that's greater than the height (X axis rotation) or
9152     * the width (Y axis rotation) of this view.</p>
9153     *
9154     * <p>The distance of the camera from the view plane can have an affect on the
9155     * perspective distortion of the view when it is rotated around the x or y axis.
9156     * For example, a large distance will result in a large viewing angle, and there
9157     * will not be much perspective distortion of the view as it rotates. A short
9158     * distance may cause much more perspective distortion upon rotation, and can
9159     * also result in some drawing artifacts if the rotated view ends up partially
9160     * behind the camera (which is why the recommendation is to use a distance at
9161     * least as far as the size of the view, if the view is to be rotated.)</p>
9162     *
9163     * <p>The distance is expressed in "depth pixels." The default distance depends
9164     * on the screen density. For instance, on a medium density display, the
9165     * default distance is 1280. On a high density display, the default distance
9166     * is 1920.</p>
9167     *
9168     * <p>If you want to specify a distance that leads to visually consistent
9169     * results across various densities, use the following formula:</p>
9170     * <pre>
9171     * float scale = context.getResources().getDisplayMetrics().density;
9172     * view.setCameraDistance(distance * scale);
9173     * </pre>
9174     *
9175     * <p>The density scale factor of a high density display is 1.5,
9176     * and 1920 = 1280 * 1.5.</p>
9177     *
9178     * @param distance The distance in "depth pixels", if negative the opposite
9179     *        value is used
9180     *
9181     * @see #setRotationX(float)
9182     * @see #setRotationY(float)
9183     */
9184    public void setCameraDistance(float distance) {
9185        invalidateViewProperty(true, false);
9186
9187        ensureTransformationInfo();
9188        final float dpi = mResources.getDisplayMetrics().densityDpi;
9189        final TransformationInfo info = mTransformationInfo;
9190        if (info.mCamera == null) {
9191            info.mCamera = new Camera();
9192            info.matrix3D = new Matrix();
9193        }
9194
9195        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9196        info.mMatrixDirty = true;
9197
9198        invalidateViewProperty(false, false);
9199        if (mDisplayList != null) {
9200            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9201        }
9202        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9203            // View was rejected last time it was drawn by its parent; this may have changed
9204            invalidateParentIfNeeded();
9205        }
9206    }
9207
9208    /**
9209     * The degrees that the view is rotated around the pivot point.
9210     *
9211     * @see #setRotation(float)
9212     * @see #getPivotX()
9213     * @see #getPivotY()
9214     *
9215     * @return The degrees of rotation.
9216     */
9217    @ViewDebug.ExportedProperty(category = "drawing")
9218    public float getRotation() {
9219        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9220    }
9221
9222    /**
9223     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9224     * result in clockwise rotation.
9225     *
9226     * @param rotation The degrees of rotation.
9227     *
9228     * @see #getRotation()
9229     * @see #getPivotX()
9230     * @see #getPivotY()
9231     * @see #setRotationX(float)
9232     * @see #setRotationY(float)
9233     *
9234     * @attr ref android.R.styleable#View_rotation
9235     */
9236    public void setRotation(float rotation) {
9237        ensureTransformationInfo();
9238        final TransformationInfo info = mTransformationInfo;
9239        if (info.mRotation != rotation) {
9240            // Double-invalidation is necessary to capture view's old and new areas
9241            invalidateViewProperty(true, false);
9242            info.mRotation = rotation;
9243            info.mMatrixDirty = true;
9244            invalidateViewProperty(false, true);
9245            if (mDisplayList != null) {
9246                mDisplayList.setRotation(rotation);
9247            }
9248            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9249                // View was rejected last time it was drawn by its parent; this may have changed
9250                invalidateParentIfNeeded();
9251            }
9252        }
9253    }
9254
9255    /**
9256     * The degrees that the view is rotated around the vertical axis through the pivot point.
9257     *
9258     * @see #getPivotX()
9259     * @see #getPivotY()
9260     * @see #setRotationY(float)
9261     *
9262     * @return The degrees of Y rotation.
9263     */
9264    @ViewDebug.ExportedProperty(category = "drawing")
9265    public float getRotationY() {
9266        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9267    }
9268
9269    /**
9270     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9271     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9272     * down the y axis.
9273     *
9274     * When rotating large views, it is recommended to adjust the camera distance
9275     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9276     *
9277     * @param rotationY The degrees of Y rotation.
9278     *
9279     * @see #getRotationY()
9280     * @see #getPivotX()
9281     * @see #getPivotY()
9282     * @see #setRotation(float)
9283     * @see #setRotationX(float)
9284     * @see #setCameraDistance(float)
9285     *
9286     * @attr ref android.R.styleable#View_rotationY
9287     */
9288    public void setRotationY(float rotationY) {
9289        ensureTransformationInfo();
9290        final TransformationInfo info = mTransformationInfo;
9291        if (info.mRotationY != rotationY) {
9292            invalidateViewProperty(true, false);
9293            info.mRotationY = rotationY;
9294            info.mMatrixDirty = true;
9295            invalidateViewProperty(false, true);
9296            if (mDisplayList != null) {
9297                mDisplayList.setRotationY(rotationY);
9298            }
9299            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9300                // View was rejected last time it was drawn by its parent; this may have changed
9301                invalidateParentIfNeeded();
9302            }
9303        }
9304    }
9305
9306    /**
9307     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9308     *
9309     * @see #getPivotX()
9310     * @see #getPivotY()
9311     * @see #setRotationX(float)
9312     *
9313     * @return The degrees of X rotation.
9314     */
9315    @ViewDebug.ExportedProperty(category = "drawing")
9316    public float getRotationX() {
9317        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9318    }
9319
9320    /**
9321     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9322     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9323     * x axis.
9324     *
9325     * When rotating large views, it is recommended to adjust the camera distance
9326     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9327     *
9328     * @param rotationX The degrees of X rotation.
9329     *
9330     * @see #getRotationX()
9331     * @see #getPivotX()
9332     * @see #getPivotY()
9333     * @see #setRotation(float)
9334     * @see #setRotationY(float)
9335     * @see #setCameraDistance(float)
9336     *
9337     * @attr ref android.R.styleable#View_rotationX
9338     */
9339    public void setRotationX(float rotationX) {
9340        ensureTransformationInfo();
9341        final TransformationInfo info = mTransformationInfo;
9342        if (info.mRotationX != rotationX) {
9343            invalidateViewProperty(true, false);
9344            info.mRotationX = rotationX;
9345            info.mMatrixDirty = true;
9346            invalidateViewProperty(false, true);
9347            if (mDisplayList != null) {
9348                mDisplayList.setRotationX(rotationX);
9349            }
9350            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9351                // View was rejected last time it was drawn by its parent; this may have changed
9352                invalidateParentIfNeeded();
9353            }
9354        }
9355    }
9356
9357    /**
9358     * The amount that the view is scaled in x around the pivot point, as a proportion of
9359     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9360     *
9361     * <p>By default, this is 1.0f.
9362     *
9363     * @see #getPivotX()
9364     * @see #getPivotY()
9365     * @return The scaling factor.
9366     */
9367    @ViewDebug.ExportedProperty(category = "drawing")
9368    public float getScaleX() {
9369        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9370    }
9371
9372    /**
9373     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9374     * the view's unscaled width. A value of 1 means that no scaling is applied.
9375     *
9376     * @param scaleX The scaling factor.
9377     * @see #getPivotX()
9378     * @see #getPivotY()
9379     *
9380     * @attr ref android.R.styleable#View_scaleX
9381     */
9382    public void setScaleX(float scaleX) {
9383        ensureTransformationInfo();
9384        final TransformationInfo info = mTransformationInfo;
9385        if (info.mScaleX != scaleX) {
9386            invalidateViewProperty(true, false);
9387            info.mScaleX = scaleX;
9388            info.mMatrixDirty = true;
9389            invalidateViewProperty(false, true);
9390            if (mDisplayList != null) {
9391                mDisplayList.setScaleX(scaleX);
9392            }
9393            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9394                // View was rejected last time it was drawn by its parent; this may have changed
9395                invalidateParentIfNeeded();
9396            }
9397        }
9398    }
9399
9400    /**
9401     * The amount that the view is scaled in y around the pivot point, as a proportion of
9402     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9403     *
9404     * <p>By default, this is 1.0f.
9405     *
9406     * @see #getPivotX()
9407     * @see #getPivotY()
9408     * @return The scaling factor.
9409     */
9410    @ViewDebug.ExportedProperty(category = "drawing")
9411    public float getScaleY() {
9412        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9413    }
9414
9415    /**
9416     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9417     * the view's unscaled width. A value of 1 means that no scaling is applied.
9418     *
9419     * @param scaleY The scaling factor.
9420     * @see #getPivotX()
9421     * @see #getPivotY()
9422     *
9423     * @attr ref android.R.styleable#View_scaleY
9424     */
9425    public void setScaleY(float scaleY) {
9426        ensureTransformationInfo();
9427        final TransformationInfo info = mTransformationInfo;
9428        if (info.mScaleY != scaleY) {
9429            invalidateViewProperty(true, false);
9430            info.mScaleY = scaleY;
9431            info.mMatrixDirty = true;
9432            invalidateViewProperty(false, true);
9433            if (mDisplayList != null) {
9434                mDisplayList.setScaleY(scaleY);
9435            }
9436            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9437                // View was rejected last time it was drawn by its parent; this may have changed
9438                invalidateParentIfNeeded();
9439            }
9440        }
9441    }
9442
9443    /**
9444     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9445     * and {@link #setScaleX(float) scaled}.
9446     *
9447     * @see #getRotation()
9448     * @see #getScaleX()
9449     * @see #getScaleY()
9450     * @see #getPivotY()
9451     * @return The x location of the pivot point.
9452     *
9453     * @attr ref android.R.styleable#View_transformPivotX
9454     */
9455    @ViewDebug.ExportedProperty(category = "drawing")
9456    public float getPivotX() {
9457        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9458    }
9459
9460    /**
9461     * Sets the x location of the point around which the view is
9462     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9463     * By default, the pivot point is centered on the object.
9464     * Setting this property disables this behavior and causes the view to use only the
9465     * explicitly set pivotX and pivotY values.
9466     *
9467     * @param pivotX The x location of the pivot point.
9468     * @see #getRotation()
9469     * @see #getScaleX()
9470     * @see #getScaleY()
9471     * @see #getPivotY()
9472     *
9473     * @attr ref android.R.styleable#View_transformPivotX
9474     */
9475    public void setPivotX(float pivotX) {
9476        ensureTransformationInfo();
9477        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9478        final TransformationInfo info = mTransformationInfo;
9479        if (info.mPivotX != pivotX) {
9480            invalidateViewProperty(true, false);
9481            info.mPivotX = pivotX;
9482            info.mMatrixDirty = true;
9483            invalidateViewProperty(false, true);
9484            if (mDisplayList != null) {
9485                mDisplayList.setPivotX(pivotX);
9486            }
9487            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9488                // View was rejected last time it was drawn by its parent; this may have changed
9489                invalidateParentIfNeeded();
9490            }
9491        }
9492    }
9493
9494    /**
9495     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9496     * and {@link #setScaleY(float) scaled}.
9497     *
9498     * @see #getRotation()
9499     * @see #getScaleX()
9500     * @see #getScaleY()
9501     * @see #getPivotY()
9502     * @return The y location of the pivot point.
9503     *
9504     * @attr ref android.R.styleable#View_transformPivotY
9505     */
9506    @ViewDebug.ExportedProperty(category = "drawing")
9507    public float getPivotY() {
9508        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9509    }
9510
9511    /**
9512     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9513     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9514     * Setting this property disables this behavior and causes the view to use only the
9515     * explicitly set pivotX and pivotY values.
9516     *
9517     * @param pivotY The y location of the pivot point.
9518     * @see #getRotation()
9519     * @see #getScaleX()
9520     * @see #getScaleY()
9521     * @see #getPivotY()
9522     *
9523     * @attr ref android.R.styleable#View_transformPivotY
9524     */
9525    public void setPivotY(float pivotY) {
9526        ensureTransformationInfo();
9527        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9528        final TransformationInfo info = mTransformationInfo;
9529        if (info.mPivotY != pivotY) {
9530            invalidateViewProperty(true, false);
9531            info.mPivotY = pivotY;
9532            info.mMatrixDirty = true;
9533            invalidateViewProperty(false, true);
9534            if (mDisplayList != null) {
9535                mDisplayList.setPivotY(pivotY);
9536            }
9537            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9538                // View was rejected last time it was drawn by its parent; this may have changed
9539                invalidateParentIfNeeded();
9540            }
9541        }
9542    }
9543
9544    /**
9545     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9546     * completely transparent and 1 means the view is completely opaque.
9547     *
9548     * <p>By default this is 1.0f.
9549     * @return The opacity of the view.
9550     */
9551    @ViewDebug.ExportedProperty(category = "drawing")
9552    public float getAlpha() {
9553        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9554    }
9555
9556    /**
9557     * Returns whether this View has content which overlaps. This function, intended to be
9558     * overridden by specific View types, is an optimization when alpha is set on a view. If
9559     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9560     * and then composited it into place, which can be expensive. If the view has no overlapping
9561     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9562     * An example of overlapping rendering is a TextView with a background image, such as a
9563     * Button. An example of non-overlapping rendering is a TextView with no background, or
9564     * an ImageView with only the foreground image. The default implementation returns true;
9565     * subclasses should override if they have cases which can be optimized.
9566     *
9567     * @return true if the content in this view might overlap, false otherwise.
9568     */
9569    public boolean hasOverlappingRendering() {
9570        return true;
9571    }
9572
9573    /**
9574     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9575     * completely transparent and 1 means the view is completely opaque.</p>
9576     *
9577     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9578     * performance implications, especially for large views. It is best to use the alpha property
9579     * sparingly and transiently, as in the case of fading animations.</p>
9580     *
9581     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9582     * strongly recommended for performance reasons to either override
9583     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9584     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9585     *
9586     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9587     * responsible for applying the opacity itself.</p>
9588     *
9589     * <p>Note that if the view is backed by a
9590     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9591     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9592     * 1.0 will supercede the alpha of the layer paint.</p>
9593     *
9594     * @param alpha The opacity of the view.
9595     *
9596     * @see #hasOverlappingRendering()
9597     * @see #setLayerType(int, android.graphics.Paint)
9598     *
9599     * @attr ref android.R.styleable#View_alpha
9600     */
9601    public void setAlpha(float alpha) {
9602        ensureTransformationInfo();
9603        if (mTransformationInfo.mAlpha != alpha) {
9604            mTransformationInfo.mAlpha = alpha;
9605            if (onSetAlpha((int) (alpha * 255))) {
9606                mPrivateFlags |= PFLAG_ALPHA_SET;
9607                // subclass is handling alpha - don't optimize rendering cache invalidation
9608                invalidateParentCaches();
9609                invalidate(true);
9610            } else {
9611                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9612                invalidateViewProperty(true, false);
9613                if (mDisplayList != null) {
9614                    mDisplayList.setAlpha(alpha);
9615                }
9616            }
9617        }
9618    }
9619
9620    /**
9621     * Faster version of setAlpha() which performs the same steps except there are
9622     * no calls to invalidate(). The caller of this function should perform proper invalidation
9623     * on the parent and this object. The return value indicates whether the subclass handles
9624     * alpha (the return value for onSetAlpha()).
9625     *
9626     * @param alpha The new value for the alpha property
9627     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9628     *         the new value for the alpha property is different from the old value
9629     */
9630    boolean setAlphaNoInvalidation(float alpha) {
9631        ensureTransformationInfo();
9632        if (mTransformationInfo.mAlpha != alpha) {
9633            mTransformationInfo.mAlpha = alpha;
9634            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9635            if (subclassHandlesAlpha) {
9636                mPrivateFlags |= PFLAG_ALPHA_SET;
9637                return true;
9638            } else {
9639                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9640                if (mDisplayList != null) {
9641                    mDisplayList.setAlpha(alpha);
9642                }
9643            }
9644        }
9645        return false;
9646    }
9647
9648    /**
9649     * Top position of this view relative to its parent.
9650     *
9651     * @return The top of this view, in pixels.
9652     */
9653    @ViewDebug.CapturedViewProperty
9654    public final int getTop() {
9655        return mTop;
9656    }
9657
9658    /**
9659     * Sets the top position of this view relative to its parent. This method is meant to be called
9660     * by the layout system and should not generally be called otherwise, because the property
9661     * may be changed at any time by the layout.
9662     *
9663     * @param top The top of this view, in pixels.
9664     */
9665    public final void setTop(int top) {
9666        if (top != mTop) {
9667            updateMatrix();
9668            final boolean matrixIsIdentity = mTransformationInfo == null
9669                    || mTransformationInfo.mMatrixIsIdentity;
9670            if (matrixIsIdentity) {
9671                if (mAttachInfo != null) {
9672                    int minTop;
9673                    int yLoc;
9674                    if (top < mTop) {
9675                        minTop = top;
9676                        yLoc = top - mTop;
9677                    } else {
9678                        minTop = mTop;
9679                        yLoc = 0;
9680                    }
9681                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9682                }
9683            } else {
9684                // Double-invalidation is necessary to capture view's old and new areas
9685                invalidate(true);
9686            }
9687
9688            int width = mRight - mLeft;
9689            int oldHeight = mBottom - mTop;
9690
9691            mTop = top;
9692            if (mDisplayList != null) {
9693                mDisplayList.setTop(mTop);
9694            }
9695
9696            sizeChange(width, mBottom - mTop, width, oldHeight);
9697
9698            if (!matrixIsIdentity) {
9699                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9700                    // A change in dimension means an auto-centered pivot point changes, too
9701                    mTransformationInfo.mMatrixDirty = true;
9702                }
9703                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9704                invalidate(true);
9705            }
9706            mBackgroundSizeChanged = true;
9707            invalidateParentIfNeeded();
9708            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9709                // View was rejected last time it was drawn by its parent; this may have changed
9710                invalidateParentIfNeeded();
9711            }
9712        }
9713    }
9714
9715    /**
9716     * Bottom position of this view relative to its parent.
9717     *
9718     * @return The bottom of this view, in pixels.
9719     */
9720    @ViewDebug.CapturedViewProperty
9721    public final int getBottom() {
9722        return mBottom;
9723    }
9724
9725    /**
9726     * True if this view has changed since the last time being drawn.
9727     *
9728     * @return The dirty state of this view.
9729     */
9730    public boolean isDirty() {
9731        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9732    }
9733
9734    /**
9735     * Sets the bottom position of this view relative to its parent. This method is meant to be
9736     * called by the layout system and should not generally be called otherwise, because the
9737     * property may be changed at any time by the layout.
9738     *
9739     * @param bottom The bottom of this view, in pixels.
9740     */
9741    public final void setBottom(int bottom) {
9742        if (bottom != mBottom) {
9743            updateMatrix();
9744            final boolean matrixIsIdentity = mTransformationInfo == null
9745                    || mTransformationInfo.mMatrixIsIdentity;
9746            if (matrixIsIdentity) {
9747                if (mAttachInfo != null) {
9748                    int maxBottom;
9749                    if (bottom < mBottom) {
9750                        maxBottom = mBottom;
9751                    } else {
9752                        maxBottom = bottom;
9753                    }
9754                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9755                }
9756            } else {
9757                // Double-invalidation is necessary to capture view's old and new areas
9758                invalidate(true);
9759            }
9760
9761            int width = mRight - mLeft;
9762            int oldHeight = mBottom - mTop;
9763
9764            mBottom = bottom;
9765            if (mDisplayList != null) {
9766                mDisplayList.setBottom(mBottom);
9767            }
9768
9769            sizeChange(width, mBottom - mTop, width, oldHeight);
9770
9771            if (!matrixIsIdentity) {
9772                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9773                    // A change in dimension means an auto-centered pivot point changes, too
9774                    mTransformationInfo.mMatrixDirty = true;
9775                }
9776                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9777                invalidate(true);
9778            }
9779            mBackgroundSizeChanged = true;
9780            invalidateParentIfNeeded();
9781            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9782                // View was rejected last time it was drawn by its parent; this may have changed
9783                invalidateParentIfNeeded();
9784            }
9785        }
9786    }
9787
9788    /**
9789     * Left position of this view relative to its parent.
9790     *
9791     * @return The left edge of this view, in pixels.
9792     */
9793    @ViewDebug.CapturedViewProperty
9794    public final int getLeft() {
9795        return mLeft;
9796    }
9797
9798    /**
9799     * Sets the left position of this view relative to its parent. This method is meant to be called
9800     * by the layout system and should not generally be called otherwise, because the property
9801     * may be changed at any time by the layout.
9802     *
9803     * @param left The bottom of this view, in pixels.
9804     */
9805    public final void setLeft(int left) {
9806        if (left != mLeft) {
9807            updateMatrix();
9808            final boolean matrixIsIdentity = mTransformationInfo == null
9809                    || mTransformationInfo.mMatrixIsIdentity;
9810            if (matrixIsIdentity) {
9811                if (mAttachInfo != null) {
9812                    int minLeft;
9813                    int xLoc;
9814                    if (left < mLeft) {
9815                        minLeft = left;
9816                        xLoc = left - mLeft;
9817                    } else {
9818                        minLeft = mLeft;
9819                        xLoc = 0;
9820                    }
9821                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9822                }
9823            } else {
9824                // Double-invalidation is necessary to capture view's old and new areas
9825                invalidate(true);
9826            }
9827
9828            int oldWidth = mRight - mLeft;
9829            int height = mBottom - mTop;
9830
9831            mLeft = left;
9832            if (mDisplayList != null) {
9833                mDisplayList.setLeft(left);
9834            }
9835
9836            sizeChange(mRight - mLeft, height, oldWidth, height);
9837
9838            if (!matrixIsIdentity) {
9839                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9840                    // A change in dimension means an auto-centered pivot point changes, too
9841                    mTransformationInfo.mMatrixDirty = true;
9842                }
9843                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9844                invalidate(true);
9845            }
9846            mBackgroundSizeChanged = true;
9847            invalidateParentIfNeeded();
9848            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9849                // View was rejected last time it was drawn by its parent; this may have changed
9850                invalidateParentIfNeeded();
9851            }
9852        }
9853    }
9854
9855    /**
9856     * Right position of this view relative to its parent.
9857     *
9858     * @return The right edge of this view, in pixels.
9859     */
9860    @ViewDebug.CapturedViewProperty
9861    public final int getRight() {
9862        return mRight;
9863    }
9864
9865    /**
9866     * Sets the right position of this view relative to its parent. This method is meant to be called
9867     * by the layout system and should not generally be called otherwise, because the property
9868     * may be changed at any time by the layout.
9869     *
9870     * @param right The bottom of this view, in pixels.
9871     */
9872    public final void setRight(int right) {
9873        if (right != mRight) {
9874            updateMatrix();
9875            final boolean matrixIsIdentity = mTransformationInfo == null
9876                    || mTransformationInfo.mMatrixIsIdentity;
9877            if (matrixIsIdentity) {
9878                if (mAttachInfo != null) {
9879                    int maxRight;
9880                    if (right < mRight) {
9881                        maxRight = mRight;
9882                    } else {
9883                        maxRight = right;
9884                    }
9885                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9886                }
9887            } else {
9888                // Double-invalidation is necessary to capture view's old and new areas
9889                invalidate(true);
9890            }
9891
9892            int oldWidth = mRight - mLeft;
9893            int height = mBottom - mTop;
9894
9895            mRight = right;
9896            if (mDisplayList != null) {
9897                mDisplayList.setRight(mRight);
9898            }
9899
9900            sizeChange(mRight - mLeft, height, oldWidth, height);
9901
9902            if (!matrixIsIdentity) {
9903                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9904                    // A change in dimension means an auto-centered pivot point changes, too
9905                    mTransformationInfo.mMatrixDirty = true;
9906                }
9907                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9908                invalidate(true);
9909            }
9910            mBackgroundSizeChanged = true;
9911            invalidateParentIfNeeded();
9912            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9913                // View was rejected last time it was drawn by its parent; this may have changed
9914                invalidateParentIfNeeded();
9915            }
9916        }
9917    }
9918
9919    /**
9920     * The visual x position of this view, in pixels. This is equivalent to the
9921     * {@link #setTranslationX(float) translationX} property plus the current
9922     * {@link #getLeft() left} property.
9923     *
9924     * @return The visual x position of this view, in pixels.
9925     */
9926    @ViewDebug.ExportedProperty(category = "drawing")
9927    public float getX() {
9928        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9929    }
9930
9931    /**
9932     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9933     * {@link #setTranslationX(float) translationX} property to be the difference between
9934     * the x value passed in and the current {@link #getLeft() left} property.
9935     *
9936     * @param x The visual x position of this view, in pixels.
9937     */
9938    public void setX(float x) {
9939        setTranslationX(x - mLeft);
9940    }
9941
9942    /**
9943     * The visual y position of this view, in pixels. This is equivalent to the
9944     * {@link #setTranslationY(float) translationY} property plus the current
9945     * {@link #getTop() top} property.
9946     *
9947     * @return The visual y position of this view, in pixels.
9948     */
9949    @ViewDebug.ExportedProperty(category = "drawing")
9950    public float getY() {
9951        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9952    }
9953
9954    /**
9955     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9956     * {@link #setTranslationY(float) translationY} property to be the difference between
9957     * the y value passed in and the current {@link #getTop() top} property.
9958     *
9959     * @param y The visual y position of this view, in pixels.
9960     */
9961    public void setY(float y) {
9962        setTranslationY(y - mTop);
9963    }
9964
9965
9966    /**
9967     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9968     * This position is post-layout, in addition to wherever the object's
9969     * layout placed it.
9970     *
9971     * @return The horizontal position of this view relative to its left position, in pixels.
9972     */
9973    @ViewDebug.ExportedProperty(category = "drawing")
9974    public float getTranslationX() {
9975        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9976    }
9977
9978    /**
9979     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9980     * This effectively positions the object post-layout, in addition to wherever the object's
9981     * layout placed it.
9982     *
9983     * @param translationX The horizontal position of this view relative to its left position,
9984     * in pixels.
9985     *
9986     * @attr ref android.R.styleable#View_translationX
9987     */
9988    public void setTranslationX(float translationX) {
9989        ensureTransformationInfo();
9990        final TransformationInfo info = mTransformationInfo;
9991        if (info.mTranslationX != translationX) {
9992            // Double-invalidation is necessary to capture view's old and new areas
9993            invalidateViewProperty(true, false);
9994            info.mTranslationX = translationX;
9995            info.mMatrixDirty = true;
9996            invalidateViewProperty(false, true);
9997            if (mDisplayList != null) {
9998                mDisplayList.setTranslationX(translationX);
9999            }
10000            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10001                // View was rejected last time it was drawn by its parent; this may have changed
10002                invalidateParentIfNeeded();
10003            }
10004        }
10005    }
10006
10007    /**
10008     * The horizontal location of this view relative to its {@link #getTop() top} position.
10009     * This position is post-layout, in addition to wherever the object's
10010     * layout placed it.
10011     *
10012     * @return The vertical position of this view relative to its top position,
10013     * in pixels.
10014     */
10015    @ViewDebug.ExportedProperty(category = "drawing")
10016    public float getTranslationY() {
10017        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10018    }
10019
10020    /**
10021     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10022     * This effectively positions the object post-layout, in addition to wherever the object's
10023     * layout placed it.
10024     *
10025     * @param translationY The vertical position of this view relative to its top position,
10026     * in pixels.
10027     *
10028     * @attr ref android.R.styleable#View_translationY
10029     */
10030    public void setTranslationY(float translationY) {
10031        ensureTransformationInfo();
10032        final TransformationInfo info = mTransformationInfo;
10033        if (info.mTranslationY != translationY) {
10034            invalidateViewProperty(true, false);
10035            info.mTranslationY = translationY;
10036            info.mMatrixDirty = true;
10037            invalidateViewProperty(false, true);
10038            if (mDisplayList != null) {
10039                mDisplayList.setTranslationY(translationY);
10040            }
10041            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10042                // View was rejected last time it was drawn by its parent; this may have changed
10043                invalidateParentIfNeeded();
10044            }
10045        }
10046    }
10047
10048    /**
10049     * Hit rectangle in parent's coordinates
10050     *
10051     * @param outRect The hit rectangle of the view.
10052     */
10053    public void getHitRect(Rect outRect) {
10054        updateMatrix();
10055        final TransformationInfo info = mTransformationInfo;
10056        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10057            outRect.set(mLeft, mTop, mRight, mBottom);
10058        } else {
10059            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10060            tmpRect.set(0, 0, getWidth(), getHeight());
10061            info.mMatrix.mapRect(tmpRect);
10062            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10063                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10064        }
10065    }
10066
10067    /**
10068     * Determines whether the given point, in local coordinates is inside the view.
10069     */
10070    /*package*/ final boolean pointInView(float localX, float localY) {
10071        return localX >= 0 && localX < (mRight - mLeft)
10072                && localY >= 0 && localY < (mBottom - mTop);
10073    }
10074
10075    /**
10076     * Utility method to determine whether the given point, in local coordinates,
10077     * is inside the view, where the area of the view is expanded by the slop factor.
10078     * This method is called while processing touch-move events to determine if the event
10079     * is still within the view.
10080     *
10081     * @hide
10082     */
10083    public boolean pointInView(float localX, float localY, float slop) {
10084        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10085                localY < ((mBottom - mTop) + slop);
10086    }
10087
10088    /**
10089     * When a view has focus and the user navigates away from it, the next view is searched for
10090     * starting from the rectangle filled in by this method.
10091     *
10092     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10093     * of the view.  However, if your view maintains some idea of internal selection,
10094     * such as a cursor, or a selected row or column, you should override this method and
10095     * fill in a more specific rectangle.
10096     *
10097     * @param r The rectangle to fill in, in this view's coordinates.
10098     */
10099    public void getFocusedRect(Rect r) {
10100        getDrawingRect(r);
10101    }
10102
10103    /**
10104     * If some part of this view is not clipped by any of its parents, then
10105     * return that area in r in global (root) coordinates. To convert r to local
10106     * coordinates (without taking possible View rotations into account), offset
10107     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10108     * If the view is completely clipped or translated out, return false.
10109     *
10110     * @param r If true is returned, r holds the global coordinates of the
10111     *        visible portion of this view.
10112     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10113     *        between this view and its root. globalOffet may be null.
10114     * @return true if r is non-empty (i.e. part of the view is visible at the
10115     *         root level.
10116     */
10117    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10118        int width = mRight - mLeft;
10119        int height = mBottom - mTop;
10120        if (width > 0 && height > 0) {
10121            r.set(0, 0, width, height);
10122            if (globalOffset != null) {
10123                globalOffset.set(-mScrollX, -mScrollY);
10124            }
10125            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10126        }
10127        return false;
10128    }
10129
10130    public final boolean getGlobalVisibleRect(Rect r) {
10131        return getGlobalVisibleRect(r, null);
10132    }
10133
10134    public final boolean getLocalVisibleRect(Rect r) {
10135        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10136        if (getGlobalVisibleRect(r, offset)) {
10137            r.offset(-offset.x, -offset.y); // make r local
10138            return true;
10139        }
10140        return false;
10141    }
10142
10143    /**
10144     * Offset this view's vertical location by the specified number of pixels.
10145     *
10146     * @param offset the number of pixels to offset the view by
10147     */
10148    public void offsetTopAndBottom(int offset) {
10149        if (offset != 0) {
10150            updateMatrix();
10151            final boolean matrixIsIdentity = mTransformationInfo == null
10152                    || mTransformationInfo.mMatrixIsIdentity;
10153            if (matrixIsIdentity) {
10154                if (mDisplayList != null) {
10155                    invalidateViewProperty(false, false);
10156                } else {
10157                    final ViewParent p = mParent;
10158                    if (p != null && mAttachInfo != null) {
10159                        final Rect r = mAttachInfo.mTmpInvalRect;
10160                        int minTop;
10161                        int maxBottom;
10162                        int yLoc;
10163                        if (offset < 0) {
10164                            minTop = mTop + offset;
10165                            maxBottom = mBottom;
10166                            yLoc = offset;
10167                        } else {
10168                            minTop = mTop;
10169                            maxBottom = mBottom + offset;
10170                            yLoc = 0;
10171                        }
10172                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10173                        p.invalidateChild(this, r);
10174                    }
10175                }
10176            } else {
10177                invalidateViewProperty(false, false);
10178            }
10179
10180            mTop += offset;
10181            mBottom += offset;
10182            if (mDisplayList != null) {
10183                mDisplayList.offsetTopAndBottom(offset);
10184                invalidateViewProperty(false, false);
10185            } else {
10186                if (!matrixIsIdentity) {
10187                    invalidateViewProperty(false, true);
10188                }
10189                invalidateParentIfNeeded();
10190            }
10191        }
10192    }
10193
10194    /**
10195     * Offset this view's horizontal location by the specified amount of pixels.
10196     *
10197     * @param offset the number of pixels to offset the view by
10198     */
10199    public void offsetLeftAndRight(int offset) {
10200        if (offset != 0) {
10201            updateMatrix();
10202            final boolean matrixIsIdentity = mTransformationInfo == null
10203                    || mTransformationInfo.mMatrixIsIdentity;
10204            if (matrixIsIdentity) {
10205                if (mDisplayList != null) {
10206                    invalidateViewProperty(false, false);
10207                } else {
10208                    final ViewParent p = mParent;
10209                    if (p != null && mAttachInfo != null) {
10210                        final Rect r = mAttachInfo.mTmpInvalRect;
10211                        int minLeft;
10212                        int maxRight;
10213                        if (offset < 0) {
10214                            minLeft = mLeft + offset;
10215                            maxRight = mRight;
10216                        } else {
10217                            minLeft = mLeft;
10218                            maxRight = mRight + offset;
10219                        }
10220                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10221                        p.invalidateChild(this, r);
10222                    }
10223                }
10224            } else {
10225                invalidateViewProperty(false, false);
10226            }
10227
10228            mLeft += offset;
10229            mRight += offset;
10230            if (mDisplayList != null) {
10231                mDisplayList.offsetLeftAndRight(offset);
10232                invalidateViewProperty(false, false);
10233            } else {
10234                if (!matrixIsIdentity) {
10235                    invalidateViewProperty(false, true);
10236                }
10237                invalidateParentIfNeeded();
10238            }
10239        }
10240    }
10241
10242    /**
10243     * Get the LayoutParams associated with this view. All views should have
10244     * layout parameters. These supply parameters to the <i>parent</i> of this
10245     * view specifying how it should be arranged. There are many subclasses of
10246     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10247     * of ViewGroup that are responsible for arranging their children.
10248     *
10249     * This method may return null if this View is not attached to a parent
10250     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10251     * was not invoked successfully. When a View is attached to a parent
10252     * ViewGroup, this method must not return null.
10253     *
10254     * @return The LayoutParams associated with this view, or null if no
10255     *         parameters have been set yet
10256     */
10257    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10258    public ViewGroup.LayoutParams getLayoutParams() {
10259        return mLayoutParams;
10260    }
10261
10262    /**
10263     * Set the layout parameters associated with this view. These supply
10264     * parameters to the <i>parent</i> of this view specifying how it should be
10265     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10266     * correspond to the different subclasses of ViewGroup that are responsible
10267     * for arranging their children.
10268     *
10269     * @param params The layout parameters for this view, cannot be null
10270     */
10271    public void setLayoutParams(ViewGroup.LayoutParams params) {
10272        if (params == null) {
10273            throw new NullPointerException("Layout parameters cannot be null");
10274        }
10275        mLayoutParams = params;
10276        resolveLayoutParams();
10277        if (mParent instanceof ViewGroup) {
10278            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10279        }
10280        requestLayout();
10281    }
10282
10283    /**
10284     * Resolve the layout parameters depending on the resolved layout direction
10285     *
10286     * @hide
10287     */
10288    public void resolveLayoutParams() {
10289        if (mLayoutParams != null) {
10290            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10291        }
10292    }
10293
10294    /**
10295     * Set the scrolled position of your view. This will cause a call to
10296     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10297     * invalidated.
10298     * @param x the x position to scroll to
10299     * @param y the y position to scroll to
10300     */
10301    public void scrollTo(int x, int y) {
10302        if (mScrollX != x || mScrollY != y) {
10303            int oldX = mScrollX;
10304            int oldY = mScrollY;
10305            mScrollX = x;
10306            mScrollY = y;
10307            invalidateParentCaches();
10308            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10309            if (!awakenScrollBars()) {
10310                postInvalidateOnAnimation();
10311            }
10312        }
10313    }
10314
10315    /**
10316     * Move the scrolled position of your view. This will cause a call to
10317     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10318     * invalidated.
10319     * @param x the amount of pixels to scroll by horizontally
10320     * @param y the amount of pixels to scroll by vertically
10321     */
10322    public void scrollBy(int x, int y) {
10323        scrollTo(mScrollX + x, mScrollY + y);
10324    }
10325
10326    /**
10327     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10328     * animation to fade the scrollbars out after a default delay. If a subclass
10329     * provides animated scrolling, the start delay should equal the duration
10330     * of the scrolling animation.</p>
10331     *
10332     * <p>The animation starts only if at least one of the scrollbars is
10333     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10334     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10335     * this method returns true, and false otherwise. If the animation is
10336     * started, this method calls {@link #invalidate()}; in that case the
10337     * caller should not call {@link #invalidate()}.</p>
10338     *
10339     * <p>This method should be invoked every time a subclass directly updates
10340     * the scroll parameters.</p>
10341     *
10342     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10343     * and {@link #scrollTo(int, int)}.</p>
10344     *
10345     * @return true if the animation is played, false otherwise
10346     *
10347     * @see #awakenScrollBars(int)
10348     * @see #scrollBy(int, int)
10349     * @see #scrollTo(int, int)
10350     * @see #isHorizontalScrollBarEnabled()
10351     * @see #isVerticalScrollBarEnabled()
10352     * @see #setHorizontalScrollBarEnabled(boolean)
10353     * @see #setVerticalScrollBarEnabled(boolean)
10354     */
10355    protected boolean awakenScrollBars() {
10356        return mScrollCache != null &&
10357                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10358    }
10359
10360    /**
10361     * Trigger the scrollbars to draw.
10362     * This method differs from awakenScrollBars() only in its default duration.
10363     * initialAwakenScrollBars() will show the scroll bars for longer than
10364     * usual to give the user more of a chance to notice them.
10365     *
10366     * @return true if the animation is played, false otherwise.
10367     */
10368    private boolean initialAwakenScrollBars() {
10369        return mScrollCache != null &&
10370                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10371    }
10372
10373    /**
10374     * <p>
10375     * Trigger the scrollbars to draw. When invoked this method starts an
10376     * animation to fade the scrollbars out after a fixed delay. If a subclass
10377     * provides animated scrolling, the start delay should equal the duration of
10378     * the scrolling animation.
10379     * </p>
10380     *
10381     * <p>
10382     * The animation starts only if at least one of the scrollbars is enabled,
10383     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10384     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10385     * this method returns true, and false otherwise. If the animation is
10386     * started, this method calls {@link #invalidate()}; in that case the caller
10387     * should not call {@link #invalidate()}.
10388     * </p>
10389     *
10390     * <p>
10391     * This method should be invoked everytime a subclass directly updates the
10392     * scroll parameters.
10393     * </p>
10394     *
10395     * @param startDelay the delay, in milliseconds, after which the animation
10396     *        should start; when the delay is 0, the animation starts
10397     *        immediately
10398     * @return true if the animation is played, false otherwise
10399     *
10400     * @see #scrollBy(int, int)
10401     * @see #scrollTo(int, int)
10402     * @see #isHorizontalScrollBarEnabled()
10403     * @see #isVerticalScrollBarEnabled()
10404     * @see #setHorizontalScrollBarEnabled(boolean)
10405     * @see #setVerticalScrollBarEnabled(boolean)
10406     */
10407    protected boolean awakenScrollBars(int startDelay) {
10408        return awakenScrollBars(startDelay, true);
10409    }
10410
10411    /**
10412     * <p>
10413     * Trigger the scrollbars to draw. When invoked this method starts an
10414     * animation to fade the scrollbars out after a fixed delay. If a subclass
10415     * provides animated scrolling, the start delay should equal the duration of
10416     * the scrolling animation.
10417     * </p>
10418     *
10419     * <p>
10420     * The animation starts only if at least one of the scrollbars is enabled,
10421     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10422     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10423     * this method returns true, and false otherwise. If the animation is
10424     * started, this method calls {@link #invalidate()} if the invalidate parameter
10425     * is set to true; in that case the caller
10426     * should not call {@link #invalidate()}.
10427     * </p>
10428     *
10429     * <p>
10430     * This method should be invoked everytime a subclass directly updates the
10431     * scroll parameters.
10432     * </p>
10433     *
10434     * @param startDelay the delay, in milliseconds, after which the animation
10435     *        should start; when the delay is 0, the animation starts
10436     *        immediately
10437     *
10438     * @param invalidate Wheter this method should call invalidate
10439     *
10440     * @return true if the animation is played, false otherwise
10441     *
10442     * @see #scrollBy(int, int)
10443     * @see #scrollTo(int, int)
10444     * @see #isHorizontalScrollBarEnabled()
10445     * @see #isVerticalScrollBarEnabled()
10446     * @see #setHorizontalScrollBarEnabled(boolean)
10447     * @see #setVerticalScrollBarEnabled(boolean)
10448     */
10449    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10450        final ScrollabilityCache scrollCache = mScrollCache;
10451
10452        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10453            return false;
10454        }
10455
10456        if (scrollCache.scrollBar == null) {
10457            scrollCache.scrollBar = new ScrollBarDrawable();
10458        }
10459
10460        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10461
10462            if (invalidate) {
10463                // Invalidate to show the scrollbars
10464                postInvalidateOnAnimation();
10465            }
10466
10467            if (scrollCache.state == ScrollabilityCache.OFF) {
10468                // FIXME: this is copied from WindowManagerService.
10469                // We should get this value from the system when it
10470                // is possible to do so.
10471                final int KEY_REPEAT_FIRST_DELAY = 750;
10472                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10473            }
10474
10475            // Tell mScrollCache when we should start fading. This may
10476            // extend the fade start time if one was already scheduled
10477            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10478            scrollCache.fadeStartTime = fadeStartTime;
10479            scrollCache.state = ScrollabilityCache.ON;
10480
10481            // Schedule our fader to run, unscheduling any old ones first
10482            if (mAttachInfo != null) {
10483                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10484                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10485            }
10486
10487            return true;
10488        }
10489
10490        return false;
10491    }
10492
10493    /**
10494     * Do not invalidate views which are not visible and which are not running an animation. They
10495     * will not get drawn and they should not set dirty flags as if they will be drawn
10496     */
10497    private boolean skipInvalidate() {
10498        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10499                (!(mParent instanceof ViewGroup) ||
10500                        !((ViewGroup) mParent).isViewTransitioning(this));
10501    }
10502    /**
10503     * Mark the area defined by dirty as needing to be drawn. If the view is
10504     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10505     * in the future. This must be called from a UI thread. To call from a non-UI
10506     * thread, call {@link #postInvalidate()}.
10507     *
10508     * WARNING: This method is destructive to dirty.
10509     * @param dirty the rectangle representing the bounds of the dirty region
10510     */
10511    public void invalidate(Rect dirty) {
10512        if (skipInvalidate()) {
10513            return;
10514        }
10515        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10516                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10517                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10518            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10519            mPrivateFlags |= PFLAG_INVALIDATED;
10520            mPrivateFlags |= PFLAG_DIRTY;
10521            final ViewParent p = mParent;
10522            final AttachInfo ai = mAttachInfo;
10523            //noinspection PointlessBooleanExpression,ConstantConditions
10524            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10525                if (p != null && ai != null && ai.mHardwareAccelerated) {
10526                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10527                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10528                    p.invalidateChild(this, null);
10529                    return;
10530                }
10531            }
10532            if (p != null && ai != null) {
10533                final int scrollX = mScrollX;
10534                final int scrollY = mScrollY;
10535                final Rect r = ai.mTmpInvalRect;
10536                r.set(dirty.left - scrollX, dirty.top - scrollY,
10537                        dirty.right - scrollX, dirty.bottom - scrollY);
10538                mParent.invalidateChild(this, r);
10539            }
10540        }
10541    }
10542
10543    /**
10544     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10545     * The coordinates of the dirty rect are relative to the view.
10546     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10547     * will be called at some point in the future. This must be called from
10548     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10549     * @param l the left position of the dirty region
10550     * @param t the top position of the dirty region
10551     * @param r the right position of the dirty region
10552     * @param b the bottom position of the dirty region
10553     */
10554    public void invalidate(int l, int t, int r, int b) {
10555        if (skipInvalidate()) {
10556            return;
10557        }
10558        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10559                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10560                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10561            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10562            mPrivateFlags |= PFLAG_INVALIDATED;
10563            mPrivateFlags |= PFLAG_DIRTY;
10564            final ViewParent p = mParent;
10565            final AttachInfo ai = mAttachInfo;
10566            //noinspection PointlessBooleanExpression,ConstantConditions
10567            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10568                if (p != null && ai != null && ai.mHardwareAccelerated) {
10569                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10570                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10571                    p.invalidateChild(this, null);
10572                    return;
10573                }
10574            }
10575            if (p != null && ai != null && l < r && t < b) {
10576                final int scrollX = mScrollX;
10577                final int scrollY = mScrollY;
10578                final Rect tmpr = ai.mTmpInvalRect;
10579                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10580                p.invalidateChild(this, tmpr);
10581            }
10582        }
10583    }
10584
10585    /**
10586     * Invalidate the whole view. If the view is visible,
10587     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10588     * the future. This must be called from a UI thread. To call from a non-UI thread,
10589     * call {@link #postInvalidate()}.
10590     */
10591    public void invalidate() {
10592        invalidate(true);
10593    }
10594
10595    /**
10596     * This is where the invalidate() work actually happens. A full invalidate()
10597     * causes the drawing cache to be invalidated, but this function can be called with
10598     * invalidateCache set to false to skip that invalidation step for cases that do not
10599     * need it (for example, a component that remains at the same dimensions with the same
10600     * content).
10601     *
10602     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10603     * well. This is usually true for a full invalidate, but may be set to false if the
10604     * View's contents or dimensions have not changed.
10605     */
10606    void invalidate(boolean invalidateCache) {
10607        if (skipInvalidate()) {
10608            return;
10609        }
10610        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10611                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10612                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10613            mLastIsOpaque = isOpaque();
10614            mPrivateFlags &= ~PFLAG_DRAWN;
10615            mPrivateFlags |= PFLAG_DIRTY;
10616            if (invalidateCache) {
10617                mPrivateFlags |= PFLAG_INVALIDATED;
10618                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10619            }
10620            final AttachInfo ai = mAttachInfo;
10621            final ViewParent p = mParent;
10622            //noinspection PointlessBooleanExpression,ConstantConditions
10623            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10624                if (p != null && ai != null && ai.mHardwareAccelerated) {
10625                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10626                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10627                    p.invalidateChild(this, null);
10628                    return;
10629                }
10630            }
10631
10632            if (p != null && ai != null) {
10633                final Rect r = ai.mTmpInvalRect;
10634                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10635                // Don't call invalidate -- we don't want to internally scroll
10636                // our own bounds
10637                p.invalidateChild(this, r);
10638            }
10639        }
10640    }
10641
10642    /**
10643     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10644     * set any flags or handle all of the cases handled by the default invalidation methods.
10645     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10646     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10647     * walk up the hierarchy, transforming the dirty rect as necessary.
10648     *
10649     * The method also handles normal invalidation logic if display list properties are not
10650     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10651     * backup approach, to handle these cases used in the various property-setting methods.
10652     *
10653     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10654     * are not being used in this view
10655     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10656     * list properties are not being used in this view
10657     */
10658    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10659        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10660            if (invalidateParent) {
10661                invalidateParentCaches();
10662            }
10663            if (forceRedraw) {
10664                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10665            }
10666            invalidate(false);
10667        } else {
10668            final AttachInfo ai = mAttachInfo;
10669            final ViewParent p = mParent;
10670            if (p != null && ai != null) {
10671                final Rect r = ai.mTmpInvalRect;
10672                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10673                if (mParent instanceof ViewGroup) {
10674                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10675                } else {
10676                    mParent.invalidateChild(this, r);
10677                }
10678            }
10679        }
10680    }
10681
10682    /**
10683     * Utility method to transform a given Rect by the current matrix of this view.
10684     */
10685    void transformRect(final Rect rect) {
10686        if (!getMatrix().isIdentity()) {
10687            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10688            boundingRect.set(rect);
10689            getMatrix().mapRect(boundingRect);
10690            rect.set((int) Math.floor(boundingRect.left),
10691                    (int) Math.floor(boundingRect.top),
10692                    (int) Math.ceil(boundingRect.right),
10693                    (int) Math.ceil(boundingRect.bottom));
10694        }
10695    }
10696
10697    /**
10698     * Used to indicate that the parent of this view should clear its caches. This functionality
10699     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10700     * which is necessary when various parent-managed properties of the view change, such as
10701     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10702     * clears the parent caches and does not causes an invalidate event.
10703     *
10704     * @hide
10705     */
10706    protected void invalidateParentCaches() {
10707        if (mParent instanceof View) {
10708            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10709        }
10710    }
10711
10712    /**
10713     * Used to indicate that the parent of this view should be invalidated. This functionality
10714     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10715     * which is necessary when various parent-managed properties of the view change, such as
10716     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10717     * an invalidation event to the parent.
10718     *
10719     * @hide
10720     */
10721    protected void invalidateParentIfNeeded() {
10722        if (isHardwareAccelerated() && mParent instanceof View) {
10723            ((View) mParent).invalidate(true);
10724        }
10725    }
10726
10727    /**
10728     * Indicates whether this View is opaque. An opaque View guarantees that it will
10729     * draw all the pixels overlapping its bounds using a fully opaque color.
10730     *
10731     * Subclasses of View should override this method whenever possible to indicate
10732     * whether an instance is opaque. Opaque Views are treated in a special way by
10733     * the View hierarchy, possibly allowing it to perform optimizations during
10734     * invalidate/draw passes.
10735     *
10736     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10737     */
10738    @ViewDebug.ExportedProperty(category = "drawing")
10739    public boolean isOpaque() {
10740        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10741                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10742    }
10743
10744    /**
10745     * @hide
10746     */
10747    protected void computeOpaqueFlags() {
10748        // Opaque if:
10749        //   - Has a background
10750        //   - Background is opaque
10751        //   - Doesn't have scrollbars or scrollbars overlay
10752
10753        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10754            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10755        } else {
10756            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10757        }
10758
10759        final int flags = mViewFlags;
10760        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10761                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10762                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10763            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10764        } else {
10765            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10766        }
10767    }
10768
10769    /**
10770     * @hide
10771     */
10772    protected boolean hasOpaqueScrollbars() {
10773        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10774    }
10775
10776    /**
10777     * @return A handler associated with the thread running the View. This
10778     * handler can be used to pump events in the UI events queue.
10779     */
10780    public Handler getHandler() {
10781        final AttachInfo attachInfo = mAttachInfo;
10782        if (attachInfo != null) {
10783            return attachInfo.mHandler;
10784        }
10785        return null;
10786    }
10787
10788    /**
10789     * Gets the view root associated with the View.
10790     * @return The view root, or null if none.
10791     * @hide
10792     */
10793    public ViewRootImpl getViewRootImpl() {
10794        if (mAttachInfo != null) {
10795            return mAttachInfo.mViewRootImpl;
10796        }
10797        return null;
10798    }
10799
10800    /**
10801     * <p>Causes the Runnable to be added to the message queue.
10802     * The runnable will be run on the user interface thread.</p>
10803     *
10804     * @param action The Runnable that will be executed.
10805     *
10806     * @return Returns true if the Runnable was successfully placed in to the
10807     *         message queue.  Returns false on failure, usually because the
10808     *         looper processing the message queue is exiting.
10809     *
10810     * @see #postDelayed
10811     * @see #removeCallbacks
10812     */
10813    public boolean post(Runnable action) {
10814        final AttachInfo attachInfo = mAttachInfo;
10815        if (attachInfo != null) {
10816            return attachInfo.mHandler.post(action);
10817        }
10818        // Assume that post will succeed later
10819        ViewRootImpl.getRunQueue().post(action);
10820        return true;
10821    }
10822
10823    /**
10824     * <p>Causes the Runnable to be added to the message queue, to be run
10825     * after the specified amount of time elapses.
10826     * The runnable will be run on the user interface thread.</p>
10827     *
10828     * @param action The Runnable that will be executed.
10829     * @param delayMillis The delay (in milliseconds) until the Runnable
10830     *        will be executed.
10831     *
10832     * @return true if the Runnable was successfully placed in to the
10833     *         message queue.  Returns false on failure, usually because the
10834     *         looper processing the message queue is exiting.  Note that a
10835     *         result of true does not mean the Runnable will be processed --
10836     *         if the looper is quit before the delivery time of the message
10837     *         occurs then the message will be dropped.
10838     *
10839     * @see #post
10840     * @see #removeCallbacks
10841     */
10842    public boolean postDelayed(Runnable action, long delayMillis) {
10843        final AttachInfo attachInfo = mAttachInfo;
10844        if (attachInfo != null) {
10845            return attachInfo.mHandler.postDelayed(action, delayMillis);
10846        }
10847        // Assume that post will succeed later
10848        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10849        return true;
10850    }
10851
10852    /**
10853     * <p>Causes the Runnable to execute on the next animation time step.
10854     * The runnable will be run on the user interface thread.</p>
10855     *
10856     * @param action The Runnable that will be executed.
10857     *
10858     * @see #postOnAnimationDelayed
10859     * @see #removeCallbacks
10860     */
10861    public void postOnAnimation(Runnable action) {
10862        final AttachInfo attachInfo = mAttachInfo;
10863        if (attachInfo != null) {
10864            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10865                    Choreographer.CALLBACK_ANIMATION, action, null);
10866        } else {
10867            // Assume that post will succeed later
10868            ViewRootImpl.getRunQueue().post(action);
10869        }
10870    }
10871
10872    /**
10873     * <p>Causes the Runnable to execute on the next animation time step,
10874     * after the specified amount of time elapses.
10875     * The runnable will be run on the user interface thread.</p>
10876     *
10877     * @param action The Runnable that will be executed.
10878     * @param delayMillis The delay (in milliseconds) until the Runnable
10879     *        will be executed.
10880     *
10881     * @see #postOnAnimation
10882     * @see #removeCallbacks
10883     */
10884    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10885        final AttachInfo attachInfo = mAttachInfo;
10886        if (attachInfo != null) {
10887            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10888                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10889        } else {
10890            // Assume that post will succeed later
10891            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10892        }
10893    }
10894
10895    /**
10896     * <p>Removes the specified Runnable from the message queue.</p>
10897     *
10898     * @param action The Runnable to remove from the message handling queue
10899     *
10900     * @return true if this view could ask the Handler to remove the Runnable,
10901     *         false otherwise. When the returned value is true, the Runnable
10902     *         may or may not have been actually removed from the message queue
10903     *         (for instance, if the Runnable was not in the queue already.)
10904     *
10905     * @see #post
10906     * @see #postDelayed
10907     * @see #postOnAnimation
10908     * @see #postOnAnimationDelayed
10909     */
10910    public boolean removeCallbacks(Runnable action) {
10911        if (action != null) {
10912            final AttachInfo attachInfo = mAttachInfo;
10913            if (attachInfo != null) {
10914                attachInfo.mHandler.removeCallbacks(action);
10915                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10916                        Choreographer.CALLBACK_ANIMATION, action, null);
10917            } else {
10918                // Assume that post will succeed later
10919                ViewRootImpl.getRunQueue().removeCallbacks(action);
10920            }
10921        }
10922        return true;
10923    }
10924
10925    /**
10926     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10927     * Use this to invalidate the View from a non-UI thread.</p>
10928     *
10929     * <p>This method can be invoked from outside of the UI thread
10930     * only when this View is attached to a window.</p>
10931     *
10932     * @see #invalidate()
10933     * @see #postInvalidateDelayed(long)
10934     */
10935    public void postInvalidate() {
10936        postInvalidateDelayed(0);
10937    }
10938
10939    /**
10940     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10941     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10942     *
10943     * <p>This method can be invoked from outside of the UI thread
10944     * only when this View is attached to a window.</p>
10945     *
10946     * @param left The left coordinate of the rectangle to invalidate.
10947     * @param top The top coordinate of the rectangle to invalidate.
10948     * @param right The right coordinate of the rectangle to invalidate.
10949     * @param bottom The bottom coordinate of the rectangle to invalidate.
10950     *
10951     * @see #invalidate(int, int, int, int)
10952     * @see #invalidate(Rect)
10953     * @see #postInvalidateDelayed(long, int, int, int, int)
10954     */
10955    public void postInvalidate(int left, int top, int right, int bottom) {
10956        postInvalidateDelayed(0, left, top, right, bottom);
10957    }
10958
10959    /**
10960     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10961     * loop. Waits for the specified amount of time.</p>
10962     *
10963     * <p>This method can be invoked from outside of the UI thread
10964     * only when this View is attached to a window.</p>
10965     *
10966     * @param delayMilliseconds the duration in milliseconds to delay the
10967     *         invalidation by
10968     *
10969     * @see #invalidate()
10970     * @see #postInvalidate()
10971     */
10972    public void postInvalidateDelayed(long delayMilliseconds) {
10973        // We try only with the AttachInfo because there's no point in invalidating
10974        // if we are not attached to our window
10975        final AttachInfo attachInfo = mAttachInfo;
10976        if (attachInfo != null) {
10977            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10978        }
10979    }
10980
10981    /**
10982     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10983     * through the event loop. Waits for the specified amount of time.</p>
10984     *
10985     * <p>This method can be invoked from outside of the UI thread
10986     * only when this View is attached to a window.</p>
10987     *
10988     * @param delayMilliseconds the duration in milliseconds to delay the
10989     *         invalidation by
10990     * @param left The left coordinate of the rectangle to invalidate.
10991     * @param top The top coordinate of the rectangle to invalidate.
10992     * @param right The right coordinate of the rectangle to invalidate.
10993     * @param bottom The bottom coordinate of the rectangle to invalidate.
10994     *
10995     * @see #invalidate(int, int, int, int)
10996     * @see #invalidate(Rect)
10997     * @see #postInvalidate(int, int, int, int)
10998     */
10999    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11000            int right, int bottom) {
11001
11002        // We try only with the AttachInfo because there's no point in invalidating
11003        // if we are not attached to our window
11004        final AttachInfo attachInfo = mAttachInfo;
11005        if (attachInfo != null) {
11006            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11007            info.target = this;
11008            info.left = left;
11009            info.top = top;
11010            info.right = right;
11011            info.bottom = bottom;
11012
11013            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11014        }
11015    }
11016
11017    /**
11018     * <p>Cause an invalidate to happen on the next animation time step, typically the
11019     * next display frame.</p>
11020     *
11021     * <p>This method can be invoked from outside of the UI thread
11022     * only when this View is attached to a window.</p>
11023     *
11024     * @see #invalidate()
11025     */
11026    public void postInvalidateOnAnimation() {
11027        // We try only with the AttachInfo because there's no point in invalidating
11028        // if we are not attached to our window
11029        final AttachInfo attachInfo = mAttachInfo;
11030        if (attachInfo != null) {
11031            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11032        }
11033    }
11034
11035    /**
11036     * <p>Cause an invalidate of the specified area to happen on the next animation
11037     * time step, typically the next display frame.</p>
11038     *
11039     * <p>This method can be invoked from outside of the UI thread
11040     * only when this View is attached to a window.</p>
11041     *
11042     * @param left The left coordinate of the rectangle to invalidate.
11043     * @param top The top coordinate of the rectangle to invalidate.
11044     * @param right The right coordinate of the rectangle to invalidate.
11045     * @param bottom The bottom coordinate of the rectangle to invalidate.
11046     *
11047     * @see #invalidate(int, int, int, int)
11048     * @see #invalidate(Rect)
11049     */
11050    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11051        // We try only with the AttachInfo because there's no point in invalidating
11052        // if we are not attached to our window
11053        final AttachInfo attachInfo = mAttachInfo;
11054        if (attachInfo != null) {
11055            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11056            info.target = this;
11057            info.left = left;
11058            info.top = top;
11059            info.right = right;
11060            info.bottom = bottom;
11061
11062            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11063        }
11064    }
11065
11066    /**
11067     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11068     * This event is sent at most once every
11069     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11070     */
11071    private void postSendViewScrolledAccessibilityEventCallback() {
11072        if (mSendViewScrolledAccessibilityEvent == null) {
11073            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11074        }
11075        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11076            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11077            postDelayed(mSendViewScrolledAccessibilityEvent,
11078                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11079        }
11080    }
11081
11082    /**
11083     * Called by a parent to request that a child update its values for mScrollX
11084     * and mScrollY if necessary. This will typically be done if the child is
11085     * animating a scroll using a {@link android.widget.Scroller Scroller}
11086     * object.
11087     */
11088    public void computeScroll() {
11089    }
11090
11091    /**
11092     * <p>Indicate whether the horizontal edges are faded when the view is
11093     * scrolled horizontally.</p>
11094     *
11095     * @return true if the horizontal edges should are faded on scroll, false
11096     *         otherwise
11097     *
11098     * @see #setHorizontalFadingEdgeEnabled(boolean)
11099     *
11100     * @attr ref android.R.styleable#View_requiresFadingEdge
11101     */
11102    public boolean isHorizontalFadingEdgeEnabled() {
11103        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11104    }
11105
11106    /**
11107     * <p>Define whether the horizontal edges should be faded when this view
11108     * is scrolled horizontally.</p>
11109     *
11110     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11111     *                                    be faded when the view is scrolled
11112     *                                    horizontally
11113     *
11114     * @see #isHorizontalFadingEdgeEnabled()
11115     *
11116     * @attr ref android.R.styleable#View_requiresFadingEdge
11117     */
11118    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11119        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11120            if (horizontalFadingEdgeEnabled) {
11121                initScrollCache();
11122            }
11123
11124            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11125        }
11126    }
11127
11128    /**
11129     * <p>Indicate whether the vertical edges are faded when the view is
11130     * scrolled horizontally.</p>
11131     *
11132     * @return true if the vertical edges should are faded on scroll, false
11133     *         otherwise
11134     *
11135     * @see #setVerticalFadingEdgeEnabled(boolean)
11136     *
11137     * @attr ref android.R.styleable#View_requiresFadingEdge
11138     */
11139    public boolean isVerticalFadingEdgeEnabled() {
11140        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11141    }
11142
11143    /**
11144     * <p>Define whether the vertical edges should be faded when this view
11145     * is scrolled vertically.</p>
11146     *
11147     * @param verticalFadingEdgeEnabled true if the vertical edges should
11148     *                                  be faded when the view is scrolled
11149     *                                  vertically
11150     *
11151     * @see #isVerticalFadingEdgeEnabled()
11152     *
11153     * @attr ref android.R.styleable#View_requiresFadingEdge
11154     */
11155    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11156        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11157            if (verticalFadingEdgeEnabled) {
11158                initScrollCache();
11159            }
11160
11161            mViewFlags ^= FADING_EDGE_VERTICAL;
11162        }
11163    }
11164
11165    /**
11166     * Returns the strength, or intensity, of the top faded edge. The strength is
11167     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11168     * returns 0.0 or 1.0 but no value in between.
11169     *
11170     * Subclasses should override this method to provide a smoother fade transition
11171     * when scrolling occurs.
11172     *
11173     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11174     */
11175    protected float getTopFadingEdgeStrength() {
11176        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11177    }
11178
11179    /**
11180     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11181     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11182     * returns 0.0 or 1.0 but no value in between.
11183     *
11184     * Subclasses should override this method to provide a smoother fade transition
11185     * when scrolling occurs.
11186     *
11187     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11188     */
11189    protected float getBottomFadingEdgeStrength() {
11190        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11191                computeVerticalScrollRange() ? 1.0f : 0.0f;
11192    }
11193
11194    /**
11195     * Returns the strength, or intensity, of the left faded edge. The strength is
11196     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11197     * returns 0.0 or 1.0 but no value in between.
11198     *
11199     * Subclasses should override this method to provide a smoother fade transition
11200     * when scrolling occurs.
11201     *
11202     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11203     */
11204    protected float getLeftFadingEdgeStrength() {
11205        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11206    }
11207
11208    /**
11209     * Returns the strength, or intensity, of the right faded edge. The strength is
11210     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11211     * returns 0.0 or 1.0 but no value in between.
11212     *
11213     * Subclasses should override this method to provide a smoother fade transition
11214     * when scrolling occurs.
11215     *
11216     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11217     */
11218    protected float getRightFadingEdgeStrength() {
11219        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11220                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11221    }
11222
11223    /**
11224     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11225     * scrollbar is not drawn by default.</p>
11226     *
11227     * @return true if the horizontal scrollbar should be painted, false
11228     *         otherwise
11229     *
11230     * @see #setHorizontalScrollBarEnabled(boolean)
11231     */
11232    public boolean isHorizontalScrollBarEnabled() {
11233        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11234    }
11235
11236    /**
11237     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11238     * scrollbar is not drawn by default.</p>
11239     *
11240     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11241     *                                   be painted
11242     *
11243     * @see #isHorizontalScrollBarEnabled()
11244     */
11245    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11246        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11247            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11248            computeOpaqueFlags();
11249            resolvePadding();
11250        }
11251    }
11252
11253    /**
11254     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11255     * scrollbar is not drawn by default.</p>
11256     *
11257     * @return true if the vertical scrollbar should be painted, false
11258     *         otherwise
11259     *
11260     * @see #setVerticalScrollBarEnabled(boolean)
11261     */
11262    public boolean isVerticalScrollBarEnabled() {
11263        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11264    }
11265
11266    /**
11267     * <p>Define whether the vertical scrollbar should be drawn or not. The
11268     * scrollbar is not drawn by default.</p>
11269     *
11270     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11271     *                                 be painted
11272     *
11273     * @see #isVerticalScrollBarEnabled()
11274     */
11275    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11276        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11277            mViewFlags ^= SCROLLBARS_VERTICAL;
11278            computeOpaqueFlags();
11279            resolvePadding();
11280        }
11281    }
11282
11283    /**
11284     * @hide
11285     */
11286    protected void recomputePadding() {
11287        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11288    }
11289
11290    /**
11291     * Define whether scrollbars will fade when the view is not scrolling.
11292     *
11293     * @param fadeScrollbars wheter to enable fading
11294     *
11295     * @attr ref android.R.styleable#View_fadeScrollbars
11296     */
11297    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11298        initScrollCache();
11299        final ScrollabilityCache scrollabilityCache = mScrollCache;
11300        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11301        if (fadeScrollbars) {
11302            scrollabilityCache.state = ScrollabilityCache.OFF;
11303        } else {
11304            scrollabilityCache.state = ScrollabilityCache.ON;
11305        }
11306    }
11307
11308    /**
11309     *
11310     * Returns true if scrollbars will fade when this view is not scrolling
11311     *
11312     * @return true if scrollbar fading is enabled
11313     *
11314     * @attr ref android.R.styleable#View_fadeScrollbars
11315     */
11316    public boolean isScrollbarFadingEnabled() {
11317        return mScrollCache != null && mScrollCache.fadeScrollBars;
11318    }
11319
11320    /**
11321     *
11322     * Returns the delay before scrollbars fade.
11323     *
11324     * @return the delay before scrollbars fade
11325     *
11326     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11327     */
11328    public int getScrollBarDefaultDelayBeforeFade() {
11329        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11330                mScrollCache.scrollBarDefaultDelayBeforeFade;
11331    }
11332
11333    /**
11334     * Define the delay before scrollbars fade.
11335     *
11336     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11337     *
11338     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11339     */
11340    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11341        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11342    }
11343
11344    /**
11345     *
11346     * Returns the scrollbar fade duration.
11347     *
11348     * @return the scrollbar fade duration
11349     *
11350     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11351     */
11352    public int getScrollBarFadeDuration() {
11353        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11354                mScrollCache.scrollBarFadeDuration;
11355    }
11356
11357    /**
11358     * Define the scrollbar fade duration.
11359     *
11360     * @param scrollBarFadeDuration - the scrollbar fade duration
11361     *
11362     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11363     */
11364    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11365        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11366    }
11367
11368    /**
11369     *
11370     * Returns the scrollbar size.
11371     *
11372     * @return the scrollbar size
11373     *
11374     * @attr ref android.R.styleable#View_scrollbarSize
11375     */
11376    public int getScrollBarSize() {
11377        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11378                mScrollCache.scrollBarSize;
11379    }
11380
11381    /**
11382     * Define the scrollbar size.
11383     *
11384     * @param scrollBarSize - the scrollbar size
11385     *
11386     * @attr ref android.R.styleable#View_scrollbarSize
11387     */
11388    public void setScrollBarSize(int scrollBarSize) {
11389        getScrollCache().scrollBarSize = scrollBarSize;
11390    }
11391
11392    /**
11393     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11394     * inset. When inset, they add to the padding of the view. And the scrollbars
11395     * can be drawn inside the padding area or on the edge of the view. For example,
11396     * if a view has a background drawable and you want to draw the scrollbars
11397     * inside the padding specified by the drawable, you can use
11398     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11399     * appear at the edge of the view, ignoring the padding, then you can use
11400     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11401     * @param style the style of the scrollbars. Should be one of
11402     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11403     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11404     * @see #SCROLLBARS_INSIDE_OVERLAY
11405     * @see #SCROLLBARS_INSIDE_INSET
11406     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11407     * @see #SCROLLBARS_OUTSIDE_INSET
11408     *
11409     * @attr ref android.R.styleable#View_scrollbarStyle
11410     */
11411    public void setScrollBarStyle(int style) {
11412        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11413            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11414            computeOpaqueFlags();
11415            resolvePadding();
11416        }
11417    }
11418
11419    /**
11420     * <p>Returns the current scrollbar style.</p>
11421     * @return the current scrollbar style
11422     * @see #SCROLLBARS_INSIDE_OVERLAY
11423     * @see #SCROLLBARS_INSIDE_INSET
11424     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11425     * @see #SCROLLBARS_OUTSIDE_INSET
11426     *
11427     * @attr ref android.R.styleable#View_scrollbarStyle
11428     */
11429    @ViewDebug.ExportedProperty(mapping = {
11430            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11431            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11432            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11433            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11434    })
11435    public int getScrollBarStyle() {
11436        return mViewFlags & SCROLLBARS_STYLE_MASK;
11437    }
11438
11439    /**
11440     * <p>Compute the horizontal range that the horizontal scrollbar
11441     * represents.</p>
11442     *
11443     * <p>The range is expressed in arbitrary units that must be the same as the
11444     * units used by {@link #computeHorizontalScrollExtent()} and
11445     * {@link #computeHorizontalScrollOffset()}.</p>
11446     *
11447     * <p>The default range is the drawing width of this view.</p>
11448     *
11449     * @return the total horizontal range represented by the horizontal
11450     *         scrollbar
11451     *
11452     * @see #computeHorizontalScrollExtent()
11453     * @see #computeHorizontalScrollOffset()
11454     * @see android.widget.ScrollBarDrawable
11455     */
11456    protected int computeHorizontalScrollRange() {
11457        return getWidth();
11458    }
11459
11460    /**
11461     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11462     * within the horizontal range. This value is used to compute the position
11463     * of the thumb within the scrollbar's track.</p>
11464     *
11465     * <p>The range is expressed in arbitrary units that must be the same as the
11466     * units used by {@link #computeHorizontalScrollRange()} and
11467     * {@link #computeHorizontalScrollExtent()}.</p>
11468     *
11469     * <p>The default offset is the scroll offset of this view.</p>
11470     *
11471     * @return the horizontal offset of the scrollbar's thumb
11472     *
11473     * @see #computeHorizontalScrollRange()
11474     * @see #computeHorizontalScrollExtent()
11475     * @see android.widget.ScrollBarDrawable
11476     */
11477    protected int computeHorizontalScrollOffset() {
11478        return mScrollX;
11479    }
11480
11481    /**
11482     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11483     * within the horizontal range. This value is used to compute the length
11484     * of the thumb within the scrollbar's track.</p>
11485     *
11486     * <p>The range is expressed in arbitrary units that must be the same as the
11487     * units used by {@link #computeHorizontalScrollRange()} and
11488     * {@link #computeHorizontalScrollOffset()}.</p>
11489     *
11490     * <p>The default extent is the drawing width of this view.</p>
11491     *
11492     * @return the horizontal extent of the scrollbar's thumb
11493     *
11494     * @see #computeHorizontalScrollRange()
11495     * @see #computeHorizontalScrollOffset()
11496     * @see android.widget.ScrollBarDrawable
11497     */
11498    protected int computeHorizontalScrollExtent() {
11499        return getWidth();
11500    }
11501
11502    /**
11503     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11504     *
11505     * <p>The range is expressed in arbitrary units that must be the same as the
11506     * units used by {@link #computeVerticalScrollExtent()} and
11507     * {@link #computeVerticalScrollOffset()}.</p>
11508     *
11509     * @return the total vertical range represented by the vertical scrollbar
11510     *
11511     * <p>The default range is the drawing height of this view.</p>
11512     *
11513     * @see #computeVerticalScrollExtent()
11514     * @see #computeVerticalScrollOffset()
11515     * @see android.widget.ScrollBarDrawable
11516     */
11517    protected int computeVerticalScrollRange() {
11518        return getHeight();
11519    }
11520
11521    /**
11522     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11523     * within the horizontal range. This value is used to compute the position
11524     * of the thumb within the scrollbar's track.</p>
11525     *
11526     * <p>The range is expressed in arbitrary units that must be the same as the
11527     * units used by {@link #computeVerticalScrollRange()} and
11528     * {@link #computeVerticalScrollExtent()}.</p>
11529     *
11530     * <p>The default offset is the scroll offset of this view.</p>
11531     *
11532     * @return the vertical offset of the scrollbar's thumb
11533     *
11534     * @see #computeVerticalScrollRange()
11535     * @see #computeVerticalScrollExtent()
11536     * @see android.widget.ScrollBarDrawable
11537     */
11538    protected int computeVerticalScrollOffset() {
11539        return mScrollY;
11540    }
11541
11542    /**
11543     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11544     * within the vertical range. This value is used to compute the length
11545     * of the thumb within the scrollbar's track.</p>
11546     *
11547     * <p>The range is expressed in arbitrary units that must be the same as the
11548     * units used by {@link #computeVerticalScrollRange()} and
11549     * {@link #computeVerticalScrollOffset()}.</p>
11550     *
11551     * <p>The default extent is the drawing height of this view.</p>
11552     *
11553     * @return the vertical extent of the scrollbar's thumb
11554     *
11555     * @see #computeVerticalScrollRange()
11556     * @see #computeVerticalScrollOffset()
11557     * @see android.widget.ScrollBarDrawable
11558     */
11559    protected int computeVerticalScrollExtent() {
11560        return getHeight();
11561    }
11562
11563    /**
11564     * Check if this view can be scrolled horizontally in a certain direction.
11565     *
11566     * @param direction Negative to check scrolling left, positive to check scrolling right.
11567     * @return true if this view can be scrolled in the specified direction, false otherwise.
11568     */
11569    public boolean canScrollHorizontally(int direction) {
11570        final int offset = computeHorizontalScrollOffset();
11571        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11572        if (range == 0) return false;
11573        if (direction < 0) {
11574            return offset > 0;
11575        } else {
11576            return offset < range - 1;
11577        }
11578    }
11579
11580    /**
11581     * Check if this view can be scrolled vertically in a certain direction.
11582     *
11583     * @param direction Negative to check scrolling up, positive to check scrolling down.
11584     * @return true if this view can be scrolled in the specified direction, false otherwise.
11585     */
11586    public boolean canScrollVertically(int direction) {
11587        final int offset = computeVerticalScrollOffset();
11588        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11589        if (range == 0) return false;
11590        if (direction < 0) {
11591            return offset > 0;
11592        } else {
11593            return offset < range - 1;
11594        }
11595    }
11596
11597    /**
11598     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11599     * scrollbars are painted only if they have been awakened first.</p>
11600     *
11601     * @param canvas the canvas on which to draw the scrollbars
11602     *
11603     * @see #awakenScrollBars(int)
11604     */
11605    protected final void onDrawScrollBars(Canvas canvas) {
11606        // scrollbars are drawn only when the animation is running
11607        final ScrollabilityCache cache = mScrollCache;
11608        if (cache != null) {
11609
11610            int state = cache.state;
11611
11612            if (state == ScrollabilityCache.OFF) {
11613                return;
11614            }
11615
11616            boolean invalidate = false;
11617
11618            if (state == ScrollabilityCache.FADING) {
11619                // We're fading -- get our fade interpolation
11620                if (cache.interpolatorValues == null) {
11621                    cache.interpolatorValues = new float[1];
11622                }
11623
11624                float[] values = cache.interpolatorValues;
11625
11626                // Stops the animation if we're done
11627                if (cache.scrollBarInterpolator.timeToValues(values) ==
11628                        Interpolator.Result.FREEZE_END) {
11629                    cache.state = ScrollabilityCache.OFF;
11630                } else {
11631                    cache.scrollBar.setAlpha(Math.round(values[0]));
11632                }
11633
11634                // This will make the scroll bars inval themselves after
11635                // drawing. We only want this when we're fading so that
11636                // we prevent excessive redraws
11637                invalidate = true;
11638            } else {
11639                // We're just on -- but we may have been fading before so
11640                // reset alpha
11641                cache.scrollBar.setAlpha(255);
11642            }
11643
11644
11645            final int viewFlags = mViewFlags;
11646
11647            final boolean drawHorizontalScrollBar =
11648                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11649            final boolean drawVerticalScrollBar =
11650                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11651                && !isVerticalScrollBarHidden();
11652
11653            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11654                final int width = mRight - mLeft;
11655                final int height = mBottom - mTop;
11656
11657                final ScrollBarDrawable scrollBar = cache.scrollBar;
11658
11659                final int scrollX = mScrollX;
11660                final int scrollY = mScrollY;
11661                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11662
11663                int left;
11664                int top;
11665                int right;
11666                int bottom;
11667
11668                if (drawHorizontalScrollBar) {
11669                    int size = scrollBar.getSize(false);
11670                    if (size <= 0) {
11671                        size = cache.scrollBarSize;
11672                    }
11673
11674                    scrollBar.setParameters(computeHorizontalScrollRange(),
11675                                            computeHorizontalScrollOffset(),
11676                                            computeHorizontalScrollExtent(), false);
11677                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11678                            getVerticalScrollbarWidth() : 0;
11679                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11680                    left = scrollX + (mPaddingLeft & inside);
11681                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11682                    bottom = top + size;
11683                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11684                    if (invalidate) {
11685                        invalidate(left, top, right, bottom);
11686                    }
11687                }
11688
11689                if (drawVerticalScrollBar) {
11690                    int size = scrollBar.getSize(true);
11691                    if (size <= 0) {
11692                        size = cache.scrollBarSize;
11693                    }
11694
11695                    scrollBar.setParameters(computeVerticalScrollRange(),
11696                                            computeVerticalScrollOffset(),
11697                                            computeVerticalScrollExtent(), true);
11698                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11699                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11700                        verticalScrollbarPosition = isLayoutRtl() ?
11701                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11702                    }
11703                    switch (verticalScrollbarPosition) {
11704                        default:
11705                        case SCROLLBAR_POSITION_RIGHT:
11706                            left = scrollX + width - size - (mUserPaddingRight & inside);
11707                            break;
11708                        case SCROLLBAR_POSITION_LEFT:
11709                            left = scrollX + (mUserPaddingLeft & inside);
11710                            break;
11711                    }
11712                    top = scrollY + (mPaddingTop & inside);
11713                    right = left + size;
11714                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11715                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11716                    if (invalidate) {
11717                        invalidate(left, top, right, bottom);
11718                    }
11719                }
11720            }
11721        }
11722    }
11723
11724    /**
11725     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11726     * FastScroller is visible.
11727     * @return whether to temporarily hide the vertical scrollbar
11728     * @hide
11729     */
11730    protected boolean isVerticalScrollBarHidden() {
11731        return false;
11732    }
11733
11734    /**
11735     * <p>Draw the horizontal scrollbar if
11736     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11737     *
11738     * @param canvas the canvas on which to draw the scrollbar
11739     * @param scrollBar the scrollbar's drawable
11740     *
11741     * @see #isHorizontalScrollBarEnabled()
11742     * @see #computeHorizontalScrollRange()
11743     * @see #computeHorizontalScrollExtent()
11744     * @see #computeHorizontalScrollOffset()
11745     * @see android.widget.ScrollBarDrawable
11746     * @hide
11747     */
11748    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11749            int l, int t, int r, int b) {
11750        scrollBar.setBounds(l, t, r, b);
11751        scrollBar.draw(canvas);
11752    }
11753
11754    /**
11755     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11756     * returns true.</p>
11757     *
11758     * @param canvas the canvas on which to draw the scrollbar
11759     * @param scrollBar the scrollbar's drawable
11760     *
11761     * @see #isVerticalScrollBarEnabled()
11762     * @see #computeVerticalScrollRange()
11763     * @see #computeVerticalScrollExtent()
11764     * @see #computeVerticalScrollOffset()
11765     * @see android.widget.ScrollBarDrawable
11766     * @hide
11767     */
11768    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11769            int l, int t, int r, int b) {
11770        scrollBar.setBounds(l, t, r, b);
11771        scrollBar.draw(canvas);
11772    }
11773
11774    /**
11775     * Implement this to do your drawing.
11776     *
11777     * @param canvas the canvas on which the background will be drawn
11778     */
11779    protected void onDraw(Canvas canvas) {
11780    }
11781
11782    /*
11783     * Caller is responsible for calling requestLayout if necessary.
11784     * (This allows addViewInLayout to not request a new layout.)
11785     */
11786    void assignParent(ViewParent parent) {
11787        if (mParent == null) {
11788            mParent = parent;
11789        } else if (parent == null) {
11790            mParent = null;
11791        } else {
11792            throw new RuntimeException("view " + this + " being added, but"
11793                    + " it already has a parent");
11794        }
11795    }
11796
11797    /**
11798     * This is called when the view is attached to a window.  At this point it
11799     * has a Surface and will start drawing.  Note that this function is
11800     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11801     * however it may be called any time before the first onDraw -- including
11802     * before or after {@link #onMeasure(int, int)}.
11803     *
11804     * @see #onDetachedFromWindow()
11805     */
11806    protected void onAttachedToWindow() {
11807        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11808            mParent.requestTransparentRegion(this);
11809        }
11810
11811        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11812            initialAwakenScrollBars();
11813            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11814        }
11815
11816        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
11817
11818        jumpDrawablesToCurrentState();
11819
11820        clearAccessibilityFocus();
11821        resetSubtreeAccessibilityStateChanged();
11822
11823        if (isFocused()) {
11824            InputMethodManager imm = InputMethodManager.peekInstance();
11825            imm.focusIn(this);
11826        }
11827
11828        if (mDisplayList != null) {
11829            mDisplayList.clearDirty();
11830        }
11831    }
11832
11833    /**
11834     * Resolve all RTL related properties.
11835     *
11836     * @return true if resolution of RTL properties has been done
11837     *
11838     * @hide
11839     */
11840    public boolean resolveRtlPropertiesIfNeeded() {
11841        if (!needRtlPropertiesResolution()) return false;
11842
11843        // Order is important here: LayoutDirection MUST be resolved first
11844        if (!isLayoutDirectionResolved()) {
11845            resolveLayoutDirection();
11846            resolveLayoutParams();
11847        }
11848        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11849        if (!isTextDirectionResolved()) {
11850            resolveTextDirection();
11851        }
11852        if (!isTextAlignmentResolved()) {
11853            resolveTextAlignment();
11854        }
11855        if (!isPaddingResolved()) {
11856            resolvePadding();
11857        }
11858        if (!isDrawablesResolved()) {
11859            resolveDrawables();
11860        }
11861        onRtlPropertiesChanged(getLayoutDirection());
11862        return true;
11863    }
11864
11865    /**
11866     * Reset resolution of all RTL related properties.
11867     *
11868     * @hide
11869     */
11870    public void resetRtlProperties() {
11871        resetResolvedLayoutDirection();
11872        resetResolvedTextDirection();
11873        resetResolvedTextAlignment();
11874        resetResolvedPadding();
11875        resetResolvedDrawables();
11876    }
11877
11878    /**
11879     * @see #onScreenStateChanged(int)
11880     */
11881    void dispatchScreenStateChanged(int screenState) {
11882        onScreenStateChanged(screenState);
11883    }
11884
11885    /**
11886     * This method is called whenever the state of the screen this view is
11887     * attached to changes. A state change will usually occurs when the screen
11888     * turns on or off (whether it happens automatically or the user does it
11889     * manually.)
11890     *
11891     * @param screenState The new state of the screen. Can be either
11892     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11893     */
11894    public void onScreenStateChanged(int screenState) {
11895    }
11896
11897    /**
11898     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11899     */
11900    private boolean hasRtlSupport() {
11901        return mContext.getApplicationInfo().hasRtlSupport();
11902    }
11903
11904    /**
11905     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11906     * RTL not supported)
11907     */
11908    private boolean isRtlCompatibilityMode() {
11909        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11910        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11911    }
11912
11913    /**
11914     * @return true if RTL properties need resolution.
11915     *
11916     */
11917    private boolean needRtlPropertiesResolution() {
11918        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11919    }
11920
11921    /**
11922     * Called when any RTL property (layout direction or text direction or text alignment) has
11923     * been changed.
11924     *
11925     * Subclasses need to override this method to take care of cached information that depends on the
11926     * resolved layout direction, or to inform child views that inherit their layout direction.
11927     *
11928     * The default implementation does nothing.
11929     *
11930     * @param layoutDirection the direction of the layout
11931     *
11932     * @see #LAYOUT_DIRECTION_LTR
11933     * @see #LAYOUT_DIRECTION_RTL
11934     */
11935    public void onRtlPropertiesChanged(int layoutDirection) {
11936    }
11937
11938    /**
11939     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11940     * that the parent directionality can and will be resolved before its children.
11941     *
11942     * @return true if resolution has been done, false otherwise.
11943     *
11944     * @hide
11945     */
11946    public boolean resolveLayoutDirection() {
11947        // Clear any previous layout direction resolution
11948        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11949
11950        if (hasRtlSupport()) {
11951            // Set resolved depending on layout direction
11952            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11953                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11954                case LAYOUT_DIRECTION_INHERIT:
11955                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11956                    // later to get the correct resolved value
11957                    if (!canResolveLayoutDirection()) return false;
11958
11959                    // Parent has not yet resolved, LTR is still the default
11960                    try {
11961                        if (!mParent.isLayoutDirectionResolved()) return false;
11962
11963                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11964                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11965                        }
11966                    } catch (AbstractMethodError e) {
11967                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11968                                " does not fully implement ViewParent", e);
11969                    }
11970                    break;
11971                case LAYOUT_DIRECTION_RTL:
11972                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11973                    break;
11974                case LAYOUT_DIRECTION_LOCALE:
11975                    if((LAYOUT_DIRECTION_RTL ==
11976                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11977                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11978                    }
11979                    break;
11980                default:
11981                    // Nothing to do, LTR by default
11982            }
11983        }
11984
11985        // Set to resolved
11986        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11987        return true;
11988    }
11989
11990    /**
11991     * Check if layout direction resolution can be done.
11992     *
11993     * @return true if layout direction resolution can be done otherwise return false.
11994     */
11995    public boolean canResolveLayoutDirection() {
11996        switch (getRawLayoutDirection()) {
11997            case LAYOUT_DIRECTION_INHERIT:
11998                if (mParent != null) {
11999                    try {
12000                        return mParent.canResolveLayoutDirection();
12001                    } catch (AbstractMethodError e) {
12002                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12003                                " does not fully implement ViewParent", e);
12004                    }
12005                }
12006                return false;
12007
12008            default:
12009                return true;
12010        }
12011    }
12012
12013    /**
12014     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12015     * {@link #onMeasure(int, int)}.
12016     *
12017     * @hide
12018     */
12019    public void resetResolvedLayoutDirection() {
12020        // Reset the current resolved bits
12021        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12022    }
12023
12024    /**
12025     * @return true if the layout direction is inherited.
12026     *
12027     * @hide
12028     */
12029    public boolean isLayoutDirectionInherited() {
12030        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12031    }
12032
12033    /**
12034     * @return true if layout direction has been resolved.
12035     */
12036    public boolean isLayoutDirectionResolved() {
12037        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12038    }
12039
12040    /**
12041     * Return if padding has been resolved
12042     *
12043     * @hide
12044     */
12045    boolean isPaddingResolved() {
12046        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12047    }
12048
12049    /**
12050     * Resolve padding depending on layout direction.
12051     *
12052     * @hide
12053     */
12054    public void resolvePadding() {
12055        if (!isRtlCompatibilityMode()) {
12056            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12057            // If start / end padding are defined, they will be resolved (hence overriding) to
12058            // left / right or right / left depending on the resolved layout direction.
12059            // If start / end padding are not defined, use the left / right ones.
12060            int resolvedLayoutDirection = getLayoutDirection();
12061            switch (resolvedLayoutDirection) {
12062                case LAYOUT_DIRECTION_RTL:
12063                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12064                        mUserPaddingRight = mUserPaddingStart;
12065                    } else {
12066                        mUserPaddingRight = mUserPaddingRightInitial;
12067                    }
12068                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12069                        mUserPaddingLeft = mUserPaddingEnd;
12070                    } else {
12071                        mUserPaddingLeft = mUserPaddingLeftInitial;
12072                    }
12073                    break;
12074                case LAYOUT_DIRECTION_LTR:
12075                default:
12076                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12077                        mUserPaddingLeft = mUserPaddingStart;
12078                    } else {
12079                        mUserPaddingLeft = mUserPaddingLeftInitial;
12080                    }
12081                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12082                        mUserPaddingRight = mUserPaddingEnd;
12083                    } else {
12084                        mUserPaddingRight = mUserPaddingRightInitial;
12085                    }
12086            }
12087
12088            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12089
12090            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
12091                    mUserPaddingBottom);
12092            onRtlPropertiesChanged(resolvedLayoutDirection);
12093        }
12094
12095        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12096    }
12097
12098    /**
12099     * Reset the resolved layout direction.
12100     *
12101     * @hide
12102     */
12103    public void resetResolvedPadding() {
12104        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12105    }
12106
12107    /**
12108     * This is called when the view is detached from a window.  At this point it
12109     * no longer has a surface for drawing.
12110     *
12111     * @see #onAttachedToWindow()
12112     */
12113    protected void onDetachedFromWindow() {
12114        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12115        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12116
12117        removeUnsetPressCallback();
12118        removeLongPressCallback();
12119        removePerformClickCallback();
12120        removeSendViewScrolledAccessibilityEventCallback();
12121
12122        destroyDrawingCache();
12123
12124        destroyLayer(false);
12125
12126        cleanupDraw();
12127
12128        mCurrentAnimation = null;
12129        mCurrentScene = null;
12130    }
12131
12132    private void cleanupDraw() {
12133        if (mAttachInfo != null) {
12134            if (mDisplayList != null) {
12135                mDisplayList.markDirty();
12136                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12137            }
12138            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12139        } else {
12140            // Should never happen
12141            clearDisplayList();
12142        }
12143    }
12144
12145    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12146    }
12147
12148    /**
12149     * @return The number of times this view has been attached to a window
12150     */
12151    protected int getWindowAttachCount() {
12152        return mWindowAttachCount;
12153    }
12154
12155    /**
12156     * Retrieve a unique token identifying the window this view is attached to.
12157     * @return Return the window's token for use in
12158     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12159     */
12160    public IBinder getWindowToken() {
12161        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12162    }
12163
12164    /**
12165     * Retrieve the {@link WindowId} for the window this view is
12166     * currently attached to.
12167     */
12168    public WindowId getWindowId() {
12169        if (mAttachInfo == null) {
12170            return null;
12171        }
12172        if (mAttachInfo.mWindowId == null) {
12173            try {
12174                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12175                        mAttachInfo.mWindowToken);
12176                mAttachInfo.mWindowId = new WindowId(
12177                        mAttachInfo.mIWindowId);
12178            } catch (RemoteException e) {
12179            }
12180        }
12181        return mAttachInfo.mWindowId;
12182    }
12183
12184    /**
12185     * Retrieve a unique token identifying the top-level "real" window of
12186     * the window that this view is attached to.  That is, this is like
12187     * {@link #getWindowToken}, except if the window this view in is a panel
12188     * window (attached to another containing window), then the token of
12189     * the containing window is returned instead.
12190     *
12191     * @return Returns the associated window token, either
12192     * {@link #getWindowToken()} or the containing window's token.
12193     */
12194    public IBinder getApplicationWindowToken() {
12195        AttachInfo ai = mAttachInfo;
12196        if (ai != null) {
12197            IBinder appWindowToken = ai.mPanelParentWindowToken;
12198            if (appWindowToken == null) {
12199                appWindowToken = ai.mWindowToken;
12200            }
12201            return appWindowToken;
12202        }
12203        return null;
12204    }
12205
12206    /**
12207     * Gets the logical display to which the view's window has been attached.
12208     *
12209     * @return The logical display, or null if the view is not currently attached to a window.
12210     */
12211    public Display getDisplay() {
12212        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12213    }
12214
12215    /**
12216     * Retrieve private session object this view hierarchy is using to
12217     * communicate with the window manager.
12218     * @return the session object to communicate with the window manager
12219     */
12220    /*package*/ IWindowSession getWindowSession() {
12221        return mAttachInfo != null ? mAttachInfo.mSession : null;
12222    }
12223
12224    /**
12225     * @param info the {@link android.view.View.AttachInfo} to associated with
12226     *        this view
12227     */
12228    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12229        //System.out.println("Attached! " + this);
12230        mAttachInfo = info;
12231        if (mOverlay != null) {
12232            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12233        }
12234        mWindowAttachCount++;
12235        // We will need to evaluate the drawable state at least once.
12236        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12237        if (mFloatingTreeObserver != null) {
12238            info.mTreeObserver.merge(mFloatingTreeObserver);
12239            mFloatingTreeObserver = null;
12240        }
12241        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12242            mAttachInfo.mScrollContainers.add(this);
12243            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12244        }
12245        performCollectViewAttributes(mAttachInfo, visibility);
12246        onAttachedToWindow();
12247
12248        ListenerInfo li = mListenerInfo;
12249        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12250                li != null ? li.mOnAttachStateChangeListeners : null;
12251        if (listeners != null && listeners.size() > 0) {
12252            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12253            // perform the dispatching. The iterator is a safe guard against listeners that
12254            // could mutate the list by calling the various add/remove methods. This prevents
12255            // the array from being modified while we iterate it.
12256            for (OnAttachStateChangeListener listener : listeners) {
12257                listener.onViewAttachedToWindow(this);
12258            }
12259        }
12260
12261        int vis = info.mWindowVisibility;
12262        if (vis != GONE) {
12263            onWindowVisibilityChanged(vis);
12264        }
12265        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12266            // If nobody has evaluated the drawable state yet, then do it now.
12267            refreshDrawableState();
12268        }
12269        needGlobalAttributesUpdate(false);
12270    }
12271
12272    void dispatchDetachedFromWindow() {
12273        AttachInfo info = mAttachInfo;
12274        if (info != null) {
12275            int vis = info.mWindowVisibility;
12276            if (vis != GONE) {
12277                onWindowVisibilityChanged(GONE);
12278            }
12279        }
12280
12281        onDetachedFromWindow();
12282
12283        ListenerInfo li = mListenerInfo;
12284        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12285                li != null ? li.mOnAttachStateChangeListeners : null;
12286        if (listeners != null && listeners.size() > 0) {
12287            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12288            // perform the dispatching. The iterator is a safe guard against listeners that
12289            // could mutate the list by calling the various add/remove methods. This prevents
12290            // the array from being modified while we iterate it.
12291            for (OnAttachStateChangeListener listener : listeners) {
12292                listener.onViewDetachedFromWindow(this);
12293            }
12294        }
12295
12296        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12297            mAttachInfo.mScrollContainers.remove(this);
12298            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12299        }
12300
12301        mAttachInfo = null;
12302        if (mOverlay != null) {
12303            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12304        }
12305    }
12306
12307    /**
12308     * Store this view hierarchy's frozen state into the given container.
12309     *
12310     * @param container The SparseArray in which to save the view's state.
12311     *
12312     * @see #restoreHierarchyState(android.util.SparseArray)
12313     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12314     * @see #onSaveInstanceState()
12315     */
12316    public void saveHierarchyState(SparseArray<Parcelable> container) {
12317        dispatchSaveInstanceState(container);
12318    }
12319
12320    /**
12321     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12322     * this view and its children. May be overridden to modify how freezing happens to a
12323     * view's children; for example, some views may want to not store state for their children.
12324     *
12325     * @param container The SparseArray in which to save the view's state.
12326     *
12327     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12328     * @see #saveHierarchyState(android.util.SparseArray)
12329     * @see #onSaveInstanceState()
12330     */
12331    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12332        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12333            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12334            Parcelable state = onSaveInstanceState();
12335            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12336                throw new IllegalStateException(
12337                        "Derived class did not call super.onSaveInstanceState()");
12338            }
12339            if (state != null) {
12340                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12341                // + ": " + state);
12342                container.put(mID, state);
12343            }
12344        }
12345    }
12346
12347    /**
12348     * Hook allowing a view to generate a representation of its internal state
12349     * that can later be used to create a new instance with that same state.
12350     * This state should only contain information that is not persistent or can
12351     * not be reconstructed later. For example, you will never store your
12352     * current position on screen because that will be computed again when a
12353     * new instance of the view is placed in its view hierarchy.
12354     * <p>
12355     * Some examples of things you may store here: the current cursor position
12356     * in a text view (but usually not the text itself since that is stored in a
12357     * content provider or other persistent storage), the currently selected
12358     * item in a list view.
12359     *
12360     * @return Returns a Parcelable object containing the view's current dynamic
12361     *         state, or null if there is nothing interesting to save. The
12362     *         default implementation returns null.
12363     * @see #onRestoreInstanceState(android.os.Parcelable)
12364     * @see #saveHierarchyState(android.util.SparseArray)
12365     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12366     * @see #setSaveEnabled(boolean)
12367     */
12368    protected Parcelable onSaveInstanceState() {
12369        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12370        return BaseSavedState.EMPTY_STATE;
12371    }
12372
12373    /**
12374     * Restore this view hierarchy's frozen state from the given container.
12375     *
12376     * @param container The SparseArray which holds previously frozen states.
12377     *
12378     * @see #saveHierarchyState(android.util.SparseArray)
12379     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12380     * @see #onRestoreInstanceState(android.os.Parcelable)
12381     */
12382    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12383        dispatchRestoreInstanceState(container);
12384    }
12385
12386    /**
12387     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12388     * state for this view and its children. May be overridden to modify how restoring
12389     * happens to a view's children; for example, some views may want to not store state
12390     * for their children.
12391     *
12392     * @param container The SparseArray which holds previously saved state.
12393     *
12394     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12395     * @see #restoreHierarchyState(android.util.SparseArray)
12396     * @see #onRestoreInstanceState(android.os.Parcelable)
12397     */
12398    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12399        if (mID != NO_ID) {
12400            Parcelable state = container.get(mID);
12401            if (state != null) {
12402                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12403                // + ": " + state);
12404                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12405                onRestoreInstanceState(state);
12406                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12407                    throw new IllegalStateException(
12408                            "Derived class did not call super.onRestoreInstanceState()");
12409                }
12410            }
12411        }
12412    }
12413
12414    /**
12415     * Hook allowing a view to re-apply a representation of its internal state that had previously
12416     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12417     * null state.
12418     *
12419     * @param state The frozen state that had previously been returned by
12420     *        {@link #onSaveInstanceState}.
12421     *
12422     * @see #onSaveInstanceState()
12423     * @see #restoreHierarchyState(android.util.SparseArray)
12424     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12425     */
12426    protected void onRestoreInstanceState(Parcelable state) {
12427        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12428        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12429            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12430                    + "received " + state.getClass().toString() + " instead. This usually happens "
12431                    + "when two views of different type have the same id in the same hierarchy. "
12432                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12433                    + "other views do not use the same id.");
12434        }
12435    }
12436
12437    /**
12438     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12439     *
12440     * @return the drawing start time in milliseconds
12441     */
12442    public long getDrawingTime() {
12443        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12444    }
12445
12446    /**
12447     * <p>Enables or disables the duplication of the parent's state into this view. When
12448     * duplication is enabled, this view gets its drawable state from its parent rather
12449     * than from its own internal properties.</p>
12450     *
12451     * <p>Note: in the current implementation, setting this property to true after the
12452     * view was added to a ViewGroup might have no effect at all. This property should
12453     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12454     *
12455     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12456     * property is enabled, an exception will be thrown.</p>
12457     *
12458     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12459     * parent, these states should not be affected by this method.</p>
12460     *
12461     * @param enabled True to enable duplication of the parent's drawable state, false
12462     *                to disable it.
12463     *
12464     * @see #getDrawableState()
12465     * @see #isDuplicateParentStateEnabled()
12466     */
12467    public void setDuplicateParentStateEnabled(boolean enabled) {
12468        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12469    }
12470
12471    /**
12472     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12473     *
12474     * @return True if this view's drawable state is duplicated from the parent,
12475     *         false otherwise
12476     *
12477     * @see #getDrawableState()
12478     * @see #setDuplicateParentStateEnabled(boolean)
12479     */
12480    public boolean isDuplicateParentStateEnabled() {
12481        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12482    }
12483
12484    /**
12485     * <p>Specifies the type of layer backing this view. The layer can be
12486     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12487     * {@link #LAYER_TYPE_HARDWARE}.</p>
12488     *
12489     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12490     * instance that controls how the layer is composed on screen. The following
12491     * properties of the paint are taken into account when composing the layer:</p>
12492     * <ul>
12493     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12494     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12495     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12496     * </ul>
12497     *
12498     * <p>If this view has an alpha value set to < 1.0 by calling
12499     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12500     * by this view's alpha value.</p>
12501     *
12502     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12503     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12504     * for more information on when and how to use layers.</p>
12505     *
12506     * @param layerType The type of layer to use with this view, must be one of
12507     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12508     *        {@link #LAYER_TYPE_HARDWARE}
12509     * @param paint The paint used to compose the layer. This argument is optional
12510     *        and can be null. It is ignored when the layer type is
12511     *        {@link #LAYER_TYPE_NONE}
12512     *
12513     * @see #getLayerType()
12514     * @see #LAYER_TYPE_NONE
12515     * @see #LAYER_TYPE_SOFTWARE
12516     * @see #LAYER_TYPE_HARDWARE
12517     * @see #setAlpha(float)
12518     *
12519     * @attr ref android.R.styleable#View_layerType
12520     */
12521    public void setLayerType(int layerType, Paint paint) {
12522        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12523            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12524                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12525        }
12526
12527        if (layerType == mLayerType) {
12528            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12529                mLayerPaint = paint == null ? new Paint() : paint;
12530                invalidateParentCaches();
12531                invalidate(true);
12532            }
12533            return;
12534        }
12535
12536        // Destroy any previous software drawing cache if needed
12537        switch (mLayerType) {
12538            case LAYER_TYPE_HARDWARE:
12539                destroyLayer(false);
12540                // fall through - non-accelerated views may use software layer mechanism instead
12541            case LAYER_TYPE_SOFTWARE:
12542                destroyDrawingCache();
12543                break;
12544            default:
12545                break;
12546        }
12547
12548        mLayerType = layerType;
12549        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12550        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12551        mLocalDirtyRect = layerDisabled ? null : new Rect();
12552
12553        invalidateParentCaches();
12554        invalidate(true);
12555    }
12556
12557    /**
12558     * Updates the {@link Paint} object used with the current layer (used only if the current
12559     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12560     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12561     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12562     * ensure that the view gets redrawn immediately.
12563     *
12564     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12565     * instance that controls how the layer is composed on screen. The following
12566     * properties of the paint are taken into account when composing the layer:</p>
12567     * <ul>
12568     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12569     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12570     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12571     * </ul>
12572     *
12573     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12574     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12575     *
12576     * @param paint The paint used to compose the layer. This argument is optional
12577     *        and can be null. It is ignored when the layer type is
12578     *        {@link #LAYER_TYPE_NONE}
12579     *
12580     * @see #setLayerType(int, android.graphics.Paint)
12581     */
12582    public void setLayerPaint(Paint paint) {
12583        int layerType = getLayerType();
12584        if (layerType != LAYER_TYPE_NONE) {
12585            mLayerPaint = paint == null ? new Paint() : paint;
12586            if (layerType == LAYER_TYPE_HARDWARE) {
12587                HardwareLayer layer = getHardwareLayer();
12588                if (layer != null) {
12589                    layer.setLayerPaint(paint);
12590                }
12591                invalidateViewProperty(false, false);
12592            } else {
12593                invalidate();
12594            }
12595        }
12596    }
12597
12598    /**
12599     * Indicates whether this view has a static layer. A view with layer type
12600     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12601     * dynamic.
12602     */
12603    boolean hasStaticLayer() {
12604        return true;
12605    }
12606
12607    /**
12608     * Indicates what type of layer is currently associated with this view. By default
12609     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12610     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12611     * for more information on the different types of layers.
12612     *
12613     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12614     *         {@link #LAYER_TYPE_HARDWARE}
12615     *
12616     * @see #setLayerType(int, android.graphics.Paint)
12617     * @see #buildLayer()
12618     * @see #LAYER_TYPE_NONE
12619     * @see #LAYER_TYPE_SOFTWARE
12620     * @see #LAYER_TYPE_HARDWARE
12621     */
12622    public int getLayerType() {
12623        return mLayerType;
12624    }
12625
12626    /**
12627     * Forces this view's layer to be created and this view to be rendered
12628     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12629     * invoking this method will have no effect.
12630     *
12631     * This method can for instance be used to render a view into its layer before
12632     * starting an animation. If this view is complex, rendering into the layer
12633     * before starting the animation will avoid skipping frames.
12634     *
12635     * @throws IllegalStateException If this view is not attached to a window
12636     *
12637     * @see #setLayerType(int, android.graphics.Paint)
12638     */
12639    public void buildLayer() {
12640        if (mLayerType == LAYER_TYPE_NONE) return;
12641
12642        final AttachInfo attachInfo = mAttachInfo;
12643        if (attachInfo == null) {
12644            throw new IllegalStateException("This view must be attached to a window first");
12645        }
12646
12647        switch (mLayerType) {
12648            case LAYER_TYPE_HARDWARE:
12649                if (attachInfo.mHardwareRenderer != null &&
12650                        attachInfo.mHardwareRenderer.isEnabled() &&
12651                        attachInfo.mHardwareRenderer.validate()) {
12652                    getHardwareLayer();
12653                    // TODO: We need a better way to handle this case
12654                    // If views have registered pre-draw listeners they need
12655                    // to be notified before we build the layer. Those listeners
12656                    // may however rely on other events to happen first so we
12657                    // cannot just invoke them here until they don't cancel the
12658                    // current frame
12659                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
12660                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12661                    }
12662                }
12663                break;
12664            case LAYER_TYPE_SOFTWARE:
12665                buildDrawingCache(true);
12666                break;
12667        }
12668    }
12669
12670    /**
12671     * <p>Returns a hardware layer that can be used to draw this view again
12672     * without executing its draw method.</p>
12673     *
12674     * @return A HardwareLayer ready to render, or null if an error occurred.
12675     */
12676    HardwareLayer getHardwareLayer() {
12677        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12678                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12679            return null;
12680        }
12681
12682        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12683
12684        final int width = mRight - mLeft;
12685        final int height = mBottom - mTop;
12686
12687        if (width == 0 || height == 0) {
12688            return null;
12689        }
12690
12691        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12692            if (mHardwareLayer == null) {
12693                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12694                        width, height, isOpaque());
12695                mLocalDirtyRect.set(0, 0, width, height);
12696            } else {
12697                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12698                    if (mHardwareLayer.resize(width, height)) {
12699                        mLocalDirtyRect.set(0, 0, width, height);
12700                    }
12701                }
12702
12703                // This should not be necessary but applications that change
12704                // the parameters of their background drawable without calling
12705                // this.setBackground(Drawable) can leave the view in a bad state
12706                // (for instance isOpaque() returns true, but the background is
12707                // not opaque.)
12708                computeOpaqueFlags();
12709
12710                final boolean opaque = isOpaque();
12711                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12712                    mHardwareLayer.setOpaque(opaque);
12713                    mLocalDirtyRect.set(0, 0, width, height);
12714                }
12715            }
12716
12717            // The layer is not valid if the underlying GPU resources cannot be allocated
12718            if (!mHardwareLayer.isValid()) {
12719                return null;
12720            }
12721
12722            mHardwareLayer.setLayerPaint(mLayerPaint);
12723            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12724            ViewRootImpl viewRoot = getViewRootImpl();
12725            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12726
12727            mLocalDirtyRect.setEmpty();
12728        }
12729
12730        return mHardwareLayer;
12731    }
12732
12733    /**
12734     * Destroys this View's hardware layer if possible.
12735     *
12736     * @return True if the layer was destroyed, false otherwise.
12737     *
12738     * @see #setLayerType(int, android.graphics.Paint)
12739     * @see #LAYER_TYPE_HARDWARE
12740     */
12741    boolean destroyLayer(boolean valid) {
12742        if (mHardwareLayer != null) {
12743            AttachInfo info = mAttachInfo;
12744            if (info != null && info.mHardwareRenderer != null &&
12745                    info.mHardwareRenderer.isEnabled() &&
12746                    (valid || info.mHardwareRenderer.validate())) {
12747
12748                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
12749                mHardwareLayer.destroy();
12750                mHardwareLayer = null;
12751
12752                if (mDisplayList != null) {
12753                    mDisplayList.reset();
12754                }
12755                invalidate(true);
12756                invalidateParentCaches();
12757            }
12758            return true;
12759        }
12760        return false;
12761    }
12762
12763    /**
12764     * Destroys all hardware rendering resources. This method is invoked
12765     * when the system needs to reclaim resources. Upon execution of this
12766     * method, you should free any OpenGL resources created by the view.
12767     *
12768     * Note: you <strong>must</strong> call
12769     * <code>super.destroyHardwareResources()</code> when overriding
12770     * this method.
12771     *
12772     * @hide
12773     */
12774    protected void destroyHardwareResources() {
12775        clearDisplayList();
12776        destroyLayer(true);
12777    }
12778
12779    /**
12780     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12781     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12782     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12783     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12784     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12785     * null.</p>
12786     *
12787     * <p>Enabling the drawing cache is similar to
12788     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12789     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12790     * drawing cache has no effect on rendering because the system uses a different mechanism
12791     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12792     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12793     * for information on how to enable software and hardware layers.</p>
12794     *
12795     * <p>This API can be used to manually generate
12796     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12797     * {@link #getDrawingCache()}.</p>
12798     *
12799     * @param enabled true to enable the drawing cache, false otherwise
12800     *
12801     * @see #isDrawingCacheEnabled()
12802     * @see #getDrawingCache()
12803     * @see #buildDrawingCache()
12804     * @see #setLayerType(int, android.graphics.Paint)
12805     */
12806    public void setDrawingCacheEnabled(boolean enabled) {
12807        mCachingFailed = false;
12808        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12809    }
12810
12811    /**
12812     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12813     *
12814     * @return true if the drawing cache is enabled
12815     *
12816     * @see #setDrawingCacheEnabled(boolean)
12817     * @see #getDrawingCache()
12818     */
12819    @ViewDebug.ExportedProperty(category = "drawing")
12820    public boolean isDrawingCacheEnabled() {
12821        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12822    }
12823
12824    /**
12825     * Debugging utility which recursively outputs the dirty state of a view and its
12826     * descendants.
12827     *
12828     * @hide
12829     */
12830    @SuppressWarnings({"UnusedDeclaration"})
12831    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12832        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12833                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12834                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12835                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12836        if (clear) {
12837            mPrivateFlags &= clearMask;
12838        }
12839        if (this instanceof ViewGroup) {
12840            ViewGroup parent = (ViewGroup) this;
12841            final int count = parent.getChildCount();
12842            for (int i = 0; i < count; i++) {
12843                final View child = parent.getChildAt(i);
12844                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12845            }
12846        }
12847    }
12848
12849    /**
12850     * This method is used by ViewGroup to cause its children to restore or recreate their
12851     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12852     * to recreate its own display list, which would happen if it went through the normal
12853     * draw/dispatchDraw mechanisms.
12854     *
12855     * @hide
12856     */
12857    protected void dispatchGetDisplayList() {}
12858
12859    /**
12860     * A view that is not attached or hardware accelerated cannot create a display list.
12861     * This method checks these conditions and returns the appropriate result.
12862     *
12863     * @return true if view has the ability to create a display list, false otherwise.
12864     *
12865     * @hide
12866     */
12867    public boolean canHaveDisplayList() {
12868        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12869    }
12870
12871    /**
12872     * @return The {@link HardwareRenderer} associated with that view or null if
12873     *         hardware rendering is not supported or this view is not attached
12874     *         to a window.
12875     *
12876     * @hide
12877     */
12878    public HardwareRenderer getHardwareRenderer() {
12879        if (mAttachInfo != null) {
12880            return mAttachInfo.mHardwareRenderer;
12881        }
12882        return null;
12883    }
12884
12885    /**
12886     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12887     * Otherwise, the same display list will be returned (after having been rendered into
12888     * along the way, depending on the invalidation state of the view).
12889     *
12890     * @param displayList The previous version of this displayList, could be null.
12891     * @param isLayer Whether the requester of the display list is a layer. If so,
12892     * the view will avoid creating a layer inside the resulting display list.
12893     * @return A new or reused DisplayList object.
12894     */
12895    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12896        if (!canHaveDisplayList()) {
12897            return null;
12898        }
12899
12900        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12901                displayList == null || !displayList.isValid() ||
12902                (!isLayer && mRecreateDisplayList))) {
12903            // Don't need to recreate the display list, just need to tell our
12904            // children to restore/recreate theirs
12905            if (displayList != null && displayList.isValid() &&
12906                    !isLayer && !mRecreateDisplayList) {
12907                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12908                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12909                dispatchGetDisplayList();
12910
12911                return displayList;
12912            }
12913
12914            if (!isLayer) {
12915                // If we got here, we're recreating it. Mark it as such to ensure that
12916                // we copy in child display lists into ours in drawChild()
12917                mRecreateDisplayList = true;
12918            }
12919            if (displayList == null) {
12920                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
12921                // If we're creating a new display list, make sure our parent gets invalidated
12922                // since they will need to recreate their display list to account for this
12923                // new child display list.
12924                invalidateParentCaches();
12925            }
12926
12927            boolean caching = false;
12928            int width = mRight - mLeft;
12929            int height = mBottom - mTop;
12930            int layerType = getLayerType();
12931
12932            final HardwareCanvas canvas = displayList.start(width, height);
12933
12934            try {
12935                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12936                    if (layerType == LAYER_TYPE_HARDWARE) {
12937                        final HardwareLayer layer = getHardwareLayer();
12938                        if (layer != null && layer.isValid()) {
12939                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12940                        } else {
12941                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12942                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12943                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12944                        }
12945                        caching = true;
12946                    } else {
12947                        buildDrawingCache(true);
12948                        Bitmap cache = getDrawingCache(true);
12949                        if (cache != null) {
12950                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12951                            caching = true;
12952                        }
12953                    }
12954                } else {
12955
12956                    computeScroll();
12957
12958                    canvas.translate(-mScrollX, -mScrollY);
12959                    if (!isLayer) {
12960                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12961                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12962                    }
12963
12964                    // Fast path for layouts with no backgrounds
12965                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12966                        dispatchDraw(canvas);
12967                        if (mOverlay != null && !mOverlay.isEmpty()) {
12968                            mOverlay.getOverlayView().draw(canvas);
12969                        }
12970                    } else {
12971                        draw(canvas);
12972                    }
12973                }
12974            } finally {
12975                displayList.end();
12976                displayList.setCaching(caching);
12977                if (isLayer) {
12978                    displayList.setLeftTopRightBottom(0, 0, width, height);
12979                } else {
12980                    setDisplayListProperties(displayList);
12981                }
12982            }
12983        } else if (!isLayer) {
12984            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12985            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12986        }
12987
12988        return displayList;
12989    }
12990
12991    /**
12992     * Get the DisplayList for the HardwareLayer
12993     *
12994     * @param layer The HardwareLayer whose DisplayList we want
12995     * @return A DisplayList fopr the specified HardwareLayer
12996     */
12997    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12998        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12999        layer.setDisplayList(displayList);
13000        return displayList;
13001    }
13002
13003
13004    /**
13005     * <p>Returns a display list that can be used to draw this view again
13006     * without executing its draw method.</p>
13007     *
13008     * @return A DisplayList ready to replay, or null if caching is not enabled.
13009     *
13010     * @hide
13011     */
13012    public DisplayList getDisplayList() {
13013        mDisplayList = getDisplayList(mDisplayList, false);
13014        return mDisplayList;
13015    }
13016
13017    private void clearDisplayList() {
13018        if (mDisplayList != null) {
13019            mDisplayList.clear();
13020        }
13021    }
13022
13023    /**
13024     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13025     *
13026     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13027     *
13028     * @see #getDrawingCache(boolean)
13029     */
13030    public Bitmap getDrawingCache() {
13031        return getDrawingCache(false);
13032    }
13033
13034    /**
13035     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13036     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13037     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13038     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13039     * request the drawing cache by calling this method and draw it on screen if the
13040     * returned bitmap is not null.</p>
13041     *
13042     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13043     * this method will create a bitmap of the same size as this view. Because this bitmap
13044     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13045     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13046     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13047     * size than the view. This implies that your application must be able to handle this
13048     * size.</p>
13049     *
13050     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13051     *        the current density of the screen when the application is in compatibility
13052     *        mode.
13053     *
13054     * @return A bitmap representing this view or null if cache is disabled.
13055     *
13056     * @see #setDrawingCacheEnabled(boolean)
13057     * @see #isDrawingCacheEnabled()
13058     * @see #buildDrawingCache(boolean)
13059     * @see #destroyDrawingCache()
13060     */
13061    public Bitmap getDrawingCache(boolean autoScale) {
13062        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13063            return null;
13064        }
13065        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13066            buildDrawingCache(autoScale);
13067        }
13068        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13069    }
13070
13071    /**
13072     * <p>Frees the resources used by the drawing cache. If you call
13073     * {@link #buildDrawingCache()} manually without calling
13074     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13075     * should cleanup the cache with this method afterwards.</p>
13076     *
13077     * @see #setDrawingCacheEnabled(boolean)
13078     * @see #buildDrawingCache()
13079     * @see #getDrawingCache()
13080     */
13081    public void destroyDrawingCache() {
13082        if (mDrawingCache != null) {
13083            mDrawingCache.recycle();
13084            mDrawingCache = null;
13085        }
13086        if (mUnscaledDrawingCache != null) {
13087            mUnscaledDrawingCache.recycle();
13088            mUnscaledDrawingCache = null;
13089        }
13090    }
13091
13092    /**
13093     * Setting a solid background color for the drawing cache's bitmaps will improve
13094     * performance and memory usage. Note, though that this should only be used if this
13095     * view will always be drawn on top of a solid color.
13096     *
13097     * @param color The background color to use for the drawing cache's bitmap
13098     *
13099     * @see #setDrawingCacheEnabled(boolean)
13100     * @see #buildDrawingCache()
13101     * @see #getDrawingCache()
13102     */
13103    public void setDrawingCacheBackgroundColor(int color) {
13104        if (color != mDrawingCacheBackgroundColor) {
13105            mDrawingCacheBackgroundColor = color;
13106            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13107        }
13108    }
13109
13110    /**
13111     * @see #setDrawingCacheBackgroundColor(int)
13112     *
13113     * @return The background color to used for the drawing cache's bitmap
13114     */
13115    public int getDrawingCacheBackgroundColor() {
13116        return mDrawingCacheBackgroundColor;
13117    }
13118
13119    /**
13120     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13121     *
13122     * @see #buildDrawingCache(boolean)
13123     */
13124    public void buildDrawingCache() {
13125        buildDrawingCache(false);
13126    }
13127
13128    /**
13129     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13130     *
13131     * <p>If you call {@link #buildDrawingCache()} manually without calling
13132     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13133     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13134     *
13135     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13136     * this method will create a bitmap of the same size as this view. Because this bitmap
13137     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13138     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13139     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13140     * size than the view. This implies that your application must be able to handle this
13141     * size.</p>
13142     *
13143     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13144     * you do not need the drawing cache bitmap, calling this method will increase memory
13145     * usage and cause the view to be rendered in software once, thus negatively impacting
13146     * performance.</p>
13147     *
13148     * @see #getDrawingCache()
13149     * @see #destroyDrawingCache()
13150     */
13151    public void buildDrawingCache(boolean autoScale) {
13152        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13153                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13154            mCachingFailed = false;
13155
13156            int width = mRight - mLeft;
13157            int height = mBottom - mTop;
13158
13159            final AttachInfo attachInfo = mAttachInfo;
13160            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13161
13162            if (autoScale && scalingRequired) {
13163                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13164                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13165            }
13166
13167            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13168            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13169            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13170
13171            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13172            final long drawingCacheSize =
13173                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13174            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13175                if (width > 0 && height > 0) {
13176                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13177                            + projectedBitmapSize + " bytes, only "
13178                            + drawingCacheSize + " available");
13179                }
13180                destroyDrawingCache();
13181                mCachingFailed = true;
13182                return;
13183            }
13184
13185            boolean clear = true;
13186            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13187
13188            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13189                Bitmap.Config quality;
13190                if (!opaque) {
13191                    // Never pick ARGB_4444 because it looks awful
13192                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13193                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13194                        case DRAWING_CACHE_QUALITY_AUTO:
13195                            quality = Bitmap.Config.ARGB_8888;
13196                            break;
13197                        case DRAWING_CACHE_QUALITY_LOW:
13198                            quality = Bitmap.Config.ARGB_8888;
13199                            break;
13200                        case DRAWING_CACHE_QUALITY_HIGH:
13201                            quality = Bitmap.Config.ARGB_8888;
13202                            break;
13203                        default:
13204                            quality = Bitmap.Config.ARGB_8888;
13205                            break;
13206                    }
13207                } else {
13208                    // Optimization for translucent windows
13209                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13210                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13211                }
13212
13213                // Try to cleanup memory
13214                if (bitmap != null) bitmap.recycle();
13215
13216                try {
13217                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13218                            width, height, quality);
13219                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13220                    if (autoScale) {
13221                        mDrawingCache = bitmap;
13222                    } else {
13223                        mUnscaledDrawingCache = bitmap;
13224                    }
13225                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13226                } catch (OutOfMemoryError e) {
13227                    // If there is not enough memory to create the bitmap cache, just
13228                    // ignore the issue as bitmap caches are not required to draw the
13229                    // view hierarchy
13230                    if (autoScale) {
13231                        mDrawingCache = null;
13232                    } else {
13233                        mUnscaledDrawingCache = null;
13234                    }
13235                    mCachingFailed = true;
13236                    return;
13237                }
13238
13239                clear = drawingCacheBackgroundColor != 0;
13240            }
13241
13242            Canvas canvas;
13243            if (attachInfo != null) {
13244                canvas = attachInfo.mCanvas;
13245                if (canvas == null) {
13246                    canvas = new Canvas();
13247                }
13248                canvas.setBitmap(bitmap);
13249                // Temporarily clobber the cached Canvas in case one of our children
13250                // is also using a drawing cache. Without this, the children would
13251                // steal the canvas by attaching their own bitmap to it and bad, bad
13252                // thing would happen (invisible views, corrupted drawings, etc.)
13253                attachInfo.mCanvas = null;
13254            } else {
13255                // This case should hopefully never or seldom happen
13256                canvas = new Canvas(bitmap);
13257            }
13258
13259            if (clear) {
13260                bitmap.eraseColor(drawingCacheBackgroundColor);
13261            }
13262
13263            computeScroll();
13264            final int restoreCount = canvas.save();
13265
13266            if (autoScale && scalingRequired) {
13267                final float scale = attachInfo.mApplicationScale;
13268                canvas.scale(scale, scale);
13269            }
13270
13271            canvas.translate(-mScrollX, -mScrollY);
13272
13273            mPrivateFlags |= PFLAG_DRAWN;
13274            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13275                    mLayerType != LAYER_TYPE_NONE) {
13276                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13277            }
13278
13279            // Fast path for layouts with no backgrounds
13280            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13281                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13282                dispatchDraw(canvas);
13283                if (mOverlay != null && !mOverlay.isEmpty()) {
13284                    mOverlay.getOverlayView().draw(canvas);
13285                }
13286            } else {
13287                draw(canvas);
13288            }
13289
13290            canvas.restoreToCount(restoreCount);
13291            canvas.setBitmap(null);
13292
13293            if (attachInfo != null) {
13294                // Restore the cached Canvas for our siblings
13295                attachInfo.mCanvas = canvas;
13296            }
13297        }
13298    }
13299
13300    /**
13301     * Create a snapshot of the view into a bitmap.  We should probably make
13302     * some form of this public, but should think about the API.
13303     */
13304    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13305        int width = mRight - mLeft;
13306        int height = mBottom - mTop;
13307
13308        final AttachInfo attachInfo = mAttachInfo;
13309        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13310        width = (int) ((width * scale) + 0.5f);
13311        height = (int) ((height * scale) + 0.5f);
13312
13313        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13314                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13315        if (bitmap == null) {
13316            throw new OutOfMemoryError();
13317        }
13318
13319        Resources resources = getResources();
13320        if (resources != null) {
13321            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13322        }
13323
13324        Canvas canvas;
13325        if (attachInfo != null) {
13326            canvas = attachInfo.mCanvas;
13327            if (canvas == null) {
13328                canvas = new Canvas();
13329            }
13330            canvas.setBitmap(bitmap);
13331            // Temporarily clobber the cached Canvas in case one of our children
13332            // is also using a drawing cache. Without this, the children would
13333            // steal the canvas by attaching their own bitmap to it and bad, bad
13334            // things would happen (invisible views, corrupted drawings, etc.)
13335            attachInfo.mCanvas = null;
13336        } else {
13337            // This case should hopefully never or seldom happen
13338            canvas = new Canvas(bitmap);
13339        }
13340
13341        if ((backgroundColor & 0xff000000) != 0) {
13342            bitmap.eraseColor(backgroundColor);
13343        }
13344
13345        computeScroll();
13346        final int restoreCount = canvas.save();
13347        canvas.scale(scale, scale);
13348        canvas.translate(-mScrollX, -mScrollY);
13349
13350        // Temporarily remove the dirty mask
13351        int flags = mPrivateFlags;
13352        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13353
13354        // Fast path for layouts with no backgrounds
13355        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13356            dispatchDraw(canvas);
13357        } else {
13358            draw(canvas);
13359        }
13360
13361        mPrivateFlags = flags;
13362
13363        canvas.restoreToCount(restoreCount);
13364        canvas.setBitmap(null);
13365
13366        if (attachInfo != null) {
13367            // Restore the cached Canvas for our siblings
13368            attachInfo.mCanvas = canvas;
13369        }
13370
13371        return bitmap;
13372    }
13373
13374    /**
13375     * Indicates whether this View is currently in edit mode. A View is usually
13376     * in edit mode when displayed within a developer tool. For instance, if
13377     * this View is being drawn by a visual user interface builder, this method
13378     * should return true.
13379     *
13380     * Subclasses should check the return value of this method to provide
13381     * different behaviors if their normal behavior might interfere with the
13382     * host environment. For instance: the class spawns a thread in its
13383     * constructor, the drawing code relies on device-specific features, etc.
13384     *
13385     * This method is usually checked in the drawing code of custom widgets.
13386     *
13387     * @return True if this View is in edit mode, false otherwise.
13388     */
13389    public boolean isInEditMode() {
13390        return false;
13391    }
13392
13393    /**
13394     * If the View draws content inside its padding and enables fading edges,
13395     * it needs to support padding offsets. Padding offsets are added to the
13396     * fading edges to extend the length of the fade so that it covers pixels
13397     * drawn inside the padding.
13398     *
13399     * Subclasses of this class should override this method if they need
13400     * to draw content inside the padding.
13401     *
13402     * @return True if padding offset must be applied, false otherwise.
13403     *
13404     * @see #getLeftPaddingOffset()
13405     * @see #getRightPaddingOffset()
13406     * @see #getTopPaddingOffset()
13407     * @see #getBottomPaddingOffset()
13408     *
13409     * @since CURRENT
13410     */
13411    protected boolean isPaddingOffsetRequired() {
13412        return false;
13413    }
13414
13415    /**
13416     * Amount by which to extend the left fading region. Called only when
13417     * {@link #isPaddingOffsetRequired()} returns true.
13418     *
13419     * @return The left padding offset in pixels.
13420     *
13421     * @see #isPaddingOffsetRequired()
13422     *
13423     * @since CURRENT
13424     */
13425    protected int getLeftPaddingOffset() {
13426        return 0;
13427    }
13428
13429    /**
13430     * Amount by which to extend the right fading region. Called only when
13431     * {@link #isPaddingOffsetRequired()} returns true.
13432     *
13433     * @return The right padding offset in pixels.
13434     *
13435     * @see #isPaddingOffsetRequired()
13436     *
13437     * @since CURRENT
13438     */
13439    protected int getRightPaddingOffset() {
13440        return 0;
13441    }
13442
13443    /**
13444     * Amount by which to extend the top fading region. Called only when
13445     * {@link #isPaddingOffsetRequired()} returns true.
13446     *
13447     * @return The top padding offset in pixels.
13448     *
13449     * @see #isPaddingOffsetRequired()
13450     *
13451     * @since CURRENT
13452     */
13453    protected int getTopPaddingOffset() {
13454        return 0;
13455    }
13456
13457    /**
13458     * Amount by which to extend the bottom fading region. Called only when
13459     * {@link #isPaddingOffsetRequired()} returns true.
13460     *
13461     * @return The bottom padding offset in pixels.
13462     *
13463     * @see #isPaddingOffsetRequired()
13464     *
13465     * @since CURRENT
13466     */
13467    protected int getBottomPaddingOffset() {
13468        return 0;
13469    }
13470
13471    /**
13472     * @hide
13473     * @param offsetRequired
13474     */
13475    protected int getFadeTop(boolean offsetRequired) {
13476        int top = mPaddingTop;
13477        if (offsetRequired) top += getTopPaddingOffset();
13478        return top;
13479    }
13480
13481    /**
13482     * @hide
13483     * @param offsetRequired
13484     */
13485    protected int getFadeHeight(boolean offsetRequired) {
13486        int padding = mPaddingTop;
13487        if (offsetRequired) padding += getTopPaddingOffset();
13488        return mBottom - mTop - mPaddingBottom - padding;
13489    }
13490
13491    /**
13492     * <p>Indicates whether this view is attached to a hardware accelerated
13493     * window or not.</p>
13494     *
13495     * <p>Even if this method returns true, it does not mean that every call
13496     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13497     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13498     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13499     * window is hardware accelerated,
13500     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13501     * return false, and this method will return true.</p>
13502     *
13503     * @return True if the view is attached to a window and the window is
13504     *         hardware accelerated; false in any other case.
13505     */
13506    public boolean isHardwareAccelerated() {
13507        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13508    }
13509
13510    /**
13511     * Sets a rectangular area on this view to which the view will be clipped
13512     * when it is drawn. Setting the value to null will remove the clip bounds
13513     * and the view will draw normally, using its full bounds.
13514     *
13515     * @param clipBounds The rectangular area, in the local coordinates of
13516     * this view, to which future drawing operations will be clipped.
13517     */
13518    public void setClipBounds(Rect clipBounds) {
13519        if (clipBounds != null) {
13520            if (clipBounds.equals(mClipBounds)) {
13521                return;
13522            }
13523            if (mClipBounds == null) {
13524                invalidate();
13525                mClipBounds = new Rect(clipBounds);
13526            } else {
13527                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13528                        Math.min(mClipBounds.top, clipBounds.top),
13529                        Math.max(mClipBounds.right, clipBounds.right),
13530                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13531                mClipBounds.set(clipBounds);
13532            }
13533        } else {
13534            if (mClipBounds != null) {
13535                invalidate();
13536                mClipBounds = null;
13537            }
13538        }
13539    }
13540
13541    /**
13542     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13543     *
13544     * @return A copy of the current clip bounds if clip bounds are set,
13545     * otherwise null.
13546     */
13547    public Rect getClipBounds() {
13548        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13549    }
13550
13551    /**
13552     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13553     * case of an active Animation being run on the view.
13554     */
13555    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13556            Animation a, boolean scalingRequired) {
13557        Transformation invalidationTransform;
13558        final int flags = parent.mGroupFlags;
13559        final boolean initialized = a.isInitialized();
13560        if (!initialized) {
13561            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13562            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13563            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13564            onAnimationStart();
13565        }
13566
13567        final Transformation t = parent.getChildTransformation();
13568        boolean more = a.getTransformation(drawingTime, t, 1f);
13569        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13570            if (parent.mInvalidationTransformation == null) {
13571                parent.mInvalidationTransformation = new Transformation();
13572            }
13573            invalidationTransform = parent.mInvalidationTransformation;
13574            a.getTransformation(drawingTime, invalidationTransform, 1f);
13575        } else {
13576            invalidationTransform = t;
13577        }
13578
13579        if (more) {
13580            if (!a.willChangeBounds()) {
13581                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13582                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13583                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13584                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13585                    // The child need to draw an animation, potentially offscreen, so
13586                    // make sure we do not cancel invalidate requests
13587                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13588                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13589                }
13590            } else {
13591                if (parent.mInvalidateRegion == null) {
13592                    parent.mInvalidateRegion = new RectF();
13593                }
13594                final RectF region = parent.mInvalidateRegion;
13595                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13596                        invalidationTransform);
13597
13598                // The child need to draw an animation, potentially offscreen, so
13599                // make sure we do not cancel invalidate requests
13600                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13601
13602                final int left = mLeft + (int) region.left;
13603                final int top = mTop + (int) region.top;
13604                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13605                        top + (int) (region.height() + .5f));
13606            }
13607        }
13608        return more;
13609    }
13610
13611    /**
13612     * This method is called by getDisplayList() when a display list is created or re-rendered.
13613     * It sets or resets the current value of all properties on that display list (resetting is
13614     * necessary when a display list is being re-created, because we need to make sure that
13615     * previously-set transform values
13616     */
13617    void setDisplayListProperties(DisplayList displayList) {
13618        if (displayList != null) {
13619            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13620            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13621            if (mParent instanceof ViewGroup) {
13622                displayList.setClipToBounds(
13623                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13624            }
13625            float alpha = 1;
13626            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13627                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13628                ViewGroup parentVG = (ViewGroup) mParent;
13629                final Transformation t = parentVG.getChildTransformation();
13630                if (parentVG.getChildStaticTransformation(this, t)) {
13631                    final int transformType = t.getTransformationType();
13632                    if (transformType != Transformation.TYPE_IDENTITY) {
13633                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13634                            alpha = t.getAlpha();
13635                        }
13636                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13637                            displayList.setMatrix(t.getMatrix());
13638                        }
13639                    }
13640                }
13641            }
13642            if (mTransformationInfo != null) {
13643                alpha *= mTransformationInfo.mAlpha;
13644                if (alpha < 1) {
13645                    final int multipliedAlpha = (int) (255 * alpha);
13646                    if (onSetAlpha(multipliedAlpha)) {
13647                        alpha = 1;
13648                    }
13649                }
13650                displayList.setTransformationInfo(alpha,
13651                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13652                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13653                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13654                        mTransformationInfo.mScaleY);
13655                if (mTransformationInfo.mCamera == null) {
13656                    mTransformationInfo.mCamera = new Camera();
13657                    mTransformationInfo.matrix3D = new Matrix();
13658                }
13659                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13660                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13661                    displayList.setPivotX(getPivotX());
13662                    displayList.setPivotY(getPivotY());
13663                }
13664            } else if (alpha < 1) {
13665                displayList.setAlpha(alpha);
13666            }
13667        }
13668    }
13669
13670    /**
13671     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13672     * This draw() method is an implementation detail and is not intended to be overridden or
13673     * to be called from anywhere else other than ViewGroup.drawChild().
13674     */
13675    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13676        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13677        boolean more = false;
13678        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13679        final int flags = parent.mGroupFlags;
13680
13681        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13682            parent.getChildTransformation().clear();
13683            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13684        }
13685
13686        Transformation transformToApply = null;
13687        boolean concatMatrix = false;
13688
13689        boolean scalingRequired = false;
13690        boolean caching;
13691        int layerType = getLayerType();
13692
13693        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13694        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13695                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13696            caching = true;
13697            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13698            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13699        } else {
13700            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13701        }
13702
13703        final Animation a = getAnimation();
13704        if (a != null) {
13705            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13706            concatMatrix = a.willChangeTransformationMatrix();
13707            if (concatMatrix) {
13708                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13709            }
13710            transformToApply = parent.getChildTransformation();
13711        } else {
13712            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13713                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13714                // No longer animating: clear out old animation matrix
13715                mDisplayList.setAnimationMatrix(null);
13716                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13717            }
13718            if (!useDisplayListProperties &&
13719                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13720                final Transformation t = parent.getChildTransformation();
13721                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
13722                if (hasTransform) {
13723                    final int transformType = t.getTransformationType();
13724                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
13725                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13726                }
13727            }
13728        }
13729
13730        concatMatrix |= !childHasIdentityMatrix;
13731
13732        // Sets the flag as early as possible to allow draw() implementations
13733        // to call invalidate() successfully when doing animations
13734        mPrivateFlags |= PFLAG_DRAWN;
13735
13736        if (!concatMatrix &&
13737                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13738                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13739                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13740                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13741            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13742            return more;
13743        }
13744        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13745
13746        if (hardwareAccelerated) {
13747            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13748            // retain the flag's value temporarily in the mRecreateDisplayList flag
13749            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13750            mPrivateFlags &= ~PFLAG_INVALIDATED;
13751        }
13752
13753        DisplayList displayList = null;
13754        Bitmap cache = null;
13755        boolean hasDisplayList = false;
13756        if (caching) {
13757            if (!hardwareAccelerated) {
13758                if (layerType != LAYER_TYPE_NONE) {
13759                    layerType = LAYER_TYPE_SOFTWARE;
13760                    buildDrawingCache(true);
13761                }
13762                cache = getDrawingCache(true);
13763            } else {
13764                switch (layerType) {
13765                    case LAYER_TYPE_SOFTWARE:
13766                        if (useDisplayListProperties) {
13767                            hasDisplayList = canHaveDisplayList();
13768                        } else {
13769                            buildDrawingCache(true);
13770                            cache = getDrawingCache(true);
13771                        }
13772                        break;
13773                    case LAYER_TYPE_HARDWARE:
13774                        if (useDisplayListProperties) {
13775                            hasDisplayList = canHaveDisplayList();
13776                        }
13777                        break;
13778                    case LAYER_TYPE_NONE:
13779                        // Delay getting the display list until animation-driven alpha values are
13780                        // set up and possibly passed on to the view
13781                        hasDisplayList = canHaveDisplayList();
13782                        break;
13783                }
13784            }
13785        }
13786        useDisplayListProperties &= hasDisplayList;
13787        if (useDisplayListProperties) {
13788            displayList = getDisplayList();
13789            if (!displayList.isValid()) {
13790                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13791                // to getDisplayList(), the display list will be marked invalid and we should not
13792                // try to use it again.
13793                displayList = null;
13794                hasDisplayList = false;
13795                useDisplayListProperties = false;
13796            }
13797        }
13798
13799        int sx = 0;
13800        int sy = 0;
13801        if (!hasDisplayList) {
13802            computeScroll();
13803            sx = mScrollX;
13804            sy = mScrollY;
13805        }
13806
13807        final boolean hasNoCache = cache == null || hasDisplayList;
13808        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13809                layerType != LAYER_TYPE_HARDWARE;
13810
13811        int restoreTo = -1;
13812        if (!useDisplayListProperties || transformToApply != null) {
13813            restoreTo = canvas.save();
13814        }
13815        if (offsetForScroll) {
13816            canvas.translate(mLeft - sx, mTop - sy);
13817        } else {
13818            if (!useDisplayListProperties) {
13819                canvas.translate(mLeft, mTop);
13820            }
13821            if (scalingRequired) {
13822                if (useDisplayListProperties) {
13823                    // TODO: Might not need this if we put everything inside the DL
13824                    restoreTo = canvas.save();
13825                }
13826                // mAttachInfo cannot be null, otherwise scalingRequired == false
13827                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13828                canvas.scale(scale, scale);
13829            }
13830        }
13831
13832        float alpha = useDisplayListProperties ? 1 : getAlpha();
13833        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13834                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13835            if (transformToApply != null || !childHasIdentityMatrix) {
13836                int transX = 0;
13837                int transY = 0;
13838
13839                if (offsetForScroll) {
13840                    transX = -sx;
13841                    transY = -sy;
13842                }
13843
13844                if (transformToApply != null) {
13845                    if (concatMatrix) {
13846                        if (useDisplayListProperties) {
13847                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13848                        } else {
13849                            // Undo the scroll translation, apply the transformation matrix,
13850                            // then redo the scroll translate to get the correct result.
13851                            canvas.translate(-transX, -transY);
13852                            canvas.concat(transformToApply.getMatrix());
13853                            canvas.translate(transX, transY);
13854                        }
13855                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13856                    }
13857
13858                    float transformAlpha = transformToApply.getAlpha();
13859                    if (transformAlpha < 1) {
13860                        alpha *= transformAlpha;
13861                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13862                    }
13863                }
13864
13865                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13866                    canvas.translate(-transX, -transY);
13867                    canvas.concat(getMatrix());
13868                    canvas.translate(transX, transY);
13869                }
13870            }
13871
13872            // Deal with alpha if it is or used to be <1
13873            if (alpha < 1 ||
13874                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13875                if (alpha < 1) {
13876                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13877                } else {
13878                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13879                }
13880                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13881                if (hasNoCache) {
13882                    final int multipliedAlpha = (int) (255 * alpha);
13883                    if (!onSetAlpha(multipliedAlpha)) {
13884                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13885                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13886                                layerType != LAYER_TYPE_NONE) {
13887                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13888                        }
13889                        if (useDisplayListProperties) {
13890                            displayList.setAlpha(alpha * getAlpha());
13891                        } else  if (layerType == LAYER_TYPE_NONE) {
13892                            final int scrollX = hasDisplayList ? 0 : sx;
13893                            final int scrollY = hasDisplayList ? 0 : sy;
13894                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13895                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13896                        }
13897                    } else {
13898                        // Alpha is handled by the child directly, clobber the layer's alpha
13899                        mPrivateFlags |= PFLAG_ALPHA_SET;
13900                    }
13901                }
13902            }
13903        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13904            onSetAlpha(255);
13905            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13906        }
13907
13908        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13909                !useDisplayListProperties && cache == null) {
13910            if (offsetForScroll) {
13911                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13912            } else {
13913                if (!scalingRequired || cache == null) {
13914                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13915                } else {
13916                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13917                }
13918            }
13919        }
13920
13921        if (!useDisplayListProperties && hasDisplayList) {
13922            displayList = getDisplayList();
13923            if (!displayList.isValid()) {
13924                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13925                // to getDisplayList(), the display list will be marked invalid and we should not
13926                // try to use it again.
13927                displayList = null;
13928                hasDisplayList = false;
13929            }
13930        }
13931
13932        if (hasNoCache) {
13933            boolean layerRendered = false;
13934            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13935                final HardwareLayer layer = getHardwareLayer();
13936                if (layer != null && layer.isValid()) {
13937                    mLayerPaint.setAlpha((int) (alpha * 255));
13938                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13939                    layerRendered = true;
13940                } else {
13941                    final int scrollX = hasDisplayList ? 0 : sx;
13942                    final int scrollY = hasDisplayList ? 0 : sy;
13943                    canvas.saveLayer(scrollX, scrollY,
13944                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13945                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13946                }
13947            }
13948
13949            if (!layerRendered) {
13950                if (!hasDisplayList) {
13951                    // Fast path for layouts with no backgrounds
13952                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13953                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13954                        dispatchDraw(canvas);
13955                    } else {
13956                        draw(canvas);
13957                    }
13958                } else {
13959                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13960                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13961                }
13962            }
13963        } else if (cache != null) {
13964            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13965            Paint cachePaint;
13966
13967            if (layerType == LAYER_TYPE_NONE) {
13968                cachePaint = parent.mCachePaint;
13969                if (cachePaint == null) {
13970                    cachePaint = new Paint();
13971                    cachePaint.setDither(false);
13972                    parent.mCachePaint = cachePaint;
13973                }
13974                if (alpha < 1) {
13975                    cachePaint.setAlpha((int) (alpha * 255));
13976                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13977                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13978                    cachePaint.setAlpha(255);
13979                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13980                }
13981            } else {
13982                cachePaint = mLayerPaint;
13983                cachePaint.setAlpha((int) (alpha * 255));
13984            }
13985            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13986        }
13987
13988        if (restoreTo >= 0) {
13989            canvas.restoreToCount(restoreTo);
13990        }
13991
13992        if (a != null && !more) {
13993            if (!hardwareAccelerated && !a.getFillAfter()) {
13994                onSetAlpha(255);
13995            }
13996            parent.finishAnimatingView(this, a);
13997        }
13998
13999        if (more && hardwareAccelerated) {
14000            // invalidation is the trigger to recreate display lists, so if we're using
14001            // display lists to render, force an invalidate to allow the animation to
14002            // continue drawing another frame
14003            parent.invalidate(true);
14004            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14005                // alpha animations should cause the child to recreate its display list
14006                invalidate(true);
14007            }
14008        }
14009
14010        mRecreateDisplayList = false;
14011
14012        return more;
14013    }
14014
14015    /**
14016     * Manually render this view (and all of its children) to the given Canvas.
14017     * The view must have already done a full layout before this function is
14018     * called.  When implementing a view, implement
14019     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14020     * If you do need to override this method, call the superclass version.
14021     *
14022     * @param canvas The Canvas to which the View is rendered.
14023     */
14024    public void draw(Canvas canvas) {
14025        if (mClipBounds != null) {
14026            canvas.clipRect(mClipBounds);
14027        }
14028        final int privateFlags = mPrivateFlags;
14029        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14030                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14031        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14032
14033        /*
14034         * Draw traversal performs several drawing steps which must be executed
14035         * in the appropriate order:
14036         *
14037         *      1. Draw the background
14038         *      2. If necessary, save the canvas' layers to prepare for fading
14039         *      3. Draw view's content
14040         *      4. Draw children
14041         *      5. If necessary, draw the fading edges and restore layers
14042         *      6. Draw decorations (scrollbars for instance)
14043         */
14044
14045        // Step 1, draw the background, if needed
14046        int saveCount;
14047
14048        if (!dirtyOpaque) {
14049            final Drawable background = mBackground;
14050            if (background != null) {
14051                final int scrollX = mScrollX;
14052                final int scrollY = mScrollY;
14053
14054                if (mBackgroundSizeChanged) {
14055                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14056                    mBackgroundSizeChanged = false;
14057                }
14058
14059                if ((scrollX | scrollY) == 0) {
14060                    background.draw(canvas);
14061                } else {
14062                    canvas.translate(scrollX, scrollY);
14063                    background.draw(canvas);
14064                    canvas.translate(-scrollX, -scrollY);
14065                }
14066            }
14067        }
14068
14069        // skip step 2 & 5 if possible (common case)
14070        final int viewFlags = mViewFlags;
14071        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14072        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14073        if (!verticalEdges && !horizontalEdges) {
14074            // Step 3, draw the content
14075            if (!dirtyOpaque) onDraw(canvas);
14076
14077            // Step 4, draw the children
14078            dispatchDraw(canvas);
14079
14080            // Step 6, draw decorations (scrollbars)
14081            onDrawScrollBars(canvas);
14082
14083            if (mOverlay != null && !mOverlay.isEmpty()) {
14084                mOverlay.getOverlayView().dispatchDraw(canvas);
14085            }
14086
14087            // we're done...
14088            return;
14089        }
14090
14091        /*
14092         * Here we do the full fledged routine...
14093         * (this is an uncommon case where speed matters less,
14094         * this is why we repeat some of the tests that have been
14095         * done above)
14096         */
14097
14098        boolean drawTop = false;
14099        boolean drawBottom = false;
14100        boolean drawLeft = false;
14101        boolean drawRight = false;
14102
14103        float topFadeStrength = 0.0f;
14104        float bottomFadeStrength = 0.0f;
14105        float leftFadeStrength = 0.0f;
14106        float rightFadeStrength = 0.0f;
14107
14108        // Step 2, save the canvas' layers
14109        int paddingLeft = mPaddingLeft;
14110
14111        final boolean offsetRequired = isPaddingOffsetRequired();
14112        if (offsetRequired) {
14113            paddingLeft += getLeftPaddingOffset();
14114        }
14115
14116        int left = mScrollX + paddingLeft;
14117        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14118        int top = mScrollY + getFadeTop(offsetRequired);
14119        int bottom = top + getFadeHeight(offsetRequired);
14120
14121        if (offsetRequired) {
14122            right += getRightPaddingOffset();
14123            bottom += getBottomPaddingOffset();
14124        }
14125
14126        final ScrollabilityCache scrollabilityCache = mScrollCache;
14127        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14128        int length = (int) fadeHeight;
14129
14130        // clip the fade length if top and bottom fades overlap
14131        // overlapping fades produce odd-looking artifacts
14132        if (verticalEdges && (top + length > bottom - length)) {
14133            length = (bottom - top) / 2;
14134        }
14135
14136        // also clip horizontal fades if necessary
14137        if (horizontalEdges && (left + length > right - length)) {
14138            length = (right - left) / 2;
14139        }
14140
14141        if (verticalEdges) {
14142            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14143            drawTop = topFadeStrength * fadeHeight > 1.0f;
14144            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14145            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14146        }
14147
14148        if (horizontalEdges) {
14149            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14150            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14151            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14152            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14153        }
14154
14155        saveCount = canvas.getSaveCount();
14156
14157        int solidColor = getSolidColor();
14158        if (solidColor == 0) {
14159            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14160
14161            if (drawTop) {
14162                canvas.saveLayer(left, top, right, top + length, null, flags);
14163            }
14164
14165            if (drawBottom) {
14166                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14167            }
14168
14169            if (drawLeft) {
14170                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14171            }
14172
14173            if (drawRight) {
14174                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14175            }
14176        } else {
14177            scrollabilityCache.setFadeColor(solidColor);
14178        }
14179
14180        // Step 3, draw the content
14181        if (!dirtyOpaque) onDraw(canvas);
14182
14183        // Step 4, draw the children
14184        dispatchDraw(canvas);
14185
14186        // Step 5, draw the fade effect and restore layers
14187        final Paint p = scrollabilityCache.paint;
14188        final Matrix matrix = scrollabilityCache.matrix;
14189        final Shader fade = scrollabilityCache.shader;
14190
14191        if (drawTop) {
14192            matrix.setScale(1, fadeHeight * topFadeStrength);
14193            matrix.postTranslate(left, top);
14194            fade.setLocalMatrix(matrix);
14195            canvas.drawRect(left, top, right, top + length, p);
14196        }
14197
14198        if (drawBottom) {
14199            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14200            matrix.postRotate(180);
14201            matrix.postTranslate(left, bottom);
14202            fade.setLocalMatrix(matrix);
14203            canvas.drawRect(left, bottom - length, right, bottom, p);
14204        }
14205
14206        if (drawLeft) {
14207            matrix.setScale(1, fadeHeight * leftFadeStrength);
14208            matrix.postRotate(-90);
14209            matrix.postTranslate(left, top);
14210            fade.setLocalMatrix(matrix);
14211            canvas.drawRect(left, top, left + length, bottom, p);
14212        }
14213
14214        if (drawRight) {
14215            matrix.setScale(1, fadeHeight * rightFadeStrength);
14216            matrix.postRotate(90);
14217            matrix.postTranslate(right, top);
14218            fade.setLocalMatrix(matrix);
14219            canvas.drawRect(right - length, top, right, bottom, p);
14220        }
14221
14222        canvas.restoreToCount(saveCount);
14223
14224        // Step 6, draw decorations (scrollbars)
14225        onDrawScrollBars(canvas);
14226
14227        if (mOverlay != null && !mOverlay.isEmpty()) {
14228            mOverlay.getOverlayView().dispatchDraw(canvas);
14229        }
14230    }
14231
14232    /**
14233     * Returns the overlay for this view, creating it if it does not yet exist.
14234     * Adding drawables to the overlay will cause them to be displayed whenever
14235     * the view itself is redrawn. Objects in the overlay should be actively
14236     * managed: remove them when they should not be displayed anymore. The
14237     * overlay will always have the same size as its host view.
14238     *
14239     * <p>Note: Overlays do not currently work correctly with {@link
14240     * SurfaceView} or {@link TextureView}; contents in overlays for these
14241     * types of views may not display correctly.</p>
14242     *
14243     * @return The ViewOverlay object for this view.
14244     * @see ViewOverlay
14245     */
14246    public ViewOverlay getOverlay() {
14247        if (mOverlay == null) {
14248            mOverlay = new ViewOverlay(mContext, this);
14249        }
14250        return mOverlay;
14251    }
14252
14253    /**
14254     * Override this if your view is known to always be drawn on top of a solid color background,
14255     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14256     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14257     * should be set to 0xFF.
14258     *
14259     * @see #setVerticalFadingEdgeEnabled(boolean)
14260     * @see #setHorizontalFadingEdgeEnabled(boolean)
14261     *
14262     * @return The known solid color background for this view, or 0 if the color may vary
14263     */
14264    @ViewDebug.ExportedProperty(category = "drawing")
14265    public int getSolidColor() {
14266        return 0;
14267    }
14268
14269    /**
14270     * Build a human readable string representation of the specified view flags.
14271     *
14272     * @param flags the view flags to convert to a string
14273     * @return a String representing the supplied flags
14274     */
14275    private static String printFlags(int flags) {
14276        String output = "";
14277        int numFlags = 0;
14278        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14279            output += "TAKES_FOCUS";
14280            numFlags++;
14281        }
14282
14283        switch (flags & VISIBILITY_MASK) {
14284        case INVISIBLE:
14285            if (numFlags > 0) {
14286                output += " ";
14287            }
14288            output += "INVISIBLE";
14289            // USELESS HERE numFlags++;
14290            break;
14291        case GONE:
14292            if (numFlags > 0) {
14293                output += " ";
14294            }
14295            output += "GONE";
14296            // USELESS HERE numFlags++;
14297            break;
14298        default:
14299            break;
14300        }
14301        return output;
14302    }
14303
14304    /**
14305     * Build a human readable string representation of the specified private
14306     * view flags.
14307     *
14308     * @param privateFlags the private view flags to convert to a string
14309     * @return a String representing the supplied flags
14310     */
14311    private static String printPrivateFlags(int privateFlags) {
14312        String output = "";
14313        int numFlags = 0;
14314
14315        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14316            output += "WANTS_FOCUS";
14317            numFlags++;
14318        }
14319
14320        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14321            if (numFlags > 0) {
14322                output += " ";
14323            }
14324            output += "FOCUSED";
14325            numFlags++;
14326        }
14327
14328        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14329            if (numFlags > 0) {
14330                output += " ";
14331            }
14332            output += "SELECTED";
14333            numFlags++;
14334        }
14335
14336        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14337            if (numFlags > 0) {
14338                output += " ";
14339            }
14340            output += "IS_ROOT_NAMESPACE";
14341            numFlags++;
14342        }
14343
14344        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14345            if (numFlags > 0) {
14346                output += " ";
14347            }
14348            output += "HAS_BOUNDS";
14349            numFlags++;
14350        }
14351
14352        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14353            if (numFlags > 0) {
14354                output += " ";
14355            }
14356            output += "DRAWN";
14357            // USELESS HERE numFlags++;
14358        }
14359        return output;
14360    }
14361
14362    /**
14363     * <p>Indicates whether or not this view's layout will be requested during
14364     * the next hierarchy layout pass.</p>
14365     *
14366     * @return true if the layout will be forced during next layout pass
14367     */
14368    public boolean isLayoutRequested() {
14369        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14370    }
14371
14372    /**
14373     * Return true if o is a ViewGroup that is laying out using optical bounds.
14374     * @hide
14375     */
14376    public static boolean isLayoutModeOptical(Object o) {
14377        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14378    }
14379
14380    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14381        Insets parentInsets = mParent instanceof View ?
14382                ((View) mParent).getOpticalInsets() : Insets.NONE;
14383        Insets childInsets = getOpticalInsets();
14384        return setFrame(
14385                left   + parentInsets.left - childInsets.left,
14386                top    + parentInsets.top  - childInsets.top,
14387                right  + parentInsets.left + childInsets.right,
14388                bottom + parentInsets.top  + childInsets.bottom);
14389    }
14390
14391    /**
14392     * Assign a size and position to a view and all of its
14393     * descendants
14394     *
14395     * <p>This is the second phase of the layout mechanism.
14396     * (The first is measuring). In this phase, each parent calls
14397     * layout on all of its children to position them.
14398     * This is typically done using the child measurements
14399     * that were stored in the measure pass().</p>
14400     *
14401     * <p>Derived classes should not override this method.
14402     * Derived classes with children should override
14403     * onLayout. In that method, they should
14404     * call layout on each of their children.</p>
14405     *
14406     * @param l Left position, relative to parent
14407     * @param t Top position, relative to parent
14408     * @param r Right position, relative to parent
14409     * @param b Bottom position, relative to parent
14410     */
14411    @SuppressWarnings({"unchecked"})
14412    public void layout(int l, int t, int r, int b) {
14413        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14414            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14415            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14416        }
14417
14418        int oldL = mLeft;
14419        int oldT = mTop;
14420        int oldB = mBottom;
14421        int oldR = mRight;
14422
14423        boolean changed = isLayoutModeOptical(mParent) ?
14424                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14425
14426        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14427            onLayout(changed, l, t, r, b);
14428            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14429
14430            ListenerInfo li = mListenerInfo;
14431            if (li != null && li.mOnLayoutChangeListeners != null) {
14432                ArrayList<OnLayoutChangeListener> listenersCopy =
14433                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14434                int numListeners = listenersCopy.size();
14435                for (int i = 0; i < numListeners; ++i) {
14436                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14437                }
14438            }
14439        }
14440
14441        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14442        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14443    }
14444
14445    /**
14446     * Called from layout when this view should
14447     * assign a size and position to each of its children.
14448     *
14449     * Derived classes with children should override
14450     * this method and call layout on each of
14451     * their children.
14452     * @param changed This is a new size or position for this view
14453     * @param left Left position, relative to parent
14454     * @param top Top position, relative to parent
14455     * @param right Right position, relative to parent
14456     * @param bottom Bottom position, relative to parent
14457     */
14458    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14459    }
14460
14461    /**
14462     * Assign a size and position to this view.
14463     *
14464     * This is called from layout.
14465     *
14466     * @param left Left position, relative to parent
14467     * @param top Top position, relative to parent
14468     * @param right Right position, relative to parent
14469     * @param bottom Bottom position, relative to parent
14470     * @return true if the new size and position are different than the
14471     *         previous ones
14472     * {@hide}
14473     */
14474    protected boolean setFrame(int left, int top, int right, int bottom) {
14475        boolean changed = false;
14476
14477        if (DBG) {
14478            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14479                    + right + "," + bottom + ")");
14480        }
14481
14482        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14483            changed = true;
14484
14485            // Remember our drawn bit
14486            int drawn = mPrivateFlags & PFLAG_DRAWN;
14487
14488            int oldWidth = mRight - mLeft;
14489            int oldHeight = mBottom - mTop;
14490            int newWidth = right - left;
14491            int newHeight = bottom - top;
14492            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14493
14494            // Invalidate our old position
14495            invalidate(sizeChanged);
14496
14497            mLeft = left;
14498            mTop = top;
14499            mRight = right;
14500            mBottom = bottom;
14501            if (mDisplayList != null) {
14502                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14503            }
14504
14505            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14506
14507
14508            if (sizeChanged) {
14509                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14510                    // A change in dimension means an auto-centered pivot point changes, too
14511                    if (mTransformationInfo != null) {
14512                        mTransformationInfo.mMatrixDirty = true;
14513                    }
14514                }
14515                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14516            }
14517
14518            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14519                // If we are visible, force the DRAWN bit to on so that
14520                // this invalidate will go through (at least to our parent).
14521                // This is because someone may have invalidated this view
14522                // before this call to setFrame came in, thereby clearing
14523                // the DRAWN bit.
14524                mPrivateFlags |= PFLAG_DRAWN;
14525                invalidate(sizeChanged);
14526                // parent display list may need to be recreated based on a change in the bounds
14527                // of any child
14528                invalidateParentCaches();
14529            }
14530
14531            // Reset drawn bit to original value (invalidate turns it off)
14532            mPrivateFlags |= drawn;
14533
14534            mBackgroundSizeChanged = true;
14535
14536            notifySubtreeAccessibilityStateChangedIfNeeded();
14537        }
14538        return changed;
14539    }
14540
14541    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14542        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14543        if (mOverlay != null) {
14544            mOverlay.getOverlayView().setRight(newWidth);
14545            mOverlay.getOverlayView().setBottom(newHeight);
14546        }
14547    }
14548
14549    /**
14550     * Finalize inflating a view from XML.  This is called as the last phase
14551     * of inflation, after all child views have been added.
14552     *
14553     * <p>Even if the subclass overrides onFinishInflate, they should always be
14554     * sure to call the super method, so that we get called.
14555     */
14556    protected void onFinishInflate() {
14557    }
14558
14559    /**
14560     * Returns the resources associated with this view.
14561     *
14562     * @return Resources object.
14563     */
14564    public Resources getResources() {
14565        return mResources;
14566    }
14567
14568    /**
14569     * Invalidates the specified Drawable.
14570     *
14571     * @param drawable the drawable to invalidate
14572     */
14573    public void invalidateDrawable(Drawable drawable) {
14574        if (verifyDrawable(drawable)) {
14575            final Rect dirty = drawable.getBounds();
14576            final int scrollX = mScrollX;
14577            final int scrollY = mScrollY;
14578
14579            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14580                    dirty.right + scrollX, dirty.bottom + scrollY);
14581        }
14582    }
14583
14584    /**
14585     * Schedules an action on a drawable to occur at a specified time.
14586     *
14587     * @param who the recipient of the action
14588     * @param what the action to run on the drawable
14589     * @param when the time at which the action must occur. Uses the
14590     *        {@link SystemClock#uptimeMillis} timebase.
14591     */
14592    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14593        if (verifyDrawable(who) && what != null) {
14594            final long delay = when - SystemClock.uptimeMillis();
14595            if (mAttachInfo != null) {
14596                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14597                        Choreographer.CALLBACK_ANIMATION, what, who,
14598                        Choreographer.subtractFrameDelay(delay));
14599            } else {
14600                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14601            }
14602        }
14603    }
14604
14605    /**
14606     * Cancels a scheduled action on a drawable.
14607     *
14608     * @param who the recipient of the action
14609     * @param what the action to cancel
14610     */
14611    public void unscheduleDrawable(Drawable who, Runnable what) {
14612        if (verifyDrawable(who) && what != null) {
14613            if (mAttachInfo != null) {
14614                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14615                        Choreographer.CALLBACK_ANIMATION, what, who);
14616            } else {
14617                ViewRootImpl.getRunQueue().removeCallbacks(what);
14618            }
14619        }
14620    }
14621
14622    /**
14623     * Unschedule any events associated with the given Drawable.  This can be
14624     * used when selecting a new Drawable into a view, so that the previous
14625     * one is completely unscheduled.
14626     *
14627     * @param who The Drawable to unschedule.
14628     *
14629     * @see #drawableStateChanged
14630     */
14631    public void unscheduleDrawable(Drawable who) {
14632        if (mAttachInfo != null && who != null) {
14633            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14634                    Choreographer.CALLBACK_ANIMATION, null, who);
14635        }
14636    }
14637
14638    /**
14639     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14640     * that the View directionality can and will be resolved before its Drawables.
14641     *
14642     * Will call {@link View#onResolveDrawables} when resolution is done.
14643     *
14644     * @hide
14645     */
14646    protected void resolveDrawables() {
14647        if (canResolveLayoutDirection()) {
14648            if (mBackground != null) {
14649                mBackground.setLayoutDirection(getLayoutDirection());
14650            }
14651            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14652            onResolveDrawables(getLayoutDirection());
14653        }
14654    }
14655
14656    /**
14657     * Called when layout direction has been resolved.
14658     *
14659     * The default implementation does nothing.
14660     *
14661     * @param layoutDirection The resolved layout direction.
14662     *
14663     * @see #LAYOUT_DIRECTION_LTR
14664     * @see #LAYOUT_DIRECTION_RTL
14665     *
14666     * @hide
14667     */
14668    public void onResolveDrawables(int layoutDirection) {
14669    }
14670
14671    /**
14672     * @hide
14673     */
14674    protected void resetResolvedDrawables() {
14675        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14676    }
14677
14678    private boolean isDrawablesResolved() {
14679        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14680    }
14681
14682    /**
14683     * If your view subclass is displaying its own Drawable objects, it should
14684     * override this function and return true for any Drawable it is
14685     * displaying.  This allows animations for those drawables to be
14686     * scheduled.
14687     *
14688     * <p>Be sure to call through to the super class when overriding this
14689     * function.
14690     *
14691     * @param who The Drawable to verify.  Return true if it is one you are
14692     *            displaying, else return the result of calling through to the
14693     *            super class.
14694     *
14695     * @return boolean If true than the Drawable is being displayed in the
14696     *         view; else false and it is not allowed to animate.
14697     *
14698     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14699     * @see #drawableStateChanged()
14700     */
14701    protected boolean verifyDrawable(Drawable who) {
14702        return who == mBackground;
14703    }
14704
14705    /**
14706     * This function is called whenever the state of the view changes in such
14707     * a way that it impacts the state of drawables being shown.
14708     *
14709     * <p>Be sure to call through to the superclass when overriding this
14710     * function.
14711     *
14712     * @see Drawable#setState(int[])
14713     */
14714    protected void drawableStateChanged() {
14715        Drawable d = mBackground;
14716        if (d != null && d.isStateful()) {
14717            d.setState(getDrawableState());
14718        }
14719    }
14720
14721    /**
14722     * Call this to force a view to update its drawable state. This will cause
14723     * drawableStateChanged to be called on this view. Views that are interested
14724     * in the new state should call getDrawableState.
14725     *
14726     * @see #drawableStateChanged
14727     * @see #getDrawableState
14728     */
14729    public void refreshDrawableState() {
14730        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14731        drawableStateChanged();
14732
14733        ViewParent parent = mParent;
14734        if (parent != null) {
14735            parent.childDrawableStateChanged(this);
14736        }
14737    }
14738
14739    /**
14740     * Return an array of resource IDs of the drawable states representing the
14741     * current state of the view.
14742     *
14743     * @return The current drawable state
14744     *
14745     * @see Drawable#setState(int[])
14746     * @see #drawableStateChanged()
14747     * @see #onCreateDrawableState(int)
14748     */
14749    public final int[] getDrawableState() {
14750        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14751            return mDrawableState;
14752        } else {
14753            mDrawableState = onCreateDrawableState(0);
14754            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14755            return mDrawableState;
14756        }
14757    }
14758
14759    /**
14760     * Generate the new {@link android.graphics.drawable.Drawable} state for
14761     * this view. This is called by the view
14762     * system when the cached Drawable state is determined to be invalid.  To
14763     * retrieve the current state, you should use {@link #getDrawableState}.
14764     *
14765     * @param extraSpace if non-zero, this is the number of extra entries you
14766     * would like in the returned array in which you can place your own
14767     * states.
14768     *
14769     * @return Returns an array holding the current {@link Drawable} state of
14770     * the view.
14771     *
14772     * @see #mergeDrawableStates(int[], int[])
14773     */
14774    protected int[] onCreateDrawableState(int extraSpace) {
14775        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14776                mParent instanceof View) {
14777            return ((View) mParent).onCreateDrawableState(extraSpace);
14778        }
14779
14780        int[] drawableState;
14781
14782        int privateFlags = mPrivateFlags;
14783
14784        int viewStateIndex = 0;
14785        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14786        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14787        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14788        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14789        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14790        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14791        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14792                HardwareRenderer.isAvailable()) {
14793            // This is set if HW acceleration is requested, even if the current
14794            // process doesn't allow it.  This is just to allow app preview
14795            // windows to better match their app.
14796            viewStateIndex |= VIEW_STATE_ACCELERATED;
14797        }
14798        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14799
14800        final int privateFlags2 = mPrivateFlags2;
14801        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14802        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14803
14804        drawableState = VIEW_STATE_SETS[viewStateIndex];
14805
14806        //noinspection ConstantIfStatement
14807        if (false) {
14808            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14809            Log.i("View", toString()
14810                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14811                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14812                    + " fo=" + hasFocus()
14813                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14814                    + " wf=" + hasWindowFocus()
14815                    + ": " + Arrays.toString(drawableState));
14816        }
14817
14818        if (extraSpace == 0) {
14819            return drawableState;
14820        }
14821
14822        final int[] fullState;
14823        if (drawableState != null) {
14824            fullState = new int[drawableState.length + extraSpace];
14825            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14826        } else {
14827            fullState = new int[extraSpace];
14828        }
14829
14830        return fullState;
14831    }
14832
14833    /**
14834     * Merge your own state values in <var>additionalState</var> into the base
14835     * state values <var>baseState</var> that were returned by
14836     * {@link #onCreateDrawableState(int)}.
14837     *
14838     * @param baseState The base state values returned by
14839     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14840     * own additional state values.
14841     *
14842     * @param additionalState The additional state values you would like
14843     * added to <var>baseState</var>; this array is not modified.
14844     *
14845     * @return As a convenience, the <var>baseState</var> array you originally
14846     * passed into the function is returned.
14847     *
14848     * @see #onCreateDrawableState(int)
14849     */
14850    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14851        final int N = baseState.length;
14852        int i = N - 1;
14853        while (i >= 0 && baseState[i] == 0) {
14854            i--;
14855        }
14856        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14857        return baseState;
14858    }
14859
14860    /**
14861     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14862     * on all Drawable objects associated with this view.
14863     */
14864    public void jumpDrawablesToCurrentState() {
14865        if (mBackground != null) {
14866            mBackground.jumpToCurrentState();
14867        }
14868    }
14869
14870    /**
14871     * Sets the background color for this view.
14872     * @param color the color of the background
14873     */
14874    @RemotableViewMethod
14875    public void setBackgroundColor(int color) {
14876        if (mBackground instanceof ColorDrawable) {
14877            ((ColorDrawable) mBackground.mutate()).setColor(color);
14878            computeOpaqueFlags();
14879            mBackgroundResource = 0;
14880        } else {
14881            setBackground(new ColorDrawable(color));
14882        }
14883    }
14884
14885    /**
14886     * Set the background to a given resource. The resource should refer to
14887     * a Drawable object or 0 to remove the background.
14888     * @param resid The identifier of the resource.
14889     *
14890     * @attr ref android.R.styleable#View_background
14891     */
14892    @RemotableViewMethod
14893    public void setBackgroundResource(int resid) {
14894        if (resid != 0 && resid == mBackgroundResource) {
14895            return;
14896        }
14897
14898        Drawable d= null;
14899        if (resid != 0) {
14900            d = mResources.getDrawable(resid);
14901        }
14902        setBackground(d);
14903
14904        mBackgroundResource = resid;
14905    }
14906
14907    /**
14908     * Set the background to a given Drawable, or remove the background. If the
14909     * background has padding, this View's padding is set to the background's
14910     * padding. However, when a background is removed, this View's padding isn't
14911     * touched. If setting the padding is desired, please use
14912     * {@link #setPadding(int, int, int, int)}.
14913     *
14914     * @param background The Drawable to use as the background, or null to remove the
14915     *        background
14916     */
14917    public void setBackground(Drawable background) {
14918        //noinspection deprecation
14919        setBackgroundDrawable(background);
14920    }
14921
14922    /**
14923     * @deprecated use {@link #setBackground(Drawable)} instead
14924     */
14925    @Deprecated
14926    public void setBackgroundDrawable(Drawable background) {
14927        computeOpaqueFlags();
14928
14929        if (background == mBackground) {
14930            return;
14931        }
14932
14933        boolean requestLayout = false;
14934
14935        mBackgroundResource = 0;
14936
14937        /*
14938         * Regardless of whether we're setting a new background or not, we want
14939         * to clear the previous drawable.
14940         */
14941        if (mBackground != null) {
14942            mBackground.setCallback(null);
14943            unscheduleDrawable(mBackground);
14944        }
14945
14946        if (background != null) {
14947            Rect padding = sThreadLocal.get();
14948            if (padding == null) {
14949                padding = new Rect();
14950                sThreadLocal.set(padding);
14951            }
14952            resetResolvedDrawables();
14953            background.setLayoutDirection(getLayoutDirection());
14954            if (background.getPadding(padding)) {
14955                resetResolvedPadding();
14956                switch (background.getLayoutDirection()) {
14957                    case LAYOUT_DIRECTION_RTL:
14958                        mUserPaddingLeftInitial = padding.right;
14959                        mUserPaddingRightInitial = padding.left;
14960                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14961                        break;
14962                    case LAYOUT_DIRECTION_LTR:
14963                    default:
14964                        mUserPaddingLeftInitial = padding.left;
14965                        mUserPaddingRightInitial = padding.right;
14966                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14967                }
14968            }
14969
14970            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14971            // if it has a different minimum size, we should layout again
14972            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14973                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14974                requestLayout = true;
14975            }
14976
14977            background.setCallback(this);
14978            if (background.isStateful()) {
14979                background.setState(getDrawableState());
14980            }
14981            background.setVisible(getVisibility() == VISIBLE, false);
14982            mBackground = background;
14983
14984            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14985                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14986                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14987                requestLayout = true;
14988            }
14989        } else {
14990            /* Remove the background */
14991            mBackground = null;
14992
14993            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14994                /*
14995                 * This view ONLY drew the background before and we're removing
14996                 * the background, so now it won't draw anything
14997                 * (hence we SKIP_DRAW)
14998                 */
14999                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15000                mPrivateFlags |= PFLAG_SKIP_DRAW;
15001            }
15002
15003            /*
15004             * When the background is set, we try to apply its padding to this
15005             * View. When the background is removed, we don't touch this View's
15006             * padding. This is noted in the Javadocs. Hence, we don't need to
15007             * requestLayout(), the invalidate() below is sufficient.
15008             */
15009
15010            // The old background's minimum size could have affected this
15011            // View's layout, so let's requestLayout
15012            requestLayout = true;
15013        }
15014
15015        computeOpaqueFlags();
15016
15017        if (requestLayout) {
15018            requestLayout();
15019        }
15020
15021        mBackgroundSizeChanged = true;
15022        invalidate(true);
15023    }
15024
15025    /**
15026     * Gets the background drawable
15027     *
15028     * @return The drawable used as the background for this view, if any.
15029     *
15030     * @see #setBackground(Drawable)
15031     *
15032     * @attr ref android.R.styleable#View_background
15033     */
15034    public Drawable getBackground() {
15035        return mBackground;
15036    }
15037
15038    /**
15039     * Sets the padding. The view may add on the space required to display
15040     * the scrollbars, depending on the style and visibility of the scrollbars.
15041     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15042     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15043     * from the values set in this call.
15044     *
15045     * @attr ref android.R.styleable#View_padding
15046     * @attr ref android.R.styleable#View_paddingBottom
15047     * @attr ref android.R.styleable#View_paddingLeft
15048     * @attr ref android.R.styleable#View_paddingRight
15049     * @attr ref android.R.styleable#View_paddingTop
15050     * @param left the left padding in pixels
15051     * @param top the top padding in pixels
15052     * @param right the right padding in pixels
15053     * @param bottom the bottom padding in pixels
15054     */
15055    public void setPadding(int left, int top, int right, int bottom) {
15056        resetResolvedPadding();
15057
15058        mUserPaddingStart = UNDEFINED_PADDING;
15059        mUserPaddingEnd = UNDEFINED_PADDING;
15060
15061        mUserPaddingLeftInitial = left;
15062        mUserPaddingRightInitial = right;
15063
15064        internalSetPadding(left, top, right, bottom);
15065    }
15066
15067    /**
15068     * @hide
15069     */
15070    protected void internalSetPadding(int left, int top, int right, int bottom) {
15071        mUserPaddingLeft = left;
15072        mUserPaddingRight = right;
15073        mUserPaddingBottom = bottom;
15074
15075        final int viewFlags = mViewFlags;
15076        boolean changed = false;
15077
15078        // Common case is there are no scroll bars.
15079        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15080            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15081                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15082                        ? 0 : getVerticalScrollbarWidth();
15083                switch (mVerticalScrollbarPosition) {
15084                    case SCROLLBAR_POSITION_DEFAULT:
15085                        if (isLayoutRtl()) {
15086                            left += offset;
15087                        } else {
15088                            right += offset;
15089                        }
15090                        break;
15091                    case SCROLLBAR_POSITION_RIGHT:
15092                        right += offset;
15093                        break;
15094                    case SCROLLBAR_POSITION_LEFT:
15095                        left += offset;
15096                        break;
15097                }
15098            }
15099            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15100                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15101                        ? 0 : getHorizontalScrollbarHeight();
15102            }
15103        }
15104
15105        if (mPaddingLeft != left) {
15106            changed = true;
15107            mPaddingLeft = left;
15108        }
15109        if (mPaddingTop != top) {
15110            changed = true;
15111            mPaddingTop = top;
15112        }
15113        if (mPaddingRight != right) {
15114            changed = true;
15115            mPaddingRight = right;
15116        }
15117        if (mPaddingBottom != bottom) {
15118            changed = true;
15119            mPaddingBottom = bottom;
15120        }
15121
15122        if (changed) {
15123            requestLayout();
15124        }
15125    }
15126
15127    /**
15128     * Sets the relative padding. The view may add on the space required to display
15129     * the scrollbars, depending on the style and visibility of the scrollbars.
15130     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15131     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15132     * from the values set in this call.
15133     *
15134     * @attr ref android.R.styleable#View_padding
15135     * @attr ref android.R.styleable#View_paddingBottom
15136     * @attr ref android.R.styleable#View_paddingStart
15137     * @attr ref android.R.styleable#View_paddingEnd
15138     * @attr ref android.R.styleable#View_paddingTop
15139     * @param start the start padding in pixels
15140     * @param top the top padding in pixels
15141     * @param end the end padding in pixels
15142     * @param bottom the bottom padding in pixels
15143     */
15144    public void setPaddingRelative(int start, int top, int end, int bottom) {
15145        resetResolvedPadding();
15146
15147        mUserPaddingStart = start;
15148        mUserPaddingEnd = end;
15149
15150        switch(getLayoutDirection()) {
15151            case LAYOUT_DIRECTION_RTL:
15152                mUserPaddingLeftInitial = end;
15153                mUserPaddingRightInitial = start;
15154                internalSetPadding(end, top, start, bottom);
15155                break;
15156            case LAYOUT_DIRECTION_LTR:
15157            default:
15158                mUserPaddingLeftInitial = start;
15159                mUserPaddingRightInitial = end;
15160                internalSetPadding(start, top, end, bottom);
15161        }
15162    }
15163
15164    /**
15165     * Returns the top padding of this view.
15166     *
15167     * @return the top padding in pixels
15168     */
15169    public int getPaddingTop() {
15170        return mPaddingTop;
15171    }
15172
15173    /**
15174     * Returns the bottom padding of this view. If there are inset and enabled
15175     * scrollbars, this value may include the space required to display the
15176     * scrollbars as well.
15177     *
15178     * @return the bottom padding in pixels
15179     */
15180    public int getPaddingBottom() {
15181        return mPaddingBottom;
15182    }
15183
15184    /**
15185     * Returns the left padding of this view. If there are inset and enabled
15186     * scrollbars, this value may include the space required to display the
15187     * scrollbars as well.
15188     *
15189     * @return the left padding in pixels
15190     */
15191    public int getPaddingLeft() {
15192        if (!isPaddingResolved()) {
15193            resolvePadding();
15194        }
15195        return mPaddingLeft;
15196    }
15197
15198    /**
15199     * Returns the start padding of this view depending on its resolved layout direction.
15200     * If there are inset and enabled scrollbars, this value may include the space
15201     * required to display the scrollbars as well.
15202     *
15203     * @return the start padding in pixels
15204     */
15205    public int getPaddingStart() {
15206        if (!isPaddingResolved()) {
15207            resolvePadding();
15208        }
15209        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15210                mPaddingRight : mPaddingLeft;
15211    }
15212
15213    /**
15214     * Returns the right padding of this view. If there are inset and enabled
15215     * scrollbars, this value may include the space required to display the
15216     * scrollbars as well.
15217     *
15218     * @return the right padding in pixels
15219     */
15220    public int getPaddingRight() {
15221        if (!isPaddingResolved()) {
15222            resolvePadding();
15223        }
15224        return mPaddingRight;
15225    }
15226
15227    /**
15228     * Returns the end padding of this view depending on its resolved layout direction.
15229     * If there are inset and enabled scrollbars, this value may include the space
15230     * required to display the scrollbars as well.
15231     *
15232     * @return the end padding in pixels
15233     */
15234    public int getPaddingEnd() {
15235        if (!isPaddingResolved()) {
15236            resolvePadding();
15237        }
15238        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15239                mPaddingLeft : mPaddingRight;
15240    }
15241
15242    /**
15243     * Return if the padding as been set thru relative values
15244     * {@link #setPaddingRelative(int, int, int, int)} or thru
15245     * @attr ref android.R.styleable#View_paddingStart or
15246     * @attr ref android.R.styleable#View_paddingEnd
15247     *
15248     * @return true if the padding is relative or false if it is not.
15249     */
15250    public boolean isPaddingRelative() {
15251        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15252    }
15253
15254    Insets computeOpticalInsets() {
15255        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15256    }
15257
15258    /**
15259     * @hide
15260     */
15261    public void resetPaddingToInitialValues() {
15262        if (isRtlCompatibilityMode()) {
15263            mPaddingLeft = mUserPaddingLeftInitial;
15264            mPaddingRight = mUserPaddingRightInitial;
15265            return;
15266        }
15267        if (isLayoutRtl()) {
15268            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15269            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15270        } else {
15271            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15272            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15273        }
15274    }
15275
15276    /**
15277     * @hide
15278     */
15279    public Insets getOpticalInsets() {
15280        if (mLayoutInsets == null) {
15281            mLayoutInsets = computeOpticalInsets();
15282        }
15283        return mLayoutInsets;
15284    }
15285
15286    /**
15287     * Changes the selection state of this view. A view can be selected or not.
15288     * Note that selection is not the same as focus. Views are typically
15289     * selected in the context of an AdapterView like ListView or GridView;
15290     * the selected view is the view that is highlighted.
15291     *
15292     * @param selected true if the view must be selected, false otherwise
15293     */
15294    public void setSelected(boolean selected) {
15295        //noinspection DoubleNegation
15296        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15297            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15298            if (!selected) resetPressedState();
15299            invalidate(true);
15300            refreshDrawableState();
15301            dispatchSetSelected(selected);
15302            notifyViewAccessibilityStateChangedIfNeeded();
15303        }
15304    }
15305
15306    /**
15307     * Dispatch setSelected to all of this View's children.
15308     *
15309     * @see #setSelected(boolean)
15310     *
15311     * @param selected The new selected state
15312     */
15313    protected void dispatchSetSelected(boolean selected) {
15314    }
15315
15316    /**
15317     * Indicates the selection state of this view.
15318     *
15319     * @return true if the view is selected, false otherwise
15320     */
15321    @ViewDebug.ExportedProperty
15322    public boolean isSelected() {
15323        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15324    }
15325
15326    /**
15327     * Changes the activated state of this view. A view can be activated or not.
15328     * Note that activation is not the same as selection.  Selection is
15329     * a transient property, representing the view (hierarchy) the user is
15330     * currently interacting with.  Activation is a longer-term state that the
15331     * user can move views in and out of.  For example, in a list view with
15332     * single or multiple selection enabled, the views in the current selection
15333     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15334     * here.)  The activated state is propagated down to children of the view it
15335     * is set on.
15336     *
15337     * @param activated true if the view must be activated, false otherwise
15338     */
15339    public void setActivated(boolean activated) {
15340        //noinspection DoubleNegation
15341        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15342            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15343            invalidate(true);
15344            refreshDrawableState();
15345            dispatchSetActivated(activated);
15346        }
15347    }
15348
15349    /**
15350     * Dispatch setActivated to all of this View's children.
15351     *
15352     * @see #setActivated(boolean)
15353     *
15354     * @param activated The new activated state
15355     */
15356    protected void dispatchSetActivated(boolean activated) {
15357    }
15358
15359    /**
15360     * Indicates the activation state of this view.
15361     *
15362     * @return true if the view is activated, false otherwise
15363     */
15364    @ViewDebug.ExportedProperty
15365    public boolean isActivated() {
15366        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15367    }
15368
15369    /**
15370     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15371     * observer can be used to get notifications when global events, like
15372     * layout, happen.
15373     *
15374     * The returned ViewTreeObserver observer is not guaranteed to remain
15375     * valid for the lifetime of this View. If the caller of this method keeps
15376     * a long-lived reference to ViewTreeObserver, it should always check for
15377     * the return value of {@link ViewTreeObserver#isAlive()}.
15378     *
15379     * @return The ViewTreeObserver for this view's hierarchy.
15380     */
15381    public ViewTreeObserver getViewTreeObserver() {
15382        if (mAttachInfo != null) {
15383            return mAttachInfo.mTreeObserver;
15384        }
15385        if (mFloatingTreeObserver == null) {
15386            mFloatingTreeObserver = new ViewTreeObserver();
15387        }
15388        return mFloatingTreeObserver;
15389    }
15390
15391    /**
15392     * <p>Finds the topmost view in the current view hierarchy.</p>
15393     *
15394     * @return the topmost view containing this view
15395     */
15396    public View getRootView() {
15397        if (mAttachInfo != null) {
15398            final View v = mAttachInfo.mRootView;
15399            if (v != null) {
15400                return v;
15401            }
15402        }
15403
15404        View parent = this;
15405
15406        while (parent.mParent != null && parent.mParent instanceof View) {
15407            parent = (View) parent.mParent;
15408        }
15409
15410        return parent;
15411    }
15412
15413    /**
15414     * <p>Computes the coordinates of this view on the screen. The argument
15415     * must be an array of two integers. After the method returns, the array
15416     * contains the x and y location in that order.</p>
15417     *
15418     * @param location an array of two integers in which to hold the coordinates
15419     */
15420    public void getLocationOnScreen(int[] location) {
15421        getLocationInWindow(location);
15422
15423        final AttachInfo info = mAttachInfo;
15424        if (info != null) {
15425            location[0] += info.mWindowLeft;
15426            location[1] += info.mWindowTop;
15427        }
15428    }
15429
15430    /**
15431     * <p>Computes the coordinates of this view in its window. The argument
15432     * must be an array of two integers. After the method returns, the array
15433     * contains the x and y location in that order.</p>
15434     *
15435     * @param location an array of two integers in which to hold the coordinates
15436     */
15437    public void getLocationInWindow(int[] location) {
15438        if (location == null || location.length < 2) {
15439            throw new IllegalArgumentException("location must be an array of two integers");
15440        }
15441
15442        if (mAttachInfo == null) {
15443            // When the view is not attached to a window, this method does not make sense
15444            location[0] = location[1] = 0;
15445            return;
15446        }
15447
15448        float[] position = mAttachInfo.mTmpTransformLocation;
15449        position[0] = position[1] = 0.0f;
15450
15451        if (!hasIdentityMatrix()) {
15452            getMatrix().mapPoints(position);
15453        }
15454
15455        position[0] += mLeft;
15456        position[1] += mTop;
15457
15458        ViewParent viewParent = mParent;
15459        while (viewParent instanceof View) {
15460            final View view = (View) viewParent;
15461
15462            position[0] -= view.mScrollX;
15463            position[1] -= view.mScrollY;
15464
15465            if (!view.hasIdentityMatrix()) {
15466                view.getMatrix().mapPoints(position);
15467            }
15468
15469            position[0] += view.mLeft;
15470            position[1] += view.mTop;
15471
15472            viewParent = view.mParent;
15473         }
15474
15475        if (viewParent instanceof ViewRootImpl) {
15476            // *cough*
15477            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15478            position[1] -= vr.mCurScrollY;
15479        }
15480
15481        location[0] = (int) (position[0] + 0.5f);
15482        location[1] = (int) (position[1] + 0.5f);
15483    }
15484
15485    /**
15486     * {@hide}
15487     * @param id the id of the view to be found
15488     * @return the view of the specified id, null if cannot be found
15489     */
15490    protected View findViewTraversal(int id) {
15491        if (id == mID) {
15492            return this;
15493        }
15494        return null;
15495    }
15496
15497    /**
15498     * {@hide}
15499     * @param tag the tag of the view to be found
15500     * @return the view of specified tag, null if cannot be found
15501     */
15502    protected View findViewWithTagTraversal(Object tag) {
15503        if (tag != null && tag.equals(mTag)) {
15504            return this;
15505        }
15506        return null;
15507    }
15508
15509    /**
15510     * {@hide}
15511     * @param predicate The predicate to evaluate.
15512     * @param childToSkip If not null, ignores this child during the recursive traversal.
15513     * @return The first view that matches the predicate or null.
15514     */
15515    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15516        if (predicate.apply(this)) {
15517            return this;
15518        }
15519        return null;
15520    }
15521
15522    /**
15523     * Look for a child view with the given id.  If this view has the given
15524     * id, return this view.
15525     *
15526     * @param id The id to search for.
15527     * @return The view that has the given id in the hierarchy or null
15528     */
15529    public final View findViewById(int id) {
15530        if (id < 0) {
15531            return null;
15532        }
15533        return findViewTraversal(id);
15534    }
15535
15536    /**
15537     * Finds a view by its unuque and stable accessibility id.
15538     *
15539     * @param accessibilityId The searched accessibility id.
15540     * @return The found view.
15541     */
15542    final View findViewByAccessibilityId(int accessibilityId) {
15543        if (accessibilityId < 0) {
15544            return null;
15545        }
15546        return findViewByAccessibilityIdTraversal(accessibilityId);
15547    }
15548
15549    /**
15550     * Performs the traversal to find a view by its unuque and stable accessibility id.
15551     *
15552     * <strong>Note:</strong>This method does not stop at the root namespace
15553     * boundary since the user can touch the screen at an arbitrary location
15554     * potentially crossing the root namespace bounday which will send an
15555     * accessibility event to accessibility services and they should be able
15556     * to obtain the event source. Also accessibility ids are guaranteed to be
15557     * unique in the window.
15558     *
15559     * @param accessibilityId The accessibility id.
15560     * @return The found view.
15561     *
15562     * @hide
15563     */
15564    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15565        if (getAccessibilityViewId() == accessibilityId) {
15566            return this;
15567        }
15568        return null;
15569    }
15570
15571    /**
15572     * Look for a child view with the given tag.  If this view has the given
15573     * tag, return this view.
15574     *
15575     * @param tag The tag to search for, using "tag.equals(getTag())".
15576     * @return The View that has the given tag in the hierarchy or null
15577     */
15578    public final View findViewWithTag(Object tag) {
15579        if (tag == null) {
15580            return null;
15581        }
15582        return findViewWithTagTraversal(tag);
15583    }
15584
15585    /**
15586     * {@hide}
15587     * Look for a child view that matches the specified predicate.
15588     * If this view matches the predicate, return this view.
15589     *
15590     * @param predicate The predicate to evaluate.
15591     * @return The first view that matches the predicate or null.
15592     */
15593    public final View findViewByPredicate(Predicate<View> predicate) {
15594        return findViewByPredicateTraversal(predicate, null);
15595    }
15596
15597    /**
15598     * {@hide}
15599     * Look for a child view that matches the specified predicate,
15600     * starting with the specified view and its descendents and then
15601     * recusively searching the ancestors and siblings of that view
15602     * until this view is reached.
15603     *
15604     * This method is useful in cases where the predicate does not match
15605     * a single unique view (perhaps multiple views use the same id)
15606     * and we are trying to find the view that is "closest" in scope to the
15607     * starting view.
15608     *
15609     * @param start The view to start from.
15610     * @param predicate The predicate to evaluate.
15611     * @return The first view that matches the predicate or null.
15612     */
15613    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15614        View childToSkip = null;
15615        for (;;) {
15616            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15617            if (view != null || start == this) {
15618                return view;
15619            }
15620
15621            ViewParent parent = start.getParent();
15622            if (parent == null || !(parent instanceof View)) {
15623                return null;
15624            }
15625
15626            childToSkip = start;
15627            start = (View) parent;
15628        }
15629    }
15630
15631    /**
15632     * Sets the identifier for this view. The identifier does not have to be
15633     * unique in this view's hierarchy. The identifier should be a positive
15634     * number.
15635     *
15636     * @see #NO_ID
15637     * @see #getId()
15638     * @see #findViewById(int)
15639     *
15640     * @param id a number used to identify the view
15641     *
15642     * @attr ref android.R.styleable#View_id
15643     */
15644    public void setId(int id) {
15645        mID = id;
15646        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15647            mID = generateViewId();
15648        }
15649    }
15650
15651    /**
15652     * {@hide}
15653     *
15654     * @param isRoot true if the view belongs to the root namespace, false
15655     *        otherwise
15656     */
15657    public void setIsRootNamespace(boolean isRoot) {
15658        if (isRoot) {
15659            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15660        } else {
15661            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15662        }
15663    }
15664
15665    /**
15666     * {@hide}
15667     *
15668     * @return true if the view belongs to the root namespace, false otherwise
15669     */
15670    public boolean isRootNamespace() {
15671        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15672    }
15673
15674    /**
15675     * Returns this view's identifier.
15676     *
15677     * @return a positive integer used to identify the view or {@link #NO_ID}
15678     *         if the view has no ID
15679     *
15680     * @see #setId(int)
15681     * @see #findViewById(int)
15682     * @attr ref android.R.styleable#View_id
15683     */
15684    @ViewDebug.CapturedViewProperty
15685    public int getId() {
15686        return mID;
15687    }
15688
15689    /**
15690     * Returns this view's tag.
15691     *
15692     * @return the Object stored in this view as a tag
15693     *
15694     * @see #setTag(Object)
15695     * @see #getTag(int)
15696     */
15697    @ViewDebug.ExportedProperty
15698    public Object getTag() {
15699        return mTag;
15700    }
15701
15702    /**
15703     * Sets the tag associated with this view. A tag can be used to mark
15704     * a view in its hierarchy and does not have to be unique within the
15705     * hierarchy. Tags can also be used to store data within a view without
15706     * resorting to another data structure.
15707     *
15708     * @param tag an Object to tag the view with
15709     *
15710     * @see #getTag()
15711     * @see #setTag(int, Object)
15712     */
15713    public void setTag(final Object tag) {
15714        mTag = tag;
15715    }
15716
15717    /**
15718     * Returns the tag associated with this view and the specified key.
15719     *
15720     * @param key The key identifying the tag
15721     *
15722     * @return the Object stored in this view as a tag
15723     *
15724     * @see #setTag(int, Object)
15725     * @see #getTag()
15726     */
15727    public Object getTag(int key) {
15728        if (mKeyedTags != null) return mKeyedTags.get(key);
15729        return null;
15730    }
15731
15732    /**
15733     * Sets a tag associated with this view and a key. A tag can be used
15734     * to mark a view in its hierarchy and does not have to be unique within
15735     * the hierarchy. Tags can also be used to store data within a view
15736     * without resorting to another data structure.
15737     *
15738     * The specified key should be an id declared in the resources of the
15739     * application to ensure it is unique (see the <a
15740     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15741     * Keys identified as belonging to
15742     * the Android framework or not associated with any package will cause
15743     * an {@link IllegalArgumentException} to be thrown.
15744     *
15745     * @param key The key identifying the tag
15746     * @param tag An Object to tag the view with
15747     *
15748     * @throws IllegalArgumentException If they specified key is not valid
15749     *
15750     * @see #setTag(Object)
15751     * @see #getTag(int)
15752     */
15753    public void setTag(int key, final Object tag) {
15754        // If the package id is 0x00 or 0x01, it's either an undefined package
15755        // or a framework id
15756        if ((key >>> 24) < 2) {
15757            throw new IllegalArgumentException("The key must be an application-specific "
15758                    + "resource id.");
15759        }
15760
15761        setKeyedTag(key, tag);
15762    }
15763
15764    /**
15765     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15766     * framework id.
15767     *
15768     * @hide
15769     */
15770    public void setTagInternal(int key, Object tag) {
15771        if ((key >>> 24) != 0x1) {
15772            throw new IllegalArgumentException("The key must be a framework-specific "
15773                    + "resource id.");
15774        }
15775
15776        setKeyedTag(key, tag);
15777    }
15778
15779    private void setKeyedTag(int key, Object tag) {
15780        if (mKeyedTags == null) {
15781            mKeyedTags = new SparseArray<Object>(2);
15782        }
15783
15784        mKeyedTags.put(key, tag);
15785    }
15786
15787    /**
15788     * Prints information about this view in the log output, with the tag
15789     * {@link #VIEW_LOG_TAG}.
15790     *
15791     * @hide
15792     */
15793    public void debug() {
15794        debug(0);
15795    }
15796
15797    /**
15798     * Prints information about this view in the log output, with the tag
15799     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15800     * indentation defined by the <code>depth</code>.
15801     *
15802     * @param depth the indentation level
15803     *
15804     * @hide
15805     */
15806    protected void debug(int depth) {
15807        String output = debugIndent(depth - 1);
15808
15809        output += "+ " + this;
15810        int id = getId();
15811        if (id != -1) {
15812            output += " (id=" + id + ")";
15813        }
15814        Object tag = getTag();
15815        if (tag != null) {
15816            output += " (tag=" + tag + ")";
15817        }
15818        Log.d(VIEW_LOG_TAG, output);
15819
15820        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15821            output = debugIndent(depth) + " FOCUSED";
15822            Log.d(VIEW_LOG_TAG, output);
15823        }
15824
15825        output = debugIndent(depth);
15826        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15827                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15828                + "} ";
15829        Log.d(VIEW_LOG_TAG, output);
15830
15831        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15832                || mPaddingBottom != 0) {
15833            output = debugIndent(depth);
15834            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15835                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15836            Log.d(VIEW_LOG_TAG, output);
15837        }
15838
15839        output = debugIndent(depth);
15840        output += "mMeasureWidth=" + mMeasuredWidth +
15841                " mMeasureHeight=" + mMeasuredHeight;
15842        Log.d(VIEW_LOG_TAG, output);
15843
15844        output = debugIndent(depth);
15845        if (mLayoutParams == null) {
15846            output += "BAD! no layout params";
15847        } else {
15848            output = mLayoutParams.debug(output);
15849        }
15850        Log.d(VIEW_LOG_TAG, output);
15851
15852        output = debugIndent(depth);
15853        output += "flags={";
15854        output += View.printFlags(mViewFlags);
15855        output += "}";
15856        Log.d(VIEW_LOG_TAG, output);
15857
15858        output = debugIndent(depth);
15859        output += "privateFlags={";
15860        output += View.printPrivateFlags(mPrivateFlags);
15861        output += "}";
15862        Log.d(VIEW_LOG_TAG, output);
15863    }
15864
15865    /**
15866     * Creates a string of whitespaces used for indentation.
15867     *
15868     * @param depth the indentation level
15869     * @return a String containing (depth * 2 + 3) * 2 white spaces
15870     *
15871     * @hide
15872     */
15873    protected static String debugIndent(int depth) {
15874        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15875        for (int i = 0; i < (depth * 2) + 3; i++) {
15876            spaces.append(' ').append(' ');
15877        }
15878        return spaces.toString();
15879    }
15880
15881    /**
15882     * <p>Return the offset of the widget's text baseline from the widget's top
15883     * boundary. If this widget does not support baseline alignment, this
15884     * method returns -1. </p>
15885     *
15886     * @return the offset of the baseline within the widget's bounds or -1
15887     *         if baseline alignment is not supported
15888     */
15889    @ViewDebug.ExportedProperty(category = "layout")
15890    public int getBaseline() {
15891        return -1;
15892    }
15893
15894    /**
15895     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15896     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15897     * a layout pass.
15898     *
15899     * @return whether the view hierarchy is currently undergoing a layout pass
15900     */
15901    public boolean isInLayout() {
15902        ViewRootImpl viewRoot = getViewRootImpl();
15903        return (viewRoot != null && viewRoot.isInLayout());
15904    }
15905
15906    /**
15907     * Call this when something has changed which has invalidated the
15908     * layout of this view. This will schedule a layout pass of the view
15909     * tree. This should not be called while the view hierarchy is currently in a layout
15910     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15911     * end of the current layout pass (and then layout will run again) or after the current
15912     * frame is drawn and the next layout occurs.
15913     *
15914     * <p>Subclasses which override this method should call the superclass method to
15915     * handle possible request-during-layout errors correctly.</p>
15916     */
15917    public void requestLayout() {
15918        if (mMeasureCache != null) mMeasureCache.clear();
15919
15920        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15921            // Only trigger request-during-layout logic if this is the view requesting it,
15922            // not the views in its parent hierarchy
15923            ViewRootImpl viewRoot = getViewRootImpl();
15924            if (viewRoot != null && viewRoot.isInLayout()) {
15925                if (!viewRoot.requestLayoutDuringLayout(this)) {
15926                    return;
15927                }
15928            }
15929            mAttachInfo.mViewRequestingLayout = this;
15930        }
15931
15932        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15933        mPrivateFlags |= PFLAG_INVALIDATED;
15934
15935        if (mParent != null && !mParent.isLayoutRequested()) {
15936            mParent.requestLayout();
15937        }
15938        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15939            mAttachInfo.mViewRequestingLayout = null;
15940        }
15941    }
15942
15943    /**
15944     * Forces this view to be laid out during the next layout pass.
15945     * This method does not call requestLayout() or forceLayout()
15946     * on the parent.
15947     */
15948    public void forceLayout() {
15949        if (mMeasureCache != null) mMeasureCache.clear();
15950
15951        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15952        mPrivateFlags |= PFLAG_INVALIDATED;
15953    }
15954
15955    /**
15956     * <p>
15957     * This is called to find out how big a view should be. The parent
15958     * supplies constraint information in the width and height parameters.
15959     * </p>
15960     *
15961     * <p>
15962     * The actual measurement work of a view is performed in
15963     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15964     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15965     * </p>
15966     *
15967     *
15968     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15969     *        parent
15970     * @param heightMeasureSpec Vertical space requirements as imposed by the
15971     *        parent
15972     *
15973     * @see #onMeasure(int, int)
15974     */
15975    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15976        boolean optical = isLayoutModeOptical(this);
15977        if (optical != isLayoutModeOptical(mParent)) {
15978            Insets insets = getOpticalInsets();
15979            int oWidth  = insets.left + insets.right;
15980            int oHeight = insets.top  + insets.bottom;
15981            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15982            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15983        }
15984
15985        // Suppress sign extension for the low bytes
15986        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
15987        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
15988
15989        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15990                widthMeasureSpec != mOldWidthMeasureSpec ||
15991                heightMeasureSpec != mOldHeightMeasureSpec) {
15992
15993            // first clears the measured dimension flag
15994            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15995
15996            resolveRtlPropertiesIfNeeded();
15997
15998            int cacheIndex = mMeasureCache.indexOfKey(key);
15999            if (cacheIndex < 0) {
16000                // measure ourselves, this should set the measured dimension flag back
16001                onMeasure(widthMeasureSpec, heightMeasureSpec);
16002                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16003            } else {
16004                long value = mMeasureCache.valueAt(cacheIndex);
16005                // Casting a long to int drops the high 32 bits, no mask needed
16006                setMeasuredDimension((int) (value >> 32), (int) value);
16007                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16008            }
16009
16010            // flag not set, setMeasuredDimension() was not invoked, we raise
16011            // an exception to warn the developer
16012            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16013                throw new IllegalStateException("onMeasure() did not set the"
16014                        + " measured dimension by calling"
16015                        + " setMeasuredDimension()");
16016            }
16017
16018            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16019        }
16020
16021        mOldWidthMeasureSpec = widthMeasureSpec;
16022        mOldHeightMeasureSpec = heightMeasureSpec;
16023
16024        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16025                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16026    }
16027
16028    /**
16029     * <p>
16030     * Measure the view and its content to determine the measured width and the
16031     * measured height. This method is invoked by {@link #measure(int, int)} and
16032     * should be overriden by subclasses to provide accurate and efficient
16033     * measurement of their contents.
16034     * </p>
16035     *
16036     * <p>
16037     * <strong>CONTRACT:</strong> When overriding this method, you
16038     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16039     * measured width and height of this view. Failure to do so will trigger an
16040     * <code>IllegalStateException</code>, thrown by
16041     * {@link #measure(int, int)}. Calling the superclass'
16042     * {@link #onMeasure(int, int)} is a valid use.
16043     * </p>
16044     *
16045     * <p>
16046     * The base class implementation of measure defaults to the background size,
16047     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16048     * override {@link #onMeasure(int, int)} to provide better measurements of
16049     * their content.
16050     * </p>
16051     *
16052     * <p>
16053     * If this method is overridden, it is the subclass's responsibility to make
16054     * sure the measured height and width are at least the view's minimum height
16055     * and width ({@link #getSuggestedMinimumHeight()} and
16056     * {@link #getSuggestedMinimumWidth()}).
16057     * </p>
16058     *
16059     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16060     *                         The requirements are encoded with
16061     *                         {@link android.view.View.MeasureSpec}.
16062     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16063     *                         The requirements are encoded with
16064     *                         {@link android.view.View.MeasureSpec}.
16065     *
16066     * @see #getMeasuredWidth()
16067     * @see #getMeasuredHeight()
16068     * @see #setMeasuredDimension(int, int)
16069     * @see #getSuggestedMinimumHeight()
16070     * @see #getSuggestedMinimumWidth()
16071     * @see android.view.View.MeasureSpec#getMode(int)
16072     * @see android.view.View.MeasureSpec#getSize(int)
16073     */
16074    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16075        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16076                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16077    }
16078
16079    /**
16080     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16081     * measured width and measured height. Failing to do so will trigger an
16082     * exception at measurement time.</p>
16083     *
16084     * @param measuredWidth The measured width of this view.  May be a complex
16085     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16086     * {@link #MEASURED_STATE_TOO_SMALL}.
16087     * @param measuredHeight The measured height of this view.  May be a complex
16088     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16089     * {@link #MEASURED_STATE_TOO_SMALL}.
16090     */
16091    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16092        boolean optical = isLayoutModeOptical(this);
16093        if (optical != isLayoutModeOptical(mParent)) {
16094            Insets insets = getOpticalInsets();
16095            int opticalWidth  = insets.left + insets.right;
16096            int opticalHeight = insets.top  + insets.bottom;
16097
16098            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16099            measuredHeight += optical ? opticalHeight : -opticalHeight;
16100        }
16101        mMeasuredWidth = measuredWidth;
16102        mMeasuredHeight = measuredHeight;
16103
16104        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16105    }
16106
16107    /**
16108     * Merge two states as returned by {@link #getMeasuredState()}.
16109     * @param curState The current state as returned from a view or the result
16110     * of combining multiple views.
16111     * @param newState The new view state to combine.
16112     * @return Returns a new integer reflecting the combination of the two
16113     * states.
16114     */
16115    public static int combineMeasuredStates(int curState, int newState) {
16116        return curState | newState;
16117    }
16118
16119    /**
16120     * Version of {@link #resolveSizeAndState(int, int, int)}
16121     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16122     */
16123    public static int resolveSize(int size, int measureSpec) {
16124        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16125    }
16126
16127    /**
16128     * Utility to reconcile a desired size and state, with constraints imposed
16129     * by a MeasureSpec.  Will take the desired size, unless a different size
16130     * is imposed by the constraints.  The returned value is a compound integer,
16131     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16132     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16133     * size is smaller than the size the view wants to be.
16134     *
16135     * @param size How big the view wants to be
16136     * @param measureSpec Constraints imposed by the parent
16137     * @return Size information bit mask as defined by
16138     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16139     */
16140    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16141        int result = size;
16142        int specMode = MeasureSpec.getMode(measureSpec);
16143        int specSize =  MeasureSpec.getSize(measureSpec);
16144        switch (specMode) {
16145        case MeasureSpec.UNSPECIFIED:
16146            result = size;
16147            break;
16148        case MeasureSpec.AT_MOST:
16149            if (specSize < size) {
16150                result = specSize | MEASURED_STATE_TOO_SMALL;
16151            } else {
16152                result = size;
16153            }
16154            break;
16155        case MeasureSpec.EXACTLY:
16156            result = specSize;
16157            break;
16158        }
16159        return result | (childMeasuredState&MEASURED_STATE_MASK);
16160    }
16161
16162    /**
16163     * Utility to return a default size. Uses the supplied size if the
16164     * MeasureSpec imposed no constraints. Will get larger if allowed
16165     * by the MeasureSpec.
16166     *
16167     * @param size Default size for this view
16168     * @param measureSpec Constraints imposed by the parent
16169     * @return The size this view should be.
16170     */
16171    public static int getDefaultSize(int size, int measureSpec) {
16172        int result = size;
16173        int specMode = MeasureSpec.getMode(measureSpec);
16174        int specSize = MeasureSpec.getSize(measureSpec);
16175
16176        switch (specMode) {
16177        case MeasureSpec.UNSPECIFIED:
16178            result = size;
16179            break;
16180        case MeasureSpec.AT_MOST:
16181        case MeasureSpec.EXACTLY:
16182            result = specSize;
16183            break;
16184        }
16185        return result;
16186    }
16187
16188    /**
16189     * Returns the suggested minimum height that the view should use. This
16190     * returns the maximum of the view's minimum height
16191     * and the background's minimum height
16192     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16193     * <p>
16194     * When being used in {@link #onMeasure(int, int)}, the caller should still
16195     * ensure the returned height is within the requirements of the parent.
16196     *
16197     * @return The suggested minimum height of the view.
16198     */
16199    protected int getSuggestedMinimumHeight() {
16200        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16201
16202    }
16203
16204    /**
16205     * Returns the suggested minimum width that the view should use. This
16206     * returns the maximum of the view's minimum width)
16207     * and the background's minimum width
16208     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16209     * <p>
16210     * When being used in {@link #onMeasure(int, int)}, the caller should still
16211     * ensure the returned width is within the requirements of the parent.
16212     *
16213     * @return The suggested minimum width of the view.
16214     */
16215    protected int getSuggestedMinimumWidth() {
16216        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16217    }
16218
16219    /**
16220     * Returns the minimum height of the view.
16221     *
16222     * @return the minimum height the view will try to be.
16223     *
16224     * @see #setMinimumHeight(int)
16225     *
16226     * @attr ref android.R.styleable#View_minHeight
16227     */
16228    public int getMinimumHeight() {
16229        return mMinHeight;
16230    }
16231
16232    /**
16233     * Sets the minimum height of the view. It is not guaranteed the view will
16234     * be able to achieve this minimum height (for example, if its parent layout
16235     * constrains it with less available height).
16236     *
16237     * @param minHeight The minimum height the view will try to be.
16238     *
16239     * @see #getMinimumHeight()
16240     *
16241     * @attr ref android.R.styleable#View_minHeight
16242     */
16243    public void setMinimumHeight(int minHeight) {
16244        mMinHeight = minHeight;
16245        requestLayout();
16246    }
16247
16248    /**
16249     * Returns the minimum width of the view.
16250     *
16251     * @return the minimum width the view will try to be.
16252     *
16253     * @see #setMinimumWidth(int)
16254     *
16255     * @attr ref android.R.styleable#View_minWidth
16256     */
16257    public int getMinimumWidth() {
16258        return mMinWidth;
16259    }
16260
16261    /**
16262     * Sets the minimum width of the view. It is not guaranteed the view will
16263     * be able to achieve this minimum width (for example, if its parent layout
16264     * constrains it with less available width).
16265     *
16266     * @param minWidth The minimum width the view will try to be.
16267     *
16268     * @see #getMinimumWidth()
16269     *
16270     * @attr ref android.R.styleable#View_minWidth
16271     */
16272    public void setMinimumWidth(int minWidth) {
16273        mMinWidth = minWidth;
16274        requestLayout();
16275
16276    }
16277
16278    /**
16279     * Get the animation currently associated with this view.
16280     *
16281     * @return The animation that is currently playing or
16282     *         scheduled to play for this view.
16283     */
16284    public Animation getAnimation() {
16285        return mCurrentAnimation;
16286    }
16287
16288    /**
16289     * Start the specified animation now.
16290     *
16291     * @param animation the animation to start now
16292     */
16293    public void startAnimation(Animation animation) {
16294        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16295        setAnimation(animation);
16296        invalidateParentCaches();
16297        invalidate(true);
16298    }
16299
16300    /**
16301     * Cancels any animations for this view.
16302     */
16303    public void clearAnimation() {
16304        if (mCurrentAnimation != null) {
16305            mCurrentAnimation.detach();
16306        }
16307        mCurrentAnimation = null;
16308        invalidateParentIfNeeded();
16309    }
16310
16311    /**
16312     * Sets the next animation to play for this view.
16313     * If you want the animation to play immediately, use
16314     * {@link #startAnimation(android.view.animation.Animation)} instead.
16315     * This method provides allows fine-grained
16316     * control over the start time and invalidation, but you
16317     * must make sure that 1) the animation has a start time set, and
16318     * 2) the view's parent (which controls animations on its children)
16319     * will be invalidated when the animation is supposed to
16320     * start.
16321     *
16322     * @param animation The next animation, or null.
16323     */
16324    public void setAnimation(Animation animation) {
16325        mCurrentAnimation = animation;
16326
16327        if (animation != null) {
16328            // If the screen is off assume the animation start time is now instead of
16329            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16330            // would cause the animation to start when the screen turns back on
16331            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16332                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16333                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16334            }
16335            animation.reset();
16336        }
16337    }
16338
16339    /**
16340     * Invoked by a parent ViewGroup to notify the start of the animation
16341     * currently associated with this view. If you override this method,
16342     * always call super.onAnimationStart();
16343     *
16344     * @see #setAnimation(android.view.animation.Animation)
16345     * @see #getAnimation()
16346     */
16347    protected void onAnimationStart() {
16348        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16349    }
16350
16351    /**
16352     * Invoked by a parent ViewGroup to notify the end of the animation
16353     * currently associated with this view. If you override this method,
16354     * always call super.onAnimationEnd();
16355     *
16356     * @see #setAnimation(android.view.animation.Animation)
16357     * @see #getAnimation()
16358     */
16359    protected void onAnimationEnd() {
16360        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16361    }
16362
16363    /**
16364     * Invoked if there is a Transform that involves alpha. Subclass that can
16365     * draw themselves with the specified alpha should return true, and then
16366     * respect that alpha when their onDraw() is called. If this returns false
16367     * then the view may be redirected to draw into an offscreen buffer to
16368     * fulfill the request, which will look fine, but may be slower than if the
16369     * subclass handles it internally. The default implementation returns false.
16370     *
16371     * @param alpha The alpha (0..255) to apply to the view's drawing
16372     * @return true if the view can draw with the specified alpha.
16373     */
16374    protected boolean onSetAlpha(int alpha) {
16375        return false;
16376    }
16377
16378    /**
16379     * This is used by the RootView to perform an optimization when
16380     * the view hierarchy contains one or several SurfaceView.
16381     * SurfaceView is always considered transparent, but its children are not,
16382     * therefore all View objects remove themselves from the global transparent
16383     * region (passed as a parameter to this function).
16384     *
16385     * @param region The transparent region for this ViewAncestor (window).
16386     *
16387     * @return Returns true if the effective visibility of the view at this
16388     * point is opaque, regardless of the transparent region; returns false
16389     * if it is possible for underlying windows to be seen behind the view.
16390     *
16391     * {@hide}
16392     */
16393    public boolean gatherTransparentRegion(Region region) {
16394        final AttachInfo attachInfo = mAttachInfo;
16395        if (region != null && attachInfo != null) {
16396            final int pflags = mPrivateFlags;
16397            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16398                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16399                // remove it from the transparent region.
16400                final int[] location = attachInfo.mTransparentLocation;
16401                getLocationInWindow(location);
16402                region.op(location[0], location[1], location[0] + mRight - mLeft,
16403                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16404            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16405                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16406                // exists, so we remove the background drawable's non-transparent
16407                // parts from this transparent region.
16408                applyDrawableToTransparentRegion(mBackground, region);
16409            }
16410        }
16411        return true;
16412    }
16413
16414    /**
16415     * Play a sound effect for this view.
16416     *
16417     * <p>The framework will play sound effects for some built in actions, such as
16418     * clicking, but you may wish to play these effects in your widget,
16419     * for instance, for internal navigation.
16420     *
16421     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16422     * {@link #isSoundEffectsEnabled()} is true.
16423     *
16424     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16425     */
16426    public void playSoundEffect(int soundConstant) {
16427        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16428            return;
16429        }
16430        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16431    }
16432
16433    /**
16434     * BZZZTT!!1!
16435     *
16436     * <p>Provide haptic feedback to the user for this view.
16437     *
16438     * <p>The framework will provide haptic feedback for some built in actions,
16439     * such as long presses, but you may wish to provide feedback for your
16440     * own widget.
16441     *
16442     * <p>The feedback will only be performed if
16443     * {@link #isHapticFeedbackEnabled()} is true.
16444     *
16445     * @param feedbackConstant One of the constants defined in
16446     * {@link HapticFeedbackConstants}
16447     */
16448    public boolean performHapticFeedback(int feedbackConstant) {
16449        return performHapticFeedback(feedbackConstant, 0);
16450    }
16451
16452    /**
16453     * BZZZTT!!1!
16454     *
16455     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16456     *
16457     * @param feedbackConstant One of the constants defined in
16458     * {@link HapticFeedbackConstants}
16459     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16460     */
16461    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16462        if (mAttachInfo == null) {
16463            return false;
16464        }
16465        //noinspection SimplifiableIfStatement
16466        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16467                && !isHapticFeedbackEnabled()) {
16468            return false;
16469        }
16470        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16471                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16472    }
16473
16474    /**
16475     * Request that the visibility of the status bar or other screen/window
16476     * decorations be changed.
16477     *
16478     * <p>This method is used to put the over device UI into temporary modes
16479     * where the user's attention is focused more on the application content,
16480     * by dimming or hiding surrounding system affordances.  This is typically
16481     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16482     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16483     * to be placed behind the action bar (and with these flags other system
16484     * affordances) so that smooth transitions between hiding and showing them
16485     * can be done.
16486     *
16487     * <p>Two representative examples of the use of system UI visibility is
16488     * implementing a content browsing application (like a magazine reader)
16489     * and a video playing application.
16490     *
16491     * <p>The first code shows a typical implementation of a View in a content
16492     * browsing application.  In this implementation, the application goes
16493     * into a content-oriented mode by hiding the status bar and action bar,
16494     * and putting the navigation elements into lights out mode.  The user can
16495     * then interact with content while in this mode.  Such an application should
16496     * provide an easy way for the user to toggle out of the mode (such as to
16497     * check information in the status bar or access notifications).  In the
16498     * implementation here, this is done simply by tapping on the content.
16499     *
16500     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16501     *      content}
16502     *
16503     * <p>This second code sample shows a typical implementation of a View
16504     * in a video playing application.  In this situation, while the video is
16505     * playing the application would like to go into a complete full-screen mode,
16506     * to use as much of the display as possible for the video.  When in this state
16507     * the user can not interact with the application; the system intercepts
16508     * touching on the screen to pop the UI out of full screen mode.  See
16509     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16510     *
16511     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16512     *      content}
16513     *
16514     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16515     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16516     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16517     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16518     */
16519    public void setSystemUiVisibility(int visibility) {
16520        if (visibility != mSystemUiVisibility) {
16521            mSystemUiVisibility = visibility;
16522            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16523                mParent.recomputeViewAttributes(this);
16524            }
16525        }
16526    }
16527
16528    /**
16529     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16530     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16531     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16532     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16533     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16534     */
16535    public int getSystemUiVisibility() {
16536        return mSystemUiVisibility;
16537    }
16538
16539    /**
16540     * Returns the current system UI visibility that is currently set for
16541     * the entire window.  This is the combination of the
16542     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16543     * views in the window.
16544     */
16545    public int getWindowSystemUiVisibility() {
16546        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16547    }
16548
16549    /**
16550     * Override to find out when the window's requested system UI visibility
16551     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16552     * This is different from the callbacks received through
16553     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16554     * in that this is only telling you about the local request of the window,
16555     * not the actual values applied by the system.
16556     */
16557    public void onWindowSystemUiVisibilityChanged(int visible) {
16558    }
16559
16560    /**
16561     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16562     * the view hierarchy.
16563     */
16564    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16565        onWindowSystemUiVisibilityChanged(visible);
16566    }
16567
16568    /**
16569     * Set a listener to receive callbacks when the visibility of the system bar changes.
16570     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16571     */
16572    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16573        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16574        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16575            mParent.recomputeViewAttributes(this);
16576        }
16577    }
16578
16579    /**
16580     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16581     * the view hierarchy.
16582     */
16583    public void dispatchSystemUiVisibilityChanged(int visibility) {
16584        ListenerInfo li = mListenerInfo;
16585        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16586            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16587                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16588        }
16589    }
16590
16591    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16592        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16593        if (val != mSystemUiVisibility) {
16594            setSystemUiVisibility(val);
16595            return true;
16596        }
16597        return false;
16598    }
16599
16600    /** @hide */
16601    public void setDisabledSystemUiVisibility(int flags) {
16602        if (mAttachInfo != null) {
16603            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16604                mAttachInfo.mDisabledSystemUiVisibility = flags;
16605                if (mParent != null) {
16606                    mParent.recomputeViewAttributes(this);
16607                }
16608            }
16609        }
16610    }
16611
16612    /**
16613     * Creates an image that the system displays during the drag and drop
16614     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16615     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16616     * appearance as the given View. The default also positions the center of the drag shadow
16617     * directly under the touch point. If no View is provided (the constructor with no parameters
16618     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16619     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16620     * default is an invisible drag shadow.
16621     * <p>
16622     * You are not required to use the View you provide to the constructor as the basis of the
16623     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16624     * anything you want as the drag shadow.
16625     * </p>
16626     * <p>
16627     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16628     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16629     *  size and position of the drag shadow. It uses this data to construct a
16630     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16631     *  so that your application can draw the shadow image in the Canvas.
16632     * </p>
16633     *
16634     * <div class="special reference">
16635     * <h3>Developer Guides</h3>
16636     * <p>For a guide to implementing drag and drop features, read the
16637     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16638     * </div>
16639     */
16640    public static class DragShadowBuilder {
16641        private final WeakReference<View> mView;
16642
16643        /**
16644         * Constructs a shadow image builder based on a View. By default, the resulting drag
16645         * shadow will have the same appearance and dimensions as the View, with the touch point
16646         * over the center of the View.
16647         * @param view A View. Any View in scope can be used.
16648         */
16649        public DragShadowBuilder(View view) {
16650            mView = new WeakReference<View>(view);
16651        }
16652
16653        /**
16654         * Construct a shadow builder object with no associated View.  This
16655         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16656         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16657         * to supply the drag shadow's dimensions and appearance without
16658         * reference to any View object. If they are not overridden, then the result is an
16659         * invisible drag shadow.
16660         */
16661        public DragShadowBuilder() {
16662            mView = new WeakReference<View>(null);
16663        }
16664
16665        /**
16666         * Returns the View object that had been passed to the
16667         * {@link #View.DragShadowBuilder(View)}
16668         * constructor.  If that View parameter was {@code null} or if the
16669         * {@link #View.DragShadowBuilder()}
16670         * constructor was used to instantiate the builder object, this method will return
16671         * null.
16672         *
16673         * @return The View object associate with this builder object.
16674         */
16675        @SuppressWarnings({"JavadocReference"})
16676        final public View getView() {
16677            return mView.get();
16678        }
16679
16680        /**
16681         * Provides the metrics for the shadow image. These include the dimensions of
16682         * the shadow image, and the point within that shadow that should
16683         * be centered under the touch location while dragging.
16684         * <p>
16685         * The default implementation sets the dimensions of the shadow to be the
16686         * same as the dimensions of the View itself and centers the shadow under
16687         * the touch point.
16688         * </p>
16689         *
16690         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16691         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16692         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16693         * image.
16694         *
16695         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16696         * shadow image that should be underneath the touch point during the drag and drop
16697         * operation. Your application must set {@link android.graphics.Point#x} to the
16698         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16699         */
16700        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16701            final View view = mView.get();
16702            if (view != null) {
16703                shadowSize.set(view.getWidth(), view.getHeight());
16704                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16705            } else {
16706                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16707            }
16708        }
16709
16710        /**
16711         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16712         * based on the dimensions it received from the
16713         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16714         *
16715         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16716         */
16717        public void onDrawShadow(Canvas canvas) {
16718            final View view = mView.get();
16719            if (view != null) {
16720                view.draw(canvas);
16721            } else {
16722                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16723            }
16724        }
16725    }
16726
16727    /**
16728     * Starts a drag and drop operation. When your application calls this method, it passes a
16729     * {@link android.view.View.DragShadowBuilder} object to the system. The
16730     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16731     * to get metrics for the drag shadow, and then calls the object's
16732     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16733     * <p>
16734     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16735     *  drag events to all the View objects in your application that are currently visible. It does
16736     *  this either by calling the View object's drag listener (an implementation of
16737     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16738     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16739     *  Both are passed a {@link android.view.DragEvent} object that has a
16740     *  {@link android.view.DragEvent#getAction()} value of
16741     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16742     * </p>
16743     * <p>
16744     * Your application can invoke startDrag() on any attached View object. The View object does not
16745     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16746     * be related to the View the user selected for dragging.
16747     * </p>
16748     * @param data A {@link android.content.ClipData} object pointing to the data to be
16749     * transferred by the drag and drop operation.
16750     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16751     * drag shadow.
16752     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16753     * drop operation. This Object is put into every DragEvent object sent by the system during the
16754     * current drag.
16755     * <p>
16756     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16757     * to the target Views. For example, it can contain flags that differentiate between a
16758     * a copy operation and a move operation.
16759     * </p>
16760     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16761     * so the parameter should be set to 0.
16762     * @return {@code true} if the method completes successfully, or
16763     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16764     * do a drag, and so no drag operation is in progress.
16765     */
16766    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16767            Object myLocalState, int flags) {
16768        if (ViewDebug.DEBUG_DRAG) {
16769            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16770        }
16771        boolean okay = false;
16772
16773        Point shadowSize = new Point();
16774        Point shadowTouchPoint = new Point();
16775        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16776
16777        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16778                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16779            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16780        }
16781
16782        if (ViewDebug.DEBUG_DRAG) {
16783            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16784                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16785        }
16786        Surface surface = new Surface();
16787        try {
16788            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16789                    flags, shadowSize.x, shadowSize.y, surface);
16790            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16791                    + " surface=" + surface);
16792            if (token != null) {
16793                Canvas canvas = surface.lockCanvas(null);
16794                try {
16795                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16796                    shadowBuilder.onDrawShadow(canvas);
16797                } finally {
16798                    surface.unlockCanvasAndPost(canvas);
16799                }
16800
16801                final ViewRootImpl root = getViewRootImpl();
16802
16803                // Cache the local state object for delivery with DragEvents
16804                root.setLocalDragState(myLocalState);
16805
16806                // repurpose 'shadowSize' for the last touch point
16807                root.getLastTouchPoint(shadowSize);
16808
16809                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16810                        shadowSize.x, shadowSize.y,
16811                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16812                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16813
16814                // Off and running!  Release our local surface instance; the drag
16815                // shadow surface is now managed by the system process.
16816                surface.release();
16817            }
16818        } catch (Exception e) {
16819            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16820            surface.destroy();
16821        }
16822
16823        return okay;
16824    }
16825
16826    /**
16827     * Handles drag events sent by the system following a call to
16828     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16829     *<p>
16830     * When the system calls this method, it passes a
16831     * {@link android.view.DragEvent} object. A call to
16832     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16833     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16834     * operation.
16835     * @param event The {@link android.view.DragEvent} sent by the system.
16836     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16837     * in DragEvent, indicating the type of drag event represented by this object.
16838     * @return {@code true} if the method was successful, otherwise {@code false}.
16839     * <p>
16840     *  The method should return {@code true} in response to an action type of
16841     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16842     *  operation.
16843     * </p>
16844     * <p>
16845     *  The method should also return {@code true} in response to an action type of
16846     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16847     *  {@code false} if it didn't.
16848     * </p>
16849     */
16850    public boolean onDragEvent(DragEvent event) {
16851        return false;
16852    }
16853
16854    /**
16855     * Detects if this View is enabled and has a drag event listener.
16856     * If both are true, then it calls the drag event listener with the
16857     * {@link android.view.DragEvent} it received. If the drag event listener returns
16858     * {@code true}, then dispatchDragEvent() returns {@code true}.
16859     * <p>
16860     * For all other cases, the method calls the
16861     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16862     * method and returns its result.
16863     * </p>
16864     * <p>
16865     * This ensures that a drag event is always consumed, even if the View does not have a drag
16866     * event listener. However, if the View has a listener and the listener returns true, then
16867     * onDragEvent() is not called.
16868     * </p>
16869     */
16870    public boolean dispatchDragEvent(DragEvent event) {
16871        ListenerInfo li = mListenerInfo;
16872        //noinspection SimplifiableIfStatement
16873        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16874                && li.mOnDragListener.onDrag(this, event)) {
16875            return true;
16876        }
16877        return onDragEvent(event);
16878    }
16879
16880    boolean canAcceptDrag() {
16881        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16882    }
16883
16884    /**
16885     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16886     * it is ever exposed at all.
16887     * @hide
16888     */
16889    public void onCloseSystemDialogs(String reason) {
16890    }
16891
16892    /**
16893     * Given a Drawable whose bounds have been set to draw into this view,
16894     * update a Region being computed for
16895     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16896     * that any non-transparent parts of the Drawable are removed from the
16897     * given transparent region.
16898     *
16899     * @param dr The Drawable whose transparency is to be applied to the region.
16900     * @param region A Region holding the current transparency information,
16901     * where any parts of the region that are set are considered to be
16902     * transparent.  On return, this region will be modified to have the
16903     * transparency information reduced by the corresponding parts of the
16904     * Drawable that are not transparent.
16905     * {@hide}
16906     */
16907    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16908        if (DBG) {
16909            Log.i("View", "Getting transparent region for: " + this);
16910        }
16911        final Region r = dr.getTransparentRegion();
16912        final Rect db = dr.getBounds();
16913        final AttachInfo attachInfo = mAttachInfo;
16914        if (r != null && attachInfo != null) {
16915            final int w = getRight()-getLeft();
16916            final int h = getBottom()-getTop();
16917            if (db.left > 0) {
16918                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16919                r.op(0, 0, db.left, h, Region.Op.UNION);
16920            }
16921            if (db.right < w) {
16922                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16923                r.op(db.right, 0, w, h, Region.Op.UNION);
16924            }
16925            if (db.top > 0) {
16926                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16927                r.op(0, 0, w, db.top, Region.Op.UNION);
16928            }
16929            if (db.bottom < h) {
16930                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16931                r.op(0, db.bottom, w, h, Region.Op.UNION);
16932            }
16933            final int[] location = attachInfo.mTransparentLocation;
16934            getLocationInWindow(location);
16935            r.translate(location[0], location[1]);
16936            region.op(r, Region.Op.INTERSECT);
16937        } else {
16938            region.op(db, Region.Op.DIFFERENCE);
16939        }
16940    }
16941
16942    private void checkForLongClick(int delayOffset) {
16943        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16944            mHasPerformedLongPress = false;
16945
16946            if (mPendingCheckForLongPress == null) {
16947                mPendingCheckForLongPress = new CheckForLongPress();
16948            }
16949            mPendingCheckForLongPress.rememberWindowAttachCount();
16950            postDelayed(mPendingCheckForLongPress,
16951                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16952        }
16953    }
16954
16955    /**
16956     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16957     * LayoutInflater} class, which provides a full range of options for view inflation.
16958     *
16959     * @param context The Context object for your activity or application.
16960     * @param resource The resource ID to inflate
16961     * @param root A view group that will be the parent.  Used to properly inflate the
16962     * layout_* parameters.
16963     * @see LayoutInflater
16964     */
16965    public static View inflate(Context context, int resource, ViewGroup root) {
16966        LayoutInflater factory = LayoutInflater.from(context);
16967        return factory.inflate(resource, root);
16968    }
16969
16970    /**
16971     * Scroll the view with standard behavior for scrolling beyond the normal
16972     * content boundaries. Views that call this method should override
16973     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16974     * results of an over-scroll operation.
16975     *
16976     * Views can use this method to handle any touch or fling-based scrolling.
16977     *
16978     * @param deltaX Change in X in pixels
16979     * @param deltaY Change in Y in pixels
16980     * @param scrollX Current X scroll value in pixels before applying deltaX
16981     * @param scrollY Current Y scroll value in pixels before applying deltaY
16982     * @param scrollRangeX Maximum content scroll range along the X axis
16983     * @param scrollRangeY Maximum content scroll range along the Y axis
16984     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16985     *          along the X axis.
16986     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16987     *          along the Y axis.
16988     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16989     * @return true if scrolling was clamped to an over-scroll boundary along either
16990     *          axis, false otherwise.
16991     */
16992    @SuppressWarnings({"UnusedParameters"})
16993    protected boolean overScrollBy(int deltaX, int deltaY,
16994            int scrollX, int scrollY,
16995            int scrollRangeX, int scrollRangeY,
16996            int maxOverScrollX, int maxOverScrollY,
16997            boolean isTouchEvent) {
16998        final int overScrollMode = mOverScrollMode;
16999        final boolean canScrollHorizontal =
17000                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17001        final boolean canScrollVertical =
17002                computeVerticalScrollRange() > computeVerticalScrollExtent();
17003        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17004                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17005        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17006                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17007
17008        int newScrollX = scrollX + deltaX;
17009        if (!overScrollHorizontal) {
17010            maxOverScrollX = 0;
17011        }
17012
17013        int newScrollY = scrollY + deltaY;
17014        if (!overScrollVertical) {
17015            maxOverScrollY = 0;
17016        }
17017
17018        // Clamp values if at the limits and record
17019        final int left = -maxOverScrollX;
17020        final int right = maxOverScrollX + scrollRangeX;
17021        final int top = -maxOverScrollY;
17022        final int bottom = maxOverScrollY + scrollRangeY;
17023
17024        boolean clampedX = false;
17025        if (newScrollX > right) {
17026            newScrollX = right;
17027            clampedX = true;
17028        } else if (newScrollX < left) {
17029            newScrollX = left;
17030            clampedX = true;
17031        }
17032
17033        boolean clampedY = false;
17034        if (newScrollY > bottom) {
17035            newScrollY = bottom;
17036            clampedY = true;
17037        } else if (newScrollY < top) {
17038            newScrollY = top;
17039            clampedY = true;
17040        }
17041
17042        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17043
17044        return clampedX || clampedY;
17045    }
17046
17047    /**
17048     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17049     * respond to the results of an over-scroll operation.
17050     *
17051     * @param scrollX New X scroll value in pixels
17052     * @param scrollY New Y scroll value in pixels
17053     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17054     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17055     */
17056    protected void onOverScrolled(int scrollX, int scrollY,
17057            boolean clampedX, boolean clampedY) {
17058        // Intentionally empty.
17059    }
17060
17061    /**
17062     * Returns the over-scroll mode for this view. The result will be
17063     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17064     * (allow over-scrolling only if the view content is larger than the container),
17065     * or {@link #OVER_SCROLL_NEVER}.
17066     *
17067     * @return This view's over-scroll mode.
17068     */
17069    public int getOverScrollMode() {
17070        return mOverScrollMode;
17071    }
17072
17073    /**
17074     * Set the over-scroll mode for this view. Valid over-scroll modes are
17075     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17076     * (allow over-scrolling only if the view content is larger than the container),
17077     * or {@link #OVER_SCROLL_NEVER}.
17078     *
17079     * Setting the over-scroll mode of a view will have an effect only if the
17080     * view is capable of scrolling.
17081     *
17082     * @param overScrollMode The new over-scroll mode for this view.
17083     */
17084    public void setOverScrollMode(int overScrollMode) {
17085        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17086                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17087                overScrollMode != OVER_SCROLL_NEVER) {
17088            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17089        }
17090        mOverScrollMode = overScrollMode;
17091    }
17092
17093    /**
17094     * Gets a scale factor that determines the distance the view should scroll
17095     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17096     * @return The vertical scroll scale factor.
17097     * @hide
17098     */
17099    protected float getVerticalScrollFactor() {
17100        if (mVerticalScrollFactor == 0) {
17101            TypedValue outValue = new TypedValue();
17102            if (!mContext.getTheme().resolveAttribute(
17103                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17104                throw new IllegalStateException(
17105                        "Expected theme to define listPreferredItemHeight.");
17106            }
17107            mVerticalScrollFactor = outValue.getDimension(
17108                    mContext.getResources().getDisplayMetrics());
17109        }
17110        return mVerticalScrollFactor;
17111    }
17112
17113    /**
17114     * Gets a scale factor that determines the distance the view should scroll
17115     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17116     * @return The horizontal scroll scale factor.
17117     * @hide
17118     */
17119    protected float getHorizontalScrollFactor() {
17120        // TODO: Should use something else.
17121        return getVerticalScrollFactor();
17122    }
17123
17124    /**
17125     * Return the value specifying the text direction or policy that was set with
17126     * {@link #setTextDirection(int)}.
17127     *
17128     * @return the defined text direction. It can be one of:
17129     *
17130     * {@link #TEXT_DIRECTION_INHERIT},
17131     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17132     * {@link #TEXT_DIRECTION_ANY_RTL},
17133     * {@link #TEXT_DIRECTION_LTR},
17134     * {@link #TEXT_DIRECTION_RTL},
17135     * {@link #TEXT_DIRECTION_LOCALE}
17136     *
17137     * @attr ref android.R.styleable#View_textDirection
17138     *
17139     * @hide
17140     */
17141    @ViewDebug.ExportedProperty(category = "text", mapping = {
17142            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17143            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17144            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17145            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17146            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17147            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17148    })
17149    public int getRawTextDirection() {
17150        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17151    }
17152
17153    /**
17154     * Set the text direction.
17155     *
17156     * @param textDirection the direction to set. Should be one of:
17157     *
17158     * {@link #TEXT_DIRECTION_INHERIT},
17159     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17160     * {@link #TEXT_DIRECTION_ANY_RTL},
17161     * {@link #TEXT_DIRECTION_LTR},
17162     * {@link #TEXT_DIRECTION_RTL},
17163     * {@link #TEXT_DIRECTION_LOCALE}
17164     *
17165     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17166     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17167     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17168     *
17169     * @attr ref android.R.styleable#View_textDirection
17170     */
17171    public void setTextDirection(int textDirection) {
17172        if (getRawTextDirection() != textDirection) {
17173            // Reset the current text direction and the resolved one
17174            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17175            resetResolvedTextDirection();
17176            // Set the new text direction
17177            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17178            // Do resolution
17179            resolveTextDirection();
17180            // Notify change
17181            onRtlPropertiesChanged(getLayoutDirection());
17182            // Refresh
17183            requestLayout();
17184            invalidate(true);
17185        }
17186    }
17187
17188    /**
17189     * Return the resolved text direction.
17190     *
17191     * @return the resolved text direction. Returns one of:
17192     *
17193     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17194     * {@link #TEXT_DIRECTION_ANY_RTL},
17195     * {@link #TEXT_DIRECTION_LTR},
17196     * {@link #TEXT_DIRECTION_RTL},
17197     * {@link #TEXT_DIRECTION_LOCALE}
17198     *
17199     * @attr ref android.R.styleable#View_textDirection
17200     */
17201    @ViewDebug.ExportedProperty(category = "text", mapping = {
17202            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17203            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17204            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17205            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17206            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17207            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17208    })
17209    public int getTextDirection() {
17210        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17211    }
17212
17213    /**
17214     * Resolve the text direction.
17215     *
17216     * @return true if resolution has been done, false otherwise.
17217     *
17218     * @hide
17219     */
17220    public boolean resolveTextDirection() {
17221        // Reset any previous text direction resolution
17222        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17223
17224        if (hasRtlSupport()) {
17225            // Set resolved text direction flag depending on text direction flag
17226            final int textDirection = getRawTextDirection();
17227            switch(textDirection) {
17228                case TEXT_DIRECTION_INHERIT:
17229                    if (!canResolveTextDirection()) {
17230                        // We cannot do the resolution if there is no parent, so use the default one
17231                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17232                        // Resolution will need to happen again later
17233                        return false;
17234                    }
17235
17236                    // Parent has not yet resolved, so we still return the default
17237                    try {
17238                        if (!mParent.isTextDirectionResolved()) {
17239                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17240                            // Resolution will need to happen again later
17241                            return false;
17242                        }
17243                    } catch (AbstractMethodError e) {
17244                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17245                                " does not fully implement ViewParent", e);
17246                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17247                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17248                        return true;
17249                    }
17250
17251                    // Set current resolved direction to the same value as the parent's one
17252                    int parentResolvedDirection;
17253                    try {
17254                        parentResolvedDirection = mParent.getTextDirection();
17255                    } catch (AbstractMethodError e) {
17256                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17257                                " does not fully implement ViewParent", e);
17258                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17259                    }
17260                    switch (parentResolvedDirection) {
17261                        case TEXT_DIRECTION_FIRST_STRONG:
17262                        case TEXT_DIRECTION_ANY_RTL:
17263                        case TEXT_DIRECTION_LTR:
17264                        case TEXT_DIRECTION_RTL:
17265                        case TEXT_DIRECTION_LOCALE:
17266                            mPrivateFlags2 |=
17267                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17268                            break;
17269                        default:
17270                            // Default resolved direction is "first strong" heuristic
17271                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17272                    }
17273                    break;
17274                case TEXT_DIRECTION_FIRST_STRONG:
17275                case TEXT_DIRECTION_ANY_RTL:
17276                case TEXT_DIRECTION_LTR:
17277                case TEXT_DIRECTION_RTL:
17278                case TEXT_DIRECTION_LOCALE:
17279                    // Resolved direction is the same as text direction
17280                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17281                    break;
17282                default:
17283                    // Default resolved direction is "first strong" heuristic
17284                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17285            }
17286        } else {
17287            // Default resolved direction is "first strong" heuristic
17288            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17289        }
17290
17291        // Set to resolved
17292        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17293        return true;
17294    }
17295
17296    /**
17297     * Check if text direction resolution can be done.
17298     *
17299     * @return true if text direction resolution can be done otherwise return false.
17300     */
17301    public boolean canResolveTextDirection() {
17302        switch (getRawTextDirection()) {
17303            case TEXT_DIRECTION_INHERIT:
17304                if (mParent != null) {
17305                    try {
17306                        return mParent.canResolveTextDirection();
17307                    } catch (AbstractMethodError e) {
17308                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17309                                " does not fully implement ViewParent", e);
17310                    }
17311                }
17312                return false;
17313
17314            default:
17315                return true;
17316        }
17317    }
17318
17319    /**
17320     * Reset resolved text direction. Text direction will be resolved during a call to
17321     * {@link #onMeasure(int, int)}.
17322     *
17323     * @hide
17324     */
17325    public void resetResolvedTextDirection() {
17326        // Reset any previous text direction resolution
17327        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17328        // Set to default value
17329        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17330    }
17331
17332    /**
17333     * @return true if text direction is inherited.
17334     *
17335     * @hide
17336     */
17337    public boolean isTextDirectionInherited() {
17338        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17339    }
17340
17341    /**
17342     * @return true if text direction is resolved.
17343     */
17344    public boolean isTextDirectionResolved() {
17345        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17346    }
17347
17348    /**
17349     * Return the value specifying the text alignment or policy that was set with
17350     * {@link #setTextAlignment(int)}.
17351     *
17352     * @return the defined text alignment. It can be one of:
17353     *
17354     * {@link #TEXT_ALIGNMENT_INHERIT},
17355     * {@link #TEXT_ALIGNMENT_GRAVITY},
17356     * {@link #TEXT_ALIGNMENT_CENTER},
17357     * {@link #TEXT_ALIGNMENT_TEXT_START},
17358     * {@link #TEXT_ALIGNMENT_TEXT_END},
17359     * {@link #TEXT_ALIGNMENT_VIEW_START},
17360     * {@link #TEXT_ALIGNMENT_VIEW_END}
17361     *
17362     * @attr ref android.R.styleable#View_textAlignment
17363     *
17364     * @hide
17365     */
17366    @ViewDebug.ExportedProperty(category = "text", mapping = {
17367            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17368            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17369            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17370            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17371            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17372            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17373            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17374    })
17375    public int getRawTextAlignment() {
17376        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17377    }
17378
17379    /**
17380     * Set the text alignment.
17381     *
17382     * @param textAlignment The text alignment to set. Should be one of
17383     *
17384     * {@link #TEXT_ALIGNMENT_INHERIT},
17385     * {@link #TEXT_ALIGNMENT_GRAVITY},
17386     * {@link #TEXT_ALIGNMENT_CENTER},
17387     * {@link #TEXT_ALIGNMENT_TEXT_START},
17388     * {@link #TEXT_ALIGNMENT_TEXT_END},
17389     * {@link #TEXT_ALIGNMENT_VIEW_START},
17390     * {@link #TEXT_ALIGNMENT_VIEW_END}
17391     *
17392     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17393     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17394     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17395     *
17396     * @attr ref android.R.styleable#View_textAlignment
17397     */
17398    public void setTextAlignment(int textAlignment) {
17399        if (textAlignment != getRawTextAlignment()) {
17400            // Reset the current and resolved text alignment
17401            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17402            resetResolvedTextAlignment();
17403            // Set the new text alignment
17404            mPrivateFlags2 |=
17405                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17406            // Do resolution
17407            resolveTextAlignment();
17408            // Notify change
17409            onRtlPropertiesChanged(getLayoutDirection());
17410            // Refresh
17411            requestLayout();
17412            invalidate(true);
17413        }
17414    }
17415
17416    /**
17417     * Return the resolved text alignment.
17418     *
17419     * @return the resolved text alignment. Returns one of:
17420     *
17421     * {@link #TEXT_ALIGNMENT_GRAVITY},
17422     * {@link #TEXT_ALIGNMENT_CENTER},
17423     * {@link #TEXT_ALIGNMENT_TEXT_START},
17424     * {@link #TEXT_ALIGNMENT_TEXT_END},
17425     * {@link #TEXT_ALIGNMENT_VIEW_START},
17426     * {@link #TEXT_ALIGNMENT_VIEW_END}
17427     *
17428     * @attr ref android.R.styleable#View_textAlignment
17429     */
17430    @ViewDebug.ExportedProperty(category = "text", mapping = {
17431            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17432            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17433            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17434            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17435            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17436            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17437            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17438    })
17439    public int getTextAlignment() {
17440        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17441                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17442    }
17443
17444    /**
17445     * Resolve the text alignment.
17446     *
17447     * @return true if resolution has been done, false otherwise.
17448     *
17449     * @hide
17450     */
17451    public boolean resolveTextAlignment() {
17452        // Reset any previous text alignment resolution
17453        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17454
17455        if (hasRtlSupport()) {
17456            // Set resolved text alignment flag depending on text alignment flag
17457            final int textAlignment = getRawTextAlignment();
17458            switch (textAlignment) {
17459                case TEXT_ALIGNMENT_INHERIT:
17460                    // Check if we can resolve the text alignment
17461                    if (!canResolveTextAlignment()) {
17462                        // We cannot do the resolution if there is no parent so use the default
17463                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17464                        // Resolution will need to happen again later
17465                        return false;
17466                    }
17467
17468                    // Parent has not yet resolved, so we still return the default
17469                    try {
17470                        if (!mParent.isTextAlignmentResolved()) {
17471                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17472                            // Resolution will need to happen again later
17473                            return false;
17474                        }
17475                    } catch (AbstractMethodError e) {
17476                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17477                                " does not fully implement ViewParent", e);
17478                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17479                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17480                        return true;
17481                    }
17482
17483                    int parentResolvedTextAlignment;
17484                    try {
17485                        parentResolvedTextAlignment = mParent.getTextAlignment();
17486                    } catch (AbstractMethodError e) {
17487                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17488                                " does not fully implement ViewParent", e);
17489                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17490                    }
17491                    switch (parentResolvedTextAlignment) {
17492                        case TEXT_ALIGNMENT_GRAVITY:
17493                        case TEXT_ALIGNMENT_TEXT_START:
17494                        case TEXT_ALIGNMENT_TEXT_END:
17495                        case TEXT_ALIGNMENT_CENTER:
17496                        case TEXT_ALIGNMENT_VIEW_START:
17497                        case TEXT_ALIGNMENT_VIEW_END:
17498                            // Resolved text alignment is the same as the parent resolved
17499                            // text alignment
17500                            mPrivateFlags2 |=
17501                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17502                            break;
17503                        default:
17504                            // Use default resolved text alignment
17505                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17506                    }
17507                    break;
17508                case TEXT_ALIGNMENT_GRAVITY:
17509                case TEXT_ALIGNMENT_TEXT_START:
17510                case TEXT_ALIGNMENT_TEXT_END:
17511                case TEXT_ALIGNMENT_CENTER:
17512                case TEXT_ALIGNMENT_VIEW_START:
17513                case TEXT_ALIGNMENT_VIEW_END:
17514                    // Resolved text alignment is the same as text alignment
17515                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17516                    break;
17517                default:
17518                    // Use default resolved text alignment
17519                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17520            }
17521        } else {
17522            // Use default resolved text alignment
17523            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17524        }
17525
17526        // Set the resolved
17527        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17528        return true;
17529    }
17530
17531    /**
17532     * Check if text alignment resolution can be done.
17533     *
17534     * @return true if text alignment resolution can be done otherwise return false.
17535     */
17536    public boolean canResolveTextAlignment() {
17537        switch (getRawTextAlignment()) {
17538            case TEXT_DIRECTION_INHERIT:
17539                if (mParent != null) {
17540                    try {
17541                        return mParent.canResolveTextAlignment();
17542                    } catch (AbstractMethodError e) {
17543                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17544                                " does not fully implement ViewParent", e);
17545                    }
17546                }
17547                return false;
17548
17549            default:
17550                return true;
17551        }
17552    }
17553
17554    /**
17555     * Reset resolved text alignment. Text alignment will be resolved during a call to
17556     * {@link #onMeasure(int, int)}.
17557     *
17558     * @hide
17559     */
17560    public void resetResolvedTextAlignment() {
17561        // Reset any previous text alignment resolution
17562        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17563        // Set to default
17564        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17565    }
17566
17567    /**
17568     * @return true if text alignment is inherited.
17569     *
17570     * @hide
17571     */
17572    public boolean isTextAlignmentInherited() {
17573        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17574    }
17575
17576    /**
17577     * @return true if text alignment is resolved.
17578     */
17579    public boolean isTextAlignmentResolved() {
17580        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17581    }
17582
17583    /**
17584     * Generate a value suitable for use in {@link #setId(int)}.
17585     * This value will not collide with ID values generated at build time by aapt for R.id.
17586     *
17587     * @return a generated ID value
17588     */
17589    public static int generateViewId() {
17590        for (;;) {
17591            final int result = sNextGeneratedId.get();
17592            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17593            int newValue = result + 1;
17594            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17595            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17596                return result;
17597            }
17598        }
17599    }
17600
17601    //
17602    // Properties
17603    //
17604    /**
17605     * A Property wrapper around the <code>alpha</code> functionality handled by the
17606     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17607     */
17608    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17609        @Override
17610        public void setValue(View object, float value) {
17611            object.setAlpha(value);
17612        }
17613
17614        @Override
17615        public Float get(View object) {
17616            return object.getAlpha();
17617        }
17618    };
17619
17620    /**
17621     * A Property wrapper around the <code>translationX</code> functionality handled by the
17622     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17623     */
17624    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17625        @Override
17626        public void setValue(View object, float value) {
17627            object.setTranslationX(value);
17628        }
17629
17630                @Override
17631        public Float get(View object) {
17632            return object.getTranslationX();
17633        }
17634    };
17635
17636    /**
17637     * A Property wrapper around the <code>translationY</code> functionality handled by the
17638     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17639     */
17640    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17641        @Override
17642        public void setValue(View object, float value) {
17643            object.setTranslationY(value);
17644        }
17645
17646        @Override
17647        public Float get(View object) {
17648            return object.getTranslationY();
17649        }
17650    };
17651
17652    /**
17653     * A Property wrapper around the <code>x</code> functionality handled by the
17654     * {@link View#setX(float)} and {@link View#getX()} methods.
17655     */
17656    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17657        @Override
17658        public void setValue(View object, float value) {
17659            object.setX(value);
17660        }
17661
17662        @Override
17663        public Float get(View object) {
17664            return object.getX();
17665        }
17666    };
17667
17668    /**
17669     * A Property wrapper around the <code>y</code> functionality handled by the
17670     * {@link View#setY(float)} and {@link View#getY()} methods.
17671     */
17672    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17673        @Override
17674        public void setValue(View object, float value) {
17675            object.setY(value);
17676        }
17677
17678        @Override
17679        public Float get(View object) {
17680            return object.getY();
17681        }
17682    };
17683
17684    /**
17685     * A Property wrapper around the <code>rotation</code> functionality handled by the
17686     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17687     */
17688    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17689        @Override
17690        public void setValue(View object, float value) {
17691            object.setRotation(value);
17692        }
17693
17694        @Override
17695        public Float get(View object) {
17696            return object.getRotation();
17697        }
17698    };
17699
17700    /**
17701     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17702     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17703     */
17704    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17705        @Override
17706        public void setValue(View object, float value) {
17707            object.setRotationX(value);
17708        }
17709
17710        @Override
17711        public Float get(View object) {
17712            return object.getRotationX();
17713        }
17714    };
17715
17716    /**
17717     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17718     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17719     */
17720    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17721        @Override
17722        public void setValue(View object, float value) {
17723            object.setRotationY(value);
17724        }
17725
17726        @Override
17727        public Float get(View object) {
17728            return object.getRotationY();
17729        }
17730    };
17731
17732    /**
17733     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17734     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17735     */
17736    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17737        @Override
17738        public void setValue(View object, float value) {
17739            object.setScaleX(value);
17740        }
17741
17742        @Override
17743        public Float get(View object) {
17744            return object.getScaleX();
17745        }
17746    };
17747
17748    /**
17749     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17750     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17751     */
17752    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17753        @Override
17754        public void setValue(View object, float value) {
17755            object.setScaleY(value);
17756        }
17757
17758        @Override
17759        public Float get(View object) {
17760            return object.getScaleY();
17761        }
17762    };
17763
17764    /**
17765     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17766     * Each MeasureSpec represents a requirement for either the width or the height.
17767     * A MeasureSpec is comprised of a size and a mode. There are three possible
17768     * modes:
17769     * <dl>
17770     * <dt>UNSPECIFIED</dt>
17771     * <dd>
17772     * The parent has not imposed any constraint on the child. It can be whatever size
17773     * it wants.
17774     * </dd>
17775     *
17776     * <dt>EXACTLY</dt>
17777     * <dd>
17778     * The parent has determined an exact size for the child. The child is going to be
17779     * given those bounds regardless of how big it wants to be.
17780     * </dd>
17781     *
17782     * <dt>AT_MOST</dt>
17783     * <dd>
17784     * The child can be as large as it wants up to the specified size.
17785     * </dd>
17786     * </dl>
17787     *
17788     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17789     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17790     */
17791    public static class MeasureSpec {
17792        private static final int MODE_SHIFT = 30;
17793        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17794
17795        /**
17796         * Measure specification mode: The parent has not imposed any constraint
17797         * on the child. It can be whatever size it wants.
17798         */
17799        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17800
17801        /**
17802         * Measure specification mode: The parent has determined an exact size
17803         * for the child. The child is going to be given those bounds regardless
17804         * of how big it wants to be.
17805         */
17806        public static final int EXACTLY     = 1 << MODE_SHIFT;
17807
17808        /**
17809         * Measure specification mode: The child can be as large as it wants up
17810         * to the specified size.
17811         */
17812        public static final int AT_MOST     = 2 << MODE_SHIFT;
17813
17814        /**
17815         * Creates a measure specification based on the supplied size and mode.
17816         *
17817         * The mode must always be one of the following:
17818         * <ul>
17819         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17820         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17821         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17822         * </ul>
17823         *
17824         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17825         * implementation was such that the order of arguments did not matter
17826         * and overflow in either value could impact the resulting MeasureSpec.
17827         * {@link android.widget.RelativeLayout} was affected by this bug.
17828         * Apps targeting API levels greater than 17 will get the fixed, more strict
17829         * behavior.</p>
17830         *
17831         * @param size the size of the measure specification
17832         * @param mode the mode of the measure specification
17833         * @return the measure specification based on size and mode
17834         */
17835        public static int makeMeasureSpec(int size, int mode) {
17836            if (sUseBrokenMakeMeasureSpec) {
17837                return size + mode;
17838            } else {
17839                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17840            }
17841        }
17842
17843        /**
17844         * Extracts the mode from the supplied measure specification.
17845         *
17846         * @param measureSpec the measure specification to extract the mode from
17847         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17848         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17849         *         {@link android.view.View.MeasureSpec#EXACTLY}
17850         */
17851        public static int getMode(int measureSpec) {
17852            return (measureSpec & MODE_MASK);
17853        }
17854
17855        /**
17856         * Extracts the size from the supplied measure specification.
17857         *
17858         * @param measureSpec the measure specification to extract the size from
17859         * @return the size in pixels defined in the supplied measure specification
17860         */
17861        public static int getSize(int measureSpec) {
17862            return (measureSpec & ~MODE_MASK);
17863        }
17864
17865        static int adjust(int measureSpec, int delta) {
17866            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17867        }
17868
17869        /**
17870         * Returns a String representation of the specified measure
17871         * specification.
17872         *
17873         * @param measureSpec the measure specification to convert to a String
17874         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17875         */
17876        public static String toString(int measureSpec) {
17877            int mode = getMode(measureSpec);
17878            int size = getSize(measureSpec);
17879
17880            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17881
17882            if (mode == UNSPECIFIED)
17883                sb.append("UNSPECIFIED ");
17884            else if (mode == EXACTLY)
17885                sb.append("EXACTLY ");
17886            else if (mode == AT_MOST)
17887                sb.append("AT_MOST ");
17888            else
17889                sb.append(mode).append(" ");
17890
17891            sb.append(size);
17892            return sb.toString();
17893        }
17894    }
17895
17896    class CheckForLongPress implements Runnable {
17897
17898        private int mOriginalWindowAttachCount;
17899
17900        public void run() {
17901            if (isPressed() && (mParent != null)
17902                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17903                if (performLongClick()) {
17904                    mHasPerformedLongPress = true;
17905                }
17906            }
17907        }
17908
17909        public void rememberWindowAttachCount() {
17910            mOriginalWindowAttachCount = mWindowAttachCount;
17911        }
17912    }
17913
17914    private final class CheckForTap implements Runnable {
17915        public void run() {
17916            mPrivateFlags &= ~PFLAG_PREPRESSED;
17917            setPressed(true);
17918            checkForLongClick(ViewConfiguration.getTapTimeout());
17919        }
17920    }
17921
17922    private final class PerformClick implements Runnable {
17923        public void run() {
17924            performClick();
17925        }
17926    }
17927
17928    /** @hide */
17929    public void hackTurnOffWindowResizeAnim(boolean off) {
17930        mAttachInfo.mTurnOffWindowResizeAnim = off;
17931    }
17932
17933    /**
17934     * This method returns a ViewPropertyAnimator object, which can be used to animate
17935     * specific properties on this View.
17936     *
17937     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17938     */
17939    public ViewPropertyAnimator animate() {
17940        if (mAnimator == null) {
17941            mAnimator = new ViewPropertyAnimator(this);
17942        }
17943        return mAnimator;
17944    }
17945
17946    /**
17947     * Set the current Scene that this view is in. The current scene is set only
17948     * on the root view of a scene, not for every view in that hierarchy. This
17949     * information is used by Scene to determine whether there is a previous
17950     * scene which should be exited before the new scene is entered.
17951     *
17952     * @param scene The new scene being set on the view
17953     *
17954     * @hide
17955     */
17956    public void setCurrentScene(Scene scene) {
17957        mCurrentScene = scene;
17958    }
17959
17960    /**
17961     * Gets the current {@link Scene} set on this view. A scene is set on a view
17962     * only if that view is the scene root.
17963     *
17964     * @return The current Scene set on this view. A value of null indicates that
17965     * no Scene is current set.
17966     */
17967    public Scene getCurrentScene() {
17968        return mCurrentScene;
17969    }
17970
17971    /**
17972     * Interface definition for a callback to be invoked when a hardware key event is
17973     * dispatched to this view. The callback will be invoked before the key event is
17974     * given to the view. This is only useful for hardware keyboards; a software input
17975     * method has no obligation to trigger this listener.
17976     */
17977    public interface OnKeyListener {
17978        /**
17979         * Called when a hardware key is dispatched to a view. This allows listeners to
17980         * get a chance to respond before the target view.
17981         * <p>Key presses in software keyboards will generally NOT trigger this method,
17982         * although some may elect to do so in some situations. Do not assume a
17983         * software input method has to be key-based; even if it is, it may use key presses
17984         * in a different way than you expect, so there is no way to reliably catch soft
17985         * input key presses.
17986         *
17987         * @param v The view the key has been dispatched to.
17988         * @param keyCode The code for the physical key that was pressed
17989         * @param event The KeyEvent object containing full information about
17990         *        the event.
17991         * @return True if the listener has consumed the event, false otherwise.
17992         */
17993        boolean onKey(View v, int keyCode, KeyEvent event);
17994    }
17995
17996    /**
17997     * Interface definition for a callback to be invoked when a touch event is
17998     * dispatched to this view. The callback will be invoked before the touch
17999     * event is given to the view.
18000     */
18001    public interface OnTouchListener {
18002        /**
18003         * Called when a touch event is dispatched to a view. This allows listeners to
18004         * get a chance to respond before the target view.
18005         *
18006         * @param v The view the touch event has been dispatched to.
18007         * @param event The MotionEvent object containing full information about
18008         *        the event.
18009         * @return True if the listener has consumed the event, false otherwise.
18010         */
18011        boolean onTouch(View v, MotionEvent event);
18012    }
18013
18014    /**
18015     * Interface definition for a callback to be invoked when a hover event is
18016     * dispatched to this view. The callback will be invoked before the hover
18017     * event is given to the view.
18018     */
18019    public interface OnHoverListener {
18020        /**
18021         * Called when a hover event is dispatched to a view. This allows listeners to
18022         * get a chance to respond before the target view.
18023         *
18024         * @param v The view the hover event has been dispatched to.
18025         * @param event The MotionEvent object containing full information about
18026         *        the event.
18027         * @return True if the listener has consumed the event, false otherwise.
18028         */
18029        boolean onHover(View v, MotionEvent event);
18030    }
18031
18032    /**
18033     * Interface definition for a callback to be invoked when a generic motion event is
18034     * dispatched to this view. The callback will be invoked before the generic motion
18035     * event is given to the view.
18036     */
18037    public interface OnGenericMotionListener {
18038        /**
18039         * Called when a generic motion event is dispatched to a view. This allows listeners to
18040         * get a chance to respond before the target view.
18041         *
18042         * @param v The view the generic motion event has been dispatched to.
18043         * @param event The MotionEvent object containing full information about
18044         *        the event.
18045         * @return True if the listener has consumed the event, false otherwise.
18046         */
18047        boolean onGenericMotion(View v, MotionEvent event);
18048    }
18049
18050    /**
18051     * Interface definition for a callback to be invoked when a view has been clicked and held.
18052     */
18053    public interface OnLongClickListener {
18054        /**
18055         * Called when a view has been clicked and held.
18056         *
18057         * @param v The view that was clicked and held.
18058         *
18059         * @return true if the callback consumed the long click, false otherwise.
18060         */
18061        boolean onLongClick(View v);
18062    }
18063
18064    /**
18065     * Interface definition for a callback to be invoked when a drag is being dispatched
18066     * to this view.  The callback will be invoked before the hosting view's own
18067     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18068     * onDrag(event) behavior, it should return 'false' from this callback.
18069     *
18070     * <div class="special reference">
18071     * <h3>Developer Guides</h3>
18072     * <p>For a guide to implementing drag and drop features, read the
18073     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18074     * </div>
18075     */
18076    public interface OnDragListener {
18077        /**
18078         * Called when a drag event is dispatched to a view. This allows listeners
18079         * to get a chance to override base View behavior.
18080         *
18081         * @param v The View that received the drag event.
18082         * @param event The {@link android.view.DragEvent} object for the drag event.
18083         * @return {@code true} if the drag event was handled successfully, or {@code false}
18084         * if the drag event was not handled. Note that {@code false} will trigger the View
18085         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18086         */
18087        boolean onDrag(View v, DragEvent event);
18088    }
18089
18090    /**
18091     * Interface definition for a callback to be invoked when the focus state of
18092     * a view changed.
18093     */
18094    public interface OnFocusChangeListener {
18095        /**
18096         * Called when the focus state of a view has changed.
18097         *
18098         * @param v The view whose state has changed.
18099         * @param hasFocus The new focus state of v.
18100         */
18101        void onFocusChange(View v, boolean hasFocus);
18102    }
18103
18104    /**
18105     * Interface definition for a callback to be invoked when a view is clicked.
18106     */
18107    public interface OnClickListener {
18108        /**
18109         * Called when a view has been clicked.
18110         *
18111         * @param v The view that was clicked.
18112         */
18113        void onClick(View v);
18114    }
18115
18116    /**
18117     * Interface definition for a callback to be invoked when the context menu
18118     * for this view is being built.
18119     */
18120    public interface OnCreateContextMenuListener {
18121        /**
18122         * Called when the context menu for this view is being built. It is not
18123         * safe to hold onto the menu after this method returns.
18124         *
18125         * @param menu The context menu that is being built
18126         * @param v The view for which the context menu is being built
18127         * @param menuInfo Extra information about the item for which the
18128         *            context menu should be shown. This information will vary
18129         *            depending on the class of v.
18130         */
18131        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18132    }
18133
18134    /**
18135     * Interface definition for a callback to be invoked when the status bar changes
18136     * visibility.  This reports <strong>global</strong> changes to the system UI
18137     * state, not what the application is requesting.
18138     *
18139     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18140     */
18141    public interface OnSystemUiVisibilityChangeListener {
18142        /**
18143         * Called when the status bar changes visibility because of a call to
18144         * {@link View#setSystemUiVisibility(int)}.
18145         *
18146         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18147         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18148         * This tells you the <strong>global</strong> state of these UI visibility
18149         * flags, not what your app is currently applying.
18150         */
18151        public void onSystemUiVisibilityChange(int visibility);
18152    }
18153
18154    /**
18155     * Interface definition for a callback to be invoked when this view is attached
18156     * or detached from its window.
18157     */
18158    public interface OnAttachStateChangeListener {
18159        /**
18160         * Called when the view is attached to a window.
18161         * @param v The view that was attached
18162         */
18163        public void onViewAttachedToWindow(View v);
18164        /**
18165         * Called when the view is detached from a window.
18166         * @param v The view that was detached
18167         */
18168        public void onViewDetachedFromWindow(View v);
18169    }
18170
18171    private final class UnsetPressedState implements Runnable {
18172        public void run() {
18173            setPressed(false);
18174        }
18175    }
18176
18177    /**
18178     * Base class for derived classes that want to save and restore their own
18179     * state in {@link android.view.View#onSaveInstanceState()}.
18180     */
18181    public static class BaseSavedState extends AbsSavedState {
18182        /**
18183         * Constructor used when reading from a parcel. Reads the state of the superclass.
18184         *
18185         * @param source
18186         */
18187        public BaseSavedState(Parcel source) {
18188            super(source);
18189        }
18190
18191        /**
18192         * Constructor called by derived classes when creating their SavedState objects
18193         *
18194         * @param superState The state of the superclass of this view
18195         */
18196        public BaseSavedState(Parcelable superState) {
18197            super(superState);
18198        }
18199
18200        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18201                new Parcelable.Creator<BaseSavedState>() {
18202            public BaseSavedState createFromParcel(Parcel in) {
18203                return new BaseSavedState(in);
18204            }
18205
18206            public BaseSavedState[] newArray(int size) {
18207                return new BaseSavedState[size];
18208            }
18209        };
18210    }
18211
18212    /**
18213     * A set of information given to a view when it is attached to its parent
18214     * window.
18215     */
18216    static class AttachInfo {
18217        interface Callbacks {
18218            void playSoundEffect(int effectId);
18219            boolean performHapticFeedback(int effectId, boolean always);
18220        }
18221
18222        /**
18223         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18224         * to a Handler. This class contains the target (View) to invalidate and
18225         * the coordinates of the dirty rectangle.
18226         *
18227         * For performance purposes, this class also implements a pool of up to
18228         * POOL_LIMIT objects that get reused. This reduces memory allocations
18229         * whenever possible.
18230         */
18231        static class InvalidateInfo {
18232            private static final int POOL_LIMIT = 10;
18233
18234            private static final SynchronizedPool<InvalidateInfo> sPool =
18235                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18236
18237            View target;
18238
18239            int left;
18240            int top;
18241            int right;
18242            int bottom;
18243
18244            public static InvalidateInfo obtain() {
18245                InvalidateInfo instance = sPool.acquire();
18246                return (instance != null) ? instance : new InvalidateInfo();
18247            }
18248
18249            public void recycle() {
18250                target = null;
18251                sPool.release(this);
18252            }
18253        }
18254
18255        final IWindowSession mSession;
18256
18257        final IWindow mWindow;
18258
18259        final IBinder mWindowToken;
18260
18261        final Display mDisplay;
18262
18263        final Callbacks mRootCallbacks;
18264
18265        HardwareCanvas mHardwareCanvas;
18266
18267        IWindowId mIWindowId;
18268        WindowId mWindowId;
18269
18270        /**
18271         * The top view of the hierarchy.
18272         */
18273        View mRootView;
18274
18275        IBinder mPanelParentWindowToken;
18276        Surface mSurface;
18277
18278        boolean mHardwareAccelerated;
18279        boolean mHardwareAccelerationRequested;
18280        HardwareRenderer mHardwareRenderer;
18281
18282        boolean mScreenOn;
18283
18284        /**
18285         * Scale factor used by the compatibility mode
18286         */
18287        float mApplicationScale;
18288
18289        /**
18290         * Indicates whether the application is in compatibility mode
18291         */
18292        boolean mScalingRequired;
18293
18294        /**
18295         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18296         */
18297        boolean mTurnOffWindowResizeAnim;
18298
18299        /**
18300         * Left position of this view's window
18301         */
18302        int mWindowLeft;
18303
18304        /**
18305         * Top position of this view's window
18306         */
18307        int mWindowTop;
18308
18309        /**
18310         * Indicates whether views need to use 32-bit drawing caches
18311         */
18312        boolean mUse32BitDrawingCache;
18313
18314        /**
18315         * For windows that are full-screen but using insets to layout inside
18316         * of the screen areas, these are the current insets to appear inside
18317         * the overscan area of the display.
18318         */
18319        final Rect mOverscanInsets = new Rect();
18320
18321        /**
18322         * For windows that are full-screen but using insets to layout inside
18323         * of the screen decorations, these are the current insets for the
18324         * content of the window.
18325         */
18326        final Rect mContentInsets = new Rect();
18327
18328        /**
18329         * For windows that are full-screen but using insets to layout inside
18330         * of the screen decorations, these are the current insets for the
18331         * actual visible parts of the window.
18332         */
18333        final Rect mVisibleInsets = new Rect();
18334
18335        /**
18336         * The internal insets given by this window.  This value is
18337         * supplied by the client (through
18338         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18339         * be given to the window manager when changed to be used in laying
18340         * out windows behind it.
18341         */
18342        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18343                = new ViewTreeObserver.InternalInsetsInfo();
18344
18345        /**
18346         * All views in the window's hierarchy that serve as scroll containers,
18347         * used to determine if the window can be resized or must be panned
18348         * to adjust for a soft input area.
18349         */
18350        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18351
18352        final KeyEvent.DispatcherState mKeyDispatchState
18353                = new KeyEvent.DispatcherState();
18354
18355        /**
18356         * Indicates whether the view's window currently has the focus.
18357         */
18358        boolean mHasWindowFocus;
18359
18360        /**
18361         * The current visibility of the window.
18362         */
18363        int mWindowVisibility;
18364
18365        /**
18366         * Indicates the time at which drawing started to occur.
18367         */
18368        long mDrawingTime;
18369
18370        /**
18371         * Indicates whether or not ignoring the DIRTY_MASK flags.
18372         */
18373        boolean mIgnoreDirtyState;
18374
18375        /**
18376         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18377         * to avoid clearing that flag prematurely.
18378         */
18379        boolean mSetIgnoreDirtyState = false;
18380
18381        /**
18382         * Indicates whether the view's window is currently in touch mode.
18383         */
18384        boolean mInTouchMode;
18385
18386        /**
18387         * Indicates that ViewAncestor should trigger a global layout change
18388         * the next time it performs a traversal
18389         */
18390        boolean mRecomputeGlobalAttributes;
18391
18392        /**
18393         * Always report new attributes at next traversal.
18394         */
18395        boolean mForceReportNewAttributes;
18396
18397        /**
18398         * Set during a traveral if any views want to keep the screen on.
18399         */
18400        boolean mKeepScreenOn;
18401
18402        /**
18403         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18404         */
18405        int mSystemUiVisibility;
18406
18407        /**
18408         * Hack to force certain system UI visibility flags to be cleared.
18409         */
18410        int mDisabledSystemUiVisibility;
18411
18412        /**
18413         * Last global system UI visibility reported by the window manager.
18414         */
18415        int mGlobalSystemUiVisibility;
18416
18417        /**
18418         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18419         * attached.
18420         */
18421        boolean mHasSystemUiListeners;
18422
18423        /**
18424         * Set if the window has requested to extend into the overscan region
18425         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18426         */
18427        boolean mOverscanRequested;
18428
18429        /**
18430         * Set if the visibility of any views has changed.
18431         */
18432        boolean mViewVisibilityChanged;
18433
18434        /**
18435         * Set to true if a view has been scrolled.
18436         */
18437        boolean mViewScrollChanged;
18438
18439        /**
18440         * Global to the view hierarchy used as a temporary for dealing with
18441         * x/y points in the transparent region computations.
18442         */
18443        final int[] mTransparentLocation = new int[2];
18444
18445        /**
18446         * Global to the view hierarchy used as a temporary for dealing with
18447         * x/y points in the ViewGroup.invalidateChild implementation.
18448         */
18449        final int[] mInvalidateChildLocation = new int[2];
18450
18451
18452        /**
18453         * Global to the view hierarchy used as a temporary for dealing with
18454         * x/y location when view is transformed.
18455         */
18456        final float[] mTmpTransformLocation = new float[2];
18457
18458        /**
18459         * The view tree observer used to dispatch global events like
18460         * layout, pre-draw, touch mode change, etc.
18461         */
18462        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18463
18464        /**
18465         * A Canvas used by the view hierarchy to perform bitmap caching.
18466         */
18467        Canvas mCanvas;
18468
18469        /**
18470         * The view root impl.
18471         */
18472        final ViewRootImpl mViewRootImpl;
18473
18474        /**
18475         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18476         * handler can be used to pump events in the UI events queue.
18477         */
18478        final Handler mHandler;
18479
18480        /**
18481         * Temporary for use in computing invalidate rectangles while
18482         * calling up the hierarchy.
18483         */
18484        final Rect mTmpInvalRect = new Rect();
18485
18486        /**
18487         * Temporary for use in computing hit areas with transformed views
18488         */
18489        final RectF mTmpTransformRect = new RectF();
18490
18491        /**
18492         * Temporary for use in transforming invalidation rect
18493         */
18494        final Matrix mTmpMatrix = new Matrix();
18495
18496        /**
18497         * Temporary for use in transforming invalidation rect
18498         */
18499        final Transformation mTmpTransformation = new Transformation();
18500
18501        /**
18502         * Temporary list for use in collecting focusable descendents of a view.
18503         */
18504        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18505
18506        /**
18507         * The id of the window for accessibility purposes.
18508         */
18509        int mAccessibilityWindowId = View.NO_ID;
18510
18511        /**
18512         * Flags related to accessibility processing.
18513         *
18514         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18515         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18516         */
18517        int mAccessibilityFetchFlags;
18518
18519        /**
18520         * The drawable for highlighting accessibility focus.
18521         */
18522        Drawable mAccessibilityFocusDrawable;
18523
18524        /**
18525         * Show where the margins, bounds and layout bounds are for each view.
18526         */
18527        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18528
18529        /**
18530         * Point used to compute visible regions.
18531         */
18532        final Point mPoint = new Point();
18533
18534        /**
18535         * Used to track which View originated a requestLayout() call, used when
18536         * requestLayout() is called during layout.
18537         */
18538        View mViewRequestingLayout;
18539
18540        /**
18541         * Creates a new set of attachment information with the specified
18542         * events handler and thread.
18543         *
18544         * @param handler the events handler the view must use
18545         */
18546        AttachInfo(IWindowSession session, IWindow window, Display display,
18547                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18548            mSession = session;
18549            mWindow = window;
18550            mWindowToken = window.asBinder();
18551            mDisplay = display;
18552            mViewRootImpl = viewRootImpl;
18553            mHandler = handler;
18554            mRootCallbacks = effectPlayer;
18555        }
18556    }
18557
18558    /**
18559     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18560     * is supported. This avoids keeping too many unused fields in most
18561     * instances of View.</p>
18562     */
18563    private static class ScrollabilityCache implements Runnable {
18564
18565        /**
18566         * Scrollbars are not visible
18567         */
18568        public static final int OFF = 0;
18569
18570        /**
18571         * Scrollbars are visible
18572         */
18573        public static final int ON = 1;
18574
18575        /**
18576         * Scrollbars are fading away
18577         */
18578        public static final int FADING = 2;
18579
18580        public boolean fadeScrollBars;
18581
18582        public int fadingEdgeLength;
18583        public int scrollBarDefaultDelayBeforeFade;
18584        public int scrollBarFadeDuration;
18585
18586        public int scrollBarSize;
18587        public ScrollBarDrawable scrollBar;
18588        public float[] interpolatorValues;
18589        public View host;
18590
18591        public final Paint paint;
18592        public final Matrix matrix;
18593        public Shader shader;
18594
18595        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18596
18597        private static final float[] OPAQUE = { 255 };
18598        private static final float[] TRANSPARENT = { 0.0f };
18599
18600        /**
18601         * When fading should start. This time moves into the future every time
18602         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18603         */
18604        public long fadeStartTime;
18605
18606
18607        /**
18608         * The current state of the scrollbars: ON, OFF, or FADING
18609         */
18610        public int state = OFF;
18611
18612        private int mLastColor;
18613
18614        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18615            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18616            scrollBarSize = configuration.getScaledScrollBarSize();
18617            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18618            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18619
18620            paint = new Paint();
18621            matrix = new Matrix();
18622            // use use a height of 1, and then wack the matrix each time we
18623            // actually use it.
18624            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18625            paint.setShader(shader);
18626            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18627
18628            this.host = host;
18629        }
18630
18631        public void setFadeColor(int color) {
18632            if (color != mLastColor) {
18633                mLastColor = color;
18634
18635                if (color != 0) {
18636                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18637                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18638                    paint.setShader(shader);
18639                    // Restore the default transfer mode (src_over)
18640                    paint.setXfermode(null);
18641                } else {
18642                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18643                    paint.setShader(shader);
18644                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18645                }
18646            }
18647        }
18648
18649        public void run() {
18650            long now = AnimationUtils.currentAnimationTimeMillis();
18651            if (now >= fadeStartTime) {
18652
18653                // the animation fades the scrollbars out by changing
18654                // the opacity (alpha) from fully opaque to fully
18655                // transparent
18656                int nextFrame = (int) now;
18657                int framesCount = 0;
18658
18659                Interpolator interpolator = scrollBarInterpolator;
18660
18661                // Start opaque
18662                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18663
18664                // End transparent
18665                nextFrame += scrollBarFadeDuration;
18666                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18667
18668                state = FADING;
18669
18670                // Kick off the fade animation
18671                host.invalidate(true);
18672            }
18673        }
18674    }
18675
18676    /**
18677     * Resuable callback for sending
18678     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18679     */
18680    private class SendViewScrolledAccessibilityEvent implements Runnable {
18681        public volatile boolean mIsPending;
18682
18683        public void run() {
18684            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18685            mIsPending = false;
18686        }
18687    }
18688
18689    /**
18690     * <p>
18691     * This class represents a delegate that can be registered in a {@link View}
18692     * to enhance accessibility support via composition rather via inheritance.
18693     * It is specifically targeted to widget developers that extend basic View
18694     * classes i.e. classes in package android.view, that would like their
18695     * applications to be backwards compatible.
18696     * </p>
18697     * <div class="special reference">
18698     * <h3>Developer Guides</h3>
18699     * <p>For more information about making applications accessible, read the
18700     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18701     * developer guide.</p>
18702     * </div>
18703     * <p>
18704     * A scenario in which a developer would like to use an accessibility delegate
18705     * is overriding a method introduced in a later API version then the minimal API
18706     * version supported by the application. For example, the method
18707     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18708     * in API version 4 when the accessibility APIs were first introduced. If a
18709     * developer would like his application to run on API version 4 devices (assuming
18710     * all other APIs used by the application are version 4 or lower) and take advantage
18711     * of this method, instead of overriding the method which would break the application's
18712     * backwards compatibility, he can override the corresponding method in this
18713     * delegate and register the delegate in the target View if the API version of
18714     * the system is high enough i.e. the API version is same or higher to the API
18715     * version that introduced
18716     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18717     * </p>
18718     * <p>
18719     * Here is an example implementation:
18720     * </p>
18721     * <code><pre><p>
18722     * if (Build.VERSION.SDK_INT >= 14) {
18723     *     // If the API version is equal of higher than the version in
18724     *     // which onInitializeAccessibilityNodeInfo was introduced we
18725     *     // register a delegate with a customized implementation.
18726     *     View view = findViewById(R.id.view_id);
18727     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18728     *         public void onInitializeAccessibilityNodeInfo(View host,
18729     *                 AccessibilityNodeInfo info) {
18730     *             // Let the default implementation populate the info.
18731     *             super.onInitializeAccessibilityNodeInfo(host, info);
18732     *             // Set some other information.
18733     *             info.setEnabled(host.isEnabled());
18734     *         }
18735     *     });
18736     * }
18737     * </code></pre></p>
18738     * <p>
18739     * This delegate contains methods that correspond to the accessibility methods
18740     * in View. If a delegate has been specified the implementation in View hands
18741     * off handling to the corresponding method in this delegate. The default
18742     * implementation the delegate methods behaves exactly as the corresponding
18743     * method in View for the case of no accessibility delegate been set. Hence,
18744     * to customize the behavior of a View method, clients can override only the
18745     * corresponding delegate method without altering the behavior of the rest
18746     * accessibility related methods of the host view.
18747     * </p>
18748     */
18749    public static class AccessibilityDelegate {
18750
18751        /**
18752         * Sends an accessibility event of the given type. If accessibility is not
18753         * enabled this method has no effect.
18754         * <p>
18755         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18756         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18757         * been set.
18758         * </p>
18759         *
18760         * @param host The View hosting the delegate.
18761         * @param eventType The type of the event to send.
18762         *
18763         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18764         */
18765        public void sendAccessibilityEvent(View host, int eventType) {
18766            host.sendAccessibilityEventInternal(eventType);
18767        }
18768
18769        /**
18770         * Performs the specified accessibility action on the view. For
18771         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18772         * <p>
18773         * The default implementation behaves as
18774         * {@link View#performAccessibilityAction(int, Bundle)
18775         *  View#performAccessibilityAction(int, Bundle)} for the case of
18776         *  no accessibility delegate been set.
18777         * </p>
18778         *
18779         * @param action The action to perform.
18780         * @return Whether the action was performed.
18781         *
18782         * @see View#performAccessibilityAction(int, Bundle)
18783         *      View#performAccessibilityAction(int, Bundle)
18784         */
18785        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18786            return host.performAccessibilityActionInternal(action, args);
18787        }
18788
18789        /**
18790         * Sends an accessibility event. This method behaves exactly as
18791         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18792         * empty {@link AccessibilityEvent} and does not perform a check whether
18793         * accessibility is enabled.
18794         * <p>
18795         * The default implementation behaves as
18796         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18797         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18798         * the case of no accessibility delegate been set.
18799         * </p>
18800         *
18801         * @param host The View hosting the delegate.
18802         * @param event The event to send.
18803         *
18804         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18805         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18806         */
18807        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18808            host.sendAccessibilityEventUncheckedInternal(event);
18809        }
18810
18811        /**
18812         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18813         * to its children for adding their text content to the event.
18814         * <p>
18815         * The default implementation behaves as
18816         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18817         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18818         * the case of no accessibility delegate been set.
18819         * </p>
18820         *
18821         * @param host The View hosting the delegate.
18822         * @param event The event.
18823         * @return True if the event population was completed.
18824         *
18825         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18826         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18827         */
18828        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18829            return host.dispatchPopulateAccessibilityEventInternal(event);
18830        }
18831
18832        /**
18833         * Gives a chance to the host View to populate the accessibility event with its
18834         * text content.
18835         * <p>
18836         * The default implementation behaves as
18837         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18838         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18839         * the case of no accessibility delegate been set.
18840         * </p>
18841         *
18842         * @param host The View hosting the delegate.
18843         * @param event The accessibility event which to populate.
18844         *
18845         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18846         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18847         */
18848        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18849            host.onPopulateAccessibilityEventInternal(event);
18850        }
18851
18852        /**
18853         * Initializes an {@link AccessibilityEvent} with information about the
18854         * the host View which is the event source.
18855         * <p>
18856         * The default implementation behaves as
18857         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18858         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18859         * the case of no accessibility delegate been set.
18860         * </p>
18861         *
18862         * @param host The View hosting the delegate.
18863         * @param event The event to initialize.
18864         *
18865         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18866         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18867         */
18868        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18869            host.onInitializeAccessibilityEventInternal(event);
18870        }
18871
18872        /**
18873         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18874         * <p>
18875         * The default implementation behaves as
18876         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18877         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18878         * the case of no accessibility delegate been set.
18879         * </p>
18880         *
18881         * @param host The View hosting the delegate.
18882         * @param info The instance to initialize.
18883         *
18884         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18885         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18886         */
18887        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18888            host.onInitializeAccessibilityNodeInfoInternal(info);
18889        }
18890
18891        /**
18892         * Called when a child of the host View has requested sending an
18893         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18894         * to augment the event.
18895         * <p>
18896         * The default implementation behaves as
18897         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18898         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18899         * the case of no accessibility delegate been set.
18900         * </p>
18901         *
18902         * @param host The View hosting the delegate.
18903         * @param child The child which requests sending the event.
18904         * @param event The event to be sent.
18905         * @return True if the event should be sent
18906         *
18907         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18908         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18909         */
18910        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18911                AccessibilityEvent event) {
18912            return host.onRequestSendAccessibilityEventInternal(child, event);
18913        }
18914
18915        /**
18916         * Gets the provider for managing a virtual view hierarchy rooted at this View
18917         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18918         * that explore the window content.
18919         * <p>
18920         * The default implementation behaves as
18921         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18922         * the case of no accessibility delegate been set.
18923         * </p>
18924         *
18925         * @return The provider.
18926         *
18927         * @see AccessibilityNodeProvider
18928         */
18929        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18930            return null;
18931        }
18932
18933        /**
18934         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
18935         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
18936         * This method is responsible for obtaining an accessibility node info from a
18937         * pool of reusable instances and calling
18938         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
18939         * view to initialize the former.
18940         * <p>
18941         * <strong>Note:</strong> The client is responsible for recycling the obtained
18942         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
18943         * creation.
18944         * </p>
18945         * <p>
18946         * The default implementation behaves as
18947         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
18948         * the case of no accessibility delegate been set.
18949         * </p>
18950         * @return A populated {@link AccessibilityNodeInfo}.
18951         *
18952         * @see AccessibilityNodeInfo
18953         *
18954         * @hide
18955         */
18956        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
18957            return host.createAccessibilityNodeInfoInternal();
18958        }
18959    }
18960
18961    private class MatchIdPredicate implements Predicate<View> {
18962        public int mId;
18963
18964        @Override
18965        public boolean apply(View view) {
18966            return (view.mID == mId);
18967        }
18968    }
18969
18970    private class MatchLabelForPredicate implements Predicate<View> {
18971        private int mLabeledId;
18972
18973        @Override
18974        public boolean apply(View view) {
18975            return (view.mLabelForId == mLabeledId);
18976        }
18977    }
18978
18979    private class SendViewStateChangedAccessibilityEvent implements Runnable {
18980        private boolean mPosted;
18981        private long mLastEventTimeMillis;
18982
18983        public void run() {
18984            mPosted = false;
18985            mLastEventTimeMillis = SystemClock.uptimeMillis();
18986            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
18987                AccessibilityEvent event = AccessibilityEvent.obtain();
18988                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
18989                event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE);
18990                sendAccessibilityEventUnchecked(event);
18991            }
18992        }
18993
18994        public void runOrPost() {
18995            if (mPosted) {
18996                return;
18997            }
18998            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
18999            final long minEventIntevalMillis =
19000                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19001            if (timeSinceLastMillis >= minEventIntevalMillis) {
19002                removeCallbacks(this);
19003                run();
19004            } else {
19005                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19006                mPosted = true;
19007            }
19008        }
19009    }
19010
19011    /**
19012     * Dump all private flags in readable format, useful for documentation and
19013     * sanity checking.
19014     */
19015    private static void dumpFlags() {
19016        final HashMap<String, String> found = Maps.newHashMap();
19017        try {
19018            for (Field field : View.class.getDeclaredFields()) {
19019                final int modifiers = field.getModifiers();
19020                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19021                    if (field.getType().equals(int.class)) {
19022                        final int value = field.getInt(null);
19023                        dumpFlag(found, field.getName(), value);
19024                    } else if (field.getType().equals(int[].class)) {
19025                        final int[] values = (int[]) field.get(null);
19026                        for (int i = 0; i < values.length; i++) {
19027                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19028                        }
19029                    }
19030                }
19031            }
19032        } catch (IllegalAccessException e) {
19033            throw new RuntimeException(e);
19034        }
19035
19036        final ArrayList<String> keys = Lists.newArrayList();
19037        keys.addAll(found.keySet());
19038        Collections.sort(keys);
19039        for (String key : keys) {
19040            Log.d(VIEW_LOG_TAG, found.get(key));
19041        }
19042    }
19043
19044    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19045        // Sort flags by prefix, then by bits, always keeping unique keys
19046        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19047        final int prefix = name.indexOf('_');
19048        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19049        final String output = bits + " " + name;
19050        found.put(key, output);
19051    }
19052}
19053