View.java revision 405436021da156fbe3c5d4de48bdefa564cf7fc0
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.Build;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Parcel;
48import android.os.Parcelable;
49import android.os.RemoteException;
50import android.os.SystemClock;
51import android.os.SystemProperties;
52import android.text.TextUtils;
53import android.util.AttributeSet;
54import android.util.FloatProperty;
55import android.util.Log;
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     * @hide
1127     */
1128    protected static final int[] PRESSED_STATE_SET;
1129    /**
1130     * Indicates the view's window has focus. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1138    // Doubles
1139    /**
1140     * Indicates the view is enabled and has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and selected.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_SELECTED_STATE_SET;
1153    /**
1154     * Indicates the view is enabled and that its window has focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused and selected.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view has the focus and that its window has the focus.
1169     *
1170     * @see #FOCUSED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is selected and that its window has the focus.
1176     *
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    // Triples
1182    /**
1183     * Indicates the view is enabled, focused and selected.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, focused and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #FOCUSED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled, selected and its window has the focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is focused, selected and its window has the focus.
1208     *
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is enabled, focused, selected and its window
1216     * has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and its window has the focus.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #WINDOW_FOCUSED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed and selected.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, selected and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and focused.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #FOCUSED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused and selected.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, focused, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and enabled.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled, selected and its window has the
1303     * focus.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #ENABLED_STATE_SET
1307     * @see #SELECTED_STATE_SET
1308     * @see #WINDOW_FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and focused.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and its window has the
1321     * focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, focused and selected.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled, focused, selected and its window
1340     * has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1349
1350    /**
1351     * The order here is very important to {@link #getDrawableState()}
1352     */
1353    private static final int[][] VIEW_STATE_SETS;
1354
1355    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1356    static final int VIEW_STATE_SELECTED = 1 << 1;
1357    static final int VIEW_STATE_FOCUSED = 1 << 2;
1358    static final int VIEW_STATE_ENABLED = 1 << 3;
1359    static final int VIEW_STATE_PRESSED = 1 << 4;
1360    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1361    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1362    static final int VIEW_STATE_HOVERED = 1 << 7;
1363    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1364    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1365
1366    static final int[] VIEW_STATE_IDS = new int[] {
1367        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1368        R.attr.state_selected,          VIEW_STATE_SELECTED,
1369        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1370        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1371        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1372        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1373        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1374        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1375        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1376        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1377    };
1378
1379    static {
1380        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1381            throw new IllegalStateException(
1382                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1383        }
1384        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1385        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1386            int viewState = R.styleable.ViewDrawableStates[i];
1387            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1388                if (VIEW_STATE_IDS[j] == viewState) {
1389                    orderedIds[i * 2] = viewState;
1390                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1391                }
1392            }
1393        }
1394        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1395        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1396        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1397            int numBits = Integer.bitCount(i);
1398            int[] set = new int[numBits];
1399            int pos = 0;
1400            for (int j = 0; j < orderedIds.length; j += 2) {
1401                if ((i & orderedIds[j+1]) != 0) {
1402                    set[pos++] = orderedIds[j];
1403                }
1404            }
1405            VIEW_STATE_SETS[i] = set;
1406        }
1407
1408        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1409        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1410        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1411        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1413        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1414        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1416        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1418        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_FOCUSED];
1421        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1422        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1426        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1440
1441        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1442        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1446        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1482                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1483                | VIEW_STATE_PRESSED];
1484    }
1485
1486    /**
1487     * Accessibility event types that are dispatched for text population.
1488     */
1489    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1490            AccessibilityEvent.TYPE_VIEW_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1492            | AccessibilityEvent.TYPE_VIEW_SELECTED
1493            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1494            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1496            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1499            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1500            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1501
1502    /**
1503     * Temporary Rect currently for use in setBackground().  This will probably
1504     * be extended in the future to hold our own class with more than just
1505     * a Rect. :)
1506     */
1507    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1508
1509    /**
1510     * Map used to store views' tags.
1511     */
1512    private SparseArray<Object> mKeyedTags;
1513
1514    /**
1515     * The next available accessibility id.
1516     */
1517    private static int sNextAccessibilityViewId;
1518
1519    /**
1520     * The animation currently associated with this view.
1521     * @hide
1522     */
1523    protected Animation mCurrentAnimation = null;
1524
1525    /**
1526     * Width as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredWidth;
1531
1532    /**
1533     * Height as measured during measure pass.
1534     * {@hide}
1535     */
1536    @ViewDebug.ExportedProperty(category = "measurement")
1537    int mMeasuredHeight;
1538
1539    /**
1540     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1541     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1542     * its display list. This flag, used only when hw accelerated, allows us to clear the
1543     * flag while retaining this information until it's needed (at getDisplayList() time and
1544     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1545     *
1546     * {@hide}
1547     */
1548    boolean mRecreateDisplayList = false;
1549
1550    /**
1551     * The view's identifier.
1552     * {@hide}
1553     *
1554     * @see #setId(int)
1555     * @see #getId()
1556     */
1557    @ViewDebug.ExportedProperty(resolveId = true)
1558    int mID = NO_ID;
1559
1560    /**
1561     * The stable ID of this view for accessibility purposes.
1562     */
1563    int mAccessibilityViewId = NO_ID;
1564
1565    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1566
1567    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1568
1569    /**
1570     * The view's tag.
1571     * {@hide}
1572     *
1573     * @see #setTag(Object)
1574     * @see #getTag()
1575     */
1576    protected Object mTag;
1577
1578    private Scene mCurrentScene = null;
1579
1580    // for mPrivateFlags:
1581    /** {@hide} */
1582    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1583    /** {@hide} */
1584    static final int PFLAG_FOCUSED                     = 0x00000002;
1585    /** {@hide} */
1586    static final int PFLAG_SELECTED                    = 0x00000004;
1587    /** {@hide} */
1588    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1589    /** {@hide} */
1590    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1591    /** {@hide} */
1592    static final int PFLAG_DRAWN                       = 0x00000020;
1593    /**
1594     * When this flag is set, this view is running an animation on behalf of its
1595     * children and should therefore not cancel invalidate requests, even if they
1596     * lie outside of this view's bounds.
1597     *
1598     * {@hide}
1599     */
1600    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1601    /** {@hide} */
1602    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1603    /** {@hide} */
1604    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1605    /** {@hide} */
1606    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1607    /** {@hide} */
1608    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1609    /** {@hide} */
1610    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1611    /** {@hide} */
1612    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1613    /** {@hide} */
1614    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1615
1616    private static final int PFLAG_PRESSED             = 0x00004000;
1617
1618    /** {@hide} */
1619    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1620    /**
1621     * Flag used to indicate that this view should be drawn once more (and only once
1622     * more) after its animation has completed.
1623     * {@hide}
1624     */
1625    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1626
1627    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1628
1629    /**
1630     * Indicates that the View returned true when onSetAlpha() was called and that
1631     * the alpha must be restored.
1632     * {@hide}
1633     */
1634    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1635
1636    /**
1637     * Set by {@link #setScrollContainer(boolean)}.
1638     */
1639    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1640
1641    /**
1642     * Set by {@link #setScrollContainer(boolean)}.
1643     */
1644    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1645
1646    /**
1647     * View flag indicating whether this view was invalidated (fully or partially.)
1648     *
1649     * @hide
1650     */
1651    static final int PFLAG_DIRTY                       = 0x00200000;
1652
1653    /**
1654     * View flag indicating whether this view was invalidated by an opaque
1655     * invalidate request.
1656     *
1657     * @hide
1658     */
1659    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1660
1661    /**
1662     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1663     *
1664     * @hide
1665     */
1666    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1667
1668    /**
1669     * Indicates whether the background is opaque.
1670     *
1671     * @hide
1672     */
1673    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1674
1675    /**
1676     * Indicates whether the scrollbars are opaque.
1677     *
1678     * @hide
1679     */
1680    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1681
1682    /**
1683     * Indicates whether the view is opaque.
1684     *
1685     * @hide
1686     */
1687    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1688
1689    /**
1690     * Indicates a prepressed state;
1691     * the short time between ACTION_DOWN and recognizing
1692     * a 'real' press. Prepressed is used to recognize quick taps
1693     * even when they are shorter than ViewConfiguration.getTapTimeout().
1694     *
1695     * @hide
1696     */
1697    private static final int PFLAG_PREPRESSED          = 0x02000000;
1698
1699    /**
1700     * Indicates whether the view is temporarily detached.
1701     *
1702     * @hide
1703     */
1704    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1705
1706    /**
1707     * Indicates that we should awaken scroll bars once attached
1708     *
1709     * @hide
1710     */
1711    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1712
1713    /**
1714     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1715     * @hide
1716     */
1717    private static final int PFLAG_HOVERED             = 0x10000000;
1718
1719    /**
1720     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1721     * for transform operations
1722     *
1723     * @hide
1724     */
1725    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1726
1727    /** {@hide} */
1728    static final int PFLAG_ACTIVATED                   = 0x40000000;
1729
1730    /**
1731     * Indicates that this view was specifically invalidated, not just dirtied because some
1732     * child view was invalidated. The flag is used to determine when we need to recreate
1733     * a view's display list (as opposed to just returning a reference to its existing
1734     * display list).
1735     *
1736     * @hide
1737     */
1738    static final int PFLAG_INVALIDATED                 = 0x80000000;
1739
1740    /**
1741     * Masks for mPrivateFlags2, as generated by dumpFlags():
1742     *
1743     * -------|-------|-------|-------|
1744     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1745     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1746     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1747     *                               1  PFLAG2_DRAG_HOVERED
1748     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1749     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1750     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1751     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1752     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1753     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1754     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1755     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1756     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1757     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1758     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1759     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1760     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1761     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1762     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1763     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1764     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1765     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1766     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1767     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1768     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1769     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1770     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1771     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1772     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1773     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1774     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1775     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1776     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1777     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1778     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1779     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1780     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1781     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1782     *   1                              PFLAG2_PADDING_RESOLVED
1783     * -------|-------|-------|-------|
1784     */
1785
1786    /**
1787     * Indicates that this view has reported that it can accept the current drag's content.
1788     * Cleared when the drag operation concludes.
1789     * @hide
1790     */
1791    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1792
1793    /**
1794     * Indicates that this view is currently directly under the drag location in a
1795     * drag-and-drop operation involving content that it can accept.  Cleared when
1796     * the drag exits the view, or when the drag operation concludes.
1797     * @hide
1798     */
1799    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1800
1801    /**
1802     * Horizontal layout direction of this view is from Left to Right.
1803     * Use with {@link #setLayoutDirection}.
1804     */
1805    public static final int LAYOUT_DIRECTION_LTR = 0;
1806
1807    /**
1808     * Horizontal layout direction of this view is from Right to Left.
1809     * Use with {@link #setLayoutDirection}.
1810     */
1811    public static final int LAYOUT_DIRECTION_RTL = 1;
1812
1813    /**
1814     * Horizontal layout direction of this view is inherited from its parent.
1815     * Use with {@link #setLayoutDirection}.
1816     */
1817    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1818
1819    /**
1820     * Horizontal layout direction of this view is from deduced from the default language
1821     * script for the locale. Use with {@link #setLayoutDirection}.
1822     */
1823    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1824
1825    /**
1826     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1827     * @hide
1828     */
1829    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1830
1831    /**
1832     * Mask for use with private flags indicating bits used for horizontal layout direction.
1833     * @hide
1834     */
1835    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1836
1837    /**
1838     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1839     * right-to-left direction.
1840     * @hide
1841     */
1842    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1843
1844    /**
1845     * Indicates whether the view horizontal layout direction has been resolved.
1846     * @hide
1847     */
1848    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1849
1850    /**
1851     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1852     * @hide
1853     */
1854    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1855            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1856
1857    /*
1858     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1859     * flag value.
1860     * @hide
1861     */
1862    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1863            LAYOUT_DIRECTION_LTR,
1864            LAYOUT_DIRECTION_RTL,
1865            LAYOUT_DIRECTION_INHERIT,
1866            LAYOUT_DIRECTION_LOCALE
1867    };
1868
1869    /**
1870     * Default horizontal layout direction.
1871     */
1872    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1873
1874    /**
1875     * Default horizontal layout direction.
1876     * @hide
1877     */
1878    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1879
1880    /**
1881     * Indicates that the view is tracking some sort of transient state
1882     * that the app should not need to be aware of, but that the framework
1883     * should take special care to preserve.
1884     *
1885     * @hide
1886     */
1887    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1888
1889    /**
1890     * Text direction is inherited thru {@link ViewGroup}
1891     */
1892    public static final int TEXT_DIRECTION_INHERIT = 0;
1893
1894    /**
1895     * Text direction is using "first strong algorithm". The first strong directional character
1896     * determines the paragraph direction. If there is no strong directional character, the
1897     * paragraph direction is the view's resolved layout direction.
1898     */
1899    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1900
1901    /**
1902     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1903     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1904     * If there are neither, the paragraph direction is the view's resolved layout direction.
1905     */
1906    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1907
1908    /**
1909     * Text direction is forced to LTR.
1910     */
1911    public static final int TEXT_DIRECTION_LTR = 3;
1912
1913    /**
1914     * Text direction is forced to RTL.
1915     */
1916    public static final int TEXT_DIRECTION_RTL = 4;
1917
1918    /**
1919     * Text direction is coming from the system Locale.
1920     */
1921    public static final int TEXT_DIRECTION_LOCALE = 5;
1922
1923    /**
1924     * Default text direction is inherited
1925     */
1926    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1927
1928    /**
1929     * Default resolved text direction
1930     * @hide
1931     */
1932    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1933
1934    /**
1935     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1936     * @hide
1937     */
1938    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1939
1940    /**
1941     * Mask for use with private flags indicating bits used for text direction.
1942     * @hide
1943     */
1944    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1945            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1946
1947    /**
1948     * Array of text direction flags for mapping attribute "textDirection" to correct
1949     * flag value.
1950     * @hide
1951     */
1952    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1953            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1957            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1958            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1959    };
1960
1961    /**
1962     * Indicates whether the view text direction has been resolved.
1963     * @hide
1964     */
1965    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1966            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1967
1968    /**
1969     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1970     * @hide
1971     */
1972    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1973
1974    /**
1975     * Mask for use with private flags indicating bits used for resolved text direction.
1976     * @hide
1977     */
1978    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1979            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1980
1981    /**
1982     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1983     * @hide
1984     */
1985    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1986            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1987
1988    /*
1989     * Default text alignment. The text alignment of this View is inherited from its parent.
1990     * Use with {@link #setTextAlignment(int)}
1991     */
1992    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1993
1994    /**
1995     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1996     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1997     *
1998     * Use with {@link #setTextAlignment(int)}
1999     */
2000    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2001
2002    /**
2003     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2004     *
2005     * Use with {@link #setTextAlignment(int)}
2006     */
2007    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2008
2009    /**
2010     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2011     *
2012     * Use with {@link #setTextAlignment(int)}
2013     */
2014    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2015
2016    /**
2017     * Center the paragraph, e.g. ALIGN_CENTER.
2018     *
2019     * Use with {@link #setTextAlignment(int)}
2020     */
2021    public static final int TEXT_ALIGNMENT_CENTER = 4;
2022
2023    /**
2024     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2025     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2026     *
2027     * Use with {@link #setTextAlignment(int)}
2028     */
2029    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2030
2031    /**
2032     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2033     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2034     *
2035     * Use with {@link #setTextAlignment(int)}
2036     */
2037    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2038
2039    /**
2040     * Default text alignment is inherited
2041     */
2042    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2043
2044    /**
2045     * Default resolved text alignment
2046     * @hide
2047     */
2048    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2049
2050    /**
2051      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2052      * @hide
2053      */
2054    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2055
2056    /**
2057      * Mask for use with private flags indicating bits used for text alignment.
2058      * @hide
2059      */
2060    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2061
2062    /**
2063     * Array of text direction flags for mapping attribute "textAlignment" to correct
2064     * flag value.
2065     * @hide
2066     */
2067    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2068            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2073            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2074            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2075    };
2076
2077    /**
2078     * Indicates whether the view text alignment has been resolved.
2079     * @hide
2080     */
2081    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2082
2083    /**
2084     * Bit shift to get the resolved text alignment.
2085     * @hide
2086     */
2087    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2088
2089    /**
2090     * Mask for use with private flags indicating bits used for text alignment.
2091     * @hide
2092     */
2093    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2094            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2095
2096    /**
2097     * Indicates whether if the view text alignment has been resolved to gravity
2098     */
2099    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2100            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2101
2102    // Accessiblity constants for mPrivateFlags2
2103
2104    /**
2105     * Shift for the bits in {@link #mPrivateFlags2} related to the
2106     * "importantForAccessibility" attribute.
2107     */
2108    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2109
2110    /**
2111     * Automatically determine whether a view is important for accessibility.
2112     */
2113    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2114
2115    /**
2116     * The view is important for accessibility.
2117     */
2118    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2119
2120    /**
2121     * The view is not important for accessibility.
2122     */
2123    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2124
2125    /**
2126     * The default whether the view is important for accessibility.
2127     */
2128    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2129
2130    /**
2131     * Mask for obtainig the bits which specify how to determine
2132     * whether a view is important for accessibility.
2133     */
2134    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2135        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2136        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2137
2138    /**
2139     * Flag indicating whether a view has accessibility focus.
2140     */
2141    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2142
2143    /**
2144     * Flag whether the accessibility state of the subtree rooted at this view changed.
2145     */
2146    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2147
2148    /**
2149     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2150     * is used to check whether later changes to the view's transform should invalidate the
2151     * view to force the quickReject test to run again.
2152     */
2153    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2154
2155    /**
2156     * Flag indicating that start/end padding has been resolved into left/right padding
2157     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2158     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2159     * during measurement. In some special cases this is required such as when an adapter-based
2160     * view measures prospective children without attaching them to a window.
2161     */
2162    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2163
2164    /**
2165     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2166     */
2167    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2168
2169    /**
2170     * Group of bits indicating that RTL properties resolution is done.
2171     */
2172    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2173            PFLAG2_TEXT_DIRECTION_RESOLVED |
2174            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2175            PFLAG2_PADDING_RESOLVED |
2176            PFLAG2_DRAWABLE_RESOLVED;
2177
2178    // There are a couple of flags left in mPrivateFlags2
2179
2180    /* End of masks for mPrivateFlags2 */
2181
2182    /* Masks for mPrivateFlags3 */
2183
2184    /**
2185     * Flag indicating that view has a transform animation set on it. This is used to track whether
2186     * an animation is cleared between successive frames, in order to tell the associated
2187     * DisplayList to clear its animation matrix.
2188     */
2189    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2190
2191    /**
2192     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2193     * animation is cleared between successive frames, in order to tell the associated
2194     * DisplayList to restore its alpha value.
2195     */
2196    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2197
2198    /**
2199     * Flag indicating that the view has been through at least one layout since it
2200     * was last attached to a window.
2201     */
2202    static final int PFLAG3_HAS_LAYOUT = 0x4;
2203
2204
2205    /* End of masks for mPrivateFlags3 */
2206
2207    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2208
2209    /**
2210     * Always allow a user to over-scroll this view, provided it is a
2211     * view that can scroll.
2212     *
2213     * @see #getOverScrollMode()
2214     * @see #setOverScrollMode(int)
2215     */
2216    public static final int OVER_SCROLL_ALWAYS = 0;
2217
2218    /**
2219     * Allow a user to over-scroll this view only if the content is large
2220     * enough to meaningfully scroll, provided it is a view that can scroll.
2221     *
2222     * @see #getOverScrollMode()
2223     * @see #setOverScrollMode(int)
2224     */
2225    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2226
2227    /**
2228     * Never allow a user to over-scroll this view.
2229     *
2230     * @see #getOverScrollMode()
2231     * @see #setOverScrollMode(int)
2232     */
2233    public static final int OVER_SCROLL_NEVER = 2;
2234
2235    /**
2236     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2237     * requested the system UI (status bar) to be visible (the default).
2238     *
2239     * @see #setSystemUiVisibility(int)
2240     */
2241    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2242
2243    /**
2244     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2245     * system UI to enter an unobtrusive "low profile" mode.
2246     *
2247     * <p>This is for use in games, book readers, video players, or any other
2248     * "immersive" application where the usual system chrome is deemed too distracting.
2249     *
2250     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2251     *
2252     * @see #setSystemUiVisibility(int)
2253     */
2254    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2255
2256    /**
2257     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2258     * system navigation be temporarily hidden.
2259     *
2260     * <p>This is an even less obtrusive state than that called for by
2261     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2262     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2263     * those to disappear. This is useful (in conjunction with the
2264     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2265     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2266     * window flags) for displaying content using every last pixel on the display.
2267     *
2268     * <p>There is a limitation: because navigation controls are so important, the least user
2269     * interaction will cause them to reappear immediately.  When this happens, both
2270     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2271     * so that both elements reappear at the same time.
2272     *
2273     * @see #setSystemUiVisibility(int)
2274     */
2275    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2276
2277    /**
2278     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2279     * into the normal fullscreen mode so that its content can take over the screen
2280     * while still allowing the user to interact with the application.
2281     *
2282     * <p>This has the same visual effect as
2283     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2284     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2285     * meaning that non-critical screen decorations (such as the status bar) will be
2286     * hidden while the user is in the View's window, focusing the experience on
2287     * that content.  Unlike the window flag, if you are using ActionBar in
2288     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2289     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2290     * hide the action bar.
2291     *
2292     * <p>This approach to going fullscreen is best used over the window flag when
2293     * it is a transient state -- that is, the application does this at certain
2294     * points in its user interaction where it wants to allow the user to focus
2295     * on content, but not as a continuous state.  For situations where the application
2296     * would like to simply stay full screen the entire time (such as a game that
2297     * wants to take over the screen), the
2298     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2299     * is usually a better approach.  The state set here will be removed by the system
2300     * in various situations (such as the user moving to another application) like
2301     * the other system UI states.
2302     *
2303     * <p>When using this flag, the application should provide some easy facility
2304     * for the user to go out of it.  A common example would be in an e-book
2305     * reader, where tapping on the screen brings back whatever screen and UI
2306     * decorations that had been hidden while the user was immersed in reading
2307     * the book.
2308     *
2309     * @see #setSystemUiVisibility(int)
2310     */
2311    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2312
2313    /**
2314     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2315     * flags, we would like a stable view of the content insets given to
2316     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2317     * will always represent the worst case that the application can expect
2318     * as a continuous state.  In the stock Android UI this is the space for
2319     * the system bar, nav bar, and status bar, but not more transient elements
2320     * such as an input method.
2321     *
2322     * The stable layout your UI sees is based on the system UI modes you can
2323     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2324     * then you will get a stable layout for changes of the
2325     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2326     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2327     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2328     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2329     * with a stable layout.  (Note that you should avoid using
2330     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2331     *
2332     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2333     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2334     * then a hidden status bar will be considered a "stable" state for purposes
2335     * here.  This allows your UI to continually hide the status bar, while still
2336     * using the system UI flags to hide the action bar while still retaining
2337     * a stable layout.  Note that changing the window fullscreen flag will never
2338     * provide a stable layout for a clean transition.
2339     *
2340     * <p>If you are using ActionBar in
2341     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2342     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2343     * insets it adds to those given to the application.
2344     */
2345    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2346
2347    /**
2348     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2349     * to be layed out as if it has requested
2350     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2351     * allows it to avoid artifacts when switching in and out of that mode, at
2352     * the expense that some of its user interface may be covered by screen
2353     * decorations when they are shown.  You can perform layout of your inner
2354     * UI elements to account for the navigation system UI through the
2355     * {@link #fitSystemWindows(Rect)} method.
2356     */
2357    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2358
2359    /**
2360     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2361     * to be layed out as if it has requested
2362     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2363     * allows it to avoid artifacts when switching in and out of that mode, at
2364     * the expense that some of its user interface may be covered by screen
2365     * decorations when they are shown.  You can perform layout of your inner
2366     * UI elements to account for non-fullscreen system UI through the
2367     * {@link #fitSystemWindows(Rect)} method.
2368     */
2369    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2370
2371    /**
2372     * Flag for {@link #setSystemUiVisibility(int)}: View would like to receive touch events
2373     * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the
2374     * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system
2375     * clear these flags upon interaction.  The system may compensate by temporarily overlaying
2376     * transparent system ui while also delivering the event.
2377     */
2378    public static final int SYSTEM_UI_FLAG_ALLOW_OVERLAY = 0x00000800;
2379
2380    /**
2381     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2382     */
2383    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2384
2385    /**
2386     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2387     */
2388    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2389
2390    /**
2391     * @hide
2392     *
2393     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2394     * out of the public fields to keep the undefined bits out of the developer's way.
2395     *
2396     * Flag to make the status bar not expandable.  Unless you also
2397     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2398     */
2399    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2400
2401    /**
2402     * @hide
2403     *
2404     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2405     * out of the public fields to keep the undefined bits out of the developer's way.
2406     *
2407     * Flag to hide notification icons and scrolling ticker text.
2408     */
2409    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2410
2411    /**
2412     * @hide
2413     *
2414     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2415     * out of the public fields to keep the undefined bits out of the developer's way.
2416     *
2417     * Flag to disable incoming notification alerts.  This will not block
2418     * icons, but it will block sound, vibrating and other visual or aural notifications.
2419     */
2420    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2421
2422    /**
2423     * @hide
2424     *
2425     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2426     * out of the public fields to keep the undefined bits out of the developer's way.
2427     *
2428     * Flag to hide only the scrolling ticker.  Note that
2429     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2430     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2431     */
2432    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2433
2434    /**
2435     * @hide
2436     *
2437     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2438     * out of the public fields to keep the undefined bits out of the developer's way.
2439     *
2440     * Flag to hide the center system info area.
2441     */
2442    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2443
2444    /**
2445     * @hide
2446     *
2447     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2448     * out of the public fields to keep the undefined bits out of the developer's way.
2449     *
2450     * Flag to hide only the home button.  Don't use this
2451     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2452     */
2453    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2454
2455    /**
2456     * @hide
2457     *
2458     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2459     * out of the public fields to keep the undefined bits out of the developer's way.
2460     *
2461     * Flag to hide only the back button. Don't use this
2462     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2463     */
2464    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2465
2466    /**
2467     * @hide
2468     *
2469     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2470     * out of the public fields to keep the undefined bits out of the developer's way.
2471     *
2472     * Flag to hide only the clock.  You might use this if your activity has
2473     * its own clock making the status bar's clock redundant.
2474     */
2475    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2476
2477    /**
2478     * @hide
2479     *
2480     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2481     * out of the public fields to keep the undefined bits out of the developer's way.
2482     *
2483     * Flag to hide only the recent apps button. Don't use this
2484     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2485     */
2486    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2487
2488    /**
2489     * @hide
2490     *
2491     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2492     * out of the public fields to keep the undefined bits out of the developer's way.
2493     *
2494     * Flag to disable the global search gesture. Don't use this
2495     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2496     */
2497    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2498
2499    /**
2500     * @hide
2501     *
2502     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2503     * out of the public fields to keep the undefined bits out of the developer's way.
2504     *
2505     * Flag to specify that the status bar should temporarily overlay underlying content
2506     * that is otherwise assuming the status bar is hidden.  The status bar may
2507     * have some degree of transparency while in this temporary overlay mode.
2508     */
2509    public static final int STATUS_BAR_OVERLAY = 0x04000000;
2510
2511    /**
2512     * @hide
2513     *
2514     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2515     * out of the public fields to keep the undefined bits out of the developer's way.
2516     *
2517     * Flag to specify that the navigation bar should temporarily overlay underlying content
2518     * that is otherwise assuming the navigation bar is hidden.  The navigation bar mayu
2519     * have some degree of transparency while in this temporary overlay mode.
2520     */
2521    public static final int NAVIGATION_BAR_OVERLAY = 0x08000000;
2522
2523    /**
2524     * @hide
2525     */
2526    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2527
2528    /**
2529     * These are the system UI flags that can be cleared by events outside
2530     * of an application.  Currently this is just the ability to tap on the
2531     * screen while hiding the navigation bar to have it return.
2532     * @hide
2533     */
2534    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2535            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2536            | SYSTEM_UI_FLAG_FULLSCREEN;
2537
2538    /**
2539     * Flags that can impact the layout in relation to system UI.
2540     */
2541    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2542            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2543            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2544
2545    /**
2546     * Find views that render the specified text.
2547     *
2548     * @see #findViewsWithText(ArrayList, CharSequence, int)
2549     */
2550    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2551
2552    /**
2553     * Find find views that contain the specified content description.
2554     *
2555     * @see #findViewsWithText(ArrayList, CharSequence, int)
2556     */
2557    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2558
2559    /**
2560     * Find views that contain {@link AccessibilityNodeProvider}. Such
2561     * a View is a root of virtual view hierarchy and may contain the searched
2562     * text. If this flag is set Views with providers are automatically
2563     * added and it is a responsibility of the client to call the APIs of
2564     * the provider to determine whether the virtual tree rooted at this View
2565     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2566     * represeting the virtual views with this text.
2567     *
2568     * @see #findViewsWithText(ArrayList, CharSequence, int)
2569     *
2570     * @hide
2571     */
2572    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2573
2574    /**
2575     * The undefined cursor position.
2576     *
2577     * @hide
2578     */
2579    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2580
2581    /**
2582     * Indicates that the screen has changed state and is now off.
2583     *
2584     * @see #onScreenStateChanged(int)
2585     */
2586    public static final int SCREEN_STATE_OFF = 0x0;
2587
2588    /**
2589     * Indicates that the screen has changed state and is now on.
2590     *
2591     * @see #onScreenStateChanged(int)
2592     */
2593    public static final int SCREEN_STATE_ON = 0x1;
2594
2595    /**
2596     * Controls the over-scroll mode for this view.
2597     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2598     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2599     * and {@link #OVER_SCROLL_NEVER}.
2600     */
2601    private int mOverScrollMode;
2602
2603    /**
2604     * The parent this view is attached to.
2605     * {@hide}
2606     *
2607     * @see #getParent()
2608     */
2609    protected ViewParent mParent;
2610
2611    /**
2612     * {@hide}
2613     */
2614    AttachInfo mAttachInfo;
2615
2616    /**
2617     * {@hide}
2618     */
2619    @ViewDebug.ExportedProperty(flagMapping = {
2620        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2621                name = "FORCE_LAYOUT"),
2622        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2623                name = "LAYOUT_REQUIRED"),
2624        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2625            name = "DRAWING_CACHE_INVALID", outputIf = false),
2626        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2627        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2628        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2629        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2630    })
2631    int mPrivateFlags;
2632    int mPrivateFlags2;
2633    int mPrivateFlags3;
2634
2635    /**
2636     * This view's request for the visibility of the status bar.
2637     * @hide
2638     */
2639    @ViewDebug.ExportedProperty(flagMapping = {
2640        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2641                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2642                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2643        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2644                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2645                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2646        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2647                                equals = SYSTEM_UI_FLAG_VISIBLE,
2648                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2649    })
2650    int mSystemUiVisibility;
2651
2652    /**
2653     * Reference count for transient state.
2654     * @see #setHasTransientState(boolean)
2655     */
2656    int mTransientStateCount = 0;
2657
2658    /**
2659     * Count of how many windows this view has been attached to.
2660     */
2661    int mWindowAttachCount;
2662
2663    /**
2664     * The layout parameters associated with this view and used by the parent
2665     * {@link android.view.ViewGroup} to determine how this view should be
2666     * laid out.
2667     * {@hide}
2668     */
2669    protected ViewGroup.LayoutParams mLayoutParams;
2670
2671    /**
2672     * The view flags hold various views states.
2673     * {@hide}
2674     */
2675    @ViewDebug.ExportedProperty
2676    int mViewFlags;
2677
2678    static class TransformationInfo {
2679        /**
2680         * The transform matrix for the View. This transform is calculated internally
2681         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2682         * is used by default. Do *not* use this variable directly; instead call
2683         * getMatrix(), which will automatically recalculate the matrix if necessary
2684         * to get the correct matrix based on the latest rotation and scale properties.
2685         */
2686        private final Matrix mMatrix = new Matrix();
2687
2688        /**
2689         * The transform matrix for the View. This transform is calculated internally
2690         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2691         * is used by default. Do *not* use this variable directly; instead call
2692         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2693         * to get the correct matrix based on the latest rotation and scale properties.
2694         */
2695        private Matrix mInverseMatrix;
2696
2697        /**
2698         * An internal variable that tracks whether we need to recalculate the
2699         * transform matrix, based on whether the rotation or scaleX/Y properties
2700         * have changed since the matrix was last calculated.
2701         */
2702        boolean mMatrixDirty = false;
2703
2704        /**
2705         * An internal variable that tracks whether we need to recalculate the
2706         * transform matrix, based on whether the rotation or scaleX/Y properties
2707         * have changed since the matrix was last calculated.
2708         */
2709        private boolean mInverseMatrixDirty = true;
2710
2711        /**
2712         * A variable that tracks whether we need to recalculate the
2713         * transform matrix, based on whether the rotation or scaleX/Y properties
2714         * have changed since the matrix was last calculated. This variable
2715         * is only valid after a call to updateMatrix() or to a function that
2716         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2717         */
2718        private boolean mMatrixIsIdentity = true;
2719
2720        /**
2721         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2722         */
2723        private Camera mCamera = null;
2724
2725        /**
2726         * This matrix is used when computing the matrix for 3D rotations.
2727         */
2728        private Matrix matrix3D = null;
2729
2730        /**
2731         * These prev values are used to recalculate a centered pivot point when necessary. The
2732         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2733         * set), so thes values are only used then as well.
2734         */
2735        private int mPrevWidth = -1;
2736        private int mPrevHeight = -1;
2737
2738        /**
2739         * The degrees rotation around the vertical axis through the pivot point.
2740         */
2741        @ViewDebug.ExportedProperty
2742        float mRotationY = 0f;
2743
2744        /**
2745         * The degrees rotation around the horizontal axis through the pivot point.
2746         */
2747        @ViewDebug.ExportedProperty
2748        float mRotationX = 0f;
2749
2750        /**
2751         * The degrees rotation around the pivot point.
2752         */
2753        @ViewDebug.ExportedProperty
2754        float mRotation = 0f;
2755
2756        /**
2757         * The amount of translation of the object away from its left property (post-layout).
2758         */
2759        @ViewDebug.ExportedProperty
2760        float mTranslationX = 0f;
2761
2762        /**
2763         * The amount of translation of the object away from its top property (post-layout).
2764         */
2765        @ViewDebug.ExportedProperty
2766        float mTranslationY = 0f;
2767
2768        /**
2769         * The amount of scale in the x direction around the pivot point. A
2770         * value of 1 means no scaling is applied.
2771         */
2772        @ViewDebug.ExportedProperty
2773        float mScaleX = 1f;
2774
2775        /**
2776         * The amount of scale in the y direction around the pivot point. A
2777         * value of 1 means no scaling is applied.
2778         */
2779        @ViewDebug.ExportedProperty
2780        float mScaleY = 1f;
2781
2782        /**
2783         * The x location of the point around which the view is rotated and scaled.
2784         */
2785        @ViewDebug.ExportedProperty
2786        float mPivotX = 0f;
2787
2788        /**
2789         * The y location of the point around which the view is rotated and scaled.
2790         */
2791        @ViewDebug.ExportedProperty
2792        float mPivotY = 0f;
2793
2794        /**
2795         * The opacity of the View. This is a value from 0 to 1, where 0 means
2796         * completely transparent and 1 means completely opaque.
2797         */
2798        @ViewDebug.ExportedProperty
2799        float mAlpha = 1f;
2800    }
2801
2802    TransformationInfo mTransformationInfo;
2803
2804    /**
2805     * Current clip bounds. to which all drawing of this view are constrained.
2806     */
2807    private Rect mClipBounds = null;
2808
2809    private boolean mLastIsOpaque;
2810
2811    /**
2812     * Convenience value to check for float values that are close enough to zero to be considered
2813     * zero.
2814     */
2815    private static final float NONZERO_EPSILON = .001f;
2816
2817    /**
2818     * The distance in pixels from the left edge of this view's parent
2819     * to the left edge of this view.
2820     * {@hide}
2821     */
2822    @ViewDebug.ExportedProperty(category = "layout")
2823    protected int mLeft;
2824    /**
2825     * The distance in pixels from the left edge of this view's parent
2826     * to the right edge of this view.
2827     * {@hide}
2828     */
2829    @ViewDebug.ExportedProperty(category = "layout")
2830    protected int mRight;
2831    /**
2832     * The distance in pixels from the top edge of this view's parent
2833     * to the top edge of this view.
2834     * {@hide}
2835     */
2836    @ViewDebug.ExportedProperty(category = "layout")
2837    protected int mTop;
2838    /**
2839     * The distance in pixels from the top edge of this view's parent
2840     * to the bottom edge of this view.
2841     * {@hide}
2842     */
2843    @ViewDebug.ExportedProperty(category = "layout")
2844    protected int mBottom;
2845
2846    /**
2847     * The offset, in pixels, by which the content of this view is scrolled
2848     * horizontally.
2849     * {@hide}
2850     */
2851    @ViewDebug.ExportedProperty(category = "scrolling")
2852    protected int mScrollX;
2853    /**
2854     * The offset, in pixels, by which the content of this view is scrolled
2855     * vertically.
2856     * {@hide}
2857     */
2858    @ViewDebug.ExportedProperty(category = "scrolling")
2859    protected int mScrollY;
2860
2861    /**
2862     * The left padding in pixels, that is the distance in pixels between the
2863     * left edge of this view and the left edge of its content.
2864     * {@hide}
2865     */
2866    @ViewDebug.ExportedProperty(category = "padding")
2867    protected int mPaddingLeft = 0;
2868    /**
2869     * The right padding in pixels, that is the distance in pixels between the
2870     * right edge of this view and the right edge of its content.
2871     * {@hide}
2872     */
2873    @ViewDebug.ExportedProperty(category = "padding")
2874    protected int mPaddingRight = 0;
2875    /**
2876     * The top padding in pixels, that is the distance in pixels between the
2877     * top edge of this view and the top edge of its content.
2878     * {@hide}
2879     */
2880    @ViewDebug.ExportedProperty(category = "padding")
2881    protected int mPaddingTop;
2882    /**
2883     * The bottom padding in pixels, that is the distance in pixels between the
2884     * bottom edge of this view and the bottom edge of its content.
2885     * {@hide}
2886     */
2887    @ViewDebug.ExportedProperty(category = "padding")
2888    protected int mPaddingBottom;
2889
2890    /**
2891     * The layout insets in pixels, that is the distance in pixels between the
2892     * visible edges of this view its bounds.
2893     */
2894    private Insets mLayoutInsets;
2895
2896    /**
2897     * Briefly describes the view and is primarily used for accessibility support.
2898     */
2899    private CharSequence mContentDescription;
2900
2901    /**
2902     * Specifies the id of a view for which this view serves as a label for
2903     * accessibility purposes.
2904     */
2905    private int mLabelForId = View.NO_ID;
2906
2907    /**
2908     * Predicate for matching labeled view id with its label for
2909     * accessibility purposes.
2910     */
2911    private MatchLabelForPredicate mMatchLabelForPredicate;
2912
2913    /**
2914     * Predicate for matching a view by its id.
2915     */
2916    private MatchIdPredicate mMatchIdPredicate;
2917
2918    /**
2919     * Cache the paddingRight set by the user to append to the scrollbar's size.
2920     *
2921     * @hide
2922     */
2923    @ViewDebug.ExportedProperty(category = "padding")
2924    protected int mUserPaddingRight;
2925
2926    /**
2927     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2928     *
2929     * @hide
2930     */
2931    @ViewDebug.ExportedProperty(category = "padding")
2932    protected int mUserPaddingBottom;
2933
2934    /**
2935     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2936     *
2937     * @hide
2938     */
2939    @ViewDebug.ExportedProperty(category = "padding")
2940    protected int mUserPaddingLeft;
2941
2942    /**
2943     * Cache the paddingStart set by the user to append to the scrollbar's size.
2944     *
2945     */
2946    @ViewDebug.ExportedProperty(category = "padding")
2947    int mUserPaddingStart;
2948
2949    /**
2950     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2951     *
2952     */
2953    @ViewDebug.ExportedProperty(category = "padding")
2954    int mUserPaddingEnd;
2955
2956    /**
2957     * Cache initial left padding.
2958     *
2959     * @hide
2960     */
2961    int mUserPaddingLeftInitial;
2962
2963    /**
2964     * Cache initial right padding.
2965     *
2966     * @hide
2967     */
2968    int mUserPaddingRightInitial;
2969
2970    /**
2971     * Default undefined padding
2972     */
2973    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2974
2975    /**
2976     * @hide
2977     */
2978    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2979    /**
2980     * @hide
2981     */
2982    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2983
2984    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2985    private Drawable mBackground;
2986
2987    private int mBackgroundResource;
2988    private boolean mBackgroundSizeChanged;
2989
2990    static class ListenerInfo {
2991        /**
2992         * Listener used to dispatch focus change events.
2993         * This field should be made private, so it is hidden from the SDK.
2994         * {@hide}
2995         */
2996        protected OnFocusChangeListener mOnFocusChangeListener;
2997
2998        /**
2999         * Listeners for layout change events.
3000         */
3001        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3002
3003        /**
3004         * Listeners for attach events.
3005         */
3006        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3007
3008        /**
3009         * Listener used to dispatch click events.
3010         * This field should be made private, so it is hidden from the SDK.
3011         * {@hide}
3012         */
3013        public OnClickListener mOnClickListener;
3014
3015        /**
3016         * Listener used to dispatch long click events.
3017         * This field should be made private, so it is hidden from the SDK.
3018         * {@hide}
3019         */
3020        protected OnLongClickListener mOnLongClickListener;
3021
3022        /**
3023         * Listener used to build the context menu.
3024         * This field should be made private, so it is hidden from the SDK.
3025         * {@hide}
3026         */
3027        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3028
3029        private OnKeyListener mOnKeyListener;
3030
3031        private OnTouchListener mOnTouchListener;
3032
3033        private OnHoverListener mOnHoverListener;
3034
3035        private OnGenericMotionListener mOnGenericMotionListener;
3036
3037        private OnDragListener mOnDragListener;
3038
3039        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3040    }
3041
3042    ListenerInfo mListenerInfo;
3043
3044    /**
3045     * The application environment this view lives in.
3046     * This field should be made private, so it is hidden from the SDK.
3047     * {@hide}
3048     */
3049    protected Context mContext;
3050
3051    private final Resources mResources;
3052
3053    private ScrollabilityCache mScrollCache;
3054
3055    private int[] mDrawableState = null;
3056
3057    /**
3058     * Set to true when drawing cache is enabled and cannot be created.
3059     *
3060     * @hide
3061     */
3062    public boolean mCachingFailed;
3063
3064    private Bitmap mDrawingCache;
3065    private Bitmap mUnscaledDrawingCache;
3066    private HardwareLayer mHardwareLayer;
3067    DisplayList mDisplayList;
3068
3069    /**
3070     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3071     * the user may specify which view to go to next.
3072     */
3073    private int mNextFocusLeftId = View.NO_ID;
3074
3075    /**
3076     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3077     * the user may specify which view to go to next.
3078     */
3079    private int mNextFocusRightId = View.NO_ID;
3080
3081    /**
3082     * When this view has focus and the next focus is {@link #FOCUS_UP},
3083     * the user may specify which view to go to next.
3084     */
3085    private int mNextFocusUpId = View.NO_ID;
3086
3087    /**
3088     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3089     * the user may specify which view to go to next.
3090     */
3091    private int mNextFocusDownId = View.NO_ID;
3092
3093    /**
3094     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3095     * the user may specify which view to go to next.
3096     */
3097    int mNextFocusForwardId = View.NO_ID;
3098
3099    private CheckForLongPress mPendingCheckForLongPress;
3100    private CheckForTap mPendingCheckForTap = null;
3101    private PerformClick mPerformClick;
3102    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3103
3104    private UnsetPressedState mUnsetPressedState;
3105
3106    /**
3107     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3108     * up event while a long press is invoked as soon as the long press duration is reached, so
3109     * a long press could be performed before the tap is checked, in which case the tap's action
3110     * should not be invoked.
3111     */
3112    private boolean mHasPerformedLongPress;
3113
3114    /**
3115     * The minimum height of the view. We'll try our best to have the height
3116     * of this view to at least this amount.
3117     */
3118    @ViewDebug.ExportedProperty(category = "measurement")
3119    private int mMinHeight;
3120
3121    /**
3122     * The minimum width of the view. We'll try our best to have the width
3123     * of this view to at least this amount.
3124     */
3125    @ViewDebug.ExportedProperty(category = "measurement")
3126    private int mMinWidth;
3127
3128    /**
3129     * The delegate to handle touch events that are physically in this view
3130     * but should be handled by another view.
3131     */
3132    private TouchDelegate mTouchDelegate = null;
3133
3134    /**
3135     * Solid color to use as a background when creating the drawing cache. Enables
3136     * the cache to use 16 bit bitmaps instead of 32 bit.
3137     */
3138    private int mDrawingCacheBackgroundColor = 0;
3139
3140    /**
3141     * Special tree observer used when mAttachInfo is null.
3142     */
3143    private ViewTreeObserver mFloatingTreeObserver;
3144
3145    /**
3146     * Cache the touch slop from the context that created the view.
3147     */
3148    private int mTouchSlop;
3149
3150    /**
3151     * Object that handles automatic animation of view properties.
3152     */
3153    private ViewPropertyAnimator mAnimator = null;
3154
3155    /**
3156     * Flag indicating that a drag can cross window boundaries.  When
3157     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3158     * with this flag set, all visible applications will be able to participate
3159     * in the drag operation and receive the dragged content.
3160     *
3161     * @hide
3162     */
3163    public static final int DRAG_FLAG_GLOBAL = 1;
3164
3165    /**
3166     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3167     */
3168    private float mVerticalScrollFactor;
3169
3170    /**
3171     * Position of the vertical scroll bar.
3172     */
3173    private int mVerticalScrollbarPosition;
3174
3175    /**
3176     * Position the scroll bar at the default position as determined by the system.
3177     */
3178    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3179
3180    /**
3181     * Position the scroll bar along the left edge.
3182     */
3183    public static final int SCROLLBAR_POSITION_LEFT = 1;
3184
3185    /**
3186     * Position the scroll bar along the right edge.
3187     */
3188    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3189
3190    /**
3191     * Indicates that the view does not have a layer.
3192     *
3193     * @see #getLayerType()
3194     * @see #setLayerType(int, android.graphics.Paint)
3195     * @see #LAYER_TYPE_SOFTWARE
3196     * @see #LAYER_TYPE_HARDWARE
3197     */
3198    public static final int LAYER_TYPE_NONE = 0;
3199
3200    /**
3201     * <p>Indicates that the view has a software layer. A software layer is backed
3202     * by a bitmap and causes the view to be rendered using Android's software
3203     * rendering pipeline, even if hardware acceleration is enabled.</p>
3204     *
3205     * <p>Software layers have various usages:</p>
3206     * <p>When the application is not using hardware acceleration, a software layer
3207     * is useful to apply a specific color filter and/or blending mode and/or
3208     * translucency to a view and all its children.</p>
3209     * <p>When the application is using hardware acceleration, a software layer
3210     * is useful to render drawing primitives not supported by the hardware
3211     * accelerated pipeline. It can also be used to cache a complex view tree
3212     * into a texture and reduce the complexity of drawing operations. For instance,
3213     * when animating a complex view tree with a translation, a software layer can
3214     * be used to render the view tree only once.</p>
3215     * <p>Software layers should be avoided when the affected view tree updates
3216     * often. Every update will require to re-render the software layer, which can
3217     * potentially be slow (particularly when hardware acceleration is turned on
3218     * since the layer will have to be uploaded into a hardware texture after every
3219     * update.)</p>
3220     *
3221     * @see #getLayerType()
3222     * @see #setLayerType(int, android.graphics.Paint)
3223     * @see #LAYER_TYPE_NONE
3224     * @see #LAYER_TYPE_HARDWARE
3225     */
3226    public static final int LAYER_TYPE_SOFTWARE = 1;
3227
3228    /**
3229     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3230     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3231     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3232     * rendering pipeline, but only if hardware acceleration is turned on for the
3233     * view hierarchy. When hardware acceleration is turned off, hardware layers
3234     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3235     *
3236     * <p>A hardware layer is useful to apply a specific color filter and/or
3237     * blending mode and/or translucency to a view and all its children.</p>
3238     * <p>A hardware layer can be used to cache a complex view tree into a
3239     * texture and reduce the complexity of drawing operations. For instance,
3240     * when animating a complex view tree with a translation, a hardware layer can
3241     * be used to render the view tree only once.</p>
3242     * <p>A hardware layer can also be used to increase the rendering quality when
3243     * rotation transformations are applied on a view. It can also be used to
3244     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3245     *
3246     * @see #getLayerType()
3247     * @see #setLayerType(int, android.graphics.Paint)
3248     * @see #LAYER_TYPE_NONE
3249     * @see #LAYER_TYPE_SOFTWARE
3250     */
3251    public static final int LAYER_TYPE_HARDWARE = 2;
3252
3253    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3254            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3255            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3256            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3257    })
3258    int mLayerType = LAYER_TYPE_NONE;
3259    Paint mLayerPaint;
3260    Rect mLocalDirtyRect;
3261
3262    /**
3263     * Set to true when the view is sending hover accessibility events because it
3264     * is the innermost hovered view.
3265     */
3266    private boolean mSendingHoverAccessibilityEvents;
3267
3268    /**
3269     * Delegate for injecting accessibility functionality.
3270     */
3271    AccessibilityDelegate mAccessibilityDelegate;
3272
3273    /**
3274     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3275     * and add/remove objects to/from the overlay directly through the Overlay methods.
3276     */
3277    ViewOverlay mOverlay;
3278
3279    /**
3280     * Consistency verifier for debugging purposes.
3281     * @hide
3282     */
3283    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3284            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3285                    new InputEventConsistencyVerifier(this, 0) : null;
3286
3287    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3288
3289    /**
3290     * Simple constructor to use when creating a view from code.
3291     *
3292     * @param context The Context the view is running in, through which it can
3293     *        access the current theme, resources, etc.
3294     */
3295    public View(Context context) {
3296        mContext = context;
3297        mResources = context != null ? context.getResources() : null;
3298        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3299        // Set some flags defaults
3300        mPrivateFlags2 =
3301                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3302                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3303                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3304                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3305                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3306                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3307        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3308        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3309        mUserPaddingStart = UNDEFINED_PADDING;
3310        mUserPaddingEnd = UNDEFINED_PADDING;
3311
3312        if (!sUseBrokenMakeMeasureSpec && context.getApplicationInfo().targetSdkVersion <=
3313                Build.VERSION_CODES.JELLY_BEAN_MR1 ) {
3314            // Older apps may need this compatibility hack for measurement.
3315            sUseBrokenMakeMeasureSpec = true;
3316        }
3317    }
3318
3319    /**
3320     * Constructor that is called when inflating a view from XML. This is called
3321     * when a view is being constructed from an XML file, supplying attributes
3322     * that were specified in the XML file. This version uses a default style of
3323     * 0, so the only attribute values applied are those in the Context's Theme
3324     * and the given AttributeSet.
3325     *
3326     * <p>
3327     * The method onFinishInflate() will be called after all children have been
3328     * added.
3329     *
3330     * @param context The Context the view is running in, through which it can
3331     *        access the current theme, resources, etc.
3332     * @param attrs The attributes of the XML tag that is inflating the view.
3333     * @see #View(Context, AttributeSet, int)
3334     */
3335    public View(Context context, AttributeSet attrs) {
3336        this(context, attrs, 0);
3337    }
3338
3339    /**
3340     * Perform inflation from XML and apply a class-specific base style. This
3341     * constructor of View allows subclasses to use their own base style when
3342     * they are inflating. For example, a Button class's constructor would call
3343     * this version of the super class constructor and supply
3344     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3345     * the theme's button style to modify all of the base view attributes (in
3346     * particular its background) as well as the Button class's attributes.
3347     *
3348     * @param context The Context the view is running in, through which it can
3349     *        access the current theme, resources, etc.
3350     * @param attrs The attributes of the XML tag that is inflating the view.
3351     * @param defStyle The default style to apply to this view. If 0, no style
3352     *        will be applied (beyond what is included in the theme). This may
3353     *        either be an attribute resource, whose value will be retrieved
3354     *        from the current theme, or an explicit style resource.
3355     * @see #View(Context, AttributeSet)
3356     */
3357    public View(Context context, AttributeSet attrs, int defStyle) {
3358        this(context);
3359
3360        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3361                defStyle, 0);
3362
3363        Drawable background = null;
3364
3365        int leftPadding = -1;
3366        int topPadding = -1;
3367        int rightPadding = -1;
3368        int bottomPadding = -1;
3369        int startPadding = UNDEFINED_PADDING;
3370        int endPadding = UNDEFINED_PADDING;
3371
3372        int padding = -1;
3373
3374        int viewFlagValues = 0;
3375        int viewFlagMasks = 0;
3376
3377        boolean setScrollContainer = false;
3378
3379        int x = 0;
3380        int y = 0;
3381
3382        float tx = 0;
3383        float ty = 0;
3384        float rotation = 0;
3385        float rotationX = 0;
3386        float rotationY = 0;
3387        float sx = 1f;
3388        float sy = 1f;
3389        boolean transformSet = false;
3390
3391        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3392        int overScrollMode = mOverScrollMode;
3393        boolean initializeScrollbars = false;
3394
3395        boolean leftPaddingDefined = false;
3396        boolean rightPaddingDefined = false;
3397        boolean startPaddingDefined = false;
3398        boolean endPaddingDefined = false;
3399
3400        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3401
3402        final int N = a.getIndexCount();
3403        for (int i = 0; i < N; i++) {
3404            int attr = a.getIndex(i);
3405            switch (attr) {
3406                case com.android.internal.R.styleable.View_background:
3407                    background = a.getDrawable(attr);
3408                    break;
3409                case com.android.internal.R.styleable.View_padding:
3410                    padding = a.getDimensionPixelSize(attr, -1);
3411                    mUserPaddingLeftInitial = padding;
3412                    mUserPaddingRightInitial = padding;
3413                    leftPaddingDefined = true;
3414                    rightPaddingDefined = true;
3415                    break;
3416                 case com.android.internal.R.styleable.View_paddingLeft:
3417                    leftPadding = a.getDimensionPixelSize(attr, -1);
3418                    mUserPaddingLeftInitial = leftPadding;
3419                    leftPaddingDefined = true;
3420                    break;
3421                case com.android.internal.R.styleable.View_paddingTop:
3422                    topPadding = a.getDimensionPixelSize(attr, -1);
3423                    break;
3424                case com.android.internal.R.styleable.View_paddingRight:
3425                    rightPadding = a.getDimensionPixelSize(attr, -1);
3426                    mUserPaddingRightInitial = rightPadding;
3427                    rightPaddingDefined = true;
3428                    break;
3429                case com.android.internal.R.styleable.View_paddingBottom:
3430                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3431                    break;
3432                case com.android.internal.R.styleable.View_paddingStart:
3433                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3434                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3435                    break;
3436                case com.android.internal.R.styleable.View_paddingEnd:
3437                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3438                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3439                    break;
3440                case com.android.internal.R.styleable.View_scrollX:
3441                    x = a.getDimensionPixelOffset(attr, 0);
3442                    break;
3443                case com.android.internal.R.styleable.View_scrollY:
3444                    y = a.getDimensionPixelOffset(attr, 0);
3445                    break;
3446                case com.android.internal.R.styleable.View_alpha:
3447                    setAlpha(a.getFloat(attr, 1f));
3448                    break;
3449                case com.android.internal.R.styleable.View_transformPivotX:
3450                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3451                    break;
3452                case com.android.internal.R.styleable.View_transformPivotY:
3453                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3454                    break;
3455                case com.android.internal.R.styleable.View_translationX:
3456                    tx = a.getDimensionPixelOffset(attr, 0);
3457                    transformSet = true;
3458                    break;
3459                case com.android.internal.R.styleable.View_translationY:
3460                    ty = a.getDimensionPixelOffset(attr, 0);
3461                    transformSet = true;
3462                    break;
3463                case com.android.internal.R.styleable.View_rotation:
3464                    rotation = a.getFloat(attr, 0);
3465                    transformSet = true;
3466                    break;
3467                case com.android.internal.R.styleable.View_rotationX:
3468                    rotationX = a.getFloat(attr, 0);
3469                    transformSet = true;
3470                    break;
3471                case com.android.internal.R.styleable.View_rotationY:
3472                    rotationY = a.getFloat(attr, 0);
3473                    transformSet = true;
3474                    break;
3475                case com.android.internal.R.styleable.View_scaleX:
3476                    sx = a.getFloat(attr, 1f);
3477                    transformSet = true;
3478                    break;
3479                case com.android.internal.R.styleable.View_scaleY:
3480                    sy = a.getFloat(attr, 1f);
3481                    transformSet = true;
3482                    break;
3483                case com.android.internal.R.styleable.View_id:
3484                    mID = a.getResourceId(attr, NO_ID);
3485                    break;
3486                case com.android.internal.R.styleable.View_tag:
3487                    mTag = a.getText(attr);
3488                    break;
3489                case com.android.internal.R.styleable.View_fitsSystemWindows:
3490                    if (a.getBoolean(attr, false)) {
3491                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3492                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3493                    }
3494                    break;
3495                case com.android.internal.R.styleable.View_focusable:
3496                    if (a.getBoolean(attr, false)) {
3497                        viewFlagValues |= FOCUSABLE;
3498                        viewFlagMasks |= FOCUSABLE_MASK;
3499                    }
3500                    break;
3501                case com.android.internal.R.styleable.View_focusableInTouchMode:
3502                    if (a.getBoolean(attr, false)) {
3503                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3504                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3505                    }
3506                    break;
3507                case com.android.internal.R.styleable.View_clickable:
3508                    if (a.getBoolean(attr, false)) {
3509                        viewFlagValues |= CLICKABLE;
3510                        viewFlagMasks |= CLICKABLE;
3511                    }
3512                    break;
3513                case com.android.internal.R.styleable.View_longClickable:
3514                    if (a.getBoolean(attr, false)) {
3515                        viewFlagValues |= LONG_CLICKABLE;
3516                        viewFlagMasks |= LONG_CLICKABLE;
3517                    }
3518                    break;
3519                case com.android.internal.R.styleable.View_saveEnabled:
3520                    if (!a.getBoolean(attr, true)) {
3521                        viewFlagValues |= SAVE_DISABLED;
3522                        viewFlagMasks |= SAVE_DISABLED_MASK;
3523                    }
3524                    break;
3525                case com.android.internal.R.styleable.View_duplicateParentState:
3526                    if (a.getBoolean(attr, false)) {
3527                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3528                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3529                    }
3530                    break;
3531                case com.android.internal.R.styleable.View_visibility:
3532                    final int visibility = a.getInt(attr, 0);
3533                    if (visibility != 0) {
3534                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3535                        viewFlagMasks |= VISIBILITY_MASK;
3536                    }
3537                    break;
3538                case com.android.internal.R.styleable.View_layoutDirection:
3539                    // Clear any layout direction flags (included resolved bits) already set
3540                    mPrivateFlags2 &=
3541                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3542                    // Set the layout direction flags depending on the value of the attribute
3543                    final int layoutDirection = a.getInt(attr, -1);
3544                    final int value = (layoutDirection != -1) ?
3545                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3546                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3547                    break;
3548                case com.android.internal.R.styleable.View_drawingCacheQuality:
3549                    final int cacheQuality = a.getInt(attr, 0);
3550                    if (cacheQuality != 0) {
3551                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3552                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3553                    }
3554                    break;
3555                case com.android.internal.R.styleable.View_contentDescription:
3556                    setContentDescription(a.getString(attr));
3557                    break;
3558                case com.android.internal.R.styleable.View_labelFor:
3559                    setLabelFor(a.getResourceId(attr, NO_ID));
3560                    break;
3561                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3562                    if (!a.getBoolean(attr, true)) {
3563                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3564                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3565                    }
3566                    break;
3567                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3568                    if (!a.getBoolean(attr, true)) {
3569                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3570                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3571                    }
3572                    break;
3573                case R.styleable.View_scrollbars:
3574                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3575                    if (scrollbars != SCROLLBARS_NONE) {
3576                        viewFlagValues |= scrollbars;
3577                        viewFlagMasks |= SCROLLBARS_MASK;
3578                        initializeScrollbars = true;
3579                    }
3580                    break;
3581                //noinspection deprecation
3582                case R.styleable.View_fadingEdge:
3583                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3584                        // Ignore the attribute starting with ICS
3585                        break;
3586                    }
3587                    // With builds < ICS, fall through and apply fading edges
3588                case R.styleable.View_requiresFadingEdge:
3589                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3590                    if (fadingEdge != FADING_EDGE_NONE) {
3591                        viewFlagValues |= fadingEdge;
3592                        viewFlagMasks |= FADING_EDGE_MASK;
3593                        initializeFadingEdge(a);
3594                    }
3595                    break;
3596                case R.styleable.View_scrollbarStyle:
3597                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3598                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3599                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3600                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3601                    }
3602                    break;
3603                case R.styleable.View_isScrollContainer:
3604                    setScrollContainer = true;
3605                    if (a.getBoolean(attr, false)) {
3606                        setScrollContainer(true);
3607                    }
3608                    break;
3609                case com.android.internal.R.styleable.View_keepScreenOn:
3610                    if (a.getBoolean(attr, false)) {
3611                        viewFlagValues |= KEEP_SCREEN_ON;
3612                        viewFlagMasks |= KEEP_SCREEN_ON;
3613                    }
3614                    break;
3615                case R.styleable.View_filterTouchesWhenObscured:
3616                    if (a.getBoolean(attr, false)) {
3617                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3618                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3619                    }
3620                    break;
3621                case R.styleable.View_nextFocusLeft:
3622                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3623                    break;
3624                case R.styleable.View_nextFocusRight:
3625                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3626                    break;
3627                case R.styleable.View_nextFocusUp:
3628                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3629                    break;
3630                case R.styleable.View_nextFocusDown:
3631                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3632                    break;
3633                case R.styleable.View_nextFocusForward:
3634                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3635                    break;
3636                case R.styleable.View_minWidth:
3637                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3638                    break;
3639                case R.styleable.View_minHeight:
3640                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3641                    break;
3642                case R.styleable.View_onClick:
3643                    if (context.isRestricted()) {
3644                        throw new IllegalStateException("The android:onClick attribute cannot "
3645                                + "be used within a restricted context");
3646                    }
3647
3648                    final String handlerName = a.getString(attr);
3649                    if (handlerName != null) {
3650                        setOnClickListener(new OnClickListener() {
3651                            private Method mHandler;
3652
3653                            public void onClick(View v) {
3654                                if (mHandler == null) {
3655                                    try {
3656                                        mHandler = getContext().getClass().getMethod(handlerName,
3657                                                View.class);
3658                                    } catch (NoSuchMethodException e) {
3659                                        int id = getId();
3660                                        String idText = id == NO_ID ? "" : " with id '"
3661                                                + getContext().getResources().getResourceEntryName(
3662                                                    id) + "'";
3663                                        throw new IllegalStateException("Could not find a method " +
3664                                                handlerName + "(View) in the activity "
3665                                                + getContext().getClass() + " for onClick handler"
3666                                                + " on view " + View.this.getClass() + idText, e);
3667                                    }
3668                                }
3669
3670                                try {
3671                                    mHandler.invoke(getContext(), View.this);
3672                                } catch (IllegalAccessException e) {
3673                                    throw new IllegalStateException("Could not execute non "
3674                                            + "public method of the activity", e);
3675                                } catch (InvocationTargetException e) {
3676                                    throw new IllegalStateException("Could not execute "
3677                                            + "method of the activity", e);
3678                                }
3679                            }
3680                        });
3681                    }
3682                    break;
3683                case R.styleable.View_overScrollMode:
3684                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3685                    break;
3686                case R.styleable.View_verticalScrollbarPosition:
3687                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3688                    break;
3689                case R.styleable.View_layerType:
3690                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3691                    break;
3692                case R.styleable.View_textDirection:
3693                    // Clear any text direction flag already set
3694                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3695                    // Set the text direction flags depending on the value of the attribute
3696                    final int textDirection = a.getInt(attr, -1);
3697                    if (textDirection != -1) {
3698                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3699                    }
3700                    break;
3701                case R.styleable.View_textAlignment:
3702                    // Clear any text alignment flag already set
3703                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3704                    // Set the text alignment flag depending on the value of the attribute
3705                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3706                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3707                    break;
3708                case R.styleable.View_importantForAccessibility:
3709                    setImportantForAccessibility(a.getInt(attr,
3710                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3711                    break;
3712            }
3713        }
3714
3715        setOverScrollMode(overScrollMode);
3716
3717        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3718        // the resolved layout direction). Those cached values will be used later during padding
3719        // resolution.
3720        mUserPaddingStart = startPadding;
3721        mUserPaddingEnd = endPadding;
3722
3723        if (background != null) {
3724            setBackground(background);
3725        }
3726
3727        if (padding >= 0) {
3728            leftPadding = padding;
3729            topPadding = padding;
3730            rightPadding = padding;
3731            bottomPadding = padding;
3732            mUserPaddingLeftInitial = padding;
3733            mUserPaddingRightInitial = padding;
3734        }
3735
3736        if (isRtlCompatibilityMode()) {
3737            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3738            // left / right padding are used if defined (meaning here nothing to do). If they are not
3739            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3740            // start / end and resolve them as left / right (layout direction is not taken into account).
3741            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3742            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3743            // defined.
3744            if (!leftPaddingDefined && startPaddingDefined) {
3745                leftPadding = startPadding;
3746            }
3747            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3748            if (!rightPaddingDefined && endPaddingDefined) {
3749                rightPadding = endPadding;
3750            }
3751            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3752        } else {
3753            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3754            // values defined. Otherwise, left /right values are used.
3755            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3756            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3757            // defined.
3758            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3759
3760            if (leftPaddingDefined && !hasRelativePadding) {
3761                mUserPaddingLeftInitial = leftPadding;
3762            }
3763            if (rightPaddingDefined && !hasRelativePadding) {
3764                mUserPaddingRightInitial = rightPadding;
3765            }
3766        }
3767
3768        internalSetPadding(
3769                mUserPaddingLeftInitial,
3770                topPadding >= 0 ? topPadding : mPaddingTop,
3771                mUserPaddingRightInitial,
3772                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3773
3774        if (viewFlagMasks != 0) {
3775            setFlags(viewFlagValues, viewFlagMasks);
3776        }
3777
3778        if (initializeScrollbars) {
3779            initializeScrollbars(a);
3780        }
3781
3782        a.recycle();
3783
3784        // Needs to be called after mViewFlags is set
3785        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3786            recomputePadding();
3787        }
3788
3789        if (x != 0 || y != 0) {
3790            scrollTo(x, y);
3791        }
3792
3793        if (transformSet) {
3794            setTranslationX(tx);
3795            setTranslationY(ty);
3796            setRotation(rotation);
3797            setRotationX(rotationX);
3798            setRotationY(rotationY);
3799            setScaleX(sx);
3800            setScaleY(sy);
3801        }
3802
3803        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3804            setScrollContainer(true);
3805        }
3806
3807        computeOpaqueFlags();
3808    }
3809
3810    /**
3811     * Non-public constructor for use in testing
3812     */
3813    View() {
3814        mResources = null;
3815    }
3816
3817    public String toString() {
3818        StringBuilder out = new StringBuilder(128);
3819        out.append(getClass().getName());
3820        out.append('{');
3821        out.append(Integer.toHexString(System.identityHashCode(this)));
3822        out.append(' ');
3823        switch (mViewFlags&VISIBILITY_MASK) {
3824            case VISIBLE: out.append('V'); break;
3825            case INVISIBLE: out.append('I'); break;
3826            case GONE: out.append('G'); break;
3827            default: out.append('.'); break;
3828        }
3829        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3830        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3831        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3832        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3833        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3834        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3835        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3836        out.append(' ');
3837        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3838        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3839        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3840        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3841            out.append('p');
3842        } else {
3843            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3844        }
3845        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3846        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3847        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3848        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3849        out.append(' ');
3850        out.append(mLeft);
3851        out.append(',');
3852        out.append(mTop);
3853        out.append('-');
3854        out.append(mRight);
3855        out.append(',');
3856        out.append(mBottom);
3857        final int id = getId();
3858        if (id != NO_ID) {
3859            out.append(" #");
3860            out.append(Integer.toHexString(id));
3861            final Resources r = mResources;
3862            if (id != 0 && r != null) {
3863                try {
3864                    String pkgname;
3865                    switch (id&0xff000000) {
3866                        case 0x7f000000:
3867                            pkgname="app";
3868                            break;
3869                        case 0x01000000:
3870                            pkgname="android";
3871                            break;
3872                        default:
3873                            pkgname = r.getResourcePackageName(id);
3874                            break;
3875                    }
3876                    String typename = r.getResourceTypeName(id);
3877                    String entryname = r.getResourceEntryName(id);
3878                    out.append(" ");
3879                    out.append(pkgname);
3880                    out.append(":");
3881                    out.append(typename);
3882                    out.append("/");
3883                    out.append(entryname);
3884                } catch (Resources.NotFoundException e) {
3885                }
3886            }
3887        }
3888        out.append("}");
3889        return out.toString();
3890    }
3891
3892    /**
3893     * <p>
3894     * Initializes the fading edges from a given set of styled attributes. This
3895     * method should be called by subclasses that need fading edges and when an
3896     * instance of these subclasses is created programmatically rather than
3897     * being inflated from XML. This method is automatically called when the XML
3898     * is inflated.
3899     * </p>
3900     *
3901     * @param a the styled attributes set to initialize the fading edges from
3902     */
3903    protected void initializeFadingEdge(TypedArray a) {
3904        initScrollCache();
3905
3906        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3907                R.styleable.View_fadingEdgeLength,
3908                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3909    }
3910
3911    /**
3912     * Returns the size of the vertical faded edges used to indicate that more
3913     * content in this view is visible.
3914     *
3915     * @return The size in pixels of the vertical faded edge or 0 if vertical
3916     *         faded edges are not enabled for this view.
3917     * @attr ref android.R.styleable#View_fadingEdgeLength
3918     */
3919    public int getVerticalFadingEdgeLength() {
3920        if (isVerticalFadingEdgeEnabled()) {
3921            ScrollabilityCache cache = mScrollCache;
3922            if (cache != null) {
3923                return cache.fadingEdgeLength;
3924            }
3925        }
3926        return 0;
3927    }
3928
3929    /**
3930     * Set the size of the faded edge used to indicate that more content in this
3931     * view is available.  Will not change whether the fading edge is enabled; use
3932     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3933     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3934     * for the vertical or horizontal fading edges.
3935     *
3936     * @param length The size in pixels of the faded edge used to indicate that more
3937     *        content in this view is visible.
3938     */
3939    public void setFadingEdgeLength(int length) {
3940        initScrollCache();
3941        mScrollCache.fadingEdgeLength = length;
3942    }
3943
3944    /**
3945     * Returns the size of the horizontal faded edges used to indicate that more
3946     * content in this view is visible.
3947     *
3948     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3949     *         faded edges are not enabled for this view.
3950     * @attr ref android.R.styleable#View_fadingEdgeLength
3951     */
3952    public int getHorizontalFadingEdgeLength() {
3953        if (isHorizontalFadingEdgeEnabled()) {
3954            ScrollabilityCache cache = mScrollCache;
3955            if (cache != null) {
3956                return cache.fadingEdgeLength;
3957            }
3958        }
3959        return 0;
3960    }
3961
3962    /**
3963     * Returns the width of the vertical scrollbar.
3964     *
3965     * @return The width in pixels of the vertical scrollbar or 0 if there
3966     *         is no vertical scrollbar.
3967     */
3968    public int getVerticalScrollbarWidth() {
3969        ScrollabilityCache cache = mScrollCache;
3970        if (cache != null) {
3971            ScrollBarDrawable scrollBar = cache.scrollBar;
3972            if (scrollBar != null) {
3973                int size = scrollBar.getSize(true);
3974                if (size <= 0) {
3975                    size = cache.scrollBarSize;
3976                }
3977                return size;
3978            }
3979            return 0;
3980        }
3981        return 0;
3982    }
3983
3984    /**
3985     * Returns the height of the horizontal scrollbar.
3986     *
3987     * @return The height in pixels of the horizontal scrollbar or 0 if
3988     *         there is no horizontal scrollbar.
3989     */
3990    protected int getHorizontalScrollbarHeight() {
3991        ScrollabilityCache cache = mScrollCache;
3992        if (cache != null) {
3993            ScrollBarDrawable scrollBar = cache.scrollBar;
3994            if (scrollBar != null) {
3995                int size = scrollBar.getSize(false);
3996                if (size <= 0) {
3997                    size = cache.scrollBarSize;
3998                }
3999                return size;
4000            }
4001            return 0;
4002        }
4003        return 0;
4004    }
4005
4006    /**
4007     * <p>
4008     * Initializes the scrollbars from a given set of styled attributes. This
4009     * method should be called by subclasses that need scrollbars and when an
4010     * instance of these subclasses is created programmatically rather than
4011     * being inflated from XML. This method is automatically called when the XML
4012     * is inflated.
4013     * </p>
4014     *
4015     * @param a the styled attributes set to initialize the scrollbars from
4016     */
4017    protected void initializeScrollbars(TypedArray a) {
4018        initScrollCache();
4019
4020        final ScrollabilityCache scrollabilityCache = mScrollCache;
4021
4022        if (scrollabilityCache.scrollBar == null) {
4023            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4024        }
4025
4026        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4027
4028        if (!fadeScrollbars) {
4029            scrollabilityCache.state = ScrollabilityCache.ON;
4030        }
4031        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4032
4033
4034        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4035                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4036                        .getScrollBarFadeDuration());
4037        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4038                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4039                ViewConfiguration.getScrollDefaultDelay());
4040
4041
4042        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4043                com.android.internal.R.styleable.View_scrollbarSize,
4044                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4045
4046        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4047        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4048
4049        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4050        if (thumb != null) {
4051            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4052        }
4053
4054        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4055                false);
4056        if (alwaysDraw) {
4057            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4058        }
4059
4060        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4061        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4062
4063        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4064        if (thumb != null) {
4065            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4066        }
4067
4068        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4069                false);
4070        if (alwaysDraw) {
4071            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4072        }
4073
4074        // Apply layout direction to the new Drawables if needed
4075        final int layoutDirection = getLayoutDirection();
4076        if (track != null) {
4077            track.setLayoutDirection(layoutDirection);
4078        }
4079        if (thumb != null) {
4080            thumb.setLayoutDirection(layoutDirection);
4081        }
4082
4083        // Re-apply user/background padding so that scrollbar(s) get added
4084        resolvePadding();
4085    }
4086
4087    /**
4088     * <p>
4089     * Initalizes the scrollability cache if necessary.
4090     * </p>
4091     */
4092    private void initScrollCache() {
4093        if (mScrollCache == null) {
4094            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4095        }
4096    }
4097
4098    private ScrollabilityCache getScrollCache() {
4099        initScrollCache();
4100        return mScrollCache;
4101    }
4102
4103    /**
4104     * Set the position of the vertical scroll bar. Should be one of
4105     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4106     * {@link #SCROLLBAR_POSITION_RIGHT}.
4107     *
4108     * @param position Where the vertical scroll bar should be positioned.
4109     */
4110    public void setVerticalScrollbarPosition(int position) {
4111        if (mVerticalScrollbarPosition != position) {
4112            mVerticalScrollbarPosition = position;
4113            computeOpaqueFlags();
4114            resolvePadding();
4115        }
4116    }
4117
4118    /**
4119     * @return The position where the vertical scroll bar will show, if applicable.
4120     * @see #setVerticalScrollbarPosition(int)
4121     */
4122    public int getVerticalScrollbarPosition() {
4123        return mVerticalScrollbarPosition;
4124    }
4125
4126    ListenerInfo getListenerInfo() {
4127        if (mListenerInfo != null) {
4128            return mListenerInfo;
4129        }
4130        mListenerInfo = new ListenerInfo();
4131        return mListenerInfo;
4132    }
4133
4134    /**
4135     * Register a callback to be invoked when focus of this view changed.
4136     *
4137     * @param l The callback that will run.
4138     */
4139    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4140        getListenerInfo().mOnFocusChangeListener = l;
4141    }
4142
4143    /**
4144     * Add a listener that will be called when the bounds of the view change due to
4145     * layout processing.
4146     *
4147     * @param listener The listener that will be called when layout bounds change.
4148     */
4149    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4150        ListenerInfo li = getListenerInfo();
4151        if (li.mOnLayoutChangeListeners == null) {
4152            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4153        }
4154        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4155            li.mOnLayoutChangeListeners.add(listener);
4156        }
4157    }
4158
4159    /**
4160     * Remove a listener for layout changes.
4161     *
4162     * @param listener The listener for layout bounds change.
4163     */
4164    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4165        ListenerInfo li = mListenerInfo;
4166        if (li == null || li.mOnLayoutChangeListeners == null) {
4167            return;
4168        }
4169        li.mOnLayoutChangeListeners.remove(listener);
4170    }
4171
4172    /**
4173     * Add a listener for attach state changes.
4174     *
4175     * This listener will be called whenever this view is attached or detached
4176     * from a window. Remove the listener using
4177     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4178     *
4179     * @param listener Listener to attach
4180     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4181     */
4182    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4183        ListenerInfo li = getListenerInfo();
4184        if (li.mOnAttachStateChangeListeners == null) {
4185            li.mOnAttachStateChangeListeners
4186                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4187        }
4188        li.mOnAttachStateChangeListeners.add(listener);
4189    }
4190
4191    /**
4192     * Remove a listener for attach state changes. The listener will receive no further
4193     * notification of window attach/detach events.
4194     *
4195     * @param listener Listener to remove
4196     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4197     */
4198    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4199        ListenerInfo li = mListenerInfo;
4200        if (li == null || li.mOnAttachStateChangeListeners == null) {
4201            return;
4202        }
4203        li.mOnAttachStateChangeListeners.remove(listener);
4204    }
4205
4206    /**
4207     * Returns the focus-change callback registered for this view.
4208     *
4209     * @return The callback, or null if one is not registered.
4210     */
4211    public OnFocusChangeListener getOnFocusChangeListener() {
4212        ListenerInfo li = mListenerInfo;
4213        return li != null ? li.mOnFocusChangeListener : null;
4214    }
4215
4216    /**
4217     * Register a callback to be invoked when this view is clicked. If this view is not
4218     * clickable, it becomes clickable.
4219     *
4220     * @param l The callback that will run
4221     *
4222     * @see #setClickable(boolean)
4223     */
4224    public void setOnClickListener(OnClickListener l) {
4225        if (!isClickable()) {
4226            setClickable(true);
4227        }
4228        getListenerInfo().mOnClickListener = l;
4229    }
4230
4231    /**
4232     * Return whether this view has an attached OnClickListener.  Returns
4233     * true if there is a listener, false if there is none.
4234     */
4235    public boolean hasOnClickListeners() {
4236        ListenerInfo li = mListenerInfo;
4237        return (li != null && li.mOnClickListener != null);
4238    }
4239
4240    /**
4241     * Register a callback to be invoked when this view is clicked and held. If this view is not
4242     * long clickable, it becomes long clickable.
4243     *
4244     * @param l The callback that will run
4245     *
4246     * @see #setLongClickable(boolean)
4247     */
4248    public void setOnLongClickListener(OnLongClickListener l) {
4249        if (!isLongClickable()) {
4250            setLongClickable(true);
4251        }
4252        getListenerInfo().mOnLongClickListener = l;
4253    }
4254
4255    /**
4256     * Register a callback to be invoked when the context menu for this view is
4257     * being built. If this view is not long clickable, it becomes long clickable.
4258     *
4259     * @param l The callback that will run
4260     *
4261     */
4262    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4263        if (!isLongClickable()) {
4264            setLongClickable(true);
4265        }
4266        getListenerInfo().mOnCreateContextMenuListener = l;
4267    }
4268
4269    /**
4270     * Call this view's OnClickListener, if it is defined.  Performs all normal
4271     * actions associated with clicking: reporting accessibility event, playing
4272     * a sound, etc.
4273     *
4274     * @return True there was an assigned OnClickListener that was called, false
4275     *         otherwise is returned.
4276     */
4277    public boolean performClick() {
4278        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4279
4280        ListenerInfo li = mListenerInfo;
4281        if (li != null && li.mOnClickListener != null) {
4282            playSoundEffect(SoundEffectConstants.CLICK);
4283            li.mOnClickListener.onClick(this);
4284            return true;
4285        }
4286
4287        return false;
4288    }
4289
4290    /**
4291     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4292     * this only calls the listener, and does not do any associated clicking
4293     * actions like reporting an accessibility event.
4294     *
4295     * @return True there was an assigned OnClickListener that was called, false
4296     *         otherwise is returned.
4297     */
4298    public boolean callOnClick() {
4299        ListenerInfo li = mListenerInfo;
4300        if (li != null && li.mOnClickListener != null) {
4301            li.mOnClickListener.onClick(this);
4302            return true;
4303        }
4304        return false;
4305    }
4306
4307    /**
4308     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4309     * OnLongClickListener did not consume the event.
4310     *
4311     * @return True if one of the above receivers consumed the event, false otherwise.
4312     */
4313    public boolean performLongClick() {
4314        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4315
4316        boolean handled = false;
4317        ListenerInfo li = mListenerInfo;
4318        if (li != null && li.mOnLongClickListener != null) {
4319            handled = li.mOnLongClickListener.onLongClick(View.this);
4320        }
4321        if (!handled) {
4322            handled = showContextMenu();
4323        }
4324        if (handled) {
4325            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4326        }
4327        return handled;
4328    }
4329
4330    /**
4331     * Performs button-related actions during a touch down event.
4332     *
4333     * @param event The event.
4334     * @return True if the down was consumed.
4335     *
4336     * @hide
4337     */
4338    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4339        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4340            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4341                return true;
4342            }
4343        }
4344        return false;
4345    }
4346
4347    /**
4348     * Bring up the context menu for this view.
4349     *
4350     * @return Whether a context menu was displayed.
4351     */
4352    public boolean showContextMenu() {
4353        return getParent().showContextMenuForChild(this);
4354    }
4355
4356    /**
4357     * Bring up the context menu for this view, referring to the item under the specified point.
4358     *
4359     * @param x The referenced x coordinate.
4360     * @param y The referenced y coordinate.
4361     * @param metaState The keyboard modifiers that were pressed.
4362     * @return Whether a context menu was displayed.
4363     *
4364     * @hide
4365     */
4366    public boolean showContextMenu(float x, float y, int metaState) {
4367        return showContextMenu();
4368    }
4369
4370    /**
4371     * Start an action mode.
4372     *
4373     * @param callback Callback that will control the lifecycle of the action mode
4374     * @return The new action mode if it is started, null otherwise
4375     *
4376     * @see ActionMode
4377     */
4378    public ActionMode startActionMode(ActionMode.Callback callback) {
4379        ViewParent parent = getParent();
4380        if (parent == null) return null;
4381        return parent.startActionModeForChild(this, callback);
4382    }
4383
4384    /**
4385     * Register a callback to be invoked when a hardware key is pressed in this view.
4386     * Key presses in software input methods will generally not trigger the methods of
4387     * this listener.
4388     * @param l the key listener to attach to this view
4389     */
4390    public void setOnKeyListener(OnKeyListener l) {
4391        getListenerInfo().mOnKeyListener = l;
4392    }
4393
4394    /**
4395     * Register a callback to be invoked when a touch event is sent to this view.
4396     * @param l the touch listener to attach to this view
4397     */
4398    public void setOnTouchListener(OnTouchListener l) {
4399        getListenerInfo().mOnTouchListener = l;
4400    }
4401
4402    /**
4403     * Register a callback to be invoked when a generic motion event is sent to this view.
4404     * @param l the generic motion listener to attach to this view
4405     */
4406    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4407        getListenerInfo().mOnGenericMotionListener = l;
4408    }
4409
4410    /**
4411     * Register a callback to be invoked when a hover event is sent to this view.
4412     * @param l the hover listener to attach to this view
4413     */
4414    public void setOnHoverListener(OnHoverListener l) {
4415        getListenerInfo().mOnHoverListener = l;
4416    }
4417
4418    /**
4419     * Register a drag event listener callback object for this View. The parameter is
4420     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4421     * View, the system calls the
4422     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4423     * @param l An implementation of {@link android.view.View.OnDragListener}.
4424     */
4425    public void setOnDragListener(OnDragListener l) {
4426        getListenerInfo().mOnDragListener = l;
4427    }
4428
4429    /**
4430     * Give this view focus. This will cause
4431     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4432     *
4433     * Note: this does not check whether this {@link View} should get focus, it just
4434     * gives it focus no matter what.  It should only be called internally by framework
4435     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4436     *
4437     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4438     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4439     *        focus moved when requestFocus() is called. It may not always
4440     *        apply, in which case use the default View.FOCUS_DOWN.
4441     * @param previouslyFocusedRect The rectangle of the view that had focus
4442     *        prior in this View's coordinate system.
4443     */
4444    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4445        if (DBG) {
4446            System.out.println(this + " requestFocus()");
4447        }
4448
4449        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4450            mPrivateFlags |= PFLAG_FOCUSED;
4451
4452            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4453
4454            if (mParent != null) {
4455                mParent.requestChildFocus(this, this);
4456            }
4457
4458            if (mAttachInfo != null) {
4459                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4460            }
4461
4462            onFocusChanged(true, direction, previouslyFocusedRect);
4463            refreshDrawableState();
4464        }
4465    }
4466
4467    /**
4468     * Request that a rectangle of this view be visible on the screen,
4469     * scrolling if necessary just enough.
4470     *
4471     * <p>A View should call this if it maintains some notion of which part
4472     * of its content is interesting.  For example, a text editing view
4473     * should call this when its cursor moves.
4474     *
4475     * @param rectangle The rectangle.
4476     * @return Whether any parent scrolled.
4477     */
4478    public boolean requestRectangleOnScreen(Rect rectangle) {
4479        return requestRectangleOnScreen(rectangle, false);
4480    }
4481
4482    /**
4483     * Request that a rectangle of this view be visible on the screen,
4484     * scrolling if necessary just enough.
4485     *
4486     * <p>A View should call this if it maintains some notion of which part
4487     * of its content is interesting.  For example, a text editing view
4488     * should call this when its cursor moves.
4489     *
4490     * <p>When <code>immediate</code> is set to true, scrolling will not be
4491     * animated.
4492     *
4493     * @param rectangle The rectangle.
4494     * @param immediate True to forbid animated scrolling, false otherwise
4495     * @return Whether any parent scrolled.
4496     */
4497    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4498        if (mParent == null) {
4499            return false;
4500        }
4501
4502        View child = this;
4503
4504        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4505        position.set(rectangle);
4506
4507        ViewParent parent = mParent;
4508        boolean scrolled = false;
4509        while (parent != null) {
4510            rectangle.set((int) position.left, (int) position.top,
4511                    (int) position.right, (int) position.bottom);
4512
4513            scrolled |= parent.requestChildRectangleOnScreen(child,
4514                    rectangle, immediate);
4515
4516            if (!child.hasIdentityMatrix()) {
4517                child.getMatrix().mapRect(position);
4518            }
4519
4520            position.offset(child.mLeft, child.mTop);
4521
4522            if (!(parent instanceof View)) {
4523                break;
4524            }
4525
4526            View parentView = (View) parent;
4527
4528            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4529
4530            child = parentView;
4531            parent = child.getParent();
4532        }
4533
4534        return scrolled;
4535    }
4536
4537    /**
4538     * Called when this view wants to give up focus. If focus is cleared
4539     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4540     * <p>
4541     * <strong>Note:</strong> When a View clears focus the framework is trying
4542     * to give focus to the first focusable View from the top. Hence, if this
4543     * View is the first from the top that can take focus, then all callbacks
4544     * related to clearing focus will be invoked after wich the framework will
4545     * give focus to this view.
4546     * </p>
4547     */
4548    public void clearFocus() {
4549        if (DBG) {
4550            System.out.println(this + " clearFocus()");
4551        }
4552
4553        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4554            mPrivateFlags &= ~PFLAG_FOCUSED;
4555
4556            if (mParent != null) {
4557                mParent.clearChildFocus(this);
4558            }
4559
4560            onFocusChanged(false, 0, null);
4561
4562            refreshDrawableState();
4563
4564            if (!rootViewRequestFocus()) {
4565                notifyGlobalFocusCleared(this);
4566            }
4567        }
4568    }
4569
4570    void notifyGlobalFocusCleared(View oldFocus) {
4571        if (oldFocus != null && mAttachInfo != null) {
4572            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4573        }
4574    }
4575
4576    boolean rootViewRequestFocus() {
4577        final View root = getRootView();
4578        return root != null && root.requestFocus();
4579    }
4580
4581    /**
4582     * Called internally by the view system when a new view is getting focus.
4583     * This is what clears the old focus.
4584     */
4585    void unFocus() {
4586        if (DBG) {
4587            System.out.println(this + " unFocus()");
4588        }
4589
4590        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4591            mPrivateFlags &= ~PFLAG_FOCUSED;
4592
4593            onFocusChanged(false, 0, null);
4594            refreshDrawableState();
4595        }
4596    }
4597
4598    /**
4599     * Returns true if this view has focus iteself, or is the ancestor of the
4600     * view that has focus.
4601     *
4602     * @return True if this view has or contains focus, false otherwise.
4603     */
4604    @ViewDebug.ExportedProperty(category = "focus")
4605    public boolean hasFocus() {
4606        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4607    }
4608
4609    /**
4610     * Returns true if this view is focusable or if it contains a reachable View
4611     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4612     * is a View whose parents do not block descendants focus.
4613     *
4614     * Only {@link #VISIBLE} views are considered focusable.
4615     *
4616     * @return True if the view is focusable or if the view contains a focusable
4617     *         View, false otherwise.
4618     *
4619     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4620     */
4621    public boolean hasFocusable() {
4622        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4623    }
4624
4625    /**
4626     * Called by the view system when the focus state of this view changes.
4627     * When the focus change event is caused by directional navigation, direction
4628     * and previouslyFocusedRect provide insight into where the focus is coming from.
4629     * When overriding, be sure to call up through to the super class so that
4630     * the standard focus handling will occur.
4631     *
4632     * @param gainFocus True if the View has focus; false otherwise.
4633     * @param direction The direction focus has moved when requestFocus()
4634     *                  is called to give this view focus. Values are
4635     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4636     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4637     *                  It may not always apply, in which case use the default.
4638     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4639     *        system, of the previously focused view.  If applicable, this will be
4640     *        passed in as finer grained information about where the focus is coming
4641     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4642     */
4643    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4644        if (gainFocus) {
4645            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4646        } else {
4647            notifyViewAccessibilityStateChangedIfNeeded();
4648        }
4649
4650        InputMethodManager imm = InputMethodManager.peekInstance();
4651        if (!gainFocus) {
4652            if (isPressed()) {
4653                setPressed(false);
4654            }
4655            if (imm != null && mAttachInfo != null
4656                    && mAttachInfo.mHasWindowFocus) {
4657                imm.focusOut(this);
4658            }
4659            onFocusLost();
4660        } else if (imm != null && mAttachInfo != null
4661                && mAttachInfo.mHasWindowFocus) {
4662            imm.focusIn(this);
4663        }
4664
4665        invalidate(true);
4666        ListenerInfo li = mListenerInfo;
4667        if (li != null && li.mOnFocusChangeListener != null) {
4668            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4669        }
4670
4671        if (mAttachInfo != null) {
4672            mAttachInfo.mKeyDispatchState.reset(this);
4673        }
4674    }
4675
4676    /**
4677     * Sends an accessibility event of the given type. If accessibility is
4678     * not enabled this method has no effect. The default implementation calls
4679     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4680     * to populate information about the event source (this View), then calls
4681     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4682     * populate the text content of the event source including its descendants,
4683     * and last calls
4684     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4685     * on its parent to resuest sending of the event to interested parties.
4686     * <p>
4687     * If an {@link AccessibilityDelegate} has been specified via calling
4688     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4689     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4690     * responsible for handling this call.
4691     * </p>
4692     *
4693     * @param eventType The type of the event to send, as defined by several types from
4694     * {@link android.view.accessibility.AccessibilityEvent}, such as
4695     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4696     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4697     *
4698     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4699     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4700     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4701     * @see AccessibilityDelegate
4702     */
4703    public void sendAccessibilityEvent(int eventType) {
4704        // Excluded views do not send accessibility events.
4705        if (!includeForAccessibility()) {
4706            return;
4707        }
4708        if (mAccessibilityDelegate != null) {
4709            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4710        } else {
4711            sendAccessibilityEventInternal(eventType);
4712        }
4713    }
4714
4715    /**
4716     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4717     * {@link AccessibilityEvent} to make an announcement which is related to some
4718     * sort of a context change for which none of the events representing UI transitions
4719     * is a good fit. For example, announcing a new page in a book. If accessibility
4720     * is not enabled this method does nothing.
4721     *
4722     * @param text The announcement text.
4723     */
4724    public void announceForAccessibility(CharSequence text) {
4725        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4726            AccessibilityEvent event = AccessibilityEvent.obtain(
4727                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4728            onInitializeAccessibilityEvent(event);
4729            event.getText().add(text);
4730            event.setContentDescription(null);
4731            mParent.requestSendAccessibilityEvent(this, event);
4732        }
4733    }
4734
4735    /**
4736     * @see #sendAccessibilityEvent(int)
4737     *
4738     * Note: Called from the default {@link AccessibilityDelegate}.
4739     */
4740    void sendAccessibilityEventInternal(int eventType) {
4741        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4742            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4743        }
4744    }
4745
4746    /**
4747     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4748     * takes as an argument an empty {@link AccessibilityEvent} and does not
4749     * perform a check whether accessibility is enabled.
4750     * <p>
4751     * If an {@link AccessibilityDelegate} has been specified via calling
4752     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4753     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4754     * is responsible for handling this call.
4755     * </p>
4756     *
4757     * @param event The event to send.
4758     *
4759     * @see #sendAccessibilityEvent(int)
4760     */
4761    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4762        if (mAccessibilityDelegate != null) {
4763            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4764        } else {
4765            sendAccessibilityEventUncheckedInternal(event);
4766        }
4767    }
4768
4769    /**
4770     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4771     *
4772     * Note: Called from the default {@link AccessibilityDelegate}.
4773     */
4774    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4775        if (!isShown()) {
4776            return;
4777        }
4778        onInitializeAccessibilityEvent(event);
4779        // Only a subset of accessibility events populates text content.
4780        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4781            dispatchPopulateAccessibilityEvent(event);
4782        }
4783        // In the beginning we called #isShown(), so we know that getParent() is not null.
4784        getParent().requestSendAccessibilityEvent(this, event);
4785    }
4786
4787    /**
4788     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4789     * to its children for adding their text content to the event. Note that the
4790     * event text is populated in a separate dispatch path since we add to the
4791     * event not only the text of the source but also the text of all its descendants.
4792     * A typical implementation will call
4793     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4794     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4795     * on each child. Override this method if custom population of the event text
4796     * content is required.
4797     * <p>
4798     * If an {@link AccessibilityDelegate} has been specified via calling
4799     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4800     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4801     * is responsible for handling this call.
4802     * </p>
4803     * <p>
4804     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4805     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4806     * </p>
4807     *
4808     * @param event The event.
4809     *
4810     * @return True if the event population was completed.
4811     */
4812    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4813        if (mAccessibilityDelegate != null) {
4814            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4815        } else {
4816            return dispatchPopulateAccessibilityEventInternal(event);
4817        }
4818    }
4819
4820    /**
4821     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4822     *
4823     * Note: Called from the default {@link AccessibilityDelegate}.
4824     */
4825    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4826        onPopulateAccessibilityEvent(event);
4827        return false;
4828    }
4829
4830    /**
4831     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4832     * giving a chance to this View to populate the accessibility event with its
4833     * text content. While this method is free to modify event
4834     * attributes other than text content, doing so should normally be performed in
4835     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4836     * <p>
4837     * Example: Adding formatted date string to an accessibility event in addition
4838     *          to the text added by the super implementation:
4839     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4840     *     super.onPopulateAccessibilityEvent(event);
4841     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4842     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4843     *         mCurrentDate.getTimeInMillis(), flags);
4844     *     event.getText().add(selectedDateUtterance);
4845     * }</pre>
4846     * <p>
4847     * If an {@link AccessibilityDelegate} has been specified via calling
4848     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4849     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4850     * is responsible for handling this call.
4851     * </p>
4852     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4853     * information to the event, in case the default implementation has basic information to add.
4854     * </p>
4855     *
4856     * @param event The accessibility event which to populate.
4857     *
4858     * @see #sendAccessibilityEvent(int)
4859     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4860     */
4861    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4862        if (mAccessibilityDelegate != null) {
4863            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4864        } else {
4865            onPopulateAccessibilityEventInternal(event);
4866        }
4867    }
4868
4869    /**
4870     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4871     *
4872     * Note: Called from the default {@link AccessibilityDelegate}.
4873     */
4874    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4875
4876    }
4877
4878    /**
4879     * Initializes an {@link AccessibilityEvent} with information about
4880     * this View which is the event source. In other words, the source of
4881     * an accessibility event is the view whose state change triggered firing
4882     * the event.
4883     * <p>
4884     * Example: Setting the password property of an event in addition
4885     *          to properties set by the super implementation:
4886     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4887     *     super.onInitializeAccessibilityEvent(event);
4888     *     event.setPassword(true);
4889     * }</pre>
4890     * <p>
4891     * If an {@link AccessibilityDelegate} has been specified via calling
4892     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4893     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4894     * is responsible for handling this call.
4895     * </p>
4896     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4897     * information to the event, in case the default implementation has basic information to add.
4898     * </p>
4899     * @param event The event to initialize.
4900     *
4901     * @see #sendAccessibilityEvent(int)
4902     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4903     */
4904    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4905        if (mAccessibilityDelegate != null) {
4906            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4907        } else {
4908            onInitializeAccessibilityEventInternal(event);
4909        }
4910    }
4911
4912    /**
4913     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4914     *
4915     * Note: Called from the default {@link AccessibilityDelegate}.
4916     */
4917    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4918        event.setSource(this);
4919        event.setClassName(View.class.getName());
4920        event.setPackageName(getContext().getPackageName());
4921        event.setEnabled(isEnabled());
4922        event.setContentDescription(mContentDescription);
4923
4924        switch (event.getEventType()) {
4925            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4926                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4927                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4928                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4929                event.setItemCount(focusablesTempList.size());
4930                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4931                if (mAttachInfo != null) {
4932                    focusablesTempList.clear();
4933                }
4934            } break;
4935            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4936                CharSequence text = getIterableTextForAccessibility();
4937                if (text != null && text.length() > 0) {
4938                    event.setFromIndex(getAccessibilitySelectionStart());
4939                    event.setToIndex(getAccessibilitySelectionEnd());
4940                    event.setItemCount(text.length());
4941                }
4942            } break;
4943        }
4944    }
4945
4946    /**
4947     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4948     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4949     * This method is responsible for obtaining an accessibility node info from a
4950     * pool of reusable instances and calling
4951     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4952     * initialize the former.
4953     * <p>
4954     * Note: The client is responsible for recycling the obtained instance by calling
4955     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4956     * </p>
4957     *
4958     * @return A populated {@link AccessibilityNodeInfo}.
4959     *
4960     * @see AccessibilityNodeInfo
4961     */
4962    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4963        if (mAccessibilityDelegate != null) {
4964            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
4965        } else {
4966            return createAccessibilityNodeInfoInternal();
4967        }
4968    }
4969
4970    /**
4971     * @see #createAccessibilityNodeInfo()
4972     */
4973    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
4974        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4975        if (provider != null) {
4976            return provider.createAccessibilityNodeInfo(View.NO_ID);
4977        } else {
4978            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4979            onInitializeAccessibilityNodeInfo(info);
4980            return info;
4981        }
4982    }
4983
4984    /**
4985     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4986     * The base implementation sets:
4987     * <ul>
4988     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4989     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4990     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4991     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4992     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4993     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4994     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4995     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4996     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4997     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4998     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4999     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5000     * </ul>
5001     * <p>
5002     * Subclasses should override this method, call the super implementation,
5003     * and set additional attributes.
5004     * </p>
5005     * <p>
5006     * If an {@link AccessibilityDelegate} has been specified via calling
5007     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5008     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5009     * is responsible for handling this call.
5010     * </p>
5011     *
5012     * @param info The instance to initialize.
5013     */
5014    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5015        if (mAccessibilityDelegate != null) {
5016            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5017        } else {
5018            onInitializeAccessibilityNodeInfoInternal(info);
5019        }
5020    }
5021
5022    /**
5023     * Gets the location of this view in screen coordintates.
5024     *
5025     * @param outRect The output location
5026     */
5027    void getBoundsOnScreen(Rect outRect) {
5028        if (mAttachInfo == null) {
5029            return;
5030        }
5031
5032        RectF position = mAttachInfo.mTmpTransformRect;
5033        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5034
5035        if (!hasIdentityMatrix()) {
5036            getMatrix().mapRect(position);
5037        }
5038
5039        position.offset(mLeft, mTop);
5040
5041        ViewParent parent = mParent;
5042        while (parent instanceof View) {
5043            View parentView = (View) parent;
5044
5045            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5046
5047            if (!parentView.hasIdentityMatrix()) {
5048                parentView.getMatrix().mapRect(position);
5049            }
5050
5051            position.offset(parentView.mLeft, parentView.mTop);
5052
5053            parent = parentView.mParent;
5054        }
5055
5056        if (parent instanceof ViewRootImpl) {
5057            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5058            position.offset(0, -viewRootImpl.mCurScrollY);
5059        }
5060
5061        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5062
5063        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5064                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5065    }
5066
5067    /**
5068     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5069     *
5070     * Note: Called from the default {@link AccessibilityDelegate}.
5071     */
5072    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5073        Rect bounds = mAttachInfo.mTmpInvalRect;
5074
5075        getDrawingRect(bounds);
5076        info.setBoundsInParent(bounds);
5077
5078        getBoundsOnScreen(bounds);
5079        info.setBoundsInScreen(bounds);
5080
5081        ViewParent parent = getParentForAccessibility();
5082        if (parent instanceof View) {
5083            info.setParent((View) parent);
5084        }
5085
5086        if (mID != View.NO_ID) {
5087            View rootView = getRootView();
5088            if (rootView == null) {
5089                rootView = this;
5090            }
5091            View label = rootView.findLabelForView(this, mID);
5092            if (label != null) {
5093                info.setLabeledBy(label);
5094            }
5095
5096            if ((mAttachInfo.mAccessibilityFetchFlags
5097                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5098                    && Resources.resourceHasPackage(mID)) {
5099                try {
5100                    String viewId = getResources().getResourceName(mID);
5101                    info.setViewIdResourceName(viewId);
5102                } catch (Resources.NotFoundException nfe) {
5103                    /* ignore */
5104                }
5105            }
5106        }
5107
5108        if (mLabelForId != View.NO_ID) {
5109            View rootView = getRootView();
5110            if (rootView == null) {
5111                rootView = this;
5112            }
5113            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5114            if (labeled != null) {
5115                info.setLabelFor(labeled);
5116            }
5117        }
5118
5119        info.setVisibleToUser(isVisibleToUser());
5120
5121        info.setPackageName(mContext.getPackageName());
5122        info.setClassName(View.class.getName());
5123        info.setContentDescription(getContentDescription());
5124
5125        info.setEnabled(isEnabled());
5126        info.setClickable(isClickable());
5127        info.setFocusable(isFocusable());
5128        info.setFocused(isFocused());
5129        info.setAccessibilityFocused(isAccessibilityFocused());
5130        info.setSelected(isSelected());
5131        info.setLongClickable(isLongClickable());
5132
5133        // TODO: These make sense only if we are in an AdapterView but all
5134        // views can be selected. Maybe from accessibility perspective
5135        // we should report as selectable view in an AdapterView.
5136        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5137        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5138
5139        if (isFocusable()) {
5140            if (isFocused()) {
5141                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5142            } else {
5143                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5144            }
5145        }
5146
5147        if (!isAccessibilityFocused()) {
5148            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5149        } else {
5150            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5151        }
5152
5153        if (isClickable() && isEnabled()) {
5154            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5155        }
5156
5157        if (isLongClickable() && isEnabled()) {
5158            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5159        }
5160
5161        CharSequence text = getIterableTextForAccessibility();
5162        if (text != null && text.length() > 0) {
5163            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5164
5165            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5166            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5167            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5168            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5169                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5170                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5171        }
5172    }
5173
5174    private View findLabelForView(View view, int labeledId) {
5175        if (mMatchLabelForPredicate == null) {
5176            mMatchLabelForPredicate = new MatchLabelForPredicate();
5177        }
5178        mMatchLabelForPredicate.mLabeledId = labeledId;
5179        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5180    }
5181
5182    /**
5183     * Computes whether this view is visible to the user. Such a view is
5184     * attached, visible, all its predecessors are visible, it is not clipped
5185     * entirely by its predecessors, and has an alpha greater than zero.
5186     *
5187     * @return Whether the view is visible on the screen.
5188     *
5189     * @hide
5190     */
5191    protected boolean isVisibleToUser() {
5192        return isVisibleToUser(null);
5193    }
5194
5195    /**
5196     * Computes whether the given portion of this view is visible to the user.
5197     * Such a view is attached, visible, all its predecessors are visible,
5198     * has an alpha greater than zero, and the specified portion is not
5199     * clipped entirely by its predecessors.
5200     *
5201     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5202     *                    <code>null</code>, and the entire view will be tested in this case.
5203     *                    When <code>true</code> is returned by the function, the actual visible
5204     *                    region will be stored in this parameter; that is, if boundInView is fully
5205     *                    contained within the view, no modification will be made, otherwise regions
5206     *                    outside of the visible area of the view will be clipped.
5207     *
5208     * @return Whether the specified portion of the view is visible on the screen.
5209     *
5210     * @hide
5211     */
5212    protected boolean isVisibleToUser(Rect boundInView) {
5213        if (mAttachInfo != null) {
5214            // Attached to invisible window means this view is not visible.
5215            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5216                return false;
5217            }
5218            // An invisible predecessor or one with alpha zero means
5219            // that this view is not visible to the user.
5220            Object current = this;
5221            while (current instanceof View) {
5222                View view = (View) current;
5223                // We have attach info so this view is attached and there is no
5224                // need to check whether we reach to ViewRootImpl on the way up.
5225                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5226                    return false;
5227                }
5228                current = view.mParent;
5229            }
5230            // Check if the view is entirely covered by its predecessors.
5231            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5232            Point offset = mAttachInfo.mPoint;
5233            if (!getGlobalVisibleRect(visibleRect, offset)) {
5234                return false;
5235            }
5236            // Check if the visible portion intersects the rectangle of interest.
5237            if (boundInView != null) {
5238                visibleRect.offset(-offset.x, -offset.y);
5239                return boundInView.intersect(visibleRect);
5240            }
5241            return true;
5242        }
5243        return false;
5244    }
5245
5246    /**
5247     * Returns the delegate for implementing accessibility support via
5248     * composition. For more details see {@link AccessibilityDelegate}.
5249     *
5250     * @return The delegate, or null if none set.
5251     *
5252     * @hide
5253     */
5254    public AccessibilityDelegate getAccessibilityDelegate() {
5255        return mAccessibilityDelegate;
5256    }
5257
5258    /**
5259     * Sets a delegate for implementing accessibility support via composition as
5260     * opposed to inheritance. The delegate's primary use is for implementing
5261     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5262     *
5263     * @param delegate The delegate instance.
5264     *
5265     * @see AccessibilityDelegate
5266     */
5267    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5268        mAccessibilityDelegate = delegate;
5269    }
5270
5271    /**
5272     * Gets the provider for managing a virtual view hierarchy rooted at this View
5273     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5274     * that explore the window content.
5275     * <p>
5276     * If this method returns an instance, this instance is responsible for managing
5277     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5278     * View including the one representing the View itself. Similarly the returned
5279     * instance is responsible for performing accessibility actions on any virtual
5280     * view or the root view itself.
5281     * </p>
5282     * <p>
5283     * If an {@link AccessibilityDelegate} has been specified via calling
5284     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5285     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5286     * is responsible for handling this call.
5287     * </p>
5288     *
5289     * @return The provider.
5290     *
5291     * @see AccessibilityNodeProvider
5292     */
5293    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5294        if (mAccessibilityDelegate != null) {
5295            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5296        } else {
5297            return null;
5298        }
5299    }
5300
5301    /**
5302     * Gets the unique identifier of this view on the screen for accessibility purposes.
5303     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5304     *
5305     * @return The view accessibility id.
5306     *
5307     * @hide
5308     */
5309    public int getAccessibilityViewId() {
5310        if (mAccessibilityViewId == NO_ID) {
5311            mAccessibilityViewId = sNextAccessibilityViewId++;
5312        }
5313        return mAccessibilityViewId;
5314    }
5315
5316    /**
5317     * Gets the unique identifier of the window in which this View reseides.
5318     *
5319     * @return The window accessibility id.
5320     *
5321     * @hide
5322     */
5323    public int getAccessibilityWindowId() {
5324        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5325    }
5326
5327    /**
5328     * Gets the {@link View} description. It briefly describes the view and is
5329     * primarily used for accessibility support. Set this property to enable
5330     * better accessibility support for your application. This is especially
5331     * true for views that do not have textual representation (For example,
5332     * ImageButton).
5333     *
5334     * @return The content description.
5335     *
5336     * @attr ref android.R.styleable#View_contentDescription
5337     */
5338    @ViewDebug.ExportedProperty(category = "accessibility")
5339    public CharSequence getContentDescription() {
5340        return mContentDescription;
5341    }
5342
5343    /**
5344     * Sets the {@link View} description. It briefly describes the view and is
5345     * primarily used for accessibility support. Set this property to enable
5346     * better accessibility support for your application. This is especially
5347     * true for views that do not have textual representation (For example,
5348     * ImageButton).
5349     *
5350     * @param contentDescription The content description.
5351     *
5352     * @attr ref android.R.styleable#View_contentDescription
5353     */
5354    @RemotableViewMethod
5355    public void setContentDescription(CharSequence contentDescription) {
5356        if (mContentDescription == null) {
5357            if (contentDescription == null) {
5358                return;
5359            }
5360        } else if (mContentDescription.equals(contentDescription)) {
5361            return;
5362        }
5363        mContentDescription = contentDescription;
5364        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5365        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5366            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5367            notifySubtreeAccessibilityStateChangedIfNeeded();
5368        } else {
5369            notifyViewAccessibilityStateChangedIfNeeded();
5370        }
5371    }
5372
5373    /**
5374     * Gets the id of a view for which this view serves as a label for
5375     * accessibility purposes.
5376     *
5377     * @return The labeled view id.
5378     */
5379    @ViewDebug.ExportedProperty(category = "accessibility")
5380    public int getLabelFor() {
5381        return mLabelForId;
5382    }
5383
5384    /**
5385     * Sets the id of a view for which this view serves as a label for
5386     * accessibility purposes.
5387     *
5388     * @param id The labeled view id.
5389     */
5390    @RemotableViewMethod
5391    public void setLabelFor(int id) {
5392        mLabelForId = id;
5393        if (mLabelForId != View.NO_ID
5394                && mID == View.NO_ID) {
5395            mID = generateViewId();
5396        }
5397    }
5398
5399    /**
5400     * Invoked whenever this view loses focus, either by losing window focus or by losing
5401     * focus within its window. This method can be used to clear any state tied to the
5402     * focus. For instance, if a button is held pressed with the trackball and the window
5403     * loses focus, this method can be used to cancel the press.
5404     *
5405     * Subclasses of View overriding this method should always call super.onFocusLost().
5406     *
5407     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5408     * @see #onWindowFocusChanged(boolean)
5409     *
5410     * @hide pending API council approval
5411     */
5412    protected void onFocusLost() {
5413        resetPressedState();
5414    }
5415
5416    private void resetPressedState() {
5417        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5418            return;
5419        }
5420
5421        if (isPressed()) {
5422            setPressed(false);
5423
5424            if (!mHasPerformedLongPress) {
5425                removeLongPressCallback();
5426            }
5427        }
5428    }
5429
5430    /**
5431     * Returns true if this view has focus
5432     *
5433     * @return True if this view has focus, false otherwise.
5434     */
5435    @ViewDebug.ExportedProperty(category = "focus")
5436    public boolean isFocused() {
5437        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5438    }
5439
5440    /**
5441     * Find the view in the hierarchy rooted at this view that currently has
5442     * focus.
5443     *
5444     * @return The view that currently has focus, or null if no focused view can
5445     *         be found.
5446     */
5447    public View findFocus() {
5448        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5449    }
5450
5451    /**
5452     * Indicates whether this view is one of the set of scrollable containers in
5453     * its window.
5454     *
5455     * @return whether this view is one of the set of scrollable containers in
5456     * its window
5457     *
5458     * @attr ref android.R.styleable#View_isScrollContainer
5459     */
5460    public boolean isScrollContainer() {
5461        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5462    }
5463
5464    /**
5465     * Change whether this view is one of the set of scrollable containers in
5466     * its window.  This will be used to determine whether the window can
5467     * resize or must pan when a soft input area is open -- scrollable
5468     * containers allow the window to use resize mode since the container
5469     * will appropriately shrink.
5470     *
5471     * @attr ref android.R.styleable#View_isScrollContainer
5472     */
5473    public void setScrollContainer(boolean isScrollContainer) {
5474        if (isScrollContainer) {
5475            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5476                mAttachInfo.mScrollContainers.add(this);
5477                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5478            }
5479            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5480        } else {
5481            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5482                mAttachInfo.mScrollContainers.remove(this);
5483            }
5484            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5485        }
5486    }
5487
5488    /**
5489     * Returns the quality of the drawing cache.
5490     *
5491     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5492     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5493     *
5494     * @see #setDrawingCacheQuality(int)
5495     * @see #setDrawingCacheEnabled(boolean)
5496     * @see #isDrawingCacheEnabled()
5497     *
5498     * @attr ref android.R.styleable#View_drawingCacheQuality
5499     */
5500    public int getDrawingCacheQuality() {
5501        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5502    }
5503
5504    /**
5505     * Set the drawing cache quality of this view. This value is used only when the
5506     * drawing cache is enabled
5507     *
5508     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5509     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5510     *
5511     * @see #getDrawingCacheQuality()
5512     * @see #setDrawingCacheEnabled(boolean)
5513     * @see #isDrawingCacheEnabled()
5514     *
5515     * @attr ref android.R.styleable#View_drawingCacheQuality
5516     */
5517    public void setDrawingCacheQuality(int quality) {
5518        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5519    }
5520
5521    /**
5522     * Returns whether the screen should remain on, corresponding to the current
5523     * value of {@link #KEEP_SCREEN_ON}.
5524     *
5525     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5526     *
5527     * @see #setKeepScreenOn(boolean)
5528     *
5529     * @attr ref android.R.styleable#View_keepScreenOn
5530     */
5531    public boolean getKeepScreenOn() {
5532        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5533    }
5534
5535    /**
5536     * Controls whether the screen should remain on, modifying the
5537     * value of {@link #KEEP_SCREEN_ON}.
5538     *
5539     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5540     *
5541     * @see #getKeepScreenOn()
5542     *
5543     * @attr ref android.R.styleable#View_keepScreenOn
5544     */
5545    public void setKeepScreenOn(boolean keepScreenOn) {
5546        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5547    }
5548
5549    /**
5550     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5551     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5552     *
5553     * @attr ref android.R.styleable#View_nextFocusLeft
5554     */
5555    public int getNextFocusLeftId() {
5556        return mNextFocusLeftId;
5557    }
5558
5559    /**
5560     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5561     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5562     * decide automatically.
5563     *
5564     * @attr ref android.R.styleable#View_nextFocusLeft
5565     */
5566    public void setNextFocusLeftId(int nextFocusLeftId) {
5567        mNextFocusLeftId = nextFocusLeftId;
5568    }
5569
5570    /**
5571     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5572     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5573     *
5574     * @attr ref android.R.styleable#View_nextFocusRight
5575     */
5576    public int getNextFocusRightId() {
5577        return mNextFocusRightId;
5578    }
5579
5580    /**
5581     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5582     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5583     * decide automatically.
5584     *
5585     * @attr ref android.R.styleable#View_nextFocusRight
5586     */
5587    public void setNextFocusRightId(int nextFocusRightId) {
5588        mNextFocusRightId = nextFocusRightId;
5589    }
5590
5591    /**
5592     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5593     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5594     *
5595     * @attr ref android.R.styleable#View_nextFocusUp
5596     */
5597    public int getNextFocusUpId() {
5598        return mNextFocusUpId;
5599    }
5600
5601    /**
5602     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5603     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5604     * decide automatically.
5605     *
5606     * @attr ref android.R.styleable#View_nextFocusUp
5607     */
5608    public void setNextFocusUpId(int nextFocusUpId) {
5609        mNextFocusUpId = nextFocusUpId;
5610    }
5611
5612    /**
5613     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5614     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5615     *
5616     * @attr ref android.R.styleable#View_nextFocusDown
5617     */
5618    public int getNextFocusDownId() {
5619        return mNextFocusDownId;
5620    }
5621
5622    /**
5623     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5624     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5625     * decide automatically.
5626     *
5627     * @attr ref android.R.styleable#View_nextFocusDown
5628     */
5629    public void setNextFocusDownId(int nextFocusDownId) {
5630        mNextFocusDownId = nextFocusDownId;
5631    }
5632
5633    /**
5634     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5635     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5636     *
5637     * @attr ref android.R.styleable#View_nextFocusForward
5638     */
5639    public int getNextFocusForwardId() {
5640        return mNextFocusForwardId;
5641    }
5642
5643    /**
5644     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5645     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5646     * decide automatically.
5647     *
5648     * @attr ref android.R.styleable#View_nextFocusForward
5649     */
5650    public void setNextFocusForwardId(int nextFocusForwardId) {
5651        mNextFocusForwardId = nextFocusForwardId;
5652    }
5653
5654    /**
5655     * Returns the visibility of this view and all of its ancestors
5656     *
5657     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5658     */
5659    public boolean isShown() {
5660        View current = this;
5661        //noinspection ConstantConditions
5662        do {
5663            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5664                return false;
5665            }
5666            ViewParent parent = current.mParent;
5667            if (parent == null) {
5668                return false; // We are not attached to the view root
5669            }
5670            if (!(parent instanceof View)) {
5671                return true;
5672            }
5673            current = (View) parent;
5674        } while (current != null);
5675
5676        return false;
5677    }
5678
5679    /**
5680     * Called by the view hierarchy when the content insets for a window have
5681     * changed, to allow it to adjust its content to fit within those windows.
5682     * The content insets tell you the space that the status bar, input method,
5683     * and other system windows infringe on the application's window.
5684     *
5685     * <p>You do not normally need to deal with this function, since the default
5686     * window decoration given to applications takes care of applying it to the
5687     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5688     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5689     * and your content can be placed under those system elements.  You can then
5690     * use this method within your view hierarchy if you have parts of your UI
5691     * which you would like to ensure are not being covered.
5692     *
5693     * <p>The default implementation of this method simply applies the content
5694     * inset's to the view's padding, consuming that content (modifying the
5695     * insets to be 0), and returning true.  This behavior is off by default, but can
5696     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5697     *
5698     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5699     * insets object is propagated down the hierarchy, so any changes made to it will
5700     * be seen by all following views (including potentially ones above in
5701     * the hierarchy since this is a depth-first traversal).  The first view
5702     * that returns true will abort the entire traversal.
5703     *
5704     * <p>The default implementation works well for a situation where it is
5705     * used with a container that covers the entire window, allowing it to
5706     * apply the appropriate insets to its content on all edges.  If you need
5707     * a more complicated layout (such as two different views fitting system
5708     * windows, one on the top of the window, and one on the bottom),
5709     * you can override the method and handle the insets however you would like.
5710     * Note that the insets provided by the framework are always relative to the
5711     * far edges of the window, not accounting for the location of the called view
5712     * within that window.  (In fact when this method is called you do not yet know
5713     * where the layout will place the view, as it is done before layout happens.)
5714     *
5715     * <p>Note: unlike many View methods, there is no dispatch phase to this
5716     * call.  If you are overriding it in a ViewGroup and want to allow the
5717     * call to continue to your children, you must be sure to call the super
5718     * implementation.
5719     *
5720     * <p>Here is a sample layout that makes use of fitting system windows
5721     * to have controls for a video view placed inside of the window decorations
5722     * that it hides and shows.  This can be used with code like the second
5723     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5724     *
5725     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5726     *
5727     * @param insets Current content insets of the window.  Prior to
5728     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5729     * the insets or else you and Android will be unhappy.
5730     *
5731     * @return Return true if this view applied the insets and it should not
5732     * continue propagating further down the hierarchy, false otherwise.
5733     * @see #getFitsSystemWindows()
5734     * @see #setFitsSystemWindows(boolean)
5735     * @see #setSystemUiVisibility(int)
5736     */
5737    protected boolean fitSystemWindows(Rect insets) {
5738        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5739            mUserPaddingStart = UNDEFINED_PADDING;
5740            mUserPaddingEnd = UNDEFINED_PADDING;
5741            Rect localInsets = sThreadLocal.get();
5742            if (localInsets == null) {
5743                localInsets = new Rect();
5744                sThreadLocal.set(localInsets);
5745            }
5746            boolean res = computeFitSystemWindows(insets, localInsets);
5747            internalSetPadding(localInsets.left, localInsets.top,
5748                    localInsets.right, localInsets.bottom);
5749            return res;
5750        }
5751        return false;
5752    }
5753
5754    /**
5755     * @hide Compute the insets that should be consumed by this view and the ones
5756     * that should propagate to those under it.
5757     */
5758    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5759        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5760                || mAttachInfo == null
5761                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5762                        && !mAttachInfo.mOverscanRequested)) {
5763            outLocalInsets.set(inoutInsets);
5764            inoutInsets.set(0, 0, 0, 0);
5765            return true;
5766        } else {
5767            // The application wants to take care of fitting system window for
5768            // the content...  however we still need to take care of any overscan here.
5769            final Rect overscan = mAttachInfo.mOverscanInsets;
5770            outLocalInsets.set(overscan);
5771            inoutInsets.left -= overscan.left;
5772            inoutInsets.top -= overscan.top;
5773            inoutInsets.right -= overscan.right;
5774            inoutInsets.bottom -= overscan.bottom;
5775            return false;
5776        }
5777    }
5778
5779    /**
5780     * Sets whether or not this view should account for system screen decorations
5781     * such as the status bar and inset its content; that is, controlling whether
5782     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5783     * executed.  See that method for more details.
5784     *
5785     * <p>Note that if you are providing your own implementation of
5786     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5787     * flag to true -- your implementation will be overriding the default
5788     * implementation that checks this flag.
5789     *
5790     * @param fitSystemWindows If true, then the default implementation of
5791     * {@link #fitSystemWindows(Rect)} will be executed.
5792     *
5793     * @attr ref android.R.styleable#View_fitsSystemWindows
5794     * @see #getFitsSystemWindows()
5795     * @see #fitSystemWindows(Rect)
5796     * @see #setSystemUiVisibility(int)
5797     */
5798    public void setFitsSystemWindows(boolean fitSystemWindows) {
5799        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5800    }
5801
5802    /**
5803     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5804     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5805     * will be executed.
5806     *
5807     * @return Returns true if the default implementation of
5808     * {@link #fitSystemWindows(Rect)} will be executed.
5809     *
5810     * @attr ref android.R.styleable#View_fitsSystemWindows
5811     * @see #setFitsSystemWindows()
5812     * @see #fitSystemWindows(Rect)
5813     * @see #setSystemUiVisibility(int)
5814     */
5815    public boolean getFitsSystemWindows() {
5816        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5817    }
5818
5819    /** @hide */
5820    public boolean fitsSystemWindows() {
5821        return getFitsSystemWindows();
5822    }
5823
5824    /**
5825     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5826     */
5827    public void requestFitSystemWindows() {
5828        if (mParent != null) {
5829            mParent.requestFitSystemWindows();
5830        }
5831    }
5832
5833    /**
5834     * For use by PhoneWindow to make its own system window fitting optional.
5835     * @hide
5836     */
5837    public void makeOptionalFitsSystemWindows() {
5838        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5839    }
5840
5841    /**
5842     * Returns the visibility status for this view.
5843     *
5844     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5845     * @attr ref android.R.styleable#View_visibility
5846     */
5847    @ViewDebug.ExportedProperty(mapping = {
5848        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5849        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5850        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5851    })
5852    public int getVisibility() {
5853        return mViewFlags & VISIBILITY_MASK;
5854    }
5855
5856    /**
5857     * Set the enabled state of this view.
5858     *
5859     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5860     * @attr ref android.R.styleable#View_visibility
5861     */
5862    @RemotableViewMethod
5863    public void setVisibility(int visibility) {
5864        setFlags(visibility, VISIBILITY_MASK);
5865        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5866    }
5867
5868    /**
5869     * Returns the enabled status for this view. The interpretation of the
5870     * enabled state varies by subclass.
5871     *
5872     * @return True if this view is enabled, false otherwise.
5873     */
5874    @ViewDebug.ExportedProperty
5875    public boolean isEnabled() {
5876        return (mViewFlags & ENABLED_MASK) == ENABLED;
5877    }
5878
5879    /**
5880     * Set the enabled state of this view. The interpretation of the enabled
5881     * state varies by subclass.
5882     *
5883     * @param enabled True if this view is enabled, false otherwise.
5884     */
5885    @RemotableViewMethod
5886    public void setEnabled(boolean enabled) {
5887        if (enabled == isEnabled()) return;
5888
5889        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5890
5891        /*
5892         * The View most likely has to change its appearance, so refresh
5893         * the drawable state.
5894         */
5895        refreshDrawableState();
5896
5897        // Invalidate too, since the default behavior for views is to be
5898        // be drawn at 50% alpha rather than to change the drawable.
5899        invalidate(true);
5900    }
5901
5902    /**
5903     * Set whether this view can receive the focus.
5904     *
5905     * Setting this to false will also ensure that this view is not focusable
5906     * in touch mode.
5907     *
5908     * @param focusable If true, this view can receive the focus.
5909     *
5910     * @see #setFocusableInTouchMode(boolean)
5911     * @attr ref android.R.styleable#View_focusable
5912     */
5913    public void setFocusable(boolean focusable) {
5914        if (!focusable) {
5915            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5916        }
5917        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5918    }
5919
5920    /**
5921     * Set whether this view can receive focus while in touch mode.
5922     *
5923     * Setting this to true will also ensure that this view is focusable.
5924     *
5925     * @param focusableInTouchMode If true, this view can receive the focus while
5926     *   in touch mode.
5927     *
5928     * @see #setFocusable(boolean)
5929     * @attr ref android.R.styleable#View_focusableInTouchMode
5930     */
5931    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5932        // Focusable in touch mode should always be set before the focusable flag
5933        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5934        // which, in touch mode, will not successfully request focus on this view
5935        // because the focusable in touch mode flag is not set
5936        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5937        if (focusableInTouchMode) {
5938            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5939        }
5940    }
5941
5942    /**
5943     * Set whether this view should have sound effects enabled for events such as
5944     * clicking and touching.
5945     *
5946     * <p>You may wish to disable sound effects for a view if you already play sounds,
5947     * for instance, a dial key that plays dtmf tones.
5948     *
5949     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5950     * @see #isSoundEffectsEnabled()
5951     * @see #playSoundEffect(int)
5952     * @attr ref android.R.styleable#View_soundEffectsEnabled
5953     */
5954    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5955        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5956    }
5957
5958    /**
5959     * @return whether this view should have sound effects enabled for events such as
5960     *     clicking and touching.
5961     *
5962     * @see #setSoundEffectsEnabled(boolean)
5963     * @see #playSoundEffect(int)
5964     * @attr ref android.R.styleable#View_soundEffectsEnabled
5965     */
5966    @ViewDebug.ExportedProperty
5967    public boolean isSoundEffectsEnabled() {
5968        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5969    }
5970
5971    /**
5972     * Set whether this view should have haptic feedback for events such as
5973     * long presses.
5974     *
5975     * <p>You may wish to disable haptic feedback if your view already controls
5976     * its own haptic feedback.
5977     *
5978     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5979     * @see #isHapticFeedbackEnabled()
5980     * @see #performHapticFeedback(int)
5981     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5982     */
5983    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5984        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5985    }
5986
5987    /**
5988     * @return whether this view should have haptic feedback enabled for events
5989     * long presses.
5990     *
5991     * @see #setHapticFeedbackEnabled(boolean)
5992     * @see #performHapticFeedback(int)
5993     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5994     */
5995    @ViewDebug.ExportedProperty
5996    public boolean isHapticFeedbackEnabled() {
5997        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5998    }
5999
6000    /**
6001     * Returns the layout direction for this view.
6002     *
6003     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6004     *   {@link #LAYOUT_DIRECTION_RTL},
6005     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6006     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6007     *
6008     * @attr ref android.R.styleable#View_layoutDirection
6009     *
6010     * @hide
6011     */
6012    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6013        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6014        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6015        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6016        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6017    })
6018    public int getRawLayoutDirection() {
6019        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6020    }
6021
6022    /**
6023     * Set the layout direction for this view. This will propagate a reset of layout direction
6024     * resolution to the view's children and resolve layout direction for this view.
6025     *
6026     * @param layoutDirection the layout direction to set. Should be one of:
6027     *
6028     * {@link #LAYOUT_DIRECTION_LTR},
6029     * {@link #LAYOUT_DIRECTION_RTL},
6030     * {@link #LAYOUT_DIRECTION_INHERIT},
6031     * {@link #LAYOUT_DIRECTION_LOCALE}.
6032     *
6033     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6034     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6035     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6036     *
6037     * @attr ref android.R.styleable#View_layoutDirection
6038     */
6039    @RemotableViewMethod
6040    public void setLayoutDirection(int layoutDirection) {
6041        if (getRawLayoutDirection() != layoutDirection) {
6042            // Reset the current layout direction and the resolved one
6043            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6044            resetRtlProperties();
6045            // Set the new layout direction (filtered)
6046            mPrivateFlags2 |=
6047                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6048            // We need to resolve all RTL properties as they all depend on layout direction
6049            resolveRtlPropertiesIfNeeded();
6050            requestLayout();
6051            invalidate(true);
6052        }
6053    }
6054
6055    /**
6056     * Returns the resolved layout direction for this view.
6057     *
6058     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6059     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6060     *
6061     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6062     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6063     *
6064     * @attr ref android.R.styleable#View_layoutDirection
6065     */
6066    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6067        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6068        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6069    })
6070    public int getLayoutDirection() {
6071        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6072        if (targetSdkVersion < JELLY_BEAN_MR1) {
6073            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6074            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6075        }
6076        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6077                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6078    }
6079
6080    /**
6081     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6082     * layout attribute and/or the inherited value from the parent
6083     *
6084     * @return true if the layout is right-to-left.
6085     *
6086     * @hide
6087     */
6088    @ViewDebug.ExportedProperty(category = "layout")
6089    public boolean isLayoutRtl() {
6090        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6091    }
6092
6093    /**
6094     * Indicates whether the view is currently tracking transient state that the
6095     * app should not need to concern itself with saving and restoring, but that
6096     * the framework should take special note to preserve when possible.
6097     *
6098     * <p>A view with transient state cannot be trivially rebound from an external
6099     * data source, such as an adapter binding item views in a list. This may be
6100     * because the view is performing an animation, tracking user selection
6101     * of content, or similar.</p>
6102     *
6103     * @return true if the view has transient state
6104     */
6105    @ViewDebug.ExportedProperty(category = "layout")
6106    public boolean hasTransientState() {
6107        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6108    }
6109
6110    /**
6111     * Set whether this view is currently tracking transient state that the
6112     * framework should attempt to preserve when possible. This flag is reference counted,
6113     * so every call to setHasTransientState(true) should be paired with a later call
6114     * to setHasTransientState(false).
6115     *
6116     * <p>A view with transient state cannot be trivially rebound from an external
6117     * data source, such as an adapter binding item views in a list. This may be
6118     * because the view is performing an animation, tracking user selection
6119     * of content, or similar.</p>
6120     *
6121     * @param hasTransientState true if this view has transient state
6122     */
6123    public void setHasTransientState(boolean hasTransientState) {
6124        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6125                mTransientStateCount - 1;
6126        if (mTransientStateCount < 0) {
6127            mTransientStateCount = 0;
6128            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6129                    "unmatched pair of setHasTransientState calls");
6130        } else if ((hasTransientState && mTransientStateCount == 1) ||
6131                (!hasTransientState && mTransientStateCount == 0)) {
6132            // update flag if we've just incremented up from 0 or decremented down to 0
6133            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6134                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6135            if (mParent != null) {
6136                try {
6137                    mParent.childHasTransientStateChanged(this, hasTransientState);
6138                } catch (AbstractMethodError e) {
6139                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6140                            " does not fully implement ViewParent", e);
6141                }
6142            }
6143        }
6144    }
6145
6146    /**
6147     * Returns true if this view is currently attached to a window.
6148     */
6149    public boolean isAttachedToWindow() {
6150        return mAttachInfo != null;
6151    }
6152
6153    /**
6154     * Returns true if this view has been through at least one layout since it
6155     * was last attached to or detached from a window.
6156     */
6157    public boolean hasLayout() {
6158        return (mPrivateFlags3 & PFLAG3_HAS_LAYOUT) == PFLAG3_HAS_LAYOUT;
6159    }
6160
6161    /**
6162     * If this view doesn't do any drawing on its own, set this flag to
6163     * allow further optimizations. By default, this flag is not set on
6164     * View, but could be set on some View subclasses such as ViewGroup.
6165     *
6166     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6167     * you should clear this flag.
6168     *
6169     * @param willNotDraw whether or not this View draw on its own
6170     */
6171    public void setWillNotDraw(boolean willNotDraw) {
6172        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6173    }
6174
6175    /**
6176     * Returns whether or not this View draws on its own.
6177     *
6178     * @return true if this view has nothing to draw, false otherwise
6179     */
6180    @ViewDebug.ExportedProperty(category = "drawing")
6181    public boolean willNotDraw() {
6182        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6183    }
6184
6185    /**
6186     * When a View's drawing cache is enabled, drawing is redirected to an
6187     * offscreen bitmap. Some views, like an ImageView, must be able to
6188     * bypass this mechanism if they already draw a single bitmap, to avoid
6189     * unnecessary usage of the memory.
6190     *
6191     * @param willNotCacheDrawing true if this view does not cache its
6192     *        drawing, false otherwise
6193     */
6194    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6195        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6196    }
6197
6198    /**
6199     * Returns whether or not this View can cache its drawing or not.
6200     *
6201     * @return true if this view does not cache its drawing, false otherwise
6202     */
6203    @ViewDebug.ExportedProperty(category = "drawing")
6204    public boolean willNotCacheDrawing() {
6205        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6206    }
6207
6208    /**
6209     * Indicates whether this view reacts to click events or not.
6210     *
6211     * @return true if the view is clickable, false otherwise
6212     *
6213     * @see #setClickable(boolean)
6214     * @attr ref android.R.styleable#View_clickable
6215     */
6216    @ViewDebug.ExportedProperty
6217    public boolean isClickable() {
6218        return (mViewFlags & CLICKABLE) == CLICKABLE;
6219    }
6220
6221    /**
6222     * Enables or disables click events for this view. When a view
6223     * is clickable it will change its state to "pressed" on every click.
6224     * Subclasses should set the view clickable to visually react to
6225     * user's clicks.
6226     *
6227     * @param clickable true to make the view clickable, false otherwise
6228     *
6229     * @see #isClickable()
6230     * @attr ref android.R.styleable#View_clickable
6231     */
6232    public void setClickable(boolean clickable) {
6233        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6234    }
6235
6236    /**
6237     * Indicates whether this view reacts to long click events or not.
6238     *
6239     * @return true if the view is long clickable, false otherwise
6240     *
6241     * @see #setLongClickable(boolean)
6242     * @attr ref android.R.styleable#View_longClickable
6243     */
6244    public boolean isLongClickable() {
6245        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6246    }
6247
6248    /**
6249     * Enables or disables long click events for this view. When a view is long
6250     * clickable it reacts to the user holding down the button for a longer
6251     * duration than a tap. This event can either launch the listener or a
6252     * context menu.
6253     *
6254     * @param longClickable true to make the view long clickable, false otherwise
6255     * @see #isLongClickable()
6256     * @attr ref android.R.styleable#View_longClickable
6257     */
6258    public void setLongClickable(boolean longClickable) {
6259        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6260    }
6261
6262    /**
6263     * Sets the pressed state for this view.
6264     *
6265     * @see #isClickable()
6266     * @see #setClickable(boolean)
6267     *
6268     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6269     *        the View's internal state from a previously set "pressed" state.
6270     */
6271    public void setPressed(boolean pressed) {
6272        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6273
6274        if (pressed) {
6275            mPrivateFlags |= PFLAG_PRESSED;
6276        } else {
6277            mPrivateFlags &= ~PFLAG_PRESSED;
6278        }
6279
6280        if (needsRefresh) {
6281            refreshDrawableState();
6282        }
6283        dispatchSetPressed(pressed);
6284    }
6285
6286    /**
6287     * Dispatch setPressed to all of this View's children.
6288     *
6289     * @see #setPressed(boolean)
6290     *
6291     * @param pressed The new pressed state
6292     */
6293    protected void dispatchSetPressed(boolean pressed) {
6294    }
6295
6296    /**
6297     * Indicates whether the view is currently in pressed state. Unless
6298     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6299     * the pressed state.
6300     *
6301     * @see #setPressed(boolean)
6302     * @see #isClickable()
6303     * @see #setClickable(boolean)
6304     *
6305     * @return true if the view is currently pressed, false otherwise
6306     */
6307    public boolean isPressed() {
6308        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6309    }
6310
6311    /**
6312     * Indicates whether this view will save its state (that is,
6313     * whether its {@link #onSaveInstanceState} method will be called).
6314     *
6315     * @return Returns true if the view state saving is enabled, else false.
6316     *
6317     * @see #setSaveEnabled(boolean)
6318     * @attr ref android.R.styleable#View_saveEnabled
6319     */
6320    public boolean isSaveEnabled() {
6321        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6322    }
6323
6324    /**
6325     * Controls whether the saving of this view's state is
6326     * enabled (that is, whether its {@link #onSaveInstanceState} method
6327     * will be called).  Note that even if freezing is enabled, the
6328     * view still must have an id assigned to it (via {@link #setId(int)})
6329     * for its state to be saved.  This flag can only disable the
6330     * saving of this view; any child views may still have their state saved.
6331     *
6332     * @param enabled Set to false to <em>disable</em> state saving, or true
6333     * (the default) to allow it.
6334     *
6335     * @see #isSaveEnabled()
6336     * @see #setId(int)
6337     * @see #onSaveInstanceState()
6338     * @attr ref android.R.styleable#View_saveEnabled
6339     */
6340    public void setSaveEnabled(boolean enabled) {
6341        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6342    }
6343
6344    /**
6345     * Gets whether the framework should discard touches when the view's
6346     * window is obscured by another visible window.
6347     * Refer to the {@link View} security documentation for more details.
6348     *
6349     * @return True if touch filtering is enabled.
6350     *
6351     * @see #setFilterTouchesWhenObscured(boolean)
6352     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6353     */
6354    @ViewDebug.ExportedProperty
6355    public boolean getFilterTouchesWhenObscured() {
6356        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6357    }
6358
6359    /**
6360     * Sets whether the framework should discard touches when the view's
6361     * window is obscured by another visible window.
6362     * Refer to the {@link View} security documentation for more details.
6363     *
6364     * @param enabled True if touch filtering should be enabled.
6365     *
6366     * @see #getFilterTouchesWhenObscured
6367     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6368     */
6369    public void setFilterTouchesWhenObscured(boolean enabled) {
6370        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6371                FILTER_TOUCHES_WHEN_OBSCURED);
6372    }
6373
6374    /**
6375     * Indicates whether the entire hierarchy under this view will save its
6376     * state when a state saving traversal occurs from its parent.  The default
6377     * is true; if false, these views will not be saved unless
6378     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6379     *
6380     * @return Returns true if the view state saving from parent is enabled, else false.
6381     *
6382     * @see #setSaveFromParentEnabled(boolean)
6383     */
6384    public boolean isSaveFromParentEnabled() {
6385        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6386    }
6387
6388    /**
6389     * Controls whether the entire hierarchy under this view will save its
6390     * state when a state saving traversal occurs from its parent.  The default
6391     * is true; if false, these views will not be saved unless
6392     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6393     *
6394     * @param enabled Set to false to <em>disable</em> state saving, or true
6395     * (the default) to allow it.
6396     *
6397     * @see #isSaveFromParentEnabled()
6398     * @see #setId(int)
6399     * @see #onSaveInstanceState()
6400     */
6401    public void setSaveFromParentEnabled(boolean enabled) {
6402        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6403    }
6404
6405
6406    /**
6407     * Returns whether this View is able to take focus.
6408     *
6409     * @return True if this view can take focus, or false otherwise.
6410     * @attr ref android.R.styleable#View_focusable
6411     */
6412    @ViewDebug.ExportedProperty(category = "focus")
6413    public final boolean isFocusable() {
6414        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6415    }
6416
6417    /**
6418     * When a view is focusable, it may not want to take focus when in touch mode.
6419     * For example, a button would like focus when the user is navigating via a D-pad
6420     * so that the user can click on it, but once the user starts touching the screen,
6421     * the button shouldn't take focus
6422     * @return Whether the view is focusable in touch mode.
6423     * @attr ref android.R.styleable#View_focusableInTouchMode
6424     */
6425    @ViewDebug.ExportedProperty
6426    public final boolean isFocusableInTouchMode() {
6427        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6428    }
6429
6430    /**
6431     * Find the nearest view in the specified direction that can take focus.
6432     * This does not actually give focus to that view.
6433     *
6434     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6435     *
6436     * @return The nearest focusable in the specified direction, or null if none
6437     *         can be found.
6438     */
6439    public View focusSearch(int direction) {
6440        if (mParent != null) {
6441            return mParent.focusSearch(this, direction);
6442        } else {
6443            return null;
6444        }
6445    }
6446
6447    /**
6448     * This method is the last chance for the focused view and its ancestors to
6449     * respond to an arrow key. This is called when the focused view did not
6450     * consume the key internally, nor could the view system find a new view in
6451     * the requested direction to give focus to.
6452     *
6453     * @param focused The currently focused view.
6454     * @param direction The direction focus wants to move. One of FOCUS_UP,
6455     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6456     * @return True if the this view consumed this unhandled move.
6457     */
6458    public boolean dispatchUnhandledMove(View focused, int direction) {
6459        return false;
6460    }
6461
6462    /**
6463     * If a user manually specified the next view id for a particular direction,
6464     * use the root to look up the view.
6465     * @param root The root view of the hierarchy containing this view.
6466     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6467     * or FOCUS_BACKWARD.
6468     * @return The user specified next view, or null if there is none.
6469     */
6470    View findUserSetNextFocus(View root, int direction) {
6471        switch (direction) {
6472            case FOCUS_LEFT:
6473                if (mNextFocusLeftId == View.NO_ID) return null;
6474                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6475            case FOCUS_RIGHT:
6476                if (mNextFocusRightId == View.NO_ID) return null;
6477                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6478            case FOCUS_UP:
6479                if (mNextFocusUpId == View.NO_ID) return null;
6480                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6481            case FOCUS_DOWN:
6482                if (mNextFocusDownId == View.NO_ID) return null;
6483                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6484            case FOCUS_FORWARD:
6485                if (mNextFocusForwardId == View.NO_ID) return null;
6486                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6487            case FOCUS_BACKWARD: {
6488                if (mID == View.NO_ID) return null;
6489                final int id = mID;
6490                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6491                    @Override
6492                    public boolean apply(View t) {
6493                        return t.mNextFocusForwardId == id;
6494                    }
6495                });
6496            }
6497        }
6498        return null;
6499    }
6500
6501    private View findViewInsideOutShouldExist(View root, int id) {
6502        if (mMatchIdPredicate == null) {
6503            mMatchIdPredicate = new MatchIdPredicate();
6504        }
6505        mMatchIdPredicate.mId = id;
6506        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6507        if (result == null) {
6508            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6509        }
6510        return result;
6511    }
6512
6513    /**
6514     * Find and return all focusable views that are descendants of this view,
6515     * possibly including this view if it is focusable itself.
6516     *
6517     * @param direction The direction of the focus
6518     * @return A list of focusable views
6519     */
6520    public ArrayList<View> getFocusables(int direction) {
6521        ArrayList<View> result = new ArrayList<View>(24);
6522        addFocusables(result, direction);
6523        return result;
6524    }
6525
6526    /**
6527     * Add any focusable views that are descendants of this view (possibly
6528     * including this view if it is focusable itself) to views.  If we are in touch mode,
6529     * only add views that are also focusable in touch mode.
6530     *
6531     * @param views Focusable views found so far
6532     * @param direction The direction of the focus
6533     */
6534    public void addFocusables(ArrayList<View> views, int direction) {
6535        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6536    }
6537
6538    /**
6539     * Adds any focusable views that are descendants of this view (possibly
6540     * including this view if it is focusable itself) to views. This method
6541     * adds all focusable views regardless if we are in touch mode or
6542     * only views focusable in touch mode if we are in touch mode or
6543     * only views that can take accessibility focus if accessibility is enabeld
6544     * depending on the focusable mode paramater.
6545     *
6546     * @param views Focusable views found so far or null if all we are interested is
6547     *        the number of focusables.
6548     * @param direction The direction of the focus.
6549     * @param focusableMode The type of focusables to be added.
6550     *
6551     * @see #FOCUSABLES_ALL
6552     * @see #FOCUSABLES_TOUCH_MODE
6553     */
6554    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6555        if (views == null) {
6556            return;
6557        }
6558        if (!isFocusable()) {
6559            return;
6560        }
6561        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6562                && isInTouchMode() && !isFocusableInTouchMode()) {
6563            return;
6564        }
6565        views.add(this);
6566    }
6567
6568    /**
6569     * Finds the Views that contain given text. The containment is case insensitive.
6570     * The search is performed by either the text that the View renders or the content
6571     * description that describes the view for accessibility purposes and the view does
6572     * not render or both. Clients can specify how the search is to be performed via
6573     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6574     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6575     *
6576     * @param outViews The output list of matching Views.
6577     * @param searched The text to match against.
6578     *
6579     * @see #FIND_VIEWS_WITH_TEXT
6580     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6581     * @see #setContentDescription(CharSequence)
6582     */
6583    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6584        if (getAccessibilityNodeProvider() != null) {
6585            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6586                outViews.add(this);
6587            }
6588        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6589                && (searched != null && searched.length() > 0)
6590                && (mContentDescription != null && mContentDescription.length() > 0)) {
6591            String searchedLowerCase = searched.toString().toLowerCase();
6592            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6593            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6594                outViews.add(this);
6595            }
6596        }
6597    }
6598
6599    /**
6600     * Find and return all touchable views that are descendants of this view,
6601     * possibly including this view if it is touchable itself.
6602     *
6603     * @return A list of touchable views
6604     */
6605    public ArrayList<View> getTouchables() {
6606        ArrayList<View> result = new ArrayList<View>();
6607        addTouchables(result);
6608        return result;
6609    }
6610
6611    /**
6612     * Add any touchable views that are descendants of this view (possibly
6613     * including this view if it is touchable itself) to views.
6614     *
6615     * @param views Touchable views found so far
6616     */
6617    public void addTouchables(ArrayList<View> views) {
6618        final int viewFlags = mViewFlags;
6619
6620        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6621                && (viewFlags & ENABLED_MASK) == ENABLED) {
6622            views.add(this);
6623        }
6624    }
6625
6626    /**
6627     * Returns whether this View is accessibility focused.
6628     *
6629     * @return True if this View is accessibility focused.
6630     */
6631    boolean isAccessibilityFocused() {
6632        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6633    }
6634
6635    /**
6636     * Call this to try to give accessibility focus to this view.
6637     *
6638     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6639     * returns false or the view is no visible or the view already has accessibility
6640     * focus.
6641     *
6642     * See also {@link #focusSearch(int)}, which is what you call to say that you
6643     * have focus, and you want your parent to look for the next one.
6644     *
6645     * @return Whether this view actually took accessibility focus.
6646     *
6647     * @hide
6648     */
6649    public boolean requestAccessibilityFocus() {
6650        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6651        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6652            return false;
6653        }
6654        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6655            return false;
6656        }
6657        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6658            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6659            ViewRootImpl viewRootImpl = getViewRootImpl();
6660            if (viewRootImpl != null) {
6661                viewRootImpl.setAccessibilityFocus(this, null);
6662            }
6663            invalidate();
6664            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6665            return true;
6666        }
6667        return false;
6668    }
6669
6670    /**
6671     * Call this to try to clear accessibility focus of this view.
6672     *
6673     * See also {@link #focusSearch(int)}, which is what you call to say that you
6674     * have focus, and you want your parent to look for the next one.
6675     *
6676     * @hide
6677     */
6678    public void clearAccessibilityFocus() {
6679        clearAccessibilityFocusNoCallbacks();
6680        // Clear the global reference of accessibility focus if this
6681        // view or any of its descendants had accessibility focus.
6682        ViewRootImpl viewRootImpl = getViewRootImpl();
6683        if (viewRootImpl != null) {
6684            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6685            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6686                viewRootImpl.setAccessibilityFocus(null, null);
6687            }
6688        }
6689    }
6690
6691    private void sendAccessibilityHoverEvent(int eventType) {
6692        // Since we are not delivering to a client accessibility events from not
6693        // important views (unless the clinet request that) we need to fire the
6694        // event from the deepest view exposed to the client. As a consequence if
6695        // the user crosses a not exposed view the client will see enter and exit
6696        // of the exposed predecessor followed by and enter and exit of that same
6697        // predecessor when entering and exiting the not exposed descendant. This
6698        // is fine since the client has a clear idea which view is hovered at the
6699        // price of a couple more events being sent. This is a simple and
6700        // working solution.
6701        View source = this;
6702        while (true) {
6703            if (source.includeForAccessibility()) {
6704                source.sendAccessibilityEvent(eventType);
6705                return;
6706            }
6707            ViewParent parent = source.getParent();
6708            if (parent instanceof View) {
6709                source = (View) parent;
6710            } else {
6711                return;
6712            }
6713        }
6714    }
6715
6716    /**
6717     * Clears accessibility focus without calling any callback methods
6718     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6719     * is used for clearing accessibility focus when giving this focus to
6720     * another view.
6721     */
6722    void clearAccessibilityFocusNoCallbacks() {
6723        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6724            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6725            invalidate();
6726            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6727        }
6728    }
6729
6730    /**
6731     * Call this to try to give focus to a specific view or to one of its
6732     * descendants.
6733     *
6734     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6735     * false), or if it is focusable and it is not focusable in touch mode
6736     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6737     *
6738     * See also {@link #focusSearch(int)}, which is what you call to say that you
6739     * have focus, and you want your parent to look for the next one.
6740     *
6741     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6742     * {@link #FOCUS_DOWN} and <code>null</code>.
6743     *
6744     * @return Whether this view or one of its descendants actually took focus.
6745     */
6746    public final boolean requestFocus() {
6747        return requestFocus(View.FOCUS_DOWN);
6748    }
6749
6750    /**
6751     * Call this to try to give focus to a specific view or to one of its
6752     * descendants and give it a hint about what direction focus is heading.
6753     *
6754     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6755     * false), or if it is focusable and it is not focusable in touch mode
6756     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6757     *
6758     * See also {@link #focusSearch(int)}, which is what you call to say that you
6759     * have focus, and you want your parent to look for the next one.
6760     *
6761     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6762     * <code>null</code> set for the previously focused rectangle.
6763     *
6764     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6765     * @return Whether this view or one of its descendants actually took focus.
6766     */
6767    public final boolean requestFocus(int direction) {
6768        return requestFocus(direction, null);
6769    }
6770
6771    /**
6772     * Call this to try to give focus to a specific view or to one of its descendants
6773     * and give it hints about the direction and a specific rectangle that the focus
6774     * is coming from.  The rectangle can help give larger views a finer grained hint
6775     * about where focus is coming from, and therefore, where to show selection, or
6776     * forward focus change internally.
6777     *
6778     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6779     * false), or if it is focusable and it is not focusable in touch mode
6780     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6781     *
6782     * A View will not take focus if it is not visible.
6783     *
6784     * A View will not take focus if one of its parents has
6785     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6786     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6787     *
6788     * See also {@link #focusSearch(int)}, which is what you call to say that you
6789     * have focus, and you want your parent to look for the next one.
6790     *
6791     * You may wish to override this method if your custom {@link View} has an internal
6792     * {@link View} that it wishes to forward the request to.
6793     *
6794     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6795     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6796     *        to give a finer grained hint about where focus is coming from.  May be null
6797     *        if there is no hint.
6798     * @return Whether this view or one of its descendants actually took focus.
6799     */
6800    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6801        return requestFocusNoSearch(direction, previouslyFocusedRect);
6802    }
6803
6804    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6805        // need to be focusable
6806        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6807                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6808            return false;
6809        }
6810
6811        // need to be focusable in touch mode if in touch mode
6812        if (isInTouchMode() &&
6813            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6814               return false;
6815        }
6816
6817        // need to not have any parents blocking us
6818        if (hasAncestorThatBlocksDescendantFocus()) {
6819            return false;
6820        }
6821
6822        handleFocusGainInternal(direction, previouslyFocusedRect);
6823        return true;
6824    }
6825
6826    /**
6827     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6828     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6829     * touch mode to request focus when they are touched.
6830     *
6831     * @return Whether this view or one of its descendants actually took focus.
6832     *
6833     * @see #isInTouchMode()
6834     *
6835     */
6836    public final boolean requestFocusFromTouch() {
6837        // Leave touch mode if we need to
6838        if (isInTouchMode()) {
6839            ViewRootImpl viewRoot = getViewRootImpl();
6840            if (viewRoot != null) {
6841                viewRoot.ensureTouchMode(false);
6842            }
6843        }
6844        return requestFocus(View.FOCUS_DOWN);
6845    }
6846
6847    /**
6848     * @return Whether any ancestor of this view blocks descendant focus.
6849     */
6850    private boolean hasAncestorThatBlocksDescendantFocus() {
6851        ViewParent ancestor = mParent;
6852        while (ancestor instanceof ViewGroup) {
6853            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6854            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6855                return true;
6856            } else {
6857                ancestor = vgAncestor.getParent();
6858            }
6859        }
6860        return false;
6861    }
6862
6863    /**
6864     * Gets the mode for determining whether this View is important for accessibility
6865     * which is if it fires accessibility events and if it is reported to
6866     * accessibility services that query the screen.
6867     *
6868     * @return The mode for determining whether a View is important for accessibility.
6869     *
6870     * @attr ref android.R.styleable#View_importantForAccessibility
6871     *
6872     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6873     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6874     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6875     */
6876    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6877            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6878            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6879            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6880        })
6881    public int getImportantForAccessibility() {
6882        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6883                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6884    }
6885
6886    /**
6887     * Sets how to determine whether this view is important for accessibility
6888     * which is if it fires accessibility events and if it is reported to
6889     * accessibility services that query the screen.
6890     *
6891     * @param mode How to determine whether this view is important for accessibility.
6892     *
6893     * @attr ref android.R.styleable#View_importantForAccessibility
6894     *
6895     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6896     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6897     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6898     */
6899    public void setImportantForAccessibility(int mode) {
6900        final boolean oldIncludeForAccessibility = includeForAccessibility();
6901        if (mode != getImportantForAccessibility()) {
6902            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6903            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6904                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6905            if (oldIncludeForAccessibility != includeForAccessibility()) {
6906                notifySubtreeAccessibilityStateChangedIfNeeded();
6907            } else {
6908                notifyViewAccessibilityStateChangedIfNeeded();
6909            }
6910        }
6911    }
6912
6913    /**
6914     * Gets whether this view should be exposed for accessibility.
6915     *
6916     * @return Whether the view is exposed for accessibility.
6917     *
6918     * @hide
6919     */
6920    public boolean isImportantForAccessibility() {
6921        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6922                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6923        switch (mode) {
6924            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6925                return true;
6926            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6927                return false;
6928            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6929                return isActionableForAccessibility() || hasListenersForAccessibility()
6930                        || getAccessibilityNodeProvider() != null;
6931            default:
6932                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6933                        + mode);
6934        }
6935    }
6936
6937    /**
6938     * Gets the parent for accessibility purposes. Note that the parent for
6939     * accessibility is not necessary the immediate parent. It is the first
6940     * predecessor that is important for accessibility.
6941     *
6942     * @return The parent for accessibility purposes.
6943     */
6944    public ViewParent getParentForAccessibility() {
6945        if (mParent instanceof View) {
6946            View parentView = (View) mParent;
6947            if (parentView.includeForAccessibility()) {
6948                return mParent;
6949            } else {
6950                return mParent.getParentForAccessibility();
6951            }
6952        }
6953        return null;
6954    }
6955
6956    /**
6957     * Adds the children of a given View for accessibility. Since some Views are
6958     * not important for accessibility the children for accessibility are not
6959     * necessarily direct children of the view, rather they are the first level of
6960     * descendants important for accessibility.
6961     *
6962     * @param children The list of children for accessibility.
6963     */
6964    public void addChildrenForAccessibility(ArrayList<View> children) {
6965        if (includeForAccessibility()) {
6966            children.add(this);
6967        }
6968    }
6969
6970    /**
6971     * Whether to regard this view for accessibility. A view is regarded for
6972     * accessibility if it is important for accessibility or the querying
6973     * accessibility service has explicitly requested that view not
6974     * important for accessibility are regarded.
6975     *
6976     * @return Whether to regard the view for accessibility.
6977     *
6978     * @hide
6979     */
6980    public boolean includeForAccessibility() {
6981        if (mAttachInfo != null) {
6982            return (mAttachInfo.mAccessibilityFetchFlags
6983                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6984                    || isImportantForAccessibility();
6985        }
6986        return false;
6987    }
6988
6989    /**
6990     * Returns whether the View is considered actionable from
6991     * accessibility perspective. Such view are important for
6992     * accessibility.
6993     *
6994     * @return True if the view is actionable for accessibility.
6995     *
6996     * @hide
6997     */
6998    public boolean isActionableForAccessibility() {
6999        return (isClickable() || isLongClickable() || isFocusable());
7000    }
7001
7002    /**
7003     * Returns whether the View has registered callbacks wich makes it
7004     * important for accessibility.
7005     *
7006     * @return True if the view is actionable for accessibility.
7007     */
7008    private boolean hasListenersForAccessibility() {
7009        ListenerInfo info = getListenerInfo();
7010        return mTouchDelegate != null || info.mOnKeyListener != null
7011                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7012                || info.mOnHoverListener != null || info.mOnDragListener != null;
7013    }
7014
7015    /**
7016     * Notifies that the accessibility state of this view changed. The change
7017     * is local to this view and does not represent structural changes such
7018     * as children and parent. For example, the view became focusable. The
7019     * notification is at at most once every
7020     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7021     * to avoid unnecessary load to the system. Also once a view has a pending
7022     * notifucation this method is a NOP until the notification has been sent.
7023     *
7024     * @hide
7025     */
7026    public void notifyViewAccessibilityStateChangedIfNeeded() {
7027        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7028            return;
7029        }
7030        if (mSendViewStateChangedAccessibilityEvent == null) {
7031            mSendViewStateChangedAccessibilityEvent =
7032                    new SendViewStateChangedAccessibilityEvent();
7033        }
7034        mSendViewStateChangedAccessibilityEvent.runOrPost();
7035    }
7036
7037    /**
7038     * Notifies that the accessibility state of this view changed. The change
7039     * is *not* local to this view and does represent structural changes such
7040     * as children and parent. For example, the view size changed. The
7041     * notification is at at most once every
7042     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7043     * to avoid unnecessary load to the system. Also once a view has a pending
7044     * notifucation this method is a NOP until the notification has been sent.
7045     *
7046     * @hide
7047     */
7048    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7049        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7050            return;
7051        }
7052        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7053            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7054            if (mParent != null) {
7055                mParent.childAccessibilityStateChanged(this);
7056            }
7057        }
7058    }
7059
7060    /**
7061     * Reset the flag indicating the accessibility state of the subtree rooted
7062     * at this view changed.
7063     */
7064    void resetSubtreeAccessibilityStateChanged() {
7065        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7066    }
7067
7068    /**
7069     * Performs the specified accessibility action on the view. For
7070     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7071     * <p>
7072     * If an {@link AccessibilityDelegate} has been specified via calling
7073     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7074     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7075     * is responsible for handling this call.
7076     * </p>
7077     *
7078     * @param action The action to perform.
7079     * @param arguments Optional action arguments.
7080     * @return Whether the action was performed.
7081     */
7082    public boolean performAccessibilityAction(int action, Bundle arguments) {
7083      if (mAccessibilityDelegate != null) {
7084          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7085      } else {
7086          return performAccessibilityActionInternal(action, arguments);
7087      }
7088    }
7089
7090   /**
7091    * @see #performAccessibilityAction(int, Bundle)
7092    *
7093    * Note: Called from the default {@link AccessibilityDelegate}.
7094    */
7095    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7096        switch (action) {
7097            case AccessibilityNodeInfo.ACTION_CLICK: {
7098                if (isClickable()) {
7099                    performClick();
7100                    return true;
7101                }
7102            } break;
7103            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7104                if (isLongClickable()) {
7105                    performLongClick();
7106                    return true;
7107                }
7108            } break;
7109            case AccessibilityNodeInfo.ACTION_FOCUS: {
7110                if (!hasFocus()) {
7111                    // Get out of touch mode since accessibility
7112                    // wants to move focus around.
7113                    getViewRootImpl().ensureTouchMode(false);
7114                    return requestFocus();
7115                }
7116            } break;
7117            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7118                if (hasFocus()) {
7119                    clearFocus();
7120                    return !isFocused();
7121                }
7122            } break;
7123            case AccessibilityNodeInfo.ACTION_SELECT: {
7124                if (!isSelected()) {
7125                    setSelected(true);
7126                    return isSelected();
7127                }
7128            } break;
7129            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7130                if (isSelected()) {
7131                    setSelected(false);
7132                    return !isSelected();
7133                }
7134            } break;
7135            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7136                if (!isAccessibilityFocused()) {
7137                    return requestAccessibilityFocus();
7138                }
7139            } break;
7140            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7141                if (isAccessibilityFocused()) {
7142                    clearAccessibilityFocus();
7143                    return true;
7144                }
7145            } break;
7146            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7147                if (arguments != null) {
7148                    final int granularity = arguments.getInt(
7149                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7150                    final boolean extendSelection = arguments.getBoolean(
7151                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7152                    return traverseAtGranularity(granularity, true, extendSelection);
7153                }
7154            } break;
7155            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7156                if (arguments != null) {
7157                    final int granularity = arguments.getInt(
7158                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7159                    final boolean extendSelection = arguments.getBoolean(
7160                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7161                    return traverseAtGranularity(granularity, false, extendSelection);
7162                }
7163            } break;
7164            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7165                CharSequence text = getIterableTextForAccessibility();
7166                if (text == null) {
7167                    return false;
7168                }
7169                final int start = (arguments != null) ? arguments.getInt(
7170                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7171                final int end = (arguments != null) ? arguments.getInt(
7172                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7173                // Only cursor position can be specified (selection length == 0)
7174                if ((getAccessibilitySelectionStart() != start
7175                        || getAccessibilitySelectionEnd() != end)
7176                        && (start == end)) {
7177                    setAccessibilitySelection(start, end);
7178                    notifyViewAccessibilityStateChangedIfNeeded();
7179                    return true;
7180                }
7181            } break;
7182        }
7183        return false;
7184    }
7185
7186    private boolean traverseAtGranularity(int granularity, boolean forward,
7187            boolean extendSelection) {
7188        CharSequence text = getIterableTextForAccessibility();
7189        if (text == null || text.length() == 0) {
7190            return false;
7191        }
7192        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7193        if (iterator == null) {
7194            return false;
7195        }
7196        int current = getAccessibilitySelectionEnd();
7197        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7198            current = forward ? 0 : text.length();
7199        }
7200        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7201        if (range == null) {
7202            return false;
7203        }
7204        final int segmentStart = range[0];
7205        final int segmentEnd = range[1];
7206        int selectionStart;
7207        int selectionEnd;
7208        if (extendSelection && isAccessibilitySelectionExtendable()) {
7209            selectionStart = getAccessibilitySelectionStart();
7210            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7211                selectionStart = forward ? segmentStart : segmentEnd;
7212            }
7213            selectionEnd = forward ? segmentEnd : segmentStart;
7214        } else {
7215            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7216        }
7217        setAccessibilitySelection(selectionStart, selectionEnd);
7218        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7219                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7220        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7221        return true;
7222    }
7223
7224    /**
7225     * Gets the text reported for accessibility purposes.
7226     *
7227     * @return The accessibility text.
7228     *
7229     * @hide
7230     */
7231    public CharSequence getIterableTextForAccessibility() {
7232        return getContentDescription();
7233    }
7234
7235    /**
7236     * Gets whether accessibility selection can be extended.
7237     *
7238     * @return If selection is extensible.
7239     *
7240     * @hide
7241     */
7242    public boolean isAccessibilitySelectionExtendable() {
7243        return false;
7244    }
7245
7246    /**
7247     * @hide
7248     */
7249    public int getAccessibilitySelectionStart() {
7250        return mAccessibilityCursorPosition;
7251    }
7252
7253    /**
7254     * @hide
7255     */
7256    public int getAccessibilitySelectionEnd() {
7257        return getAccessibilitySelectionStart();
7258    }
7259
7260    /**
7261     * @hide
7262     */
7263    public void setAccessibilitySelection(int start, int end) {
7264        if (start ==  end && end == mAccessibilityCursorPosition) {
7265            return;
7266        }
7267        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7268            mAccessibilityCursorPosition = start;
7269        } else {
7270            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7271        }
7272        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7273    }
7274
7275    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7276            int fromIndex, int toIndex) {
7277        if (mParent == null) {
7278            return;
7279        }
7280        AccessibilityEvent event = AccessibilityEvent.obtain(
7281                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7282        onInitializeAccessibilityEvent(event);
7283        onPopulateAccessibilityEvent(event);
7284        event.setFromIndex(fromIndex);
7285        event.setToIndex(toIndex);
7286        event.setAction(action);
7287        event.setMovementGranularity(granularity);
7288        mParent.requestSendAccessibilityEvent(this, event);
7289    }
7290
7291    /**
7292     * @hide
7293     */
7294    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7295        switch (granularity) {
7296            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7297                CharSequence text = getIterableTextForAccessibility();
7298                if (text != null && text.length() > 0) {
7299                    CharacterTextSegmentIterator iterator =
7300                        CharacterTextSegmentIterator.getInstance(
7301                                mContext.getResources().getConfiguration().locale);
7302                    iterator.initialize(text.toString());
7303                    return iterator;
7304                }
7305            } break;
7306            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7307                CharSequence text = getIterableTextForAccessibility();
7308                if (text != null && text.length() > 0) {
7309                    WordTextSegmentIterator iterator =
7310                        WordTextSegmentIterator.getInstance(
7311                                mContext.getResources().getConfiguration().locale);
7312                    iterator.initialize(text.toString());
7313                    return iterator;
7314                }
7315            } break;
7316            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7317                CharSequence text = getIterableTextForAccessibility();
7318                if (text != null && text.length() > 0) {
7319                    ParagraphTextSegmentIterator iterator =
7320                        ParagraphTextSegmentIterator.getInstance();
7321                    iterator.initialize(text.toString());
7322                    return iterator;
7323                }
7324            } break;
7325        }
7326        return null;
7327    }
7328
7329    /**
7330     * @hide
7331     */
7332    public void dispatchStartTemporaryDetach() {
7333        clearAccessibilityFocus();
7334        clearDisplayList();
7335
7336        onStartTemporaryDetach();
7337    }
7338
7339    /**
7340     * This is called when a container is going to temporarily detach a child, with
7341     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7342     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7343     * {@link #onDetachedFromWindow()} when the container is done.
7344     */
7345    public void onStartTemporaryDetach() {
7346        removeUnsetPressCallback();
7347        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7348    }
7349
7350    /**
7351     * @hide
7352     */
7353    public void dispatchFinishTemporaryDetach() {
7354        onFinishTemporaryDetach();
7355    }
7356
7357    /**
7358     * Called after {@link #onStartTemporaryDetach} when the container is done
7359     * changing the view.
7360     */
7361    public void onFinishTemporaryDetach() {
7362    }
7363
7364    /**
7365     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7366     * for this view's window.  Returns null if the view is not currently attached
7367     * to the window.  Normally you will not need to use this directly, but
7368     * just use the standard high-level event callbacks like
7369     * {@link #onKeyDown(int, KeyEvent)}.
7370     */
7371    public KeyEvent.DispatcherState getKeyDispatcherState() {
7372        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7373    }
7374
7375    /**
7376     * Dispatch a key event before it is processed by any input method
7377     * associated with the view hierarchy.  This can be used to intercept
7378     * key events in special situations before the IME consumes them; a
7379     * typical example would be handling the BACK key to update the application's
7380     * UI instead of allowing the IME to see it and close itself.
7381     *
7382     * @param event The key event to be dispatched.
7383     * @return True if the event was handled, false otherwise.
7384     */
7385    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7386        return onKeyPreIme(event.getKeyCode(), event);
7387    }
7388
7389    /**
7390     * Dispatch a key event to the next view on the focus path. This path runs
7391     * from the top of the view tree down to the currently focused view. If this
7392     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7393     * the next node down the focus path. This method also fires any key
7394     * listeners.
7395     *
7396     * @param event The key event to be dispatched.
7397     * @return True if the event was handled, false otherwise.
7398     */
7399    public boolean dispatchKeyEvent(KeyEvent event) {
7400        if (mInputEventConsistencyVerifier != null) {
7401            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7402        }
7403
7404        // Give any attached key listener a first crack at the event.
7405        //noinspection SimplifiableIfStatement
7406        ListenerInfo li = mListenerInfo;
7407        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7408                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7409            return true;
7410        }
7411
7412        if (event.dispatch(this, mAttachInfo != null
7413                ? mAttachInfo.mKeyDispatchState : null, this)) {
7414            return true;
7415        }
7416
7417        if (mInputEventConsistencyVerifier != null) {
7418            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7419        }
7420        return false;
7421    }
7422
7423    /**
7424     * Dispatches a key shortcut event.
7425     *
7426     * @param event The key event to be dispatched.
7427     * @return True if the event was handled by the view, false otherwise.
7428     */
7429    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7430        return onKeyShortcut(event.getKeyCode(), event);
7431    }
7432
7433    /**
7434     * Pass the touch screen motion event down to the target view, or this
7435     * view if it is the target.
7436     *
7437     * @param event The motion event to be dispatched.
7438     * @return True if the event was handled by the view, false otherwise.
7439     */
7440    public boolean dispatchTouchEvent(MotionEvent event) {
7441        if (mInputEventConsistencyVerifier != null) {
7442            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7443        }
7444
7445        if (onFilterTouchEventForSecurity(event)) {
7446            //noinspection SimplifiableIfStatement
7447            ListenerInfo li = mListenerInfo;
7448            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7449                    && li.mOnTouchListener.onTouch(this, event)) {
7450                return true;
7451            }
7452
7453            if (onTouchEvent(event)) {
7454                return true;
7455            }
7456        }
7457
7458        if (mInputEventConsistencyVerifier != null) {
7459            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7460        }
7461        return false;
7462    }
7463
7464    /**
7465     * Filter the touch event to apply security policies.
7466     *
7467     * @param event The motion event to be filtered.
7468     * @return True if the event should be dispatched, false if the event should be dropped.
7469     *
7470     * @see #getFilterTouchesWhenObscured
7471     */
7472    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7473        //noinspection RedundantIfStatement
7474        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7475                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7476            // Window is obscured, drop this touch.
7477            return false;
7478        }
7479        return true;
7480    }
7481
7482    /**
7483     * Pass a trackball motion event down to the focused view.
7484     *
7485     * @param event The motion event to be dispatched.
7486     * @return True if the event was handled by the view, false otherwise.
7487     */
7488    public boolean dispatchTrackballEvent(MotionEvent event) {
7489        if (mInputEventConsistencyVerifier != null) {
7490            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7491        }
7492
7493        return onTrackballEvent(event);
7494    }
7495
7496    /**
7497     * Dispatch a generic motion event.
7498     * <p>
7499     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7500     * are delivered to the view under the pointer.  All other generic motion events are
7501     * delivered to the focused view.  Hover events are handled specially and are delivered
7502     * to {@link #onHoverEvent(MotionEvent)}.
7503     * </p>
7504     *
7505     * @param event The motion event to be dispatched.
7506     * @return True if the event was handled by the view, false otherwise.
7507     */
7508    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7509        if (mInputEventConsistencyVerifier != null) {
7510            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7511        }
7512
7513        final int source = event.getSource();
7514        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7515            final int action = event.getAction();
7516            if (action == MotionEvent.ACTION_HOVER_ENTER
7517                    || action == MotionEvent.ACTION_HOVER_MOVE
7518                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7519                if (dispatchHoverEvent(event)) {
7520                    return true;
7521                }
7522            } else if (dispatchGenericPointerEvent(event)) {
7523                return true;
7524            }
7525        } else if (dispatchGenericFocusedEvent(event)) {
7526            return true;
7527        }
7528
7529        if (dispatchGenericMotionEventInternal(event)) {
7530            return true;
7531        }
7532
7533        if (mInputEventConsistencyVerifier != null) {
7534            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7535        }
7536        return false;
7537    }
7538
7539    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7540        //noinspection SimplifiableIfStatement
7541        ListenerInfo li = mListenerInfo;
7542        if (li != null && li.mOnGenericMotionListener != null
7543                && (mViewFlags & ENABLED_MASK) == ENABLED
7544                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7545            return true;
7546        }
7547
7548        if (onGenericMotionEvent(event)) {
7549            return true;
7550        }
7551
7552        if (mInputEventConsistencyVerifier != null) {
7553            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7554        }
7555        return false;
7556    }
7557
7558    /**
7559     * Dispatch a hover event.
7560     * <p>
7561     * Do not call this method directly.
7562     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7563     * </p>
7564     *
7565     * @param event The motion event to be dispatched.
7566     * @return True if the event was handled by the view, false otherwise.
7567     */
7568    protected boolean dispatchHoverEvent(MotionEvent event) {
7569        //noinspection SimplifiableIfStatement
7570        ListenerInfo li = mListenerInfo;
7571        if (li != null && li.mOnHoverListener != null
7572                && (mViewFlags & ENABLED_MASK) == ENABLED
7573                && li.mOnHoverListener.onHover(this, event)) {
7574            return true;
7575        }
7576
7577        return onHoverEvent(event);
7578    }
7579
7580    /**
7581     * Returns true if the view has a child to which it has recently sent
7582     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7583     * it does not have a hovered child, then it must be the innermost hovered view.
7584     * @hide
7585     */
7586    protected boolean hasHoveredChild() {
7587        return false;
7588    }
7589
7590    /**
7591     * Dispatch a generic motion event to the view under the first pointer.
7592     * <p>
7593     * Do not call this method directly.
7594     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7595     * </p>
7596     *
7597     * @param event The motion event to be dispatched.
7598     * @return True if the event was handled by the view, false otherwise.
7599     */
7600    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7601        return false;
7602    }
7603
7604    /**
7605     * Dispatch a generic motion event to the currently focused view.
7606     * <p>
7607     * Do not call this method directly.
7608     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7609     * </p>
7610     *
7611     * @param event The motion event to be dispatched.
7612     * @return True if the event was handled by the view, false otherwise.
7613     */
7614    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7615        return false;
7616    }
7617
7618    /**
7619     * Dispatch a pointer event.
7620     * <p>
7621     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7622     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7623     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7624     * and should not be expected to handle other pointing device features.
7625     * </p>
7626     *
7627     * @param event The motion event to be dispatched.
7628     * @return True if the event was handled by the view, false otherwise.
7629     * @hide
7630     */
7631    public final boolean dispatchPointerEvent(MotionEvent event) {
7632        if (event.isTouchEvent()) {
7633            return dispatchTouchEvent(event);
7634        } else {
7635            return dispatchGenericMotionEvent(event);
7636        }
7637    }
7638
7639    /**
7640     * Called when the window containing this view gains or loses window focus.
7641     * ViewGroups should override to route to their children.
7642     *
7643     * @param hasFocus True if the window containing this view now has focus,
7644     *        false otherwise.
7645     */
7646    public void dispatchWindowFocusChanged(boolean hasFocus) {
7647        onWindowFocusChanged(hasFocus);
7648    }
7649
7650    /**
7651     * Called when the window containing this view gains or loses focus.  Note
7652     * that this is separate from view focus: to receive key events, both
7653     * your view and its window must have focus.  If a window is displayed
7654     * on top of yours that takes input focus, then your own window will lose
7655     * focus but the view focus will remain unchanged.
7656     *
7657     * @param hasWindowFocus True if the window containing this view now has
7658     *        focus, false otherwise.
7659     */
7660    public void onWindowFocusChanged(boolean hasWindowFocus) {
7661        InputMethodManager imm = InputMethodManager.peekInstance();
7662        if (!hasWindowFocus) {
7663            if (isPressed()) {
7664                setPressed(false);
7665            }
7666            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7667                imm.focusOut(this);
7668            }
7669            removeLongPressCallback();
7670            removeTapCallback();
7671            onFocusLost();
7672        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7673            imm.focusIn(this);
7674        }
7675        refreshDrawableState();
7676    }
7677
7678    /**
7679     * Returns true if this view is in a window that currently has window focus.
7680     * Note that this is not the same as the view itself having focus.
7681     *
7682     * @return True if this view is in a window that currently has window focus.
7683     */
7684    public boolean hasWindowFocus() {
7685        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7686    }
7687
7688    /**
7689     * Dispatch a view visibility change down the view hierarchy.
7690     * ViewGroups should override to route to their children.
7691     * @param changedView The view whose visibility changed. Could be 'this' or
7692     * an ancestor view.
7693     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7694     * {@link #INVISIBLE} or {@link #GONE}.
7695     */
7696    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7697        onVisibilityChanged(changedView, visibility);
7698    }
7699
7700    /**
7701     * Called when the visibility of the view or an ancestor of the view is changed.
7702     * @param changedView The view whose visibility changed. Could be 'this' or
7703     * an ancestor view.
7704     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7705     * {@link #INVISIBLE} or {@link #GONE}.
7706     */
7707    protected void onVisibilityChanged(View changedView, int visibility) {
7708        if (visibility == VISIBLE) {
7709            if (mAttachInfo != null) {
7710                initialAwakenScrollBars();
7711            } else {
7712                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7713            }
7714        }
7715    }
7716
7717    /**
7718     * Dispatch a hint about whether this view is displayed. For instance, when
7719     * a View moves out of the screen, it might receives a display hint indicating
7720     * the view is not displayed. Applications should not <em>rely</em> on this hint
7721     * as there is no guarantee that they will receive one.
7722     *
7723     * @param hint A hint about whether or not this view is displayed:
7724     * {@link #VISIBLE} or {@link #INVISIBLE}.
7725     */
7726    public void dispatchDisplayHint(int hint) {
7727        onDisplayHint(hint);
7728    }
7729
7730    /**
7731     * Gives this view a hint about whether is displayed or not. For instance, when
7732     * a View moves out of the screen, it might receives a display hint indicating
7733     * the view is not displayed. Applications should not <em>rely</em> on this hint
7734     * as there is no guarantee that they will receive one.
7735     *
7736     * @param hint A hint about whether or not this view is displayed:
7737     * {@link #VISIBLE} or {@link #INVISIBLE}.
7738     */
7739    protected void onDisplayHint(int hint) {
7740    }
7741
7742    /**
7743     * Dispatch a window visibility change down the view hierarchy.
7744     * ViewGroups should override to route to their children.
7745     *
7746     * @param visibility The new visibility of the window.
7747     *
7748     * @see #onWindowVisibilityChanged(int)
7749     */
7750    public void dispatchWindowVisibilityChanged(int visibility) {
7751        onWindowVisibilityChanged(visibility);
7752    }
7753
7754    /**
7755     * Called when the window containing has change its visibility
7756     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7757     * that this tells you whether or not your window is being made visible
7758     * to the window manager; this does <em>not</em> tell you whether or not
7759     * your window is obscured by other windows on the screen, even if it
7760     * is itself visible.
7761     *
7762     * @param visibility The new visibility of the window.
7763     */
7764    protected void onWindowVisibilityChanged(int visibility) {
7765        if (visibility == VISIBLE) {
7766            initialAwakenScrollBars();
7767        }
7768    }
7769
7770    /**
7771     * Returns the current visibility of the window this view is attached to
7772     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7773     *
7774     * @return Returns the current visibility of the view's window.
7775     */
7776    public int getWindowVisibility() {
7777        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7778    }
7779
7780    /**
7781     * Retrieve the overall visible display size in which the window this view is
7782     * attached to has been positioned in.  This takes into account screen
7783     * decorations above the window, for both cases where the window itself
7784     * is being position inside of them or the window is being placed under
7785     * then and covered insets are used for the window to position its content
7786     * inside.  In effect, this tells you the available area where content can
7787     * be placed and remain visible to users.
7788     *
7789     * <p>This function requires an IPC back to the window manager to retrieve
7790     * the requested information, so should not be used in performance critical
7791     * code like drawing.
7792     *
7793     * @param outRect Filled in with the visible display frame.  If the view
7794     * is not attached to a window, this is simply the raw display size.
7795     */
7796    public void getWindowVisibleDisplayFrame(Rect outRect) {
7797        if (mAttachInfo != null) {
7798            try {
7799                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7800            } catch (RemoteException e) {
7801                return;
7802            }
7803            // XXX This is really broken, and probably all needs to be done
7804            // in the window manager, and we need to know more about whether
7805            // we want the area behind or in front of the IME.
7806            final Rect insets = mAttachInfo.mVisibleInsets;
7807            outRect.left += insets.left;
7808            outRect.top += insets.top;
7809            outRect.right -= insets.right;
7810            outRect.bottom -= insets.bottom;
7811            return;
7812        }
7813        // The view is not attached to a display so we don't have a context.
7814        // Make a best guess about the display size.
7815        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7816        d.getRectSize(outRect);
7817    }
7818
7819    /**
7820     * Dispatch a notification about a resource configuration change down
7821     * the view hierarchy.
7822     * ViewGroups should override to route to their children.
7823     *
7824     * @param newConfig The new resource configuration.
7825     *
7826     * @see #onConfigurationChanged(android.content.res.Configuration)
7827     */
7828    public void dispatchConfigurationChanged(Configuration newConfig) {
7829        onConfigurationChanged(newConfig);
7830    }
7831
7832    /**
7833     * Called when the current configuration of the resources being used
7834     * by the application have changed.  You can use this to decide when
7835     * to reload resources that can changed based on orientation and other
7836     * configuration characterstics.  You only need to use this if you are
7837     * not relying on the normal {@link android.app.Activity} mechanism of
7838     * recreating the activity instance upon a configuration change.
7839     *
7840     * @param newConfig The new resource configuration.
7841     */
7842    protected void onConfigurationChanged(Configuration newConfig) {
7843    }
7844
7845    /**
7846     * Private function to aggregate all per-view attributes in to the view
7847     * root.
7848     */
7849    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7850        performCollectViewAttributes(attachInfo, visibility);
7851    }
7852
7853    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7854        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7855            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7856                attachInfo.mKeepScreenOn = true;
7857            }
7858            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7859            ListenerInfo li = mListenerInfo;
7860            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7861                attachInfo.mHasSystemUiListeners = true;
7862            }
7863        }
7864    }
7865
7866    void needGlobalAttributesUpdate(boolean force) {
7867        final AttachInfo ai = mAttachInfo;
7868        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7869            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7870                    || ai.mHasSystemUiListeners) {
7871                ai.mRecomputeGlobalAttributes = true;
7872            }
7873        }
7874    }
7875
7876    /**
7877     * Returns whether the device is currently in touch mode.  Touch mode is entered
7878     * once the user begins interacting with the device by touch, and affects various
7879     * things like whether focus is always visible to the user.
7880     *
7881     * @return Whether the device is in touch mode.
7882     */
7883    @ViewDebug.ExportedProperty
7884    public boolean isInTouchMode() {
7885        if (mAttachInfo != null) {
7886            return mAttachInfo.mInTouchMode;
7887        } else {
7888            return ViewRootImpl.isInTouchMode();
7889        }
7890    }
7891
7892    /**
7893     * Returns the context the view is running in, through which it can
7894     * access the current theme, resources, etc.
7895     *
7896     * @return The view's Context.
7897     */
7898    @ViewDebug.CapturedViewProperty
7899    public final Context getContext() {
7900        return mContext;
7901    }
7902
7903    /**
7904     * Handle a key event before it is processed by any input method
7905     * associated with the view hierarchy.  This can be used to intercept
7906     * key events in special situations before the IME consumes them; a
7907     * typical example would be handling the BACK key to update the application's
7908     * UI instead of allowing the IME to see it and close itself.
7909     *
7910     * @param keyCode The value in event.getKeyCode().
7911     * @param event Description of the key event.
7912     * @return If you handled the event, return true. If you want to allow the
7913     *         event to be handled by the next receiver, return false.
7914     */
7915    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7916        return false;
7917    }
7918
7919    /**
7920     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7921     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7922     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7923     * is released, if the view is enabled and clickable.
7924     *
7925     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7926     * although some may elect to do so in some situations. Do not rely on this to
7927     * catch software key presses.
7928     *
7929     * @param keyCode A key code that represents the button pressed, from
7930     *                {@link android.view.KeyEvent}.
7931     * @param event   The KeyEvent object that defines the button action.
7932     */
7933    public boolean onKeyDown(int keyCode, KeyEvent event) {
7934        boolean result = false;
7935
7936        switch (keyCode) {
7937            case KeyEvent.KEYCODE_DPAD_CENTER:
7938            case KeyEvent.KEYCODE_ENTER: {
7939                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7940                    return true;
7941                }
7942                // Long clickable items don't necessarily have to be clickable
7943                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7944                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7945                        (event.getRepeatCount() == 0)) {
7946                    setPressed(true);
7947                    checkForLongClick(0);
7948                    return true;
7949                }
7950                break;
7951            }
7952        }
7953        return result;
7954    }
7955
7956    /**
7957     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7958     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7959     * the event).
7960     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7961     * although some may elect to do so in some situations. Do not rely on this to
7962     * catch software key presses.
7963     */
7964    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7965        return false;
7966    }
7967
7968    /**
7969     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7970     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7971     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7972     * {@link KeyEvent#KEYCODE_ENTER} is released.
7973     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7974     * although some may elect to do so in some situations. Do not rely on this to
7975     * catch software key presses.
7976     *
7977     * @param keyCode A key code that represents the button pressed, from
7978     *                {@link android.view.KeyEvent}.
7979     * @param event   The KeyEvent object that defines the button action.
7980     */
7981    public boolean onKeyUp(int keyCode, KeyEvent event) {
7982        boolean result = false;
7983
7984        switch (keyCode) {
7985            case KeyEvent.KEYCODE_DPAD_CENTER:
7986            case KeyEvent.KEYCODE_ENTER: {
7987                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7988                    return true;
7989                }
7990                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7991                    setPressed(false);
7992
7993                    if (!mHasPerformedLongPress) {
7994                        // This is a tap, so remove the longpress check
7995                        removeLongPressCallback();
7996
7997                        result = performClick();
7998                    }
7999                }
8000                break;
8001            }
8002        }
8003        return result;
8004    }
8005
8006    /**
8007     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8008     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8009     * the event).
8010     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8011     * although some may elect to do so in some situations. Do not rely on this to
8012     * catch software key presses.
8013     *
8014     * @param keyCode     A key code that represents the button pressed, from
8015     *                    {@link android.view.KeyEvent}.
8016     * @param repeatCount The number of times the action was made.
8017     * @param event       The KeyEvent object that defines the button action.
8018     */
8019    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8020        return false;
8021    }
8022
8023    /**
8024     * Called on the focused view when a key shortcut event is not handled.
8025     * Override this method to implement local key shortcuts for the View.
8026     * Key shortcuts can also be implemented by setting the
8027     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8028     *
8029     * @param keyCode The value in event.getKeyCode().
8030     * @param event Description of the key event.
8031     * @return If you handled the event, return true. If you want to allow the
8032     *         event to be handled by the next receiver, return false.
8033     */
8034    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8035        return false;
8036    }
8037
8038    /**
8039     * Check whether the called view is a text editor, in which case it
8040     * would make sense to automatically display a soft input window for
8041     * it.  Subclasses should override this if they implement
8042     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8043     * a call on that method would return a non-null InputConnection, and
8044     * they are really a first-class editor that the user would normally
8045     * start typing on when the go into a window containing your view.
8046     *
8047     * <p>The default implementation always returns false.  This does
8048     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8049     * will not be called or the user can not otherwise perform edits on your
8050     * view; it is just a hint to the system that this is not the primary
8051     * purpose of this view.
8052     *
8053     * @return Returns true if this view is a text editor, else false.
8054     */
8055    public boolean onCheckIsTextEditor() {
8056        return false;
8057    }
8058
8059    /**
8060     * Create a new InputConnection for an InputMethod to interact
8061     * with the view.  The default implementation returns null, since it doesn't
8062     * support input methods.  You can override this to implement such support.
8063     * This is only needed for views that take focus and text input.
8064     *
8065     * <p>When implementing this, you probably also want to implement
8066     * {@link #onCheckIsTextEditor()} to indicate you will return a
8067     * non-null InputConnection.
8068     *
8069     * @param outAttrs Fill in with attribute information about the connection.
8070     */
8071    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8072        return null;
8073    }
8074
8075    /**
8076     * Called by the {@link android.view.inputmethod.InputMethodManager}
8077     * when a view who is not the current
8078     * input connection target is trying to make a call on the manager.  The
8079     * default implementation returns false; you can override this to return
8080     * true for certain views if you are performing InputConnection proxying
8081     * to them.
8082     * @param view The View that is making the InputMethodManager call.
8083     * @return Return true to allow the call, false to reject.
8084     */
8085    public boolean checkInputConnectionProxy(View view) {
8086        return false;
8087    }
8088
8089    /**
8090     * Show the context menu for this view. It is not safe to hold on to the
8091     * menu after returning from this method.
8092     *
8093     * You should normally not overload this method. Overload
8094     * {@link #onCreateContextMenu(ContextMenu)} or define an
8095     * {@link OnCreateContextMenuListener} to add items to the context menu.
8096     *
8097     * @param menu The context menu to populate
8098     */
8099    public void createContextMenu(ContextMenu menu) {
8100        ContextMenuInfo menuInfo = getContextMenuInfo();
8101
8102        // Sets the current menu info so all items added to menu will have
8103        // my extra info set.
8104        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8105
8106        onCreateContextMenu(menu);
8107        ListenerInfo li = mListenerInfo;
8108        if (li != null && li.mOnCreateContextMenuListener != null) {
8109            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8110        }
8111
8112        // Clear the extra information so subsequent items that aren't mine don't
8113        // have my extra info.
8114        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8115
8116        if (mParent != null) {
8117            mParent.createContextMenu(menu);
8118        }
8119    }
8120
8121    /**
8122     * Views should implement this if they have extra information to associate
8123     * with the context menu. The return result is supplied as a parameter to
8124     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8125     * callback.
8126     *
8127     * @return Extra information about the item for which the context menu
8128     *         should be shown. This information will vary across different
8129     *         subclasses of View.
8130     */
8131    protected ContextMenuInfo getContextMenuInfo() {
8132        return null;
8133    }
8134
8135    /**
8136     * Views should implement this if the view itself is going to add items to
8137     * the context menu.
8138     *
8139     * @param menu the context menu to populate
8140     */
8141    protected void onCreateContextMenu(ContextMenu menu) {
8142    }
8143
8144    /**
8145     * Implement this method to handle trackball motion events.  The
8146     * <em>relative</em> movement of the trackball since the last event
8147     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8148     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8149     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8150     * they will often be fractional values, representing the more fine-grained
8151     * movement information available from a trackball).
8152     *
8153     * @param event The motion event.
8154     * @return True if the event was handled, false otherwise.
8155     */
8156    public boolean onTrackballEvent(MotionEvent event) {
8157        return false;
8158    }
8159
8160    /**
8161     * Implement this method to handle generic motion events.
8162     * <p>
8163     * Generic motion events describe joystick movements, mouse hovers, track pad
8164     * touches, scroll wheel movements and other input events.  The
8165     * {@link MotionEvent#getSource() source} of the motion event specifies
8166     * the class of input that was received.  Implementations of this method
8167     * must examine the bits in the source before processing the event.
8168     * The following code example shows how this is done.
8169     * </p><p>
8170     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8171     * are delivered to the view under the pointer.  All other generic motion events are
8172     * delivered to the focused view.
8173     * </p>
8174     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8175     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8176     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8177     *             // process the joystick movement...
8178     *             return true;
8179     *         }
8180     *     }
8181     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8182     *         switch (event.getAction()) {
8183     *             case MotionEvent.ACTION_HOVER_MOVE:
8184     *                 // process the mouse hover movement...
8185     *                 return true;
8186     *             case MotionEvent.ACTION_SCROLL:
8187     *                 // process the scroll wheel movement...
8188     *                 return true;
8189     *         }
8190     *     }
8191     *     return super.onGenericMotionEvent(event);
8192     * }</pre>
8193     *
8194     * @param event The generic motion event being processed.
8195     * @return True if the event was handled, false otherwise.
8196     */
8197    public boolean onGenericMotionEvent(MotionEvent event) {
8198        return false;
8199    }
8200
8201    /**
8202     * Implement this method to handle hover events.
8203     * <p>
8204     * This method is called whenever a pointer is hovering into, over, or out of the
8205     * bounds of a view and the view is not currently being touched.
8206     * Hover events are represented as pointer events with action
8207     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8208     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8209     * </p>
8210     * <ul>
8211     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8212     * when the pointer enters the bounds of the view.</li>
8213     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8214     * when the pointer has already entered the bounds of the view and has moved.</li>
8215     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8216     * when the pointer has exited the bounds of the view or when the pointer is
8217     * about to go down due to a button click, tap, or similar user action that
8218     * causes the view to be touched.</li>
8219     * </ul>
8220     * <p>
8221     * The view should implement this method to return true to indicate that it is
8222     * handling the hover event, such as by changing its drawable state.
8223     * </p><p>
8224     * The default implementation calls {@link #setHovered} to update the hovered state
8225     * of the view when a hover enter or hover exit event is received, if the view
8226     * is enabled and is clickable.  The default implementation also sends hover
8227     * accessibility events.
8228     * </p>
8229     *
8230     * @param event The motion event that describes the hover.
8231     * @return True if the view handled the hover event.
8232     *
8233     * @see #isHovered
8234     * @see #setHovered
8235     * @see #onHoverChanged
8236     */
8237    public boolean onHoverEvent(MotionEvent event) {
8238        // The root view may receive hover (or touch) events that are outside the bounds of
8239        // the window.  This code ensures that we only send accessibility events for
8240        // hovers that are actually within the bounds of the root view.
8241        final int action = event.getActionMasked();
8242        if (!mSendingHoverAccessibilityEvents) {
8243            if ((action == MotionEvent.ACTION_HOVER_ENTER
8244                    || action == MotionEvent.ACTION_HOVER_MOVE)
8245                    && !hasHoveredChild()
8246                    && pointInView(event.getX(), event.getY())) {
8247                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8248                mSendingHoverAccessibilityEvents = true;
8249            }
8250        } else {
8251            if (action == MotionEvent.ACTION_HOVER_EXIT
8252                    || (action == MotionEvent.ACTION_MOVE
8253                            && !pointInView(event.getX(), event.getY()))) {
8254                mSendingHoverAccessibilityEvents = false;
8255                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8256                // If the window does not have input focus we take away accessibility
8257                // focus as soon as the user stop hovering over the view.
8258                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8259                    getViewRootImpl().setAccessibilityFocus(null, null);
8260                }
8261            }
8262        }
8263
8264        if (isHoverable()) {
8265            switch (action) {
8266                case MotionEvent.ACTION_HOVER_ENTER:
8267                    setHovered(true);
8268                    break;
8269                case MotionEvent.ACTION_HOVER_EXIT:
8270                    setHovered(false);
8271                    break;
8272            }
8273
8274            // Dispatch the event to onGenericMotionEvent before returning true.
8275            // This is to provide compatibility with existing applications that
8276            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8277            // break because of the new default handling for hoverable views
8278            // in onHoverEvent.
8279            // Note that onGenericMotionEvent will be called by default when
8280            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8281            dispatchGenericMotionEventInternal(event);
8282            // The event was already handled by calling setHovered(), so always
8283            // return true.
8284            return true;
8285        }
8286
8287        return false;
8288    }
8289
8290    /**
8291     * Returns true if the view should handle {@link #onHoverEvent}
8292     * by calling {@link #setHovered} to change its hovered state.
8293     *
8294     * @return True if the view is hoverable.
8295     */
8296    private boolean isHoverable() {
8297        final int viewFlags = mViewFlags;
8298        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8299            return false;
8300        }
8301
8302        return (viewFlags & CLICKABLE) == CLICKABLE
8303                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8304    }
8305
8306    /**
8307     * Returns true if the view is currently hovered.
8308     *
8309     * @return True if the view is currently hovered.
8310     *
8311     * @see #setHovered
8312     * @see #onHoverChanged
8313     */
8314    @ViewDebug.ExportedProperty
8315    public boolean isHovered() {
8316        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8317    }
8318
8319    /**
8320     * Sets whether the view is currently hovered.
8321     * <p>
8322     * Calling this method also changes the drawable state of the view.  This
8323     * enables the view to react to hover by using different drawable resources
8324     * to change its appearance.
8325     * </p><p>
8326     * The {@link #onHoverChanged} method is called when the hovered state changes.
8327     * </p>
8328     *
8329     * @param hovered True if the view is hovered.
8330     *
8331     * @see #isHovered
8332     * @see #onHoverChanged
8333     */
8334    public void setHovered(boolean hovered) {
8335        if (hovered) {
8336            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8337                mPrivateFlags |= PFLAG_HOVERED;
8338                refreshDrawableState();
8339                onHoverChanged(true);
8340            }
8341        } else {
8342            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8343                mPrivateFlags &= ~PFLAG_HOVERED;
8344                refreshDrawableState();
8345                onHoverChanged(false);
8346            }
8347        }
8348    }
8349
8350    /**
8351     * Implement this method to handle hover state changes.
8352     * <p>
8353     * This method is called whenever the hover state changes as a result of a
8354     * call to {@link #setHovered}.
8355     * </p>
8356     *
8357     * @param hovered The current hover state, as returned by {@link #isHovered}.
8358     *
8359     * @see #isHovered
8360     * @see #setHovered
8361     */
8362    public void onHoverChanged(boolean hovered) {
8363    }
8364
8365    /**
8366     * Implement this method to handle touch screen motion events.
8367     *
8368     * @param event The motion event.
8369     * @return True if the event was handled, false otherwise.
8370     */
8371    public boolean onTouchEvent(MotionEvent event) {
8372        final int viewFlags = mViewFlags;
8373
8374        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8375            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8376                setPressed(false);
8377            }
8378            // A disabled view that is clickable still consumes the touch
8379            // events, it just doesn't respond to them.
8380            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8381                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8382        }
8383
8384        if (mTouchDelegate != null) {
8385            if (mTouchDelegate.onTouchEvent(event)) {
8386                return true;
8387            }
8388        }
8389
8390        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8391                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8392            switch (event.getAction()) {
8393                case MotionEvent.ACTION_UP:
8394                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8395                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8396                        // take focus if we don't have it already and we should in
8397                        // touch mode.
8398                        boolean focusTaken = false;
8399                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8400                            focusTaken = requestFocus();
8401                        }
8402
8403                        if (prepressed) {
8404                            // The button is being released before we actually
8405                            // showed it as pressed.  Make it show the pressed
8406                            // state now (before scheduling the click) to ensure
8407                            // the user sees it.
8408                            setPressed(true);
8409                       }
8410
8411                        if (!mHasPerformedLongPress) {
8412                            // This is a tap, so remove the longpress check
8413                            removeLongPressCallback();
8414
8415                            // Only perform take click actions if we were in the pressed state
8416                            if (!focusTaken) {
8417                                // Use a Runnable and post this rather than calling
8418                                // performClick directly. This lets other visual state
8419                                // of the view update before click actions start.
8420                                if (mPerformClick == null) {
8421                                    mPerformClick = new PerformClick();
8422                                }
8423                                if (!post(mPerformClick)) {
8424                                    performClick();
8425                                }
8426                            }
8427                        }
8428
8429                        if (mUnsetPressedState == null) {
8430                            mUnsetPressedState = new UnsetPressedState();
8431                        }
8432
8433                        if (prepressed) {
8434                            postDelayed(mUnsetPressedState,
8435                                    ViewConfiguration.getPressedStateDuration());
8436                        } else if (!post(mUnsetPressedState)) {
8437                            // If the post failed, unpress right now
8438                            mUnsetPressedState.run();
8439                        }
8440                        removeTapCallback();
8441                    }
8442                    break;
8443
8444                case MotionEvent.ACTION_DOWN:
8445                    mHasPerformedLongPress = false;
8446
8447                    if (performButtonActionOnTouchDown(event)) {
8448                        break;
8449                    }
8450
8451                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8452                    boolean isInScrollingContainer = isInScrollingContainer();
8453
8454                    // For views inside a scrolling container, delay the pressed feedback for
8455                    // a short period in case this is a scroll.
8456                    if (isInScrollingContainer) {
8457                        mPrivateFlags |= PFLAG_PREPRESSED;
8458                        if (mPendingCheckForTap == null) {
8459                            mPendingCheckForTap = new CheckForTap();
8460                        }
8461                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8462                    } else {
8463                        // Not inside a scrolling container, so show the feedback right away
8464                        setPressed(true);
8465                        checkForLongClick(0);
8466                    }
8467                    break;
8468
8469                case MotionEvent.ACTION_CANCEL:
8470                    setPressed(false);
8471                    removeTapCallback();
8472                    removeLongPressCallback();
8473                    break;
8474
8475                case MotionEvent.ACTION_MOVE:
8476                    final int x = (int) event.getX();
8477                    final int y = (int) event.getY();
8478
8479                    // Be lenient about moving outside of buttons
8480                    if (!pointInView(x, y, mTouchSlop)) {
8481                        // Outside button
8482                        removeTapCallback();
8483                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8484                            // Remove any future long press/tap checks
8485                            removeLongPressCallback();
8486
8487                            setPressed(false);
8488                        }
8489                    }
8490                    break;
8491            }
8492            return true;
8493        }
8494
8495        return false;
8496    }
8497
8498    /**
8499     * @hide
8500     */
8501    public boolean isInScrollingContainer() {
8502        ViewParent p = getParent();
8503        while (p != null && p instanceof ViewGroup) {
8504            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8505                return true;
8506            }
8507            p = p.getParent();
8508        }
8509        return false;
8510    }
8511
8512    /**
8513     * Remove the longpress detection timer.
8514     */
8515    private void removeLongPressCallback() {
8516        if (mPendingCheckForLongPress != null) {
8517          removeCallbacks(mPendingCheckForLongPress);
8518        }
8519    }
8520
8521    /**
8522     * Remove the pending click action
8523     */
8524    private void removePerformClickCallback() {
8525        if (mPerformClick != null) {
8526            removeCallbacks(mPerformClick);
8527        }
8528    }
8529
8530    /**
8531     * Remove the prepress detection timer.
8532     */
8533    private void removeUnsetPressCallback() {
8534        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8535            setPressed(false);
8536            removeCallbacks(mUnsetPressedState);
8537        }
8538    }
8539
8540    /**
8541     * Remove the tap detection timer.
8542     */
8543    private void removeTapCallback() {
8544        if (mPendingCheckForTap != null) {
8545            mPrivateFlags &= ~PFLAG_PREPRESSED;
8546            removeCallbacks(mPendingCheckForTap);
8547        }
8548    }
8549
8550    /**
8551     * Cancels a pending long press.  Your subclass can use this if you
8552     * want the context menu to come up if the user presses and holds
8553     * at the same place, but you don't want it to come up if they press
8554     * and then move around enough to cause scrolling.
8555     */
8556    public void cancelLongPress() {
8557        removeLongPressCallback();
8558
8559        /*
8560         * The prepressed state handled by the tap callback is a display
8561         * construct, but the tap callback will post a long press callback
8562         * less its own timeout. Remove it here.
8563         */
8564        removeTapCallback();
8565    }
8566
8567    /**
8568     * Remove the pending callback for sending a
8569     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8570     */
8571    private void removeSendViewScrolledAccessibilityEventCallback() {
8572        if (mSendViewScrolledAccessibilityEvent != null) {
8573            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8574            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8575        }
8576    }
8577
8578    /**
8579     * Sets the TouchDelegate for this View.
8580     */
8581    public void setTouchDelegate(TouchDelegate delegate) {
8582        mTouchDelegate = delegate;
8583    }
8584
8585    /**
8586     * Gets the TouchDelegate for this View.
8587     */
8588    public TouchDelegate getTouchDelegate() {
8589        return mTouchDelegate;
8590    }
8591
8592    /**
8593     * Set flags controlling behavior of this view.
8594     *
8595     * @param flags Constant indicating the value which should be set
8596     * @param mask Constant indicating the bit range that should be changed
8597     */
8598    void setFlags(int flags, int mask) {
8599        final boolean accessibilityEnabled =
8600                AccessibilityManager.getInstance(mContext).isEnabled();
8601        final boolean oldIncludeForAccessibility = accessibilityEnabled
8602                ? includeForAccessibility() : false;
8603
8604        int old = mViewFlags;
8605        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8606
8607        int changed = mViewFlags ^ old;
8608        if (changed == 0) {
8609            return;
8610        }
8611        int privateFlags = mPrivateFlags;
8612
8613        /* Check if the FOCUSABLE bit has changed */
8614        if (((changed & FOCUSABLE_MASK) != 0) &&
8615                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8616            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8617                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8618                /* Give up focus if we are no longer focusable */
8619                clearFocus();
8620            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8621                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8622                /*
8623                 * Tell the view system that we are now available to take focus
8624                 * if no one else already has it.
8625                 */
8626                if (mParent != null) mParent.focusableViewAvailable(this);
8627            }
8628        }
8629
8630        final int newVisibility = flags & VISIBILITY_MASK;
8631        if (newVisibility == VISIBLE) {
8632            if ((changed & VISIBILITY_MASK) != 0) {
8633                /*
8634                 * If this view is becoming visible, invalidate it in case it changed while
8635                 * it was not visible. Marking it drawn ensures that the invalidation will
8636                 * go through.
8637                 */
8638                mPrivateFlags |= PFLAG_DRAWN;
8639                invalidate(true);
8640
8641                needGlobalAttributesUpdate(true);
8642
8643                // a view becoming visible is worth notifying the parent
8644                // about in case nothing has focus.  even if this specific view
8645                // isn't focusable, it may contain something that is, so let
8646                // the root view try to give this focus if nothing else does.
8647                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8648                    mParent.focusableViewAvailable(this);
8649                }
8650            }
8651        }
8652
8653        /* Check if the GONE bit has changed */
8654        if ((changed & GONE) != 0) {
8655            needGlobalAttributesUpdate(false);
8656            requestLayout();
8657
8658            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8659                if (hasFocus()) clearFocus();
8660                clearAccessibilityFocus();
8661                destroyDrawingCache();
8662                if (mParent instanceof View) {
8663                    // GONE views noop invalidation, so invalidate the parent
8664                    ((View) mParent).invalidate(true);
8665                }
8666                // Mark the view drawn to ensure that it gets invalidated properly the next
8667                // time it is visible and gets invalidated
8668                mPrivateFlags |= PFLAG_DRAWN;
8669            }
8670            if (mAttachInfo != null) {
8671                mAttachInfo.mViewVisibilityChanged = true;
8672            }
8673        }
8674
8675        /* Check if the VISIBLE bit has changed */
8676        if ((changed & INVISIBLE) != 0) {
8677            needGlobalAttributesUpdate(false);
8678            /*
8679             * If this view is becoming invisible, set the DRAWN flag so that
8680             * the next invalidate() will not be skipped.
8681             */
8682            mPrivateFlags |= PFLAG_DRAWN;
8683
8684            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8685                // root view becoming invisible shouldn't clear focus and accessibility focus
8686                if (getRootView() != this) {
8687                    clearFocus();
8688                    clearAccessibilityFocus();
8689                }
8690            }
8691            if (mAttachInfo != null) {
8692                mAttachInfo.mViewVisibilityChanged = true;
8693            }
8694        }
8695
8696        if ((changed & VISIBILITY_MASK) != 0) {
8697            // If the view is invisible, cleanup its display list to free up resources
8698            if (newVisibility != VISIBLE) {
8699                cleanupDraw();
8700            }
8701
8702            if (mParent instanceof ViewGroup) {
8703                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8704                        (changed & VISIBILITY_MASK), newVisibility);
8705                ((View) mParent).invalidate(true);
8706            } else if (mParent != null) {
8707                mParent.invalidateChild(this, null);
8708            }
8709            dispatchVisibilityChanged(this, newVisibility);
8710        }
8711
8712        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8713            destroyDrawingCache();
8714        }
8715
8716        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8717            destroyDrawingCache();
8718            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8719            invalidateParentCaches();
8720        }
8721
8722        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8723            destroyDrawingCache();
8724            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8725        }
8726
8727        if ((changed & DRAW_MASK) != 0) {
8728            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8729                if (mBackground != null) {
8730                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8731                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8732                } else {
8733                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8734                }
8735            } else {
8736                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8737            }
8738            requestLayout();
8739            invalidate(true);
8740        }
8741
8742        if ((changed & KEEP_SCREEN_ON) != 0) {
8743            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8744                mParent.recomputeViewAttributes(this);
8745            }
8746        }
8747
8748        if (accessibilityEnabled) {
8749            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8750                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8751                if (oldIncludeForAccessibility != includeForAccessibility()) {
8752                    notifySubtreeAccessibilityStateChangedIfNeeded();
8753                } else {
8754                    notifyViewAccessibilityStateChangedIfNeeded();
8755                }
8756            }
8757            if ((changed & ENABLED_MASK) != 0) {
8758                notifyViewAccessibilityStateChangedIfNeeded();
8759            }
8760        }
8761    }
8762
8763    /**
8764     * Change the view's z order in the tree, so it's on top of other sibling
8765     * views. This ordering change may affect layout, if the parent container
8766     * uses an order-dependent layout scheme (e.g., LinearLayout). This
8767     * method should be followed by calls to {@link #requestLayout()} and
8768     * {@link View#invalidate()} on the parent.
8769     *
8770     * @see ViewGroup#bringChildToFront(View)
8771     */
8772    public void bringToFront() {
8773        if (mParent != null) {
8774            mParent.bringChildToFront(this);
8775        }
8776    }
8777
8778    /**
8779     * This is called in response to an internal scroll in this view (i.e., the
8780     * view scrolled its own contents). This is typically as a result of
8781     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8782     * called.
8783     *
8784     * @param l Current horizontal scroll origin.
8785     * @param t Current vertical scroll origin.
8786     * @param oldl Previous horizontal scroll origin.
8787     * @param oldt Previous vertical scroll origin.
8788     */
8789    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8790        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8791            postSendViewScrolledAccessibilityEventCallback();
8792        }
8793
8794        mBackgroundSizeChanged = true;
8795
8796        final AttachInfo ai = mAttachInfo;
8797        if (ai != null) {
8798            ai.mViewScrollChanged = true;
8799        }
8800    }
8801
8802    /**
8803     * Interface definition for a callback to be invoked when the layout bounds of a view
8804     * changes due to layout processing.
8805     */
8806    public interface OnLayoutChangeListener {
8807        /**
8808         * Called when the focus state of a view has changed.
8809         *
8810         * @param v The view whose state has changed.
8811         * @param left The new value of the view's left property.
8812         * @param top The new value of the view's top property.
8813         * @param right The new value of the view's right property.
8814         * @param bottom The new value of the view's bottom property.
8815         * @param oldLeft The previous value of the view's left property.
8816         * @param oldTop The previous value of the view's top property.
8817         * @param oldRight The previous value of the view's right property.
8818         * @param oldBottom The previous value of the view's bottom property.
8819         */
8820        void onLayoutChange(View v, int left, int top, int right, int bottom,
8821            int oldLeft, int oldTop, int oldRight, int oldBottom);
8822    }
8823
8824    /**
8825     * This is called during layout when the size of this view has changed. If
8826     * you were just added to the view hierarchy, you're called with the old
8827     * values of 0.
8828     *
8829     * @param w Current width of this view.
8830     * @param h Current height of this view.
8831     * @param oldw Old width of this view.
8832     * @param oldh Old height of this view.
8833     */
8834    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8835    }
8836
8837    /**
8838     * Called by draw to draw the child views. This may be overridden
8839     * by derived classes to gain control just before its children are drawn
8840     * (but after its own view has been drawn).
8841     * @param canvas the canvas on which to draw the view
8842     */
8843    protected void dispatchDraw(Canvas canvas) {
8844
8845    }
8846
8847    /**
8848     * Gets the parent of this view. Note that the parent is a
8849     * ViewParent and not necessarily a View.
8850     *
8851     * @return Parent of this view.
8852     */
8853    public final ViewParent getParent() {
8854        return mParent;
8855    }
8856
8857    /**
8858     * Set the horizontal scrolled position of your view. This will cause a call to
8859     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8860     * invalidated.
8861     * @param value the x position to scroll to
8862     */
8863    public void setScrollX(int value) {
8864        scrollTo(value, mScrollY);
8865    }
8866
8867    /**
8868     * Set the vertical scrolled position of your view. This will cause a call to
8869     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8870     * invalidated.
8871     * @param value the y position to scroll to
8872     */
8873    public void setScrollY(int value) {
8874        scrollTo(mScrollX, value);
8875    }
8876
8877    /**
8878     * Return the scrolled left position of this view. This is the left edge of
8879     * the displayed part of your view. You do not need to draw any pixels
8880     * farther left, since those are outside of the frame of your view on
8881     * screen.
8882     *
8883     * @return The left edge of the displayed part of your view, in pixels.
8884     */
8885    public final int getScrollX() {
8886        return mScrollX;
8887    }
8888
8889    /**
8890     * Return the scrolled top position of this view. This is the top edge of
8891     * the displayed part of your view. You do not need to draw any pixels above
8892     * it, since those are outside of the frame of your view on screen.
8893     *
8894     * @return The top edge of the displayed part of your view, in pixels.
8895     */
8896    public final int getScrollY() {
8897        return mScrollY;
8898    }
8899
8900    /**
8901     * Return the width of the your view.
8902     *
8903     * @return The width of your view, in pixels.
8904     */
8905    @ViewDebug.ExportedProperty(category = "layout")
8906    public final int getWidth() {
8907        return mRight - mLeft;
8908    }
8909
8910    /**
8911     * Return the height of your view.
8912     *
8913     * @return The height of your view, in pixels.
8914     */
8915    @ViewDebug.ExportedProperty(category = "layout")
8916    public final int getHeight() {
8917        return mBottom - mTop;
8918    }
8919
8920    /**
8921     * Return the visible drawing bounds of your view. Fills in the output
8922     * rectangle with the values from getScrollX(), getScrollY(),
8923     * getWidth(), and getHeight(). These bounds do not account for any
8924     * transformation properties currently set on the view, such as
8925     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8926     *
8927     * @param outRect The (scrolled) drawing bounds of the view.
8928     */
8929    public void getDrawingRect(Rect outRect) {
8930        outRect.left = mScrollX;
8931        outRect.top = mScrollY;
8932        outRect.right = mScrollX + (mRight - mLeft);
8933        outRect.bottom = mScrollY + (mBottom - mTop);
8934    }
8935
8936    /**
8937     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8938     * raw width component (that is the result is masked by
8939     * {@link #MEASURED_SIZE_MASK}).
8940     *
8941     * @return The raw measured width of this view.
8942     */
8943    public final int getMeasuredWidth() {
8944        return mMeasuredWidth & MEASURED_SIZE_MASK;
8945    }
8946
8947    /**
8948     * Return the full width measurement information for this view as computed
8949     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8950     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8951     * This should be used during measurement and layout calculations only. Use
8952     * {@link #getWidth()} to see how wide a view is after layout.
8953     *
8954     * @return The measured width of this view as a bit mask.
8955     */
8956    public final int getMeasuredWidthAndState() {
8957        return mMeasuredWidth;
8958    }
8959
8960    /**
8961     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8962     * raw width component (that is the result is masked by
8963     * {@link #MEASURED_SIZE_MASK}).
8964     *
8965     * @return The raw measured height of this view.
8966     */
8967    public final int getMeasuredHeight() {
8968        return mMeasuredHeight & MEASURED_SIZE_MASK;
8969    }
8970
8971    /**
8972     * Return the full height measurement information for this view as computed
8973     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8974     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8975     * This should be used during measurement and layout calculations only. Use
8976     * {@link #getHeight()} to see how wide a view is after layout.
8977     *
8978     * @return The measured width of this view as a bit mask.
8979     */
8980    public final int getMeasuredHeightAndState() {
8981        return mMeasuredHeight;
8982    }
8983
8984    /**
8985     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8986     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8987     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8988     * and the height component is at the shifted bits
8989     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8990     */
8991    public final int getMeasuredState() {
8992        return (mMeasuredWidth&MEASURED_STATE_MASK)
8993                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8994                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8995    }
8996
8997    /**
8998     * The transform matrix of this view, which is calculated based on the current
8999     * roation, scale, and pivot properties.
9000     *
9001     * @see #getRotation()
9002     * @see #getScaleX()
9003     * @see #getScaleY()
9004     * @see #getPivotX()
9005     * @see #getPivotY()
9006     * @return The current transform matrix for the view
9007     */
9008    public Matrix getMatrix() {
9009        if (mTransformationInfo != null) {
9010            updateMatrix();
9011            return mTransformationInfo.mMatrix;
9012        }
9013        return Matrix.IDENTITY_MATRIX;
9014    }
9015
9016    /**
9017     * Utility function to determine if the value is far enough away from zero to be
9018     * considered non-zero.
9019     * @param value A floating point value to check for zero-ness
9020     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9021     */
9022    private static boolean nonzero(float value) {
9023        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9024    }
9025
9026    /**
9027     * Returns true if the transform matrix is the identity matrix.
9028     * Recomputes the matrix if necessary.
9029     *
9030     * @return True if the transform matrix is the identity matrix, false otherwise.
9031     */
9032    final boolean hasIdentityMatrix() {
9033        if (mTransformationInfo != null) {
9034            updateMatrix();
9035            return mTransformationInfo.mMatrixIsIdentity;
9036        }
9037        return true;
9038    }
9039
9040    void ensureTransformationInfo() {
9041        if (mTransformationInfo == null) {
9042            mTransformationInfo = new TransformationInfo();
9043        }
9044    }
9045
9046    /**
9047     * Recomputes the transform matrix if necessary.
9048     */
9049    private void updateMatrix() {
9050        final TransformationInfo info = mTransformationInfo;
9051        if (info == null) {
9052            return;
9053        }
9054        if (info.mMatrixDirty) {
9055            // transform-related properties have changed since the last time someone
9056            // asked for the matrix; recalculate it with the current values
9057
9058            // Figure out if we need to update the pivot point
9059            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9060                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9061                    info.mPrevWidth = mRight - mLeft;
9062                    info.mPrevHeight = mBottom - mTop;
9063                    info.mPivotX = info.mPrevWidth / 2f;
9064                    info.mPivotY = info.mPrevHeight / 2f;
9065                }
9066            }
9067            info.mMatrix.reset();
9068            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9069                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9070                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9071                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9072            } else {
9073                if (info.mCamera == null) {
9074                    info.mCamera = new Camera();
9075                    info.matrix3D = new Matrix();
9076                }
9077                info.mCamera.save();
9078                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9079                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9080                info.mCamera.getMatrix(info.matrix3D);
9081                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9082                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9083                        info.mPivotY + info.mTranslationY);
9084                info.mMatrix.postConcat(info.matrix3D);
9085                info.mCamera.restore();
9086            }
9087            info.mMatrixDirty = false;
9088            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9089            info.mInverseMatrixDirty = true;
9090        }
9091    }
9092
9093   /**
9094     * Utility method to retrieve the inverse of the current mMatrix property.
9095     * We cache the matrix to avoid recalculating it when transform properties
9096     * have not changed.
9097     *
9098     * @return The inverse of the current matrix of this view.
9099     */
9100    final Matrix getInverseMatrix() {
9101        final TransformationInfo info = mTransformationInfo;
9102        if (info != null) {
9103            updateMatrix();
9104            if (info.mInverseMatrixDirty) {
9105                if (info.mInverseMatrix == null) {
9106                    info.mInverseMatrix = new Matrix();
9107                }
9108                info.mMatrix.invert(info.mInverseMatrix);
9109                info.mInverseMatrixDirty = false;
9110            }
9111            return info.mInverseMatrix;
9112        }
9113        return Matrix.IDENTITY_MATRIX;
9114    }
9115
9116    /**
9117     * Gets the distance along the Z axis from the camera to this view.
9118     *
9119     * @see #setCameraDistance(float)
9120     *
9121     * @return The distance along the Z axis.
9122     */
9123    public float getCameraDistance() {
9124        ensureTransformationInfo();
9125        final float dpi = mResources.getDisplayMetrics().densityDpi;
9126        final TransformationInfo info = mTransformationInfo;
9127        if (info.mCamera == null) {
9128            info.mCamera = new Camera();
9129            info.matrix3D = new Matrix();
9130        }
9131        return -(info.mCamera.getLocationZ() * dpi);
9132    }
9133
9134    /**
9135     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9136     * views are drawn) from the camera to this view. The camera's distance
9137     * affects 3D transformations, for instance rotations around the X and Y
9138     * axis. If the rotationX or rotationY properties are changed and this view is
9139     * large (more than half the size of the screen), it is recommended to always
9140     * use a camera distance that's greater than the height (X axis rotation) or
9141     * the width (Y axis rotation) of this view.</p>
9142     *
9143     * <p>The distance of the camera from the view plane can have an affect on the
9144     * perspective distortion of the view when it is rotated around the x or y axis.
9145     * For example, a large distance will result in a large viewing angle, and there
9146     * will not be much perspective distortion of the view as it rotates. A short
9147     * distance may cause much more perspective distortion upon rotation, and can
9148     * also result in some drawing artifacts if the rotated view ends up partially
9149     * behind the camera (which is why the recommendation is to use a distance at
9150     * least as far as the size of the view, if the view is to be rotated.)</p>
9151     *
9152     * <p>The distance is expressed in "depth pixels." The default distance depends
9153     * on the screen density. For instance, on a medium density display, the
9154     * default distance is 1280. On a high density display, the default distance
9155     * is 1920.</p>
9156     *
9157     * <p>If you want to specify a distance that leads to visually consistent
9158     * results across various densities, use the following formula:</p>
9159     * <pre>
9160     * float scale = context.getResources().getDisplayMetrics().density;
9161     * view.setCameraDistance(distance * scale);
9162     * </pre>
9163     *
9164     * <p>The density scale factor of a high density display is 1.5,
9165     * and 1920 = 1280 * 1.5.</p>
9166     *
9167     * @param distance The distance in "depth pixels", if negative the opposite
9168     *        value is used
9169     *
9170     * @see #setRotationX(float)
9171     * @see #setRotationY(float)
9172     */
9173    public void setCameraDistance(float distance) {
9174        invalidateViewProperty(true, false);
9175
9176        ensureTransformationInfo();
9177        final float dpi = mResources.getDisplayMetrics().densityDpi;
9178        final TransformationInfo info = mTransformationInfo;
9179        if (info.mCamera == null) {
9180            info.mCamera = new Camera();
9181            info.matrix3D = new Matrix();
9182        }
9183
9184        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9185        info.mMatrixDirty = true;
9186
9187        invalidateViewProperty(false, false);
9188        if (mDisplayList != null) {
9189            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9190        }
9191        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9192            // View was rejected last time it was drawn by its parent; this may have changed
9193            invalidateParentIfNeeded();
9194        }
9195    }
9196
9197    /**
9198     * The degrees that the view is rotated around the pivot point.
9199     *
9200     * @see #setRotation(float)
9201     * @see #getPivotX()
9202     * @see #getPivotY()
9203     *
9204     * @return The degrees of rotation.
9205     */
9206    @ViewDebug.ExportedProperty(category = "drawing")
9207    public float getRotation() {
9208        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9209    }
9210
9211    /**
9212     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9213     * result in clockwise rotation.
9214     *
9215     * @param rotation The degrees of rotation.
9216     *
9217     * @see #getRotation()
9218     * @see #getPivotX()
9219     * @see #getPivotY()
9220     * @see #setRotationX(float)
9221     * @see #setRotationY(float)
9222     *
9223     * @attr ref android.R.styleable#View_rotation
9224     */
9225    public void setRotation(float rotation) {
9226        ensureTransformationInfo();
9227        final TransformationInfo info = mTransformationInfo;
9228        if (info.mRotation != rotation) {
9229            // Double-invalidation is necessary to capture view's old and new areas
9230            invalidateViewProperty(true, false);
9231            info.mRotation = rotation;
9232            info.mMatrixDirty = true;
9233            invalidateViewProperty(false, true);
9234            if (mDisplayList != null) {
9235                mDisplayList.setRotation(rotation);
9236            }
9237            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9238                // View was rejected last time it was drawn by its parent; this may have changed
9239                invalidateParentIfNeeded();
9240            }
9241        }
9242    }
9243
9244    /**
9245     * The degrees that the view is rotated around the vertical axis through the pivot point.
9246     *
9247     * @see #getPivotX()
9248     * @see #getPivotY()
9249     * @see #setRotationY(float)
9250     *
9251     * @return The degrees of Y rotation.
9252     */
9253    @ViewDebug.ExportedProperty(category = "drawing")
9254    public float getRotationY() {
9255        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9256    }
9257
9258    /**
9259     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9260     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9261     * down the y axis.
9262     *
9263     * When rotating large views, it is recommended to adjust the camera distance
9264     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9265     *
9266     * @param rotationY The degrees of Y rotation.
9267     *
9268     * @see #getRotationY()
9269     * @see #getPivotX()
9270     * @see #getPivotY()
9271     * @see #setRotation(float)
9272     * @see #setRotationX(float)
9273     * @see #setCameraDistance(float)
9274     *
9275     * @attr ref android.R.styleable#View_rotationY
9276     */
9277    public void setRotationY(float rotationY) {
9278        ensureTransformationInfo();
9279        final TransformationInfo info = mTransformationInfo;
9280        if (info.mRotationY != rotationY) {
9281            invalidateViewProperty(true, false);
9282            info.mRotationY = rotationY;
9283            info.mMatrixDirty = true;
9284            invalidateViewProperty(false, true);
9285            if (mDisplayList != null) {
9286                mDisplayList.setRotationY(rotationY);
9287            }
9288            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9289                // View was rejected last time it was drawn by its parent; this may have changed
9290                invalidateParentIfNeeded();
9291            }
9292        }
9293    }
9294
9295    /**
9296     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9297     *
9298     * @see #getPivotX()
9299     * @see #getPivotY()
9300     * @see #setRotationX(float)
9301     *
9302     * @return The degrees of X rotation.
9303     */
9304    @ViewDebug.ExportedProperty(category = "drawing")
9305    public float getRotationX() {
9306        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9307    }
9308
9309    /**
9310     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9311     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9312     * x axis.
9313     *
9314     * When rotating large views, it is recommended to adjust the camera distance
9315     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9316     *
9317     * @param rotationX The degrees of X rotation.
9318     *
9319     * @see #getRotationX()
9320     * @see #getPivotX()
9321     * @see #getPivotY()
9322     * @see #setRotation(float)
9323     * @see #setRotationY(float)
9324     * @see #setCameraDistance(float)
9325     *
9326     * @attr ref android.R.styleable#View_rotationX
9327     */
9328    public void setRotationX(float rotationX) {
9329        ensureTransformationInfo();
9330        final TransformationInfo info = mTransformationInfo;
9331        if (info.mRotationX != rotationX) {
9332            invalidateViewProperty(true, false);
9333            info.mRotationX = rotationX;
9334            info.mMatrixDirty = true;
9335            invalidateViewProperty(false, true);
9336            if (mDisplayList != null) {
9337                mDisplayList.setRotationX(rotationX);
9338            }
9339            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9340                // View was rejected last time it was drawn by its parent; this may have changed
9341                invalidateParentIfNeeded();
9342            }
9343        }
9344    }
9345
9346    /**
9347     * The amount that the view is scaled in x around the pivot point, as a proportion of
9348     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9349     *
9350     * <p>By default, this is 1.0f.
9351     *
9352     * @see #getPivotX()
9353     * @see #getPivotY()
9354     * @return The scaling factor.
9355     */
9356    @ViewDebug.ExportedProperty(category = "drawing")
9357    public float getScaleX() {
9358        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9359    }
9360
9361    /**
9362     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9363     * the view's unscaled width. A value of 1 means that no scaling is applied.
9364     *
9365     * @param scaleX The scaling factor.
9366     * @see #getPivotX()
9367     * @see #getPivotY()
9368     *
9369     * @attr ref android.R.styleable#View_scaleX
9370     */
9371    public void setScaleX(float scaleX) {
9372        ensureTransformationInfo();
9373        final TransformationInfo info = mTransformationInfo;
9374        if (info.mScaleX != scaleX) {
9375            invalidateViewProperty(true, false);
9376            info.mScaleX = scaleX;
9377            info.mMatrixDirty = true;
9378            invalidateViewProperty(false, true);
9379            if (mDisplayList != null) {
9380                mDisplayList.setScaleX(scaleX);
9381            }
9382            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9383                // View was rejected last time it was drawn by its parent; this may have changed
9384                invalidateParentIfNeeded();
9385            }
9386        }
9387    }
9388
9389    /**
9390     * The amount that the view is scaled in y around the pivot point, as a proportion of
9391     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9392     *
9393     * <p>By default, this is 1.0f.
9394     *
9395     * @see #getPivotX()
9396     * @see #getPivotY()
9397     * @return The scaling factor.
9398     */
9399    @ViewDebug.ExportedProperty(category = "drawing")
9400    public float getScaleY() {
9401        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9402    }
9403
9404    /**
9405     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9406     * the view's unscaled width. A value of 1 means that no scaling is applied.
9407     *
9408     * @param scaleY The scaling factor.
9409     * @see #getPivotX()
9410     * @see #getPivotY()
9411     *
9412     * @attr ref android.R.styleable#View_scaleY
9413     */
9414    public void setScaleY(float scaleY) {
9415        ensureTransformationInfo();
9416        final TransformationInfo info = mTransformationInfo;
9417        if (info.mScaleY != scaleY) {
9418            invalidateViewProperty(true, false);
9419            info.mScaleY = scaleY;
9420            info.mMatrixDirty = true;
9421            invalidateViewProperty(false, true);
9422            if (mDisplayList != null) {
9423                mDisplayList.setScaleY(scaleY);
9424            }
9425            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9426                // View was rejected last time it was drawn by its parent; this may have changed
9427                invalidateParentIfNeeded();
9428            }
9429        }
9430    }
9431
9432    /**
9433     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9434     * and {@link #setScaleX(float) scaled}.
9435     *
9436     * @see #getRotation()
9437     * @see #getScaleX()
9438     * @see #getScaleY()
9439     * @see #getPivotY()
9440     * @return The x location of the pivot point.
9441     *
9442     * @attr ref android.R.styleable#View_transformPivotX
9443     */
9444    @ViewDebug.ExportedProperty(category = "drawing")
9445    public float getPivotX() {
9446        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9447    }
9448
9449    /**
9450     * Sets the x location of the point around which the view is
9451     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9452     * By default, the pivot point is centered on the object.
9453     * Setting this property disables this behavior and causes the view to use only the
9454     * explicitly set pivotX and pivotY values.
9455     *
9456     * @param pivotX The x location of the pivot point.
9457     * @see #getRotation()
9458     * @see #getScaleX()
9459     * @see #getScaleY()
9460     * @see #getPivotY()
9461     *
9462     * @attr ref android.R.styleable#View_transformPivotX
9463     */
9464    public void setPivotX(float pivotX) {
9465        ensureTransformationInfo();
9466        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9467        final TransformationInfo info = mTransformationInfo;
9468        if (info.mPivotX != pivotX) {
9469            invalidateViewProperty(true, false);
9470            info.mPivotX = pivotX;
9471            info.mMatrixDirty = true;
9472            invalidateViewProperty(false, true);
9473            if (mDisplayList != null) {
9474                mDisplayList.setPivotX(pivotX);
9475            }
9476            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9477                // View was rejected last time it was drawn by its parent; this may have changed
9478                invalidateParentIfNeeded();
9479            }
9480        }
9481    }
9482
9483    /**
9484     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9485     * and {@link #setScaleY(float) scaled}.
9486     *
9487     * @see #getRotation()
9488     * @see #getScaleX()
9489     * @see #getScaleY()
9490     * @see #getPivotY()
9491     * @return The y location of the pivot point.
9492     *
9493     * @attr ref android.R.styleable#View_transformPivotY
9494     */
9495    @ViewDebug.ExportedProperty(category = "drawing")
9496    public float getPivotY() {
9497        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9498    }
9499
9500    /**
9501     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9502     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9503     * Setting this property disables this behavior and causes the view to use only the
9504     * explicitly set pivotX and pivotY values.
9505     *
9506     * @param pivotY The y location of the pivot point.
9507     * @see #getRotation()
9508     * @see #getScaleX()
9509     * @see #getScaleY()
9510     * @see #getPivotY()
9511     *
9512     * @attr ref android.R.styleable#View_transformPivotY
9513     */
9514    public void setPivotY(float pivotY) {
9515        ensureTransformationInfo();
9516        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9517        final TransformationInfo info = mTransformationInfo;
9518        if (info.mPivotY != pivotY) {
9519            invalidateViewProperty(true, false);
9520            info.mPivotY = pivotY;
9521            info.mMatrixDirty = true;
9522            invalidateViewProperty(false, true);
9523            if (mDisplayList != null) {
9524                mDisplayList.setPivotY(pivotY);
9525            }
9526            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9527                // View was rejected last time it was drawn by its parent; this may have changed
9528                invalidateParentIfNeeded();
9529            }
9530        }
9531    }
9532
9533    /**
9534     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9535     * completely transparent and 1 means the view is completely opaque.
9536     *
9537     * <p>By default this is 1.0f.
9538     * @return The opacity of the view.
9539     */
9540    @ViewDebug.ExportedProperty(category = "drawing")
9541    public float getAlpha() {
9542        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9543    }
9544
9545    /**
9546     * Returns whether this View has content which overlaps. This function, intended to be
9547     * overridden by specific View types, is an optimization when alpha is set on a view. If
9548     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9549     * and then composited it into place, which can be expensive. If the view has no overlapping
9550     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9551     * An example of overlapping rendering is a TextView with a background image, such as a
9552     * Button. An example of non-overlapping rendering is a TextView with no background, or
9553     * an ImageView with only the foreground image. The default implementation returns true;
9554     * subclasses should override if they have cases which can be optimized.
9555     *
9556     * @return true if the content in this view might overlap, false otherwise.
9557     */
9558    public boolean hasOverlappingRendering() {
9559        return true;
9560    }
9561
9562    /**
9563     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9564     * completely transparent and 1 means the view is completely opaque.</p>
9565     *
9566     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9567     * performance implications, especially for large views. It is best to use the alpha property
9568     * sparingly and transiently, as in the case of fading animations.</p>
9569     *
9570     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9571     * strongly recommended for performance reasons to either override
9572     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9573     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9574     *
9575     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9576     * responsible for applying the opacity itself.</p>
9577     *
9578     * <p>Note that if the view is backed by a
9579     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9580     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9581     * 1.0 will supercede the alpha of the layer paint.</p>
9582     *
9583     * @param alpha The opacity of the view.
9584     *
9585     * @see #hasOverlappingRendering()
9586     * @see #setLayerType(int, android.graphics.Paint)
9587     *
9588     * @attr ref android.R.styleable#View_alpha
9589     */
9590    public void setAlpha(float alpha) {
9591        ensureTransformationInfo();
9592        if (mTransformationInfo.mAlpha != alpha) {
9593            mTransformationInfo.mAlpha = alpha;
9594            if (onSetAlpha((int) (alpha * 255))) {
9595                mPrivateFlags |= PFLAG_ALPHA_SET;
9596                // subclass is handling alpha - don't optimize rendering cache invalidation
9597                invalidateParentCaches();
9598                invalidate(true);
9599            } else {
9600                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9601                invalidateViewProperty(true, false);
9602                if (mDisplayList != null) {
9603                    mDisplayList.setAlpha(alpha);
9604                }
9605            }
9606        }
9607    }
9608
9609    /**
9610     * Faster version of setAlpha() which performs the same steps except there are
9611     * no calls to invalidate(). The caller of this function should perform proper invalidation
9612     * on the parent and this object. The return value indicates whether the subclass handles
9613     * alpha (the return value for onSetAlpha()).
9614     *
9615     * @param alpha The new value for the alpha property
9616     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9617     *         the new value for the alpha property is different from the old value
9618     */
9619    boolean setAlphaNoInvalidation(float alpha) {
9620        ensureTransformationInfo();
9621        if (mTransformationInfo.mAlpha != alpha) {
9622            mTransformationInfo.mAlpha = alpha;
9623            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9624            if (subclassHandlesAlpha) {
9625                mPrivateFlags |= PFLAG_ALPHA_SET;
9626                return true;
9627            } else {
9628                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9629                if (mDisplayList != null) {
9630                    mDisplayList.setAlpha(alpha);
9631                }
9632            }
9633        }
9634        return false;
9635    }
9636
9637    /**
9638     * Top position of this view relative to its parent.
9639     *
9640     * @return The top of this view, in pixels.
9641     */
9642    @ViewDebug.CapturedViewProperty
9643    public final int getTop() {
9644        return mTop;
9645    }
9646
9647    /**
9648     * Sets the top position of this view relative to its parent. This method is meant to be called
9649     * by the layout system and should not generally be called otherwise, because the property
9650     * may be changed at any time by the layout.
9651     *
9652     * @param top The top of this view, in pixels.
9653     */
9654    public final void setTop(int top) {
9655        if (top != mTop) {
9656            updateMatrix();
9657            final boolean matrixIsIdentity = mTransformationInfo == null
9658                    || mTransformationInfo.mMatrixIsIdentity;
9659            if (matrixIsIdentity) {
9660                if (mAttachInfo != null) {
9661                    int minTop;
9662                    int yLoc;
9663                    if (top < mTop) {
9664                        minTop = top;
9665                        yLoc = top - mTop;
9666                    } else {
9667                        minTop = mTop;
9668                        yLoc = 0;
9669                    }
9670                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9671                }
9672            } else {
9673                // Double-invalidation is necessary to capture view's old and new areas
9674                invalidate(true);
9675            }
9676
9677            int width = mRight - mLeft;
9678            int oldHeight = mBottom - mTop;
9679
9680            mTop = top;
9681            if (mDisplayList != null) {
9682                mDisplayList.setTop(mTop);
9683            }
9684
9685            sizeChange(width, mBottom - mTop, width, oldHeight);
9686
9687            if (!matrixIsIdentity) {
9688                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9689                    // A change in dimension means an auto-centered pivot point changes, too
9690                    mTransformationInfo.mMatrixDirty = true;
9691                }
9692                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9693                invalidate(true);
9694            }
9695            mBackgroundSizeChanged = true;
9696            invalidateParentIfNeeded();
9697            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9698                // View was rejected last time it was drawn by its parent; this may have changed
9699                invalidateParentIfNeeded();
9700            }
9701        }
9702    }
9703
9704    /**
9705     * Bottom position of this view relative to its parent.
9706     *
9707     * @return The bottom of this view, in pixels.
9708     */
9709    @ViewDebug.CapturedViewProperty
9710    public final int getBottom() {
9711        return mBottom;
9712    }
9713
9714    /**
9715     * True if this view has changed since the last time being drawn.
9716     *
9717     * @return The dirty state of this view.
9718     */
9719    public boolean isDirty() {
9720        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9721    }
9722
9723    /**
9724     * Sets the bottom position of this view relative to its parent. This method is meant to be
9725     * called by the layout system and should not generally be called otherwise, because the
9726     * property may be changed at any time by the layout.
9727     *
9728     * @param bottom The bottom of this view, in pixels.
9729     */
9730    public final void setBottom(int bottom) {
9731        if (bottom != mBottom) {
9732            updateMatrix();
9733            final boolean matrixIsIdentity = mTransformationInfo == null
9734                    || mTransformationInfo.mMatrixIsIdentity;
9735            if (matrixIsIdentity) {
9736                if (mAttachInfo != null) {
9737                    int maxBottom;
9738                    if (bottom < mBottom) {
9739                        maxBottom = mBottom;
9740                    } else {
9741                        maxBottom = bottom;
9742                    }
9743                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9744                }
9745            } else {
9746                // Double-invalidation is necessary to capture view's old and new areas
9747                invalidate(true);
9748            }
9749
9750            int width = mRight - mLeft;
9751            int oldHeight = mBottom - mTop;
9752
9753            mBottom = bottom;
9754            if (mDisplayList != null) {
9755                mDisplayList.setBottom(mBottom);
9756            }
9757
9758            sizeChange(width, mBottom - mTop, width, oldHeight);
9759
9760            if (!matrixIsIdentity) {
9761                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9762                    // A change in dimension means an auto-centered pivot point changes, too
9763                    mTransformationInfo.mMatrixDirty = true;
9764                }
9765                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9766                invalidate(true);
9767            }
9768            mBackgroundSizeChanged = true;
9769            invalidateParentIfNeeded();
9770            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9771                // View was rejected last time it was drawn by its parent; this may have changed
9772                invalidateParentIfNeeded();
9773            }
9774        }
9775    }
9776
9777    /**
9778     * Left position of this view relative to its parent.
9779     *
9780     * @return The left edge of this view, in pixels.
9781     */
9782    @ViewDebug.CapturedViewProperty
9783    public final int getLeft() {
9784        return mLeft;
9785    }
9786
9787    /**
9788     * Sets the left position of this view relative to its parent. This method is meant to be called
9789     * by the layout system and should not generally be called otherwise, because the property
9790     * may be changed at any time by the layout.
9791     *
9792     * @param left The bottom of this view, in pixels.
9793     */
9794    public final void setLeft(int left) {
9795        if (left != mLeft) {
9796            updateMatrix();
9797            final boolean matrixIsIdentity = mTransformationInfo == null
9798                    || mTransformationInfo.mMatrixIsIdentity;
9799            if (matrixIsIdentity) {
9800                if (mAttachInfo != null) {
9801                    int minLeft;
9802                    int xLoc;
9803                    if (left < mLeft) {
9804                        minLeft = left;
9805                        xLoc = left - mLeft;
9806                    } else {
9807                        minLeft = mLeft;
9808                        xLoc = 0;
9809                    }
9810                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9811                }
9812            } else {
9813                // Double-invalidation is necessary to capture view's old and new areas
9814                invalidate(true);
9815            }
9816
9817            int oldWidth = mRight - mLeft;
9818            int height = mBottom - mTop;
9819
9820            mLeft = left;
9821            if (mDisplayList != null) {
9822                mDisplayList.setLeft(left);
9823            }
9824
9825            sizeChange(mRight - mLeft, height, oldWidth, height);
9826
9827            if (!matrixIsIdentity) {
9828                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9829                    // A change in dimension means an auto-centered pivot point changes, too
9830                    mTransformationInfo.mMatrixDirty = true;
9831                }
9832                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9833                invalidate(true);
9834            }
9835            mBackgroundSizeChanged = true;
9836            invalidateParentIfNeeded();
9837            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9838                // View was rejected last time it was drawn by its parent; this may have changed
9839                invalidateParentIfNeeded();
9840            }
9841        }
9842    }
9843
9844    /**
9845     * Right position of this view relative to its parent.
9846     *
9847     * @return The right edge of this view, in pixels.
9848     */
9849    @ViewDebug.CapturedViewProperty
9850    public final int getRight() {
9851        return mRight;
9852    }
9853
9854    /**
9855     * Sets the right position of this view relative to its parent. This method is meant to be called
9856     * by the layout system and should not generally be called otherwise, because the property
9857     * may be changed at any time by the layout.
9858     *
9859     * @param right The bottom of this view, in pixels.
9860     */
9861    public final void setRight(int right) {
9862        if (right != mRight) {
9863            updateMatrix();
9864            final boolean matrixIsIdentity = mTransformationInfo == null
9865                    || mTransformationInfo.mMatrixIsIdentity;
9866            if (matrixIsIdentity) {
9867                if (mAttachInfo != null) {
9868                    int maxRight;
9869                    if (right < mRight) {
9870                        maxRight = mRight;
9871                    } else {
9872                        maxRight = right;
9873                    }
9874                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9875                }
9876            } else {
9877                // Double-invalidation is necessary to capture view's old and new areas
9878                invalidate(true);
9879            }
9880
9881            int oldWidth = mRight - mLeft;
9882            int height = mBottom - mTop;
9883
9884            mRight = right;
9885            if (mDisplayList != null) {
9886                mDisplayList.setRight(mRight);
9887            }
9888
9889            sizeChange(mRight - mLeft, height, oldWidth, height);
9890
9891            if (!matrixIsIdentity) {
9892                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9893                    // A change in dimension means an auto-centered pivot point changes, too
9894                    mTransformationInfo.mMatrixDirty = true;
9895                }
9896                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9897                invalidate(true);
9898            }
9899            mBackgroundSizeChanged = true;
9900            invalidateParentIfNeeded();
9901            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9902                // View was rejected last time it was drawn by its parent; this may have changed
9903                invalidateParentIfNeeded();
9904            }
9905        }
9906    }
9907
9908    /**
9909     * The visual x position of this view, in pixels. This is equivalent to the
9910     * {@link #setTranslationX(float) translationX} property plus the current
9911     * {@link #getLeft() left} property.
9912     *
9913     * @return The visual x position of this view, in pixels.
9914     */
9915    @ViewDebug.ExportedProperty(category = "drawing")
9916    public float getX() {
9917        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9918    }
9919
9920    /**
9921     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9922     * {@link #setTranslationX(float) translationX} property to be the difference between
9923     * the x value passed in and the current {@link #getLeft() left} property.
9924     *
9925     * @param x The visual x position of this view, in pixels.
9926     */
9927    public void setX(float x) {
9928        setTranslationX(x - mLeft);
9929    }
9930
9931    /**
9932     * The visual y position of this view, in pixels. This is equivalent to the
9933     * {@link #setTranslationY(float) translationY} property plus the current
9934     * {@link #getTop() top} property.
9935     *
9936     * @return The visual y position of this view, in pixels.
9937     */
9938    @ViewDebug.ExportedProperty(category = "drawing")
9939    public float getY() {
9940        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9941    }
9942
9943    /**
9944     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9945     * {@link #setTranslationY(float) translationY} property to be the difference between
9946     * the y value passed in and the current {@link #getTop() top} property.
9947     *
9948     * @param y The visual y position of this view, in pixels.
9949     */
9950    public void setY(float y) {
9951        setTranslationY(y - mTop);
9952    }
9953
9954
9955    /**
9956     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9957     * This position is post-layout, in addition to wherever the object's
9958     * layout placed it.
9959     *
9960     * @return The horizontal position of this view relative to its left position, in pixels.
9961     */
9962    @ViewDebug.ExportedProperty(category = "drawing")
9963    public float getTranslationX() {
9964        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9965    }
9966
9967    /**
9968     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9969     * This effectively positions the object post-layout, in addition to wherever the object's
9970     * layout placed it.
9971     *
9972     * @param translationX The horizontal position of this view relative to its left position,
9973     * in pixels.
9974     *
9975     * @attr ref android.R.styleable#View_translationX
9976     */
9977    public void setTranslationX(float translationX) {
9978        ensureTransformationInfo();
9979        final TransformationInfo info = mTransformationInfo;
9980        if (info.mTranslationX != translationX) {
9981            // Double-invalidation is necessary to capture view's old and new areas
9982            invalidateViewProperty(true, false);
9983            info.mTranslationX = translationX;
9984            info.mMatrixDirty = true;
9985            invalidateViewProperty(false, true);
9986            if (mDisplayList != null) {
9987                mDisplayList.setTranslationX(translationX);
9988            }
9989            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9990                // View was rejected last time it was drawn by its parent; this may have changed
9991                invalidateParentIfNeeded();
9992            }
9993        }
9994    }
9995
9996    /**
9997     * The horizontal location of this view relative to its {@link #getTop() top} position.
9998     * This position is post-layout, in addition to wherever the object's
9999     * layout placed it.
10000     *
10001     * @return The vertical position of this view relative to its top position,
10002     * in pixels.
10003     */
10004    @ViewDebug.ExportedProperty(category = "drawing")
10005    public float getTranslationY() {
10006        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10007    }
10008
10009    /**
10010     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10011     * This effectively positions the object post-layout, in addition to wherever the object's
10012     * layout placed it.
10013     *
10014     * @param translationY The vertical position of this view relative to its top position,
10015     * in pixels.
10016     *
10017     * @attr ref android.R.styleable#View_translationY
10018     */
10019    public void setTranslationY(float translationY) {
10020        ensureTransformationInfo();
10021        final TransformationInfo info = mTransformationInfo;
10022        if (info.mTranslationY != translationY) {
10023            invalidateViewProperty(true, false);
10024            info.mTranslationY = translationY;
10025            info.mMatrixDirty = true;
10026            invalidateViewProperty(false, true);
10027            if (mDisplayList != null) {
10028                mDisplayList.setTranslationY(translationY);
10029            }
10030            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10031                // View was rejected last time it was drawn by its parent; this may have changed
10032                invalidateParentIfNeeded();
10033            }
10034        }
10035    }
10036
10037    /**
10038     * Hit rectangle in parent's coordinates
10039     *
10040     * @param outRect The hit rectangle of the view.
10041     */
10042    public void getHitRect(Rect outRect) {
10043        updateMatrix();
10044        final TransformationInfo info = mTransformationInfo;
10045        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10046            outRect.set(mLeft, mTop, mRight, mBottom);
10047        } else {
10048            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10049            tmpRect.set(0, 0, getWidth(), getHeight());
10050            info.mMatrix.mapRect(tmpRect);
10051            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10052                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10053        }
10054    }
10055
10056    /**
10057     * Determines whether the given point, in local coordinates is inside the view.
10058     */
10059    /*package*/ final boolean pointInView(float localX, float localY) {
10060        return localX >= 0 && localX < (mRight - mLeft)
10061                && localY >= 0 && localY < (mBottom - mTop);
10062    }
10063
10064    /**
10065     * Utility method to determine whether the given point, in local coordinates,
10066     * is inside the view, where the area of the view is expanded by the slop factor.
10067     * This method is called while processing touch-move events to determine if the event
10068     * is still within the view.
10069     */
10070    private boolean pointInView(float localX, float localY, float slop) {
10071        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10072                localY < ((mBottom - mTop) + slop);
10073    }
10074
10075    /**
10076     * When a view has focus and the user navigates away from it, the next view is searched for
10077     * starting from the rectangle filled in by this method.
10078     *
10079     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10080     * of the view.  However, if your view maintains some idea of internal selection,
10081     * such as a cursor, or a selected row or column, you should override this method and
10082     * fill in a more specific rectangle.
10083     *
10084     * @param r The rectangle to fill in, in this view's coordinates.
10085     */
10086    public void getFocusedRect(Rect r) {
10087        getDrawingRect(r);
10088    }
10089
10090    /**
10091     * If some part of this view is not clipped by any of its parents, then
10092     * return that area in r in global (root) coordinates. To convert r to local
10093     * coordinates (without taking possible View rotations into account), offset
10094     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10095     * If the view is completely clipped or translated out, return false.
10096     *
10097     * @param r If true is returned, r holds the global coordinates of the
10098     *        visible portion of this view.
10099     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10100     *        between this view and its root. globalOffet may be null.
10101     * @return true if r is non-empty (i.e. part of the view is visible at the
10102     *         root level.
10103     */
10104    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10105        int width = mRight - mLeft;
10106        int height = mBottom - mTop;
10107        if (width > 0 && height > 0) {
10108            r.set(0, 0, width, height);
10109            if (globalOffset != null) {
10110                globalOffset.set(-mScrollX, -mScrollY);
10111            }
10112            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10113        }
10114        return false;
10115    }
10116
10117    public final boolean getGlobalVisibleRect(Rect r) {
10118        return getGlobalVisibleRect(r, null);
10119    }
10120
10121    public final boolean getLocalVisibleRect(Rect r) {
10122        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10123        if (getGlobalVisibleRect(r, offset)) {
10124            r.offset(-offset.x, -offset.y); // make r local
10125            return true;
10126        }
10127        return false;
10128    }
10129
10130    /**
10131     * Offset this view's vertical location by the specified number of pixels.
10132     *
10133     * @param offset the number of pixels to offset the view by
10134     */
10135    public void offsetTopAndBottom(int offset) {
10136        if (offset != 0) {
10137            updateMatrix();
10138            final boolean matrixIsIdentity = mTransformationInfo == null
10139                    || mTransformationInfo.mMatrixIsIdentity;
10140            if (matrixIsIdentity) {
10141                if (mDisplayList != null) {
10142                    invalidateViewProperty(false, false);
10143                } else {
10144                    final ViewParent p = mParent;
10145                    if (p != null && mAttachInfo != null) {
10146                        final Rect r = mAttachInfo.mTmpInvalRect;
10147                        int minTop;
10148                        int maxBottom;
10149                        int yLoc;
10150                        if (offset < 0) {
10151                            minTop = mTop + offset;
10152                            maxBottom = mBottom;
10153                            yLoc = offset;
10154                        } else {
10155                            minTop = mTop;
10156                            maxBottom = mBottom + offset;
10157                            yLoc = 0;
10158                        }
10159                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10160                        p.invalidateChild(this, r);
10161                    }
10162                }
10163            } else {
10164                invalidateViewProperty(false, false);
10165            }
10166
10167            mTop += offset;
10168            mBottom += offset;
10169            if (mDisplayList != null) {
10170                mDisplayList.offsetTopAndBottom(offset);
10171                invalidateViewProperty(false, false);
10172            } else {
10173                if (!matrixIsIdentity) {
10174                    invalidateViewProperty(false, true);
10175                }
10176                invalidateParentIfNeeded();
10177            }
10178        }
10179    }
10180
10181    /**
10182     * Offset this view's horizontal location by the specified amount of pixels.
10183     *
10184     * @param offset the number of pixels to offset the view by
10185     */
10186    public void offsetLeftAndRight(int offset) {
10187        if (offset != 0) {
10188            updateMatrix();
10189            final boolean matrixIsIdentity = mTransformationInfo == null
10190                    || mTransformationInfo.mMatrixIsIdentity;
10191            if (matrixIsIdentity) {
10192                if (mDisplayList != null) {
10193                    invalidateViewProperty(false, false);
10194                } else {
10195                    final ViewParent p = mParent;
10196                    if (p != null && mAttachInfo != null) {
10197                        final Rect r = mAttachInfo.mTmpInvalRect;
10198                        int minLeft;
10199                        int maxRight;
10200                        if (offset < 0) {
10201                            minLeft = mLeft + offset;
10202                            maxRight = mRight;
10203                        } else {
10204                            minLeft = mLeft;
10205                            maxRight = mRight + offset;
10206                        }
10207                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10208                        p.invalidateChild(this, r);
10209                    }
10210                }
10211            } else {
10212                invalidateViewProperty(false, false);
10213            }
10214
10215            mLeft += offset;
10216            mRight += offset;
10217            if (mDisplayList != null) {
10218                mDisplayList.offsetLeftAndRight(offset);
10219                invalidateViewProperty(false, false);
10220            } else {
10221                if (!matrixIsIdentity) {
10222                    invalidateViewProperty(false, true);
10223                }
10224                invalidateParentIfNeeded();
10225            }
10226        }
10227    }
10228
10229    /**
10230     * Get the LayoutParams associated with this view. All views should have
10231     * layout parameters. These supply parameters to the <i>parent</i> of this
10232     * view specifying how it should be arranged. There are many subclasses of
10233     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10234     * of ViewGroup that are responsible for arranging their children.
10235     *
10236     * This method may return null if this View is not attached to a parent
10237     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10238     * was not invoked successfully. When a View is attached to a parent
10239     * ViewGroup, this method must not return null.
10240     *
10241     * @return The LayoutParams associated with this view, or null if no
10242     *         parameters have been set yet
10243     */
10244    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10245    public ViewGroup.LayoutParams getLayoutParams() {
10246        return mLayoutParams;
10247    }
10248
10249    /**
10250     * Set the layout parameters associated with this view. These supply
10251     * parameters to the <i>parent</i> of this view specifying how it should be
10252     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10253     * correspond to the different subclasses of ViewGroup that are responsible
10254     * for arranging their children.
10255     *
10256     * @param params The layout parameters for this view, cannot be null
10257     */
10258    public void setLayoutParams(ViewGroup.LayoutParams params) {
10259        if (params == null) {
10260            throw new NullPointerException("Layout parameters cannot be null");
10261        }
10262        mLayoutParams = params;
10263        resolveLayoutParams();
10264        if (mParent instanceof ViewGroup) {
10265            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10266        }
10267        requestLayout();
10268    }
10269
10270    /**
10271     * Resolve the layout parameters depending on the resolved layout direction
10272     *
10273     * @hide
10274     */
10275    public void resolveLayoutParams() {
10276        if (mLayoutParams != null) {
10277            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10278        }
10279    }
10280
10281    /**
10282     * Set the scrolled position of your view. This will cause a call to
10283     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10284     * invalidated.
10285     * @param x the x position to scroll to
10286     * @param y the y position to scroll to
10287     */
10288    public void scrollTo(int x, int y) {
10289        if (mScrollX != x || mScrollY != y) {
10290            int oldX = mScrollX;
10291            int oldY = mScrollY;
10292            mScrollX = x;
10293            mScrollY = y;
10294            invalidateParentCaches();
10295            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10296            if (!awakenScrollBars()) {
10297                postInvalidateOnAnimation();
10298            }
10299        }
10300    }
10301
10302    /**
10303     * Move the scrolled position of your view. This will cause a call to
10304     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10305     * invalidated.
10306     * @param x the amount of pixels to scroll by horizontally
10307     * @param y the amount of pixels to scroll by vertically
10308     */
10309    public void scrollBy(int x, int y) {
10310        scrollTo(mScrollX + x, mScrollY + y);
10311    }
10312
10313    /**
10314     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10315     * animation to fade the scrollbars out after a default delay. If a subclass
10316     * provides animated scrolling, the start delay should equal the duration
10317     * of the scrolling animation.</p>
10318     *
10319     * <p>The animation starts only if at least one of the scrollbars is
10320     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10321     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10322     * this method returns true, and false otherwise. If the animation is
10323     * started, this method calls {@link #invalidate()}; in that case the
10324     * caller should not call {@link #invalidate()}.</p>
10325     *
10326     * <p>This method should be invoked every time a subclass directly updates
10327     * the scroll parameters.</p>
10328     *
10329     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10330     * and {@link #scrollTo(int, int)}.</p>
10331     *
10332     * @return true if the animation is played, false otherwise
10333     *
10334     * @see #awakenScrollBars(int)
10335     * @see #scrollBy(int, int)
10336     * @see #scrollTo(int, int)
10337     * @see #isHorizontalScrollBarEnabled()
10338     * @see #isVerticalScrollBarEnabled()
10339     * @see #setHorizontalScrollBarEnabled(boolean)
10340     * @see #setVerticalScrollBarEnabled(boolean)
10341     */
10342    protected boolean awakenScrollBars() {
10343        return mScrollCache != null &&
10344                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10345    }
10346
10347    /**
10348     * Trigger the scrollbars to draw.
10349     * This method differs from awakenScrollBars() only in its default duration.
10350     * initialAwakenScrollBars() will show the scroll bars for longer than
10351     * usual to give the user more of a chance to notice them.
10352     *
10353     * @return true if the animation is played, false otherwise.
10354     */
10355    private boolean initialAwakenScrollBars() {
10356        return mScrollCache != null &&
10357                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10358    }
10359
10360    /**
10361     * <p>
10362     * Trigger the scrollbars to draw. When invoked this method starts an
10363     * animation to fade the scrollbars out after a fixed delay. If a subclass
10364     * provides animated scrolling, the start delay should equal the duration of
10365     * the scrolling animation.
10366     * </p>
10367     *
10368     * <p>
10369     * The animation starts only if at least one of the scrollbars is enabled,
10370     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10371     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10372     * this method returns true, and false otherwise. If the animation is
10373     * started, this method calls {@link #invalidate()}; in that case the caller
10374     * should not call {@link #invalidate()}.
10375     * </p>
10376     *
10377     * <p>
10378     * This method should be invoked everytime a subclass directly updates the
10379     * scroll parameters.
10380     * </p>
10381     *
10382     * @param startDelay the delay, in milliseconds, after which the animation
10383     *        should start; when the delay is 0, the animation starts
10384     *        immediately
10385     * @return true if the animation is played, false otherwise
10386     *
10387     * @see #scrollBy(int, int)
10388     * @see #scrollTo(int, int)
10389     * @see #isHorizontalScrollBarEnabled()
10390     * @see #isVerticalScrollBarEnabled()
10391     * @see #setHorizontalScrollBarEnabled(boolean)
10392     * @see #setVerticalScrollBarEnabled(boolean)
10393     */
10394    protected boolean awakenScrollBars(int startDelay) {
10395        return awakenScrollBars(startDelay, true);
10396    }
10397
10398    /**
10399     * <p>
10400     * Trigger the scrollbars to draw. When invoked this method starts an
10401     * animation to fade the scrollbars out after a fixed delay. If a subclass
10402     * provides animated scrolling, the start delay should equal the duration of
10403     * the scrolling animation.
10404     * </p>
10405     *
10406     * <p>
10407     * The animation starts only if at least one of the scrollbars is enabled,
10408     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10409     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10410     * this method returns true, and false otherwise. If the animation is
10411     * started, this method calls {@link #invalidate()} if the invalidate parameter
10412     * is set to true; in that case the caller
10413     * should not call {@link #invalidate()}.
10414     * </p>
10415     *
10416     * <p>
10417     * This method should be invoked everytime a subclass directly updates the
10418     * scroll parameters.
10419     * </p>
10420     *
10421     * @param startDelay the delay, in milliseconds, after which the animation
10422     *        should start; when the delay is 0, the animation starts
10423     *        immediately
10424     *
10425     * @param invalidate Wheter this method should call invalidate
10426     *
10427     * @return true if the animation is played, false otherwise
10428     *
10429     * @see #scrollBy(int, int)
10430     * @see #scrollTo(int, int)
10431     * @see #isHorizontalScrollBarEnabled()
10432     * @see #isVerticalScrollBarEnabled()
10433     * @see #setHorizontalScrollBarEnabled(boolean)
10434     * @see #setVerticalScrollBarEnabled(boolean)
10435     */
10436    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10437        final ScrollabilityCache scrollCache = mScrollCache;
10438
10439        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10440            return false;
10441        }
10442
10443        if (scrollCache.scrollBar == null) {
10444            scrollCache.scrollBar = new ScrollBarDrawable();
10445        }
10446
10447        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10448
10449            if (invalidate) {
10450                // Invalidate to show the scrollbars
10451                postInvalidateOnAnimation();
10452            }
10453
10454            if (scrollCache.state == ScrollabilityCache.OFF) {
10455                // FIXME: this is copied from WindowManagerService.
10456                // We should get this value from the system when it
10457                // is possible to do so.
10458                final int KEY_REPEAT_FIRST_DELAY = 750;
10459                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10460            }
10461
10462            // Tell mScrollCache when we should start fading. This may
10463            // extend the fade start time if one was already scheduled
10464            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10465            scrollCache.fadeStartTime = fadeStartTime;
10466            scrollCache.state = ScrollabilityCache.ON;
10467
10468            // Schedule our fader to run, unscheduling any old ones first
10469            if (mAttachInfo != null) {
10470                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10471                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10472            }
10473
10474            return true;
10475        }
10476
10477        return false;
10478    }
10479
10480    /**
10481     * Do not invalidate views which are not visible and which are not running an animation. They
10482     * will not get drawn and they should not set dirty flags as if they will be drawn
10483     */
10484    private boolean skipInvalidate() {
10485        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10486                (!(mParent instanceof ViewGroup) ||
10487                        !((ViewGroup) mParent).isViewTransitioning(this));
10488    }
10489    /**
10490     * Mark the area defined by dirty as needing to be drawn. If the view is
10491     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10492     * in the future. This must be called from a UI thread. To call from a non-UI
10493     * thread, call {@link #postInvalidate()}.
10494     *
10495     * WARNING: This method is destructive to dirty.
10496     * @param dirty the rectangle representing the bounds of the dirty region
10497     */
10498    public void invalidate(Rect dirty) {
10499        if (skipInvalidate()) {
10500            return;
10501        }
10502        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10503                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10504                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10505            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10506            mPrivateFlags |= PFLAG_INVALIDATED;
10507            mPrivateFlags |= PFLAG_DIRTY;
10508            final ViewParent p = mParent;
10509            final AttachInfo ai = mAttachInfo;
10510            //noinspection PointlessBooleanExpression,ConstantConditions
10511            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10512                if (p != null && ai != null && ai.mHardwareAccelerated) {
10513                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10514                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10515                    p.invalidateChild(this, null);
10516                    return;
10517                }
10518            }
10519            if (p != null && ai != null) {
10520                final int scrollX = mScrollX;
10521                final int scrollY = mScrollY;
10522                final Rect r = ai.mTmpInvalRect;
10523                r.set(dirty.left - scrollX, dirty.top - scrollY,
10524                        dirty.right - scrollX, dirty.bottom - scrollY);
10525                mParent.invalidateChild(this, r);
10526            }
10527        }
10528    }
10529
10530    /**
10531     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10532     * The coordinates of the dirty rect are relative to the view.
10533     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10534     * will be called at some point in the future. This must be called from
10535     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10536     * @param l the left position of the dirty region
10537     * @param t the top position of the dirty region
10538     * @param r the right position of the dirty region
10539     * @param b the bottom position of the dirty region
10540     */
10541    public void invalidate(int l, int t, int r, int b) {
10542        if (skipInvalidate()) {
10543            return;
10544        }
10545        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10546                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10547                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10548            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10549            mPrivateFlags |= PFLAG_INVALIDATED;
10550            mPrivateFlags |= PFLAG_DIRTY;
10551            final ViewParent p = mParent;
10552            final AttachInfo ai = mAttachInfo;
10553            //noinspection PointlessBooleanExpression,ConstantConditions
10554            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10555                if (p != null && ai != null && ai.mHardwareAccelerated) {
10556                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10557                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10558                    p.invalidateChild(this, null);
10559                    return;
10560                }
10561            }
10562            if (p != null && ai != null && l < r && t < b) {
10563                final int scrollX = mScrollX;
10564                final int scrollY = mScrollY;
10565                final Rect tmpr = ai.mTmpInvalRect;
10566                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10567                p.invalidateChild(this, tmpr);
10568            }
10569        }
10570    }
10571
10572    /**
10573     * Invalidate the whole view. If the view is visible,
10574     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10575     * the future. This must be called from a UI thread. To call from a non-UI thread,
10576     * call {@link #postInvalidate()}.
10577     */
10578    public void invalidate() {
10579        invalidate(true);
10580    }
10581
10582    /**
10583     * This is where the invalidate() work actually happens. A full invalidate()
10584     * causes the drawing cache to be invalidated, but this function can be called with
10585     * invalidateCache set to false to skip that invalidation step for cases that do not
10586     * need it (for example, a component that remains at the same dimensions with the same
10587     * content).
10588     *
10589     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10590     * well. This is usually true for a full invalidate, but may be set to false if the
10591     * View's contents or dimensions have not changed.
10592     */
10593    void invalidate(boolean invalidateCache) {
10594        if (skipInvalidate()) {
10595            return;
10596        }
10597        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10598                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10599                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10600            mLastIsOpaque = isOpaque();
10601            mPrivateFlags &= ~PFLAG_DRAWN;
10602            mPrivateFlags |= PFLAG_DIRTY;
10603            if (invalidateCache) {
10604                mPrivateFlags |= PFLAG_INVALIDATED;
10605                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10606            }
10607            final AttachInfo ai = mAttachInfo;
10608            final ViewParent p = mParent;
10609            //noinspection PointlessBooleanExpression,ConstantConditions
10610            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10611                if (p != null && ai != null && ai.mHardwareAccelerated) {
10612                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10613                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10614                    p.invalidateChild(this, null);
10615                    return;
10616                }
10617            }
10618
10619            if (p != null && ai != null) {
10620                final Rect r = ai.mTmpInvalRect;
10621                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10622                // Don't call invalidate -- we don't want to internally scroll
10623                // our own bounds
10624                p.invalidateChild(this, r);
10625            }
10626        }
10627    }
10628
10629    /**
10630     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10631     * set any flags or handle all of the cases handled by the default invalidation methods.
10632     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10633     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10634     * walk up the hierarchy, transforming the dirty rect as necessary.
10635     *
10636     * The method also handles normal invalidation logic if display list properties are not
10637     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10638     * backup approach, to handle these cases used in the various property-setting methods.
10639     *
10640     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10641     * are not being used in this view
10642     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10643     * list properties are not being used in this view
10644     */
10645    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10646        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10647            if (invalidateParent) {
10648                invalidateParentCaches();
10649            }
10650            if (forceRedraw) {
10651                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10652            }
10653            invalidate(false);
10654        } else {
10655            final AttachInfo ai = mAttachInfo;
10656            final ViewParent p = mParent;
10657            if (p != null && ai != null) {
10658                final Rect r = ai.mTmpInvalRect;
10659                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10660                if (mParent instanceof ViewGroup) {
10661                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10662                } else {
10663                    mParent.invalidateChild(this, r);
10664                }
10665            }
10666        }
10667    }
10668
10669    /**
10670     * Utility method to transform a given Rect by the current matrix of this view.
10671     */
10672    void transformRect(final Rect rect) {
10673        if (!getMatrix().isIdentity()) {
10674            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10675            boundingRect.set(rect);
10676            getMatrix().mapRect(boundingRect);
10677            rect.set((int) Math.floor(boundingRect.left),
10678                    (int) Math.floor(boundingRect.top),
10679                    (int) Math.ceil(boundingRect.right),
10680                    (int) Math.ceil(boundingRect.bottom));
10681        }
10682    }
10683
10684    /**
10685     * Used to indicate that the parent of this view should clear its caches. This functionality
10686     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10687     * which is necessary when various parent-managed properties of the view change, such as
10688     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10689     * clears the parent caches and does not causes an invalidate event.
10690     *
10691     * @hide
10692     */
10693    protected void invalidateParentCaches() {
10694        if (mParent instanceof View) {
10695            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10696        }
10697    }
10698
10699    /**
10700     * Used to indicate that the parent of this view should be invalidated. This functionality
10701     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10702     * which is necessary when various parent-managed properties of the view change, such as
10703     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10704     * an invalidation event to the parent.
10705     *
10706     * @hide
10707     */
10708    protected void invalidateParentIfNeeded() {
10709        if (isHardwareAccelerated() && mParent instanceof View) {
10710            ((View) mParent).invalidate(true);
10711        }
10712    }
10713
10714    /**
10715     * Indicates whether this View is opaque. An opaque View guarantees that it will
10716     * draw all the pixels overlapping its bounds using a fully opaque color.
10717     *
10718     * Subclasses of View should override this method whenever possible to indicate
10719     * whether an instance is opaque. Opaque Views are treated in a special way by
10720     * the View hierarchy, possibly allowing it to perform optimizations during
10721     * invalidate/draw passes.
10722     *
10723     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10724     */
10725    @ViewDebug.ExportedProperty(category = "drawing")
10726    public boolean isOpaque() {
10727        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10728                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10729    }
10730
10731    /**
10732     * @hide
10733     */
10734    protected void computeOpaqueFlags() {
10735        // Opaque if:
10736        //   - Has a background
10737        //   - Background is opaque
10738        //   - Doesn't have scrollbars or scrollbars overlay
10739
10740        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10741            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10742        } else {
10743            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10744        }
10745
10746        final int flags = mViewFlags;
10747        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10748                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10749                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10750            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10751        } else {
10752            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10753        }
10754    }
10755
10756    /**
10757     * @hide
10758     */
10759    protected boolean hasOpaqueScrollbars() {
10760        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10761    }
10762
10763    /**
10764     * @return A handler associated with the thread running the View. This
10765     * handler can be used to pump events in the UI events queue.
10766     */
10767    public Handler getHandler() {
10768        final AttachInfo attachInfo = mAttachInfo;
10769        if (attachInfo != null) {
10770            return attachInfo.mHandler;
10771        }
10772        return null;
10773    }
10774
10775    /**
10776     * Gets the view root associated with the View.
10777     * @return The view root, or null if none.
10778     * @hide
10779     */
10780    public ViewRootImpl getViewRootImpl() {
10781        if (mAttachInfo != null) {
10782            return mAttachInfo.mViewRootImpl;
10783        }
10784        return null;
10785    }
10786
10787    /**
10788     * <p>Causes the Runnable to be added to the message queue.
10789     * The runnable will be run on the user interface thread.</p>
10790     *
10791     * @param action The Runnable that will be executed.
10792     *
10793     * @return Returns true if the Runnable was successfully placed in to the
10794     *         message queue.  Returns false on failure, usually because the
10795     *         looper processing the message queue is exiting.
10796     *
10797     * @see #postDelayed
10798     * @see #removeCallbacks
10799     */
10800    public boolean post(Runnable action) {
10801        final AttachInfo attachInfo = mAttachInfo;
10802        if (attachInfo != null) {
10803            return attachInfo.mHandler.post(action);
10804        }
10805        // Assume that post will succeed later
10806        ViewRootImpl.getRunQueue().post(action);
10807        return true;
10808    }
10809
10810    /**
10811     * <p>Causes the Runnable to be added to the message queue, to be run
10812     * after the specified amount of time elapses.
10813     * The runnable will be run on the user interface thread.</p>
10814     *
10815     * @param action The Runnable that will be executed.
10816     * @param delayMillis The delay (in milliseconds) until the Runnable
10817     *        will be executed.
10818     *
10819     * @return true if the Runnable was successfully placed in to the
10820     *         message queue.  Returns false on failure, usually because the
10821     *         looper processing the message queue is exiting.  Note that a
10822     *         result of true does not mean the Runnable will be processed --
10823     *         if the looper is quit before the delivery time of the message
10824     *         occurs then the message will be dropped.
10825     *
10826     * @see #post
10827     * @see #removeCallbacks
10828     */
10829    public boolean postDelayed(Runnable action, long delayMillis) {
10830        final AttachInfo attachInfo = mAttachInfo;
10831        if (attachInfo != null) {
10832            return attachInfo.mHandler.postDelayed(action, delayMillis);
10833        }
10834        // Assume that post will succeed later
10835        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10836        return true;
10837    }
10838
10839    /**
10840     * <p>Causes the Runnable to execute on the next animation time step.
10841     * The runnable will be run on the user interface thread.</p>
10842     *
10843     * @param action The Runnable that will be executed.
10844     *
10845     * @see #postOnAnimationDelayed
10846     * @see #removeCallbacks
10847     */
10848    public void postOnAnimation(Runnable action) {
10849        final AttachInfo attachInfo = mAttachInfo;
10850        if (attachInfo != null) {
10851            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10852                    Choreographer.CALLBACK_ANIMATION, action, null);
10853        } else {
10854            // Assume that post will succeed later
10855            ViewRootImpl.getRunQueue().post(action);
10856        }
10857    }
10858
10859    /**
10860     * <p>Causes the Runnable to execute on the next animation time step,
10861     * after the specified amount of time elapses.
10862     * The runnable will be run on the user interface thread.</p>
10863     *
10864     * @param action The Runnable that will be executed.
10865     * @param delayMillis The delay (in milliseconds) until the Runnable
10866     *        will be executed.
10867     *
10868     * @see #postOnAnimation
10869     * @see #removeCallbacks
10870     */
10871    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10872        final AttachInfo attachInfo = mAttachInfo;
10873        if (attachInfo != null) {
10874            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10875                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10876        } else {
10877            // Assume that post will succeed later
10878            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10879        }
10880    }
10881
10882    /**
10883     * <p>Removes the specified Runnable from the message queue.</p>
10884     *
10885     * @param action The Runnable to remove from the message handling queue
10886     *
10887     * @return true if this view could ask the Handler to remove the Runnable,
10888     *         false otherwise. When the returned value is true, the Runnable
10889     *         may or may not have been actually removed from the message queue
10890     *         (for instance, if the Runnable was not in the queue already.)
10891     *
10892     * @see #post
10893     * @see #postDelayed
10894     * @see #postOnAnimation
10895     * @see #postOnAnimationDelayed
10896     */
10897    public boolean removeCallbacks(Runnable action) {
10898        if (action != null) {
10899            final AttachInfo attachInfo = mAttachInfo;
10900            if (attachInfo != null) {
10901                attachInfo.mHandler.removeCallbacks(action);
10902                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10903                        Choreographer.CALLBACK_ANIMATION, action, null);
10904            } else {
10905                // Assume that post will succeed later
10906                ViewRootImpl.getRunQueue().removeCallbacks(action);
10907            }
10908        }
10909        return true;
10910    }
10911
10912    /**
10913     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10914     * Use this to invalidate the View from a non-UI thread.</p>
10915     *
10916     * <p>This method can be invoked from outside of the UI thread
10917     * only when this View is attached to a window.</p>
10918     *
10919     * @see #invalidate()
10920     * @see #postInvalidateDelayed(long)
10921     */
10922    public void postInvalidate() {
10923        postInvalidateDelayed(0);
10924    }
10925
10926    /**
10927     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10928     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10929     *
10930     * <p>This method can be invoked from outside of the UI thread
10931     * only when this View is attached to a window.</p>
10932     *
10933     * @param left The left coordinate of the rectangle to invalidate.
10934     * @param top The top coordinate of the rectangle to invalidate.
10935     * @param right The right coordinate of the rectangle to invalidate.
10936     * @param bottom The bottom coordinate of the rectangle to invalidate.
10937     *
10938     * @see #invalidate(int, int, int, int)
10939     * @see #invalidate(Rect)
10940     * @see #postInvalidateDelayed(long, int, int, int, int)
10941     */
10942    public void postInvalidate(int left, int top, int right, int bottom) {
10943        postInvalidateDelayed(0, left, top, right, bottom);
10944    }
10945
10946    /**
10947     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10948     * loop. Waits for the specified amount of time.</p>
10949     *
10950     * <p>This method can be invoked from outside of the UI thread
10951     * only when this View is attached to a window.</p>
10952     *
10953     * @param delayMilliseconds the duration in milliseconds to delay the
10954     *         invalidation by
10955     *
10956     * @see #invalidate()
10957     * @see #postInvalidate()
10958     */
10959    public void postInvalidateDelayed(long delayMilliseconds) {
10960        // We try only with the AttachInfo because there's no point in invalidating
10961        // if we are not attached to our window
10962        final AttachInfo attachInfo = mAttachInfo;
10963        if (attachInfo != null) {
10964            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10965        }
10966    }
10967
10968    /**
10969     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10970     * through the event loop. Waits for the specified amount of time.</p>
10971     *
10972     * <p>This method can be invoked from outside of the UI thread
10973     * only when this View is attached to a window.</p>
10974     *
10975     * @param delayMilliseconds the duration in milliseconds to delay the
10976     *         invalidation by
10977     * @param left The left coordinate of the rectangle to invalidate.
10978     * @param top The top coordinate of the rectangle to invalidate.
10979     * @param right The right coordinate of the rectangle to invalidate.
10980     * @param bottom The bottom coordinate of the rectangle to invalidate.
10981     *
10982     * @see #invalidate(int, int, int, int)
10983     * @see #invalidate(Rect)
10984     * @see #postInvalidate(int, int, int, int)
10985     */
10986    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10987            int right, int bottom) {
10988
10989        // We try only with the AttachInfo because there's no point in invalidating
10990        // if we are not attached to our window
10991        final AttachInfo attachInfo = mAttachInfo;
10992        if (attachInfo != null) {
10993            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10994            info.target = this;
10995            info.left = left;
10996            info.top = top;
10997            info.right = right;
10998            info.bottom = bottom;
10999
11000            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11001        }
11002    }
11003
11004    /**
11005     * <p>Cause an invalidate to happen on the next animation time step, typically the
11006     * next display frame.</p>
11007     *
11008     * <p>This method can be invoked from outside of the UI thread
11009     * only when this View is attached to a window.</p>
11010     *
11011     * @see #invalidate()
11012     */
11013    public void postInvalidateOnAnimation() {
11014        // We try only with the AttachInfo because there's no point in invalidating
11015        // if we are not attached to our window
11016        final AttachInfo attachInfo = mAttachInfo;
11017        if (attachInfo != null) {
11018            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11019        }
11020    }
11021
11022    /**
11023     * <p>Cause an invalidate of the specified area to happen on the next animation
11024     * time step, typically the next display frame.</p>
11025     *
11026     * <p>This method can be invoked from outside of the UI thread
11027     * only when this View is attached to a window.</p>
11028     *
11029     * @param left The left coordinate of the rectangle to invalidate.
11030     * @param top The top coordinate of the rectangle to invalidate.
11031     * @param right The right coordinate of the rectangle to invalidate.
11032     * @param bottom The bottom coordinate of the rectangle to invalidate.
11033     *
11034     * @see #invalidate(int, int, int, int)
11035     * @see #invalidate(Rect)
11036     */
11037    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11038        // We try only with the AttachInfo because there's no point in invalidating
11039        // if we are not attached to our window
11040        final AttachInfo attachInfo = mAttachInfo;
11041        if (attachInfo != null) {
11042            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11043            info.target = this;
11044            info.left = left;
11045            info.top = top;
11046            info.right = right;
11047            info.bottom = bottom;
11048
11049            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11050        }
11051    }
11052
11053    /**
11054     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11055     * This event is sent at most once every
11056     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11057     */
11058    private void postSendViewScrolledAccessibilityEventCallback() {
11059        if (mSendViewScrolledAccessibilityEvent == null) {
11060            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11061        }
11062        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11063            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11064            postDelayed(mSendViewScrolledAccessibilityEvent,
11065                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11066        }
11067    }
11068
11069    /**
11070     * Called by a parent to request that a child update its values for mScrollX
11071     * and mScrollY if necessary. This will typically be done if the child is
11072     * animating a scroll using a {@link android.widget.Scroller Scroller}
11073     * object.
11074     */
11075    public void computeScroll() {
11076    }
11077
11078    /**
11079     * <p>Indicate whether the horizontal edges are faded when the view is
11080     * scrolled horizontally.</p>
11081     *
11082     * @return true if the horizontal edges should are faded on scroll, false
11083     *         otherwise
11084     *
11085     * @see #setHorizontalFadingEdgeEnabled(boolean)
11086     *
11087     * @attr ref android.R.styleable#View_requiresFadingEdge
11088     */
11089    public boolean isHorizontalFadingEdgeEnabled() {
11090        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11091    }
11092
11093    /**
11094     * <p>Define whether the horizontal edges should be faded when this view
11095     * is scrolled horizontally.</p>
11096     *
11097     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11098     *                                    be faded when the view is scrolled
11099     *                                    horizontally
11100     *
11101     * @see #isHorizontalFadingEdgeEnabled()
11102     *
11103     * @attr ref android.R.styleable#View_requiresFadingEdge
11104     */
11105    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11106        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11107            if (horizontalFadingEdgeEnabled) {
11108                initScrollCache();
11109            }
11110
11111            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11112        }
11113    }
11114
11115    /**
11116     * <p>Indicate whether the vertical edges are faded when the view is
11117     * scrolled horizontally.</p>
11118     *
11119     * @return true if the vertical edges should are faded on scroll, false
11120     *         otherwise
11121     *
11122     * @see #setVerticalFadingEdgeEnabled(boolean)
11123     *
11124     * @attr ref android.R.styleable#View_requiresFadingEdge
11125     */
11126    public boolean isVerticalFadingEdgeEnabled() {
11127        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11128    }
11129
11130    /**
11131     * <p>Define whether the vertical edges should be faded when this view
11132     * is scrolled vertically.</p>
11133     *
11134     * @param verticalFadingEdgeEnabled true if the vertical edges should
11135     *                                  be faded when the view is scrolled
11136     *                                  vertically
11137     *
11138     * @see #isVerticalFadingEdgeEnabled()
11139     *
11140     * @attr ref android.R.styleable#View_requiresFadingEdge
11141     */
11142    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11143        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11144            if (verticalFadingEdgeEnabled) {
11145                initScrollCache();
11146            }
11147
11148            mViewFlags ^= FADING_EDGE_VERTICAL;
11149        }
11150    }
11151
11152    /**
11153     * Returns the strength, or intensity, of the top faded edge. The strength is
11154     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11155     * returns 0.0 or 1.0 but no value in between.
11156     *
11157     * Subclasses should override this method to provide a smoother fade transition
11158     * when scrolling occurs.
11159     *
11160     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11161     */
11162    protected float getTopFadingEdgeStrength() {
11163        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11164    }
11165
11166    /**
11167     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11168     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11169     * returns 0.0 or 1.0 but no value in between.
11170     *
11171     * Subclasses should override this method to provide a smoother fade transition
11172     * when scrolling occurs.
11173     *
11174     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11175     */
11176    protected float getBottomFadingEdgeStrength() {
11177        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11178                computeVerticalScrollRange() ? 1.0f : 0.0f;
11179    }
11180
11181    /**
11182     * Returns the strength, or intensity, of the left faded edge. The strength is
11183     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11184     * returns 0.0 or 1.0 but no value in between.
11185     *
11186     * Subclasses should override this method to provide a smoother fade transition
11187     * when scrolling occurs.
11188     *
11189     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11190     */
11191    protected float getLeftFadingEdgeStrength() {
11192        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11193    }
11194
11195    /**
11196     * Returns the strength, or intensity, of the right faded edge. The strength is
11197     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11198     * returns 0.0 or 1.0 but no value in between.
11199     *
11200     * Subclasses should override this method to provide a smoother fade transition
11201     * when scrolling occurs.
11202     *
11203     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11204     */
11205    protected float getRightFadingEdgeStrength() {
11206        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11207                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11208    }
11209
11210    /**
11211     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11212     * scrollbar is not drawn by default.</p>
11213     *
11214     * @return true if the horizontal scrollbar should be painted, false
11215     *         otherwise
11216     *
11217     * @see #setHorizontalScrollBarEnabled(boolean)
11218     */
11219    public boolean isHorizontalScrollBarEnabled() {
11220        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11221    }
11222
11223    /**
11224     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11225     * scrollbar is not drawn by default.</p>
11226     *
11227     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11228     *                                   be painted
11229     *
11230     * @see #isHorizontalScrollBarEnabled()
11231     */
11232    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11233        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11234            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11235            computeOpaqueFlags();
11236            resolvePadding();
11237        }
11238    }
11239
11240    /**
11241     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11242     * scrollbar is not drawn by default.</p>
11243     *
11244     * @return true if the vertical scrollbar should be painted, false
11245     *         otherwise
11246     *
11247     * @see #setVerticalScrollBarEnabled(boolean)
11248     */
11249    public boolean isVerticalScrollBarEnabled() {
11250        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11251    }
11252
11253    /**
11254     * <p>Define whether the vertical scrollbar should be drawn or not. The
11255     * scrollbar is not drawn by default.</p>
11256     *
11257     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11258     *                                 be painted
11259     *
11260     * @see #isVerticalScrollBarEnabled()
11261     */
11262    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11263        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11264            mViewFlags ^= SCROLLBARS_VERTICAL;
11265            computeOpaqueFlags();
11266            resolvePadding();
11267        }
11268    }
11269
11270    /**
11271     * @hide
11272     */
11273    protected void recomputePadding() {
11274        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11275    }
11276
11277    /**
11278     * Define whether scrollbars will fade when the view is not scrolling.
11279     *
11280     * @param fadeScrollbars wheter to enable fading
11281     *
11282     * @attr ref android.R.styleable#View_fadeScrollbars
11283     */
11284    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11285        initScrollCache();
11286        final ScrollabilityCache scrollabilityCache = mScrollCache;
11287        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11288        if (fadeScrollbars) {
11289            scrollabilityCache.state = ScrollabilityCache.OFF;
11290        } else {
11291            scrollabilityCache.state = ScrollabilityCache.ON;
11292        }
11293    }
11294
11295    /**
11296     *
11297     * Returns true if scrollbars will fade when this view is not scrolling
11298     *
11299     * @return true if scrollbar fading is enabled
11300     *
11301     * @attr ref android.R.styleable#View_fadeScrollbars
11302     */
11303    public boolean isScrollbarFadingEnabled() {
11304        return mScrollCache != null && mScrollCache.fadeScrollBars;
11305    }
11306
11307    /**
11308     *
11309     * Returns the delay before scrollbars fade.
11310     *
11311     * @return the delay before scrollbars fade
11312     *
11313     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11314     */
11315    public int getScrollBarDefaultDelayBeforeFade() {
11316        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11317                mScrollCache.scrollBarDefaultDelayBeforeFade;
11318    }
11319
11320    /**
11321     * Define the delay before scrollbars fade.
11322     *
11323     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11324     *
11325     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11326     */
11327    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11328        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11329    }
11330
11331    /**
11332     *
11333     * Returns the scrollbar fade duration.
11334     *
11335     * @return the scrollbar fade duration
11336     *
11337     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11338     */
11339    public int getScrollBarFadeDuration() {
11340        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11341                mScrollCache.scrollBarFadeDuration;
11342    }
11343
11344    /**
11345     * Define the scrollbar fade duration.
11346     *
11347     * @param scrollBarFadeDuration - the scrollbar fade duration
11348     *
11349     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11350     */
11351    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11352        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11353    }
11354
11355    /**
11356     *
11357     * Returns the scrollbar size.
11358     *
11359     * @return the scrollbar size
11360     *
11361     * @attr ref android.R.styleable#View_scrollbarSize
11362     */
11363    public int getScrollBarSize() {
11364        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11365                mScrollCache.scrollBarSize;
11366    }
11367
11368    /**
11369     * Define the scrollbar size.
11370     *
11371     * @param scrollBarSize - the scrollbar size
11372     *
11373     * @attr ref android.R.styleable#View_scrollbarSize
11374     */
11375    public void setScrollBarSize(int scrollBarSize) {
11376        getScrollCache().scrollBarSize = scrollBarSize;
11377    }
11378
11379    /**
11380     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11381     * inset. When inset, they add to the padding of the view. And the scrollbars
11382     * can be drawn inside the padding area or on the edge of the view. For example,
11383     * if a view has a background drawable and you want to draw the scrollbars
11384     * inside the padding specified by the drawable, you can use
11385     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11386     * appear at the edge of the view, ignoring the padding, then you can use
11387     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11388     * @param style the style of the scrollbars. Should be one of
11389     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11390     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11391     * @see #SCROLLBARS_INSIDE_OVERLAY
11392     * @see #SCROLLBARS_INSIDE_INSET
11393     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11394     * @see #SCROLLBARS_OUTSIDE_INSET
11395     *
11396     * @attr ref android.R.styleable#View_scrollbarStyle
11397     */
11398    public void setScrollBarStyle(int style) {
11399        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11400            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11401            computeOpaqueFlags();
11402            resolvePadding();
11403        }
11404    }
11405
11406    /**
11407     * <p>Returns the current scrollbar style.</p>
11408     * @return the current scrollbar style
11409     * @see #SCROLLBARS_INSIDE_OVERLAY
11410     * @see #SCROLLBARS_INSIDE_INSET
11411     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11412     * @see #SCROLLBARS_OUTSIDE_INSET
11413     *
11414     * @attr ref android.R.styleable#View_scrollbarStyle
11415     */
11416    @ViewDebug.ExportedProperty(mapping = {
11417            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11418            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11419            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11420            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11421    })
11422    public int getScrollBarStyle() {
11423        return mViewFlags & SCROLLBARS_STYLE_MASK;
11424    }
11425
11426    /**
11427     * <p>Compute the horizontal range that the horizontal scrollbar
11428     * represents.</p>
11429     *
11430     * <p>The range is expressed in arbitrary units that must be the same as the
11431     * units used by {@link #computeHorizontalScrollExtent()} and
11432     * {@link #computeHorizontalScrollOffset()}.</p>
11433     *
11434     * <p>The default range is the drawing width of this view.</p>
11435     *
11436     * @return the total horizontal range represented by the horizontal
11437     *         scrollbar
11438     *
11439     * @see #computeHorizontalScrollExtent()
11440     * @see #computeHorizontalScrollOffset()
11441     * @see android.widget.ScrollBarDrawable
11442     */
11443    protected int computeHorizontalScrollRange() {
11444        return getWidth();
11445    }
11446
11447    /**
11448     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11449     * within the horizontal range. This value is used to compute the position
11450     * of the thumb within the scrollbar's track.</p>
11451     *
11452     * <p>The range is expressed in arbitrary units that must be the same as the
11453     * units used by {@link #computeHorizontalScrollRange()} and
11454     * {@link #computeHorizontalScrollExtent()}.</p>
11455     *
11456     * <p>The default offset is the scroll offset of this view.</p>
11457     *
11458     * @return the horizontal offset of the scrollbar's thumb
11459     *
11460     * @see #computeHorizontalScrollRange()
11461     * @see #computeHorizontalScrollExtent()
11462     * @see android.widget.ScrollBarDrawable
11463     */
11464    protected int computeHorizontalScrollOffset() {
11465        return mScrollX;
11466    }
11467
11468    /**
11469     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11470     * within the horizontal range. This value is used to compute the length
11471     * of the thumb within the scrollbar's track.</p>
11472     *
11473     * <p>The range is expressed in arbitrary units that must be the same as the
11474     * units used by {@link #computeHorizontalScrollRange()} and
11475     * {@link #computeHorizontalScrollOffset()}.</p>
11476     *
11477     * <p>The default extent is the drawing width of this view.</p>
11478     *
11479     * @return the horizontal extent of the scrollbar's thumb
11480     *
11481     * @see #computeHorizontalScrollRange()
11482     * @see #computeHorizontalScrollOffset()
11483     * @see android.widget.ScrollBarDrawable
11484     */
11485    protected int computeHorizontalScrollExtent() {
11486        return getWidth();
11487    }
11488
11489    /**
11490     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11491     *
11492     * <p>The range is expressed in arbitrary units that must be the same as the
11493     * units used by {@link #computeVerticalScrollExtent()} and
11494     * {@link #computeVerticalScrollOffset()}.</p>
11495     *
11496     * @return the total vertical range represented by the vertical scrollbar
11497     *
11498     * <p>The default range is the drawing height of this view.</p>
11499     *
11500     * @see #computeVerticalScrollExtent()
11501     * @see #computeVerticalScrollOffset()
11502     * @see android.widget.ScrollBarDrawable
11503     */
11504    protected int computeVerticalScrollRange() {
11505        return getHeight();
11506    }
11507
11508    /**
11509     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11510     * within the horizontal range. This value is used to compute the position
11511     * of the thumb within the scrollbar's track.</p>
11512     *
11513     * <p>The range is expressed in arbitrary units that must be the same as the
11514     * units used by {@link #computeVerticalScrollRange()} and
11515     * {@link #computeVerticalScrollExtent()}.</p>
11516     *
11517     * <p>The default offset is the scroll offset of this view.</p>
11518     *
11519     * @return the vertical offset of the scrollbar's thumb
11520     *
11521     * @see #computeVerticalScrollRange()
11522     * @see #computeVerticalScrollExtent()
11523     * @see android.widget.ScrollBarDrawable
11524     */
11525    protected int computeVerticalScrollOffset() {
11526        return mScrollY;
11527    }
11528
11529    /**
11530     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11531     * within the vertical range. This value is used to compute the length
11532     * of the thumb within the scrollbar's track.</p>
11533     *
11534     * <p>The range is expressed in arbitrary units that must be the same as the
11535     * units used by {@link #computeVerticalScrollRange()} and
11536     * {@link #computeVerticalScrollOffset()}.</p>
11537     *
11538     * <p>The default extent is the drawing height of this view.</p>
11539     *
11540     * @return the vertical extent of the scrollbar's thumb
11541     *
11542     * @see #computeVerticalScrollRange()
11543     * @see #computeVerticalScrollOffset()
11544     * @see android.widget.ScrollBarDrawable
11545     */
11546    protected int computeVerticalScrollExtent() {
11547        return getHeight();
11548    }
11549
11550    /**
11551     * Check if this view can be scrolled horizontally in a certain direction.
11552     *
11553     * @param direction Negative to check scrolling left, positive to check scrolling right.
11554     * @return true if this view can be scrolled in the specified direction, false otherwise.
11555     */
11556    public boolean canScrollHorizontally(int direction) {
11557        final int offset = computeHorizontalScrollOffset();
11558        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11559        if (range == 0) return false;
11560        if (direction < 0) {
11561            return offset > 0;
11562        } else {
11563            return offset < range - 1;
11564        }
11565    }
11566
11567    /**
11568     * Check if this view can be scrolled vertically in a certain direction.
11569     *
11570     * @param direction Negative to check scrolling up, positive to check scrolling down.
11571     * @return true if this view can be scrolled in the specified direction, false otherwise.
11572     */
11573    public boolean canScrollVertically(int direction) {
11574        final int offset = computeVerticalScrollOffset();
11575        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11576        if (range == 0) return false;
11577        if (direction < 0) {
11578            return offset > 0;
11579        } else {
11580            return offset < range - 1;
11581        }
11582    }
11583
11584    /**
11585     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11586     * scrollbars are painted only if they have been awakened first.</p>
11587     *
11588     * @param canvas the canvas on which to draw the scrollbars
11589     *
11590     * @see #awakenScrollBars(int)
11591     */
11592    protected final void onDrawScrollBars(Canvas canvas) {
11593        // scrollbars are drawn only when the animation is running
11594        final ScrollabilityCache cache = mScrollCache;
11595        if (cache != null) {
11596
11597            int state = cache.state;
11598
11599            if (state == ScrollabilityCache.OFF) {
11600                return;
11601            }
11602
11603            boolean invalidate = false;
11604
11605            if (state == ScrollabilityCache.FADING) {
11606                // We're fading -- get our fade interpolation
11607                if (cache.interpolatorValues == null) {
11608                    cache.interpolatorValues = new float[1];
11609                }
11610
11611                float[] values = cache.interpolatorValues;
11612
11613                // Stops the animation if we're done
11614                if (cache.scrollBarInterpolator.timeToValues(values) ==
11615                        Interpolator.Result.FREEZE_END) {
11616                    cache.state = ScrollabilityCache.OFF;
11617                } else {
11618                    cache.scrollBar.setAlpha(Math.round(values[0]));
11619                }
11620
11621                // This will make the scroll bars inval themselves after
11622                // drawing. We only want this when we're fading so that
11623                // we prevent excessive redraws
11624                invalidate = true;
11625            } else {
11626                // We're just on -- but we may have been fading before so
11627                // reset alpha
11628                cache.scrollBar.setAlpha(255);
11629            }
11630
11631
11632            final int viewFlags = mViewFlags;
11633
11634            final boolean drawHorizontalScrollBar =
11635                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11636            final boolean drawVerticalScrollBar =
11637                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11638                && !isVerticalScrollBarHidden();
11639
11640            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11641                final int width = mRight - mLeft;
11642                final int height = mBottom - mTop;
11643
11644                final ScrollBarDrawable scrollBar = cache.scrollBar;
11645
11646                final int scrollX = mScrollX;
11647                final int scrollY = mScrollY;
11648                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11649
11650                int left;
11651                int top;
11652                int right;
11653                int bottom;
11654
11655                if (drawHorizontalScrollBar) {
11656                    int size = scrollBar.getSize(false);
11657                    if (size <= 0) {
11658                        size = cache.scrollBarSize;
11659                    }
11660
11661                    scrollBar.setParameters(computeHorizontalScrollRange(),
11662                                            computeHorizontalScrollOffset(),
11663                                            computeHorizontalScrollExtent(), false);
11664                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11665                            getVerticalScrollbarWidth() : 0;
11666                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11667                    left = scrollX + (mPaddingLeft & inside);
11668                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11669                    bottom = top + size;
11670                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11671                    if (invalidate) {
11672                        invalidate(left, top, right, bottom);
11673                    }
11674                }
11675
11676                if (drawVerticalScrollBar) {
11677                    int size = scrollBar.getSize(true);
11678                    if (size <= 0) {
11679                        size = cache.scrollBarSize;
11680                    }
11681
11682                    scrollBar.setParameters(computeVerticalScrollRange(),
11683                                            computeVerticalScrollOffset(),
11684                                            computeVerticalScrollExtent(), true);
11685                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11686                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11687                        verticalScrollbarPosition = isLayoutRtl() ?
11688                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11689                    }
11690                    switch (verticalScrollbarPosition) {
11691                        default:
11692                        case SCROLLBAR_POSITION_RIGHT:
11693                            left = scrollX + width - size - (mUserPaddingRight & inside);
11694                            break;
11695                        case SCROLLBAR_POSITION_LEFT:
11696                            left = scrollX + (mUserPaddingLeft & inside);
11697                            break;
11698                    }
11699                    top = scrollY + (mPaddingTop & inside);
11700                    right = left + size;
11701                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11702                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11703                    if (invalidate) {
11704                        invalidate(left, top, right, bottom);
11705                    }
11706                }
11707            }
11708        }
11709    }
11710
11711    /**
11712     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11713     * FastScroller is visible.
11714     * @return whether to temporarily hide the vertical scrollbar
11715     * @hide
11716     */
11717    protected boolean isVerticalScrollBarHidden() {
11718        return false;
11719    }
11720
11721    /**
11722     * <p>Draw the horizontal scrollbar if
11723     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11724     *
11725     * @param canvas the canvas on which to draw the scrollbar
11726     * @param scrollBar the scrollbar's drawable
11727     *
11728     * @see #isHorizontalScrollBarEnabled()
11729     * @see #computeHorizontalScrollRange()
11730     * @see #computeHorizontalScrollExtent()
11731     * @see #computeHorizontalScrollOffset()
11732     * @see android.widget.ScrollBarDrawable
11733     * @hide
11734     */
11735    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11736            int l, int t, int r, int b) {
11737        scrollBar.setBounds(l, t, r, b);
11738        scrollBar.draw(canvas);
11739    }
11740
11741    /**
11742     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11743     * returns true.</p>
11744     *
11745     * @param canvas the canvas on which to draw the scrollbar
11746     * @param scrollBar the scrollbar's drawable
11747     *
11748     * @see #isVerticalScrollBarEnabled()
11749     * @see #computeVerticalScrollRange()
11750     * @see #computeVerticalScrollExtent()
11751     * @see #computeVerticalScrollOffset()
11752     * @see android.widget.ScrollBarDrawable
11753     * @hide
11754     */
11755    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11756            int l, int t, int r, int b) {
11757        scrollBar.setBounds(l, t, r, b);
11758        scrollBar.draw(canvas);
11759    }
11760
11761    /**
11762     * Implement this to do your drawing.
11763     *
11764     * @param canvas the canvas on which the background will be drawn
11765     */
11766    protected void onDraw(Canvas canvas) {
11767    }
11768
11769    /*
11770     * Caller is responsible for calling requestLayout if necessary.
11771     * (This allows addViewInLayout to not request a new layout.)
11772     */
11773    void assignParent(ViewParent parent) {
11774        if (mParent == null) {
11775            mParent = parent;
11776        } else if (parent == null) {
11777            mParent = null;
11778        } else {
11779            throw new RuntimeException("view " + this + " being added, but"
11780                    + " it already has a parent");
11781        }
11782    }
11783
11784    /**
11785     * This is called when the view is attached to a window.  At this point it
11786     * has a Surface and will start drawing.  Note that this function is
11787     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11788     * however it may be called any time before the first onDraw -- including
11789     * before or after {@link #onMeasure(int, int)}.
11790     *
11791     * @see #onDetachedFromWindow()
11792     */
11793    protected void onAttachedToWindow() {
11794        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11795            mParent.requestTransparentRegion(this);
11796        }
11797
11798        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11799            initialAwakenScrollBars();
11800            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11801        }
11802
11803        mPrivateFlags3 &= ~PFLAG3_HAS_LAYOUT;
11804
11805        jumpDrawablesToCurrentState();
11806
11807        clearAccessibilityFocus();
11808        resetSubtreeAccessibilityStateChanged();
11809
11810        if (isFocused()) {
11811            InputMethodManager imm = InputMethodManager.peekInstance();
11812            imm.focusIn(this);
11813        }
11814
11815        if (mDisplayList != null) {
11816            mDisplayList.clearDirty();
11817        }
11818    }
11819
11820    /**
11821     * Resolve all RTL related properties.
11822     *
11823     * @return true if resolution of RTL properties has been done
11824     *
11825     * @hide
11826     */
11827    public boolean resolveRtlPropertiesIfNeeded() {
11828        if (!needRtlPropertiesResolution()) return false;
11829
11830        // Order is important here: LayoutDirection MUST be resolved first
11831        if (!isLayoutDirectionResolved()) {
11832            resolveLayoutDirection();
11833            resolveLayoutParams();
11834        }
11835        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11836        if (!isTextDirectionResolved()) {
11837            resolveTextDirection();
11838        }
11839        if (!isTextAlignmentResolved()) {
11840            resolveTextAlignment();
11841        }
11842        if (!isPaddingResolved()) {
11843            resolvePadding();
11844        }
11845        if (!isDrawablesResolved()) {
11846            resolveDrawables();
11847        }
11848        onRtlPropertiesChanged(getLayoutDirection());
11849        return true;
11850    }
11851
11852    /**
11853     * Reset resolution of all RTL related properties.
11854     *
11855     * @hide
11856     */
11857    public void resetRtlProperties() {
11858        resetResolvedLayoutDirection();
11859        resetResolvedTextDirection();
11860        resetResolvedTextAlignment();
11861        resetResolvedPadding();
11862        resetResolvedDrawables();
11863    }
11864
11865    /**
11866     * @see #onScreenStateChanged(int)
11867     */
11868    void dispatchScreenStateChanged(int screenState) {
11869        onScreenStateChanged(screenState);
11870    }
11871
11872    /**
11873     * This method is called whenever the state of the screen this view is
11874     * attached to changes. A state change will usually occurs when the screen
11875     * turns on or off (whether it happens automatically or the user does it
11876     * manually.)
11877     *
11878     * @param screenState The new state of the screen. Can be either
11879     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11880     */
11881    public void onScreenStateChanged(int screenState) {
11882    }
11883
11884    /**
11885     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11886     */
11887    private boolean hasRtlSupport() {
11888        return mContext.getApplicationInfo().hasRtlSupport();
11889    }
11890
11891    /**
11892     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11893     * RTL not supported)
11894     */
11895    private boolean isRtlCompatibilityMode() {
11896        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11897        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11898    }
11899
11900    /**
11901     * @return true if RTL properties need resolution.
11902     *
11903     */
11904    private boolean needRtlPropertiesResolution() {
11905        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11906    }
11907
11908    /**
11909     * Called when any RTL property (layout direction or text direction or text alignment) has
11910     * been changed.
11911     *
11912     * Subclasses need to override this method to take care of cached information that depends on the
11913     * resolved layout direction, or to inform child views that inherit their layout direction.
11914     *
11915     * The default implementation does nothing.
11916     *
11917     * @param layoutDirection the direction of the layout
11918     *
11919     * @see #LAYOUT_DIRECTION_LTR
11920     * @see #LAYOUT_DIRECTION_RTL
11921     */
11922    public void onRtlPropertiesChanged(int layoutDirection) {
11923    }
11924
11925    /**
11926     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11927     * that the parent directionality can and will be resolved before its children.
11928     *
11929     * @return true if resolution has been done, false otherwise.
11930     *
11931     * @hide
11932     */
11933    public boolean resolveLayoutDirection() {
11934        // Clear any previous layout direction resolution
11935        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11936
11937        if (hasRtlSupport()) {
11938            // Set resolved depending on layout direction
11939            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11940                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11941                case LAYOUT_DIRECTION_INHERIT:
11942                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11943                    // later to get the correct resolved value
11944                    if (!canResolveLayoutDirection()) return false;
11945
11946                    // Parent has not yet resolved, LTR is still the default
11947                    if (!mParent.isLayoutDirectionResolved()) return false;
11948
11949                    if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11950                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11951                    }
11952                    break;
11953                case LAYOUT_DIRECTION_RTL:
11954                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11955                    break;
11956                case LAYOUT_DIRECTION_LOCALE:
11957                    if((LAYOUT_DIRECTION_RTL ==
11958                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11959                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11960                    }
11961                    break;
11962                default:
11963                    // Nothing to do, LTR by default
11964            }
11965        }
11966
11967        // Set to resolved
11968        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11969        return true;
11970    }
11971
11972    /**
11973     * Check if layout direction resolution can be done.
11974     *
11975     * @return true if layout direction resolution can be done otherwise return false.
11976     *
11977     * @hide
11978     */
11979    public boolean canResolveLayoutDirection() {
11980        switch (getRawLayoutDirection()) {
11981            case LAYOUT_DIRECTION_INHERIT:
11982                return (mParent != null) && mParent.canResolveLayoutDirection();
11983            default:
11984                return true;
11985        }
11986    }
11987
11988    /**
11989     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11990     * {@link #onMeasure(int, int)}.
11991     *
11992     * @hide
11993     */
11994    public void resetResolvedLayoutDirection() {
11995        // Reset the current resolved bits
11996        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11997    }
11998
11999    /**
12000     * @return true if the layout direction is inherited.
12001     *
12002     * @hide
12003     */
12004    public boolean isLayoutDirectionInherited() {
12005        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12006    }
12007
12008    /**
12009     * @return true if layout direction has been resolved.
12010     * @hide
12011     */
12012    public boolean isLayoutDirectionResolved() {
12013        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12014    }
12015
12016    /**
12017     * Return if padding has been resolved
12018     *
12019     * @hide
12020     */
12021    boolean isPaddingResolved() {
12022        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12023    }
12024
12025    /**
12026     * Resolve padding depending on layout direction.
12027     *
12028     * @hide
12029     */
12030    public void resolvePadding() {
12031        if (!isRtlCompatibilityMode()) {
12032            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12033            // If start / end padding are defined, they will be resolved (hence overriding) to
12034            // left / right or right / left depending on the resolved layout direction.
12035            // If start / end padding are not defined, use the left / right ones.
12036            int resolvedLayoutDirection = getLayoutDirection();
12037            switch (resolvedLayoutDirection) {
12038                case LAYOUT_DIRECTION_RTL:
12039                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12040                        mUserPaddingRight = mUserPaddingStart;
12041                    } else {
12042                        mUserPaddingRight = mUserPaddingRightInitial;
12043                    }
12044                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12045                        mUserPaddingLeft = mUserPaddingEnd;
12046                    } else {
12047                        mUserPaddingLeft = mUserPaddingLeftInitial;
12048                    }
12049                    break;
12050                case LAYOUT_DIRECTION_LTR:
12051                default:
12052                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12053                        mUserPaddingLeft = mUserPaddingStart;
12054                    } else {
12055                        mUserPaddingLeft = mUserPaddingLeftInitial;
12056                    }
12057                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12058                        mUserPaddingRight = mUserPaddingEnd;
12059                    } else {
12060                        mUserPaddingRight = mUserPaddingRightInitial;
12061                    }
12062            }
12063
12064            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12065
12066            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
12067                    mUserPaddingBottom);
12068            onRtlPropertiesChanged(resolvedLayoutDirection);
12069        }
12070
12071        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12072    }
12073
12074    /**
12075     * Reset the resolved layout direction.
12076     *
12077     * @hide
12078     */
12079    public void resetResolvedPadding() {
12080        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12081    }
12082
12083    /**
12084     * This is called when the view is detached from a window.  At this point it
12085     * no longer has a surface for drawing.
12086     *
12087     * @see #onAttachedToWindow()
12088     */
12089    protected void onDetachedFromWindow() {
12090        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12091        mPrivateFlags3 &= ~PFLAG3_HAS_LAYOUT;
12092
12093        removeUnsetPressCallback();
12094        removeLongPressCallback();
12095        removePerformClickCallback();
12096        removeSendViewScrolledAccessibilityEventCallback();
12097
12098        destroyDrawingCache();
12099
12100        destroyLayer(false);
12101
12102        cleanupDraw();
12103
12104        mCurrentAnimation = null;
12105        mCurrentScene = null;
12106    }
12107
12108    private void cleanupDraw() {
12109        if (mAttachInfo != null) {
12110            if (mDisplayList != null) {
12111                mDisplayList.markDirty();
12112                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12113            }
12114            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12115        } else {
12116            // Should never happen
12117            clearDisplayList();
12118        }
12119    }
12120
12121    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12122    }
12123
12124    /**
12125     * @return The number of times this view has been attached to a window
12126     */
12127    protected int getWindowAttachCount() {
12128        return mWindowAttachCount;
12129    }
12130
12131    /**
12132     * Retrieve a unique token identifying the window this view is attached to.
12133     * @return Return the window's token for use in
12134     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12135     */
12136    public IBinder getWindowToken() {
12137        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12138    }
12139
12140    /**
12141     * Retrieve the {@link WindowId} for the window this view is
12142     * currently attached to.
12143     */
12144    public WindowId getWindowId() {
12145        if (mAttachInfo == null) {
12146            return null;
12147        }
12148        if (mAttachInfo.mWindowId == null) {
12149            try {
12150                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12151                        mAttachInfo.mWindowToken);
12152                mAttachInfo.mWindowId = new WindowId(
12153                        mAttachInfo.mIWindowId);
12154            } catch (RemoteException e) {
12155            }
12156        }
12157        return mAttachInfo.mWindowId;
12158    }
12159
12160    /**
12161     * Retrieve a unique token identifying the top-level "real" window of
12162     * the window that this view is attached to.  That is, this is like
12163     * {@link #getWindowToken}, except if the window this view in is a panel
12164     * window (attached to another containing window), then the token of
12165     * the containing window is returned instead.
12166     *
12167     * @return Returns the associated window token, either
12168     * {@link #getWindowToken()} or the containing window's token.
12169     */
12170    public IBinder getApplicationWindowToken() {
12171        AttachInfo ai = mAttachInfo;
12172        if (ai != null) {
12173            IBinder appWindowToken = ai.mPanelParentWindowToken;
12174            if (appWindowToken == null) {
12175                appWindowToken = ai.mWindowToken;
12176            }
12177            return appWindowToken;
12178        }
12179        return null;
12180    }
12181
12182    /**
12183     * Gets the logical display to which the view's window has been attached.
12184     *
12185     * @return The logical display, or null if the view is not currently attached to a window.
12186     */
12187    public Display getDisplay() {
12188        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12189    }
12190
12191    /**
12192     * Retrieve private session object this view hierarchy is using to
12193     * communicate with the window manager.
12194     * @return the session object to communicate with the window manager
12195     */
12196    /*package*/ IWindowSession getWindowSession() {
12197        return mAttachInfo != null ? mAttachInfo.mSession : null;
12198    }
12199
12200    /**
12201     * @param info the {@link android.view.View.AttachInfo} to associated with
12202     *        this view
12203     */
12204    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12205        //System.out.println("Attached! " + this);
12206        mAttachInfo = info;
12207        if (mOverlay != null) {
12208            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12209        }
12210        mWindowAttachCount++;
12211        // We will need to evaluate the drawable state at least once.
12212        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12213        if (mFloatingTreeObserver != null) {
12214            info.mTreeObserver.merge(mFloatingTreeObserver);
12215            mFloatingTreeObserver = null;
12216        }
12217        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12218            mAttachInfo.mScrollContainers.add(this);
12219            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12220        }
12221        performCollectViewAttributes(mAttachInfo, visibility);
12222        onAttachedToWindow();
12223
12224        ListenerInfo li = mListenerInfo;
12225        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12226                li != null ? li.mOnAttachStateChangeListeners : null;
12227        if (listeners != null && listeners.size() > 0) {
12228            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12229            // perform the dispatching. The iterator is a safe guard against listeners that
12230            // could mutate the list by calling the various add/remove methods. This prevents
12231            // the array from being modified while we iterate it.
12232            for (OnAttachStateChangeListener listener : listeners) {
12233                listener.onViewAttachedToWindow(this);
12234            }
12235        }
12236
12237        int vis = info.mWindowVisibility;
12238        if (vis != GONE) {
12239            onWindowVisibilityChanged(vis);
12240        }
12241        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12242            // If nobody has evaluated the drawable state yet, then do it now.
12243            refreshDrawableState();
12244        }
12245        needGlobalAttributesUpdate(false);
12246    }
12247
12248    void dispatchDetachedFromWindow() {
12249        AttachInfo info = mAttachInfo;
12250        if (info != null) {
12251            int vis = info.mWindowVisibility;
12252            if (vis != GONE) {
12253                onWindowVisibilityChanged(GONE);
12254            }
12255        }
12256
12257        onDetachedFromWindow();
12258
12259        ListenerInfo li = mListenerInfo;
12260        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12261                li != null ? li.mOnAttachStateChangeListeners : null;
12262        if (listeners != null && listeners.size() > 0) {
12263            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12264            // perform the dispatching. The iterator is a safe guard against listeners that
12265            // could mutate the list by calling the various add/remove methods. This prevents
12266            // the array from being modified while we iterate it.
12267            for (OnAttachStateChangeListener listener : listeners) {
12268                listener.onViewDetachedFromWindow(this);
12269            }
12270        }
12271
12272        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12273            mAttachInfo.mScrollContainers.remove(this);
12274            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12275        }
12276
12277        mAttachInfo = null;
12278        if (mOverlay != null) {
12279            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12280        }
12281    }
12282
12283    /**
12284     * Store this view hierarchy's frozen state into the given container.
12285     *
12286     * @param container The SparseArray in which to save the view's state.
12287     *
12288     * @see #restoreHierarchyState(android.util.SparseArray)
12289     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12290     * @see #onSaveInstanceState()
12291     */
12292    public void saveHierarchyState(SparseArray<Parcelable> container) {
12293        dispatchSaveInstanceState(container);
12294    }
12295
12296    /**
12297     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12298     * this view and its children. May be overridden to modify how freezing happens to a
12299     * view's children; for example, some views may want to not store state for their children.
12300     *
12301     * @param container The SparseArray in which to save the view's state.
12302     *
12303     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12304     * @see #saveHierarchyState(android.util.SparseArray)
12305     * @see #onSaveInstanceState()
12306     */
12307    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12308        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12309            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12310            Parcelable state = onSaveInstanceState();
12311            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12312                throw new IllegalStateException(
12313                        "Derived class did not call super.onSaveInstanceState()");
12314            }
12315            if (state != null) {
12316                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12317                // + ": " + state);
12318                container.put(mID, state);
12319            }
12320        }
12321    }
12322
12323    /**
12324     * Hook allowing a view to generate a representation of its internal state
12325     * that can later be used to create a new instance with that same state.
12326     * This state should only contain information that is not persistent or can
12327     * not be reconstructed later. For example, you will never store your
12328     * current position on screen because that will be computed again when a
12329     * new instance of the view is placed in its view hierarchy.
12330     * <p>
12331     * Some examples of things you may store here: the current cursor position
12332     * in a text view (but usually not the text itself since that is stored in a
12333     * content provider or other persistent storage), the currently selected
12334     * item in a list view.
12335     *
12336     * @return Returns a Parcelable object containing the view's current dynamic
12337     *         state, or null if there is nothing interesting to save. The
12338     *         default implementation returns null.
12339     * @see #onRestoreInstanceState(android.os.Parcelable)
12340     * @see #saveHierarchyState(android.util.SparseArray)
12341     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12342     * @see #setSaveEnabled(boolean)
12343     */
12344    protected Parcelable onSaveInstanceState() {
12345        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12346        return BaseSavedState.EMPTY_STATE;
12347    }
12348
12349    /**
12350     * Restore this view hierarchy's frozen state from the given container.
12351     *
12352     * @param container The SparseArray which holds previously frozen states.
12353     *
12354     * @see #saveHierarchyState(android.util.SparseArray)
12355     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12356     * @see #onRestoreInstanceState(android.os.Parcelable)
12357     */
12358    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12359        dispatchRestoreInstanceState(container);
12360    }
12361
12362    /**
12363     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12364     * state for this view and its children. May be overridden to modify how restoring
12365     * happens to a view's children; for example, some views may want to not store state
12366     * for their children.
12367     *
12368     * @param container The SparseArray which holds previously saved state.
12369     *
12370     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12371     * @see #restoreHierarchyState(android.util.SparseArray)
12372     * @see #onRestoreInstanceState(android.os.Parcelable)
12373     */
12374    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12375        if (mID != NO_ID) {
12376            Parcelable state = container.get(mID);
12377            if (state != null) {
12378                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12379                // + ": " + state);
12380                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12381                onRestoreInstanceState(state);
12382                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12383                    throw new IllegalStateException(
12384                            "Derived class did not call super.onRestoreInstanceState()");
12385                }
12386            }
12387        }
12388    }
12389
12390    /**
12391     * Hook allowing a view to re-apply a representation of its internal state that had previously
12392     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12393     * null state.
12394     *
12395     * @param state The frozen state that had previously been returned by
12396     *        {@link #onSaveInstanceState}.
12397     *
12398     * @see #onSaveInstanceState()
12399     * @see #restoreHierarchyState(android.util.SparseArray)
12400     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12401     */
12402    protected void onRestoreInstanceState(Parcelable state) {
12403        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12404        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12405            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12406                    + "received " + state.getClass().toString() + " instead. This usually happens "
12407                    + "when two views of different type have the same id in the same hierarchy. "
12408                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12409                    + "other views do not use the same id.");
12410        }
12411    }
12412
12413    /**
12414     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12415     *
12416     * @return the drawing start time in milliseconds
12417     */
12418    public long getDrawingTime() {
12419        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12420    }
12421
12422    /**
12423     * <p>Enables or disables the duplication of the parent's state into this view. When
12424     * duplication is enabled, this view gets its drawable state from its parent rather
12425     * than from its own internal properties.</p>
12426     *
12427     * <p>Note: in the current implementation, setting this property to true after the
12428     * view was added to a ViewGroup might have no effect at all. This property should
12429     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12430     *
12431     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12432     * property is enabled, an exception will be thrown.</p>
12433     *
12434     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12435     * parent, these states should not be affected by this method.</p>
12436     *
12437     * @param enabled True to enable duplication of the parent's drawable state, false
12438     *                to disable it.
12439     *
12440     * @see #getDrawableState()
12441     * @see #isDuplicateParentStateEnabled()
12442     */
12443    public void setDuplicateParentStateEnabled(boolean enabled) {
12444        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12445    }
12446
12447    /**
12448     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12449     *
12450     * @return True if this view's drawable state is duplicated from the parent,
12451     *         false otherwise
12452     *
12453     * @see #getDrawableState()
12454     * @see #setDuplicateParentStateEnabled(boolean)
12455     */
12456    public boolean isDuplicateParentStateEnabled() {
12457        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12458    }
12459
12460    /**
12461     * <p>Specifies the type of layer backing this view. The layer can be
12462     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12463     * {@link #LAYER_TYPE_HARDWARE}.</p>
12464     *
12465     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12466     * instance that controls how the layer is composed on screen. The following
12467     * properties of the paint are taken into account when composing the layer:</p>
12468     * <ul>
12469     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12470     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12471     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12472     * </ul>
12473     *
12474     * <p>If this view has an alpha value set to < 1.0 by calling
12475     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12476     * by this view's alpha value.</p>
12477     *
12478     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12479     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12480     * for more information on when and how to use layers.</p>
12481     *
12482     * @param layerType The type of layer to use with this view, must be one of
12483     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12484     *        {@link #LAYER_TYPE_HARDWARE}
12485     * @param paint The paint used to compose the layer. This argument is optional
12486     *        and can be null. It is ignored when the layer type is
12487     *        {@link #LAYER_TYPE_NONE}
12488     *
12489     * @see #getLayerType()
12490     * @see #LAYER_TYPE_NONE
12491     * @see #LAYER_TYPE_SOFTWARE
12492     * @see #LAYER_TYPE_HARDWARE
12493     * @see #setAlpha(float)
12494     *
12495     * @attr ref android.R.styleable#View_layerType
12496     */
12497    public void setLayerType(int layerType, Paint paint) {
12498        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12499            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12500                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12501        }
12502
12503        if (layerType == mLayerType) {
12504            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12505                mLayerPaint = paint == null ? new Paint() : paint;
12506                invalidateParentCaches();
12507                invalidate(true);
12508            }
12509            return;
12510        }
12511
12512        // Destroy any previous software drawing cache if needed
12513        switch (mLayerType) {
12514            case LAYER_TYPE_HARDWARE:
12515                destroyLayer(false);
12516                // fall through - non-accelerated views may use software layer mechanism instead
12517            case LAYER_TYPE_SOFTWARE:
12518                destroyDrawingCache();
12519                break;
12520            default:
12521                break;
12522        }
12523
12524        mLayerType = layerType;
12525        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12526        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12527        mLocalDirtyRect = layerDisabled ? null : new Rect();
12528
12529        invalidateParentCaches();
12530        invalidate(true);
12531    }
12532
12533    /**
12534     * Updates the {@link Paint} object used with the current layer (used only if the current
12535     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12536     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12537     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12538     * ensure that the view gets redrawn immediately.
12539     *
12540     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12541     * instance that controls how the layer is composed on screen. The following
12542     * properties of the paint are taken into account when composing the layer:</p>
12543     * <ul>
12544     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12545     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12546     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12547     * </ul>
12548     *
12549     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12550     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12551     *
12552     * @param paint The paint used to compose the layer. This argument is optional
12553     *        and can be null. It is ignored when the layer type is
12554     *        {@link #LAYER_TYPE_NONE}
12555     *
12556     * @see #setLayerType(int, android.graphics.Paint)
12557     */
12558    public void setLayerPaint(Paint paint) {
12559        int layerType = getLayerType();
12560        if (layerType != LAYER_TYPE_NONE) {
12561            mLayerPaint = paint == null ? new Paint() : paint;
12562            if (layerType == LAYER_TYPE_HARDWARE) {
12563                HardwareLayer layer = getHardwareLayer();
12564                if (layer != null) {
12565                    layer.setLayerPaint(paint);
12566                }
12567                invalidateViewProperty(false, false);
12568            } else {
12569                invalidate();
12570            }
12571        }
12572    }
12573
12574    /**
12575     * Indicates whether this view has a static layer. A view with layer type
12576     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12577     * dynamic.
12578     */
12579    boolean hasStaticLayer() {
12580        return true;
12581    }
12582
12583    /**
12584     * Indicates what type of layer is currently associated with this view. By default
12585     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12586     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12587     * for more information on the different types of layers.
12588     *
12589     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12590     *         {@link #LAYER_TYPE_HARDWARE}
12591     *
12592     * @see #setLayerType(int, android.graphics.Paint)
12593     * @see #buildLayer()
12594     * @see #LAYER_TYPE_NONE
12595     * @see #LAYER_TYPE_SOFTWARE
12596     * @see #LAYER_TYPE_HARDWARE
12597     */
12598    public int getLayerType() {
12599        return mLayerType;
12600    }
12601
12602    /**
12603     * Forces this view's layer to be created and this view to be rendered
12604     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12605     * invoking this method will have no effect.
12606     *
12607     * This method can for instance be used to render a view into its layer before
12608     * starting an animation. If this view is complex, rendering into the layer
12609     * before starting the animation will avoid skipping frames.
12610     *
12611     * @throws IllegalStateException If this view is not attached to a window
12612     *
12613     * @see #setLayerType(int, android.graphics.Paint)
12614     */
12615    public void buildLayer() {
12616        if (mLayerType == LAYER_TYPE_NONE) return;
12617
12618        final AttachInfo attachInfo = mAttachInfo;
12619        if (attachInfo == null) {
12620            throw new IllegalStateException("This view must be attached to a window first");
12621        }
12622
12623        switch (mLayerType) {
12624            case LAYER_TYPE_HARDWARE:
12625                if (attachInfo.mHardwareRenderer != null &&
12626                        attachInfo.mHardwareRenderer.isEnabled() &&
12627                        attachInfo.mHardwareRenderer.validate()) {
12628                    getHardwareLayer();
12629                    attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12630                }
12631                break;
12632            case LAYER_TYPE_SOFTWARE:
12633                buildDrawingCache(true);
12634                break;
12635        }
12636    }
12637
12638    /**
12639     * <p>Returns a hardware layer that can be used to draw this view again
12640     * without executing its draw method.</p>
12641     *
12642     * @return A HardwareLayer ready to render, or null if an error occurred.
12643     */
12644    HardwareLayer getHardwareLayer() {
12645        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12646                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12647            return null;
12648        }
12649
12650        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12651
12652        final int width = mRight - mLeft;
12653        final int height = mBottom - mTop;
12654
12655        if (width == 0 || height == 0) {
12656            return null;
12657        }
12658
12659        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12660            if (mHardwareLayer == null) {
12661                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12662                        width, height, isOpaque());
12663                mLocalDirtyRect.set(0, 0, width, height);
12664            } else {
12665                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12666                    if (mHardwareLayer.resize(width, height)) {
12667                        mLocalDirtyRect.set(0, 0, width, height);
12668                    }
12669                }
12670
12671                // This should not be necessary but applications that change
12672                // the parameters of their background drawable without calling
12673                // this.setBackground(Drawable) can leave the view in a bad state
12674                // (for instance isOpaque() returns true, but the background is
12675                // not opaque.)
12676                computeOpaqueFlags();
12677
12678                final boolean opaque = isOpaque();
12679                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12680                    mHardwareLayer.setOpaque(opaque);
12681                    mLocalDirtyRect.set(0, 0, width, height);
12682                }
12683            }
12684
12685            // The layer is not valid if the underlying GPU resources cannot be allocated
12686            if (!mHardwareLayer.isValid()) {
12687                return null;
12688            }
12689
12690            mHardwareLayer.setLayerPaint(mLayerPaint);
12691            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12692            ViewRootImpl viewRoot = getViewRootImpl();
12693            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12694
12695            mLocalDirtyRect.setEmpty();
12696        }
12697
12698        return mHardwareLayer;
12699    }
12700
12701    /**
12702     * Destroys this View's hardware layer if possible.
12703     *
12704     * @return True if the layer was destroyed, false otherwise.
12705     *
12706     * @see #setLayerType(int, android.graphics.Paint)
12707     * @see #LAYER_TYPE_HARDWARE
12708     */
12709    boolean destroyLayer(boolean valid) {
12710        if (mHardwareLayer != null) {
12711            AttachInfo info = mAttachInfo;
12712            if (info != null && info.mHardwareRenderer != null &&
12713                    info.mHardwareRenderer.isEnabled() &&
12714                    (valid || info.mHardwareRenderer.validate())) {
12715                mHardwareLayer.destroy();
12716                mHardwareLayer = null;
12717
12718                if (mDisplayList != null) {
12719                    mDisplayList.reset();
12720                }
12721                invalidate(true);
12722                invalidateParentCaches();
12723            }
12724            return true;
12725        }
12726        return false;
12727    }
12728
12729    /**
12730     * Destroys all hardware rendering resources. This method is invoked
12731     * when the system needs to reclaim resources. Upon execution of this
12732     * method, you should free any OpenGL resources created by the view.
12733     *
12734     * Note: you <strong>must</strong> call
12735     * <code>super.destroyHardwareResources()</code> when overriding
12736     * this method.
12737     *
12738     * @hide
12739     */
12740    protected void destroyHardwareResources() {
12741        clearDisplayList();
12742        destroyLayer(true);
12743    }
12744
12745    /**
12746     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12747     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12748     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12749     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12750     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12751     * null.</p>
12752     *
12753     * <p>Enabling the drawing cache is similar to
12754     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12755     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12756     * drawing cache has no effect on rendering because the system uses a different mechanism
12757     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12758     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12759     * for information on how to enable software and hardware layers.</p>
12760     *
12761     * <p>This API can be used to manually generate
12762     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12763     * {@link #getDrawingCache()}.</p>
12764     *
12765     * @param enabled true to enable the drawing cache, false otherwise
12766     *
12767     * @see #isDrawingCacheEnabled()
12768     * @see #getDrawingCache()
12769     * @see #buildDrawingCache()
12770     * @see #setLayerType(int, android.graphics.Paint)
12771     */
12772    public void setDrawingCacheEnabled(boolean enabled) {
12773        mCachingFailed = false;
12774        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12775    }
12776
12777    /**
12778     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12779     *
12780     * @return true if the drawing cache is enabled
12781     *
12782     * @see #setDrawingCacheEnabled(boolean)
12783     * @see #getDrawingCache()
12784     */
12785    @ViewDebug.ExportedProperty(category = "drawing")
12786    public boolean isDrawingCacheEnabled() {
12787        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12788    }
12789
12790    /**
12791     * Debugging utility which recursively outputs the dirty state of a view and its
12792     * descendants.
12793     *
12794     * @hide
12795     */
12796    @SuppressWarnings({"UnusedDeclaration"})
12797    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12798        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12799                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12800                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12801                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12802        if (clear) {
12803            mPrivateFlags &= clearMask;
12804        }
12805        if (this instanceof ViewGroup) {
12806            ViewGroup parent = (ViewGroup) this;
12807            final int count = parent.getChildCount();
12808            for (int i = 0; i < count; i++) {
12809                final View child = parent.getChildAt(i);
12810                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12811            }
12812        }
12813    }
12814
12815    /**
12816     * This method is used by ViewGroup to cause its children to restore or recreate their
12817     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12818     * to recreate its own display list, which would happen if it went through the normal
12819     * draw/dispatchDraw mechanisms.
12820     *
12821     * @hide
12822     */
12823    protected void dispatchGetDisplayList() {}
12824
12825    /**
12826     * A view that is not attached or hardware accelerated cannot create a display list.
12827     * This method checks these conditions and returns the appropriate result.
12828     *
12829     * @return true if view has the ability to create a display list, false otherwise.
12830     *
12831     * @hide
12832     */
12833    public boolean canHaveDisplayList() {
12834        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12835    }
12836
12837    /**
12838     * @return The {@link HardwareRenderer} associated with that view or null if
12839     *         hardware rendering is not supported or this view is not attached
12840     *         to a window.
12841     *
12842     * @hide
12843     */
12844    public HardwareRenderer getHardwareRenderer() {
12845        if (mAttachInfo != null) {
12846            return mAttachInfo.mHardwareRenderer;
12847        }
12848        return null;
12849    }
12850
12851    /**
12852     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12853     * Otherwise, the same display list will be returned (after having been rendered into
12854     * along the way, depending on the invalidation state of the view).
12855     *
12856     * @param displayList The previous version of this displayList, could be null.
12857     * @param isLayer Whether the requester of the display list is a layer. If so,
12858     * the view will avoid creating a layer inside the resulting display list.
12859     * @return A new or reused DisplayList object.
12860     */
12861    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12862        if (!canHaveDisplayList()) {
12863            return null;
12864        }
12865
12866        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12867                displayList == null || !displayList.isValid() ||
12868                (!isLayer && mRecreateDisplayList))) {
12869            // Don't need to recreate the display list, just need to tell our
12870            // children to restore/recreate theirs
12871            if (displayList != null && displayList.isValid() &&
12872                    !isLayer && !mRecreateDisplayList) {
12873                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12874                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12875                dispatchGetDisplayList();
12876
12877                return displayList;
12878            }
12879
12880            if (!isLayer) {
12881                // If we got here, we're recreating it. Mark it as such to ensure that
12882                // we copy in child display lists into ours in drawChild()
12883                mRecreateDisplayList = true;
12884            }
12885            if (displayList == null) {
12886                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
12887                // If we're creating a new display list, make sure our parent gets invalidated
12888                // since they will need to recreate their display list to account for this
12889                // new child display list.
12890                invalidateParentCaches();
12891            }
12892
12893            boolean caching = false;
12894            int width = mRight - mLeft;
12895            int height = mBottom - mTop;
12896            int layerType = getLayerType();
12897
12898            final HardwareCanvas canvas = displayList.start(width, height);
12899
12900            try {
12901                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12902                    if (layerType == LAYER_TYPE_HARDWARE) {
12903                        final HardwareLayer layer = getHardwareLayer();
12904                        if (layer != null && layer.isValid()) {
12905                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12906                        } else {
12907                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12908                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12909                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12910                        }
12911                        caching = true;
12912                    } else {
12913                        buildDrawingCache(true);
12914                        Bitmap cache = getDrawingCache(true);
12915                        if (cache != null) {
12916                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12917                            caching = true;
12918                        }
12919                    }
12920                } else {
12921
12922                    computeScroll();
12923
12924                    canvas.translate(-mScrollX, -mScrollY);
12925                    if (!isLayer) {
12926                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12927                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12928                    }
12929
12930                    // Fast path for layouts with no backgrounds
12931                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12932                        dispatchDraw(canvas);
12933                        if (mOverlay != null && !mOverlay.isEmpty()) {
12934                            mOverlay.getOverlayView().draw(canvas);
12935                        }
12936                    } else {
12937                        draw(canvas);
12938                    }
12939                }
12940            } finally {
12941                displayList.end();
12942                displayList.setCaching(caching);
12943                if (isLayer) {
12944                    displayList.setLeftTopRightBottom(0, 0, width, height);
12945                } else {
12946                    setDisplayListProperties(displayList);
12947                }
12948            }
12949        } else if (!isLayer) {
12950            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12951            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12952        }
12953
12954        return displayList;
12955    }
12956
12957    /**
12958     * Get the DisplayList for the HardwareLayer
12959     *
12960     * @param layer The HardwareLayer whose DisplayList we want
12961     * @return A DisplayList fopr the specified HardwareLayer
12962     */
12963    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12964        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12965        layer.setDisplayList(displayList);
12966        return displayList;
12967    }
12968
12969
12970    /**
12971     * <p>Returns a display list that can be used to draw this view again
12972     * without executing its draw method.</p>
12973     *
12974     * @return A DisplayList ready to replay, or null if caching is not enabled.
12975     *
12976     * @hide
12977     */
12978    public DisplayList getDisplayList() {
12979        mDisplayList = getDisplayList(mDisplayList, false);
12980        return mDisplayList;
12981    }
12982
12983    private void clearDisplayList() {
12984        if (mDisplayList != null) {
12985            mDisplayList.clear();
12986        }
12987    }
12988
12989    /**
12990     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12991     *
12992     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12993     *
12994     * @see #getDrawingCache(boolean)
12995     */
12996    public Bitmap getDrawingCache() {
12997        return getDrawingCache(false);
12998    }
12999
13000    /**
13001     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13002     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13003     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13004     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13005     * request the drawing cache by calling this method and draw it on screen if the
13006     * returned bitmap is not null.</p>
13007     *
13008     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13009     * this method will create a bitmap of the same size as this view. Because this bitmap
13010     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13011     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13012     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13013     * size than the view. This implies that your application must be able to handle this
13014     * size.</p>
13015     *
13016     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13017     *        the current density of the screen when the application is in compatibility
13018     *        mode.
13019     *
13020     * @return A bitmap representing this view or null if cache is disabled.
13021     *
13022     * @see #setDrawingCacheEnabled(boolean)
13023     * @see #isDrawingCacheEnabled()
13024     * @see #buildDrawingCache(boolean)
13025     * @see #destroyDrawingCache()
13026     */
13027    public Bitmap getDrawingCache(boolean autoScale) {
13028        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13029            return null;
13030        }
13031        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13032            buildDrawingCache(autoScale);
13033        }
13034        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13035    }
13036
13037    /**
13038     * <p>Frees the resources used by the drawing cache. If you call
13039     * {@link #buildDrawingCache()} manually without calling
13040     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13041     * should cleanup the cache with this method afterwards.</p>
13042     *
13043     * @see #setDrawingCacheEnabled(boolean)
13044     * @see #buildDrawingCache()
13045     * @see #getDrawingCache()
13046     */
13047    public void destroyDrawingCache() {
13048        if (mDrawingCache != null) {
13049            mDrawingCache.recycle();
13050            mDrawingCache = null;
13051        }
13052        if (mUnscaledDrawingCache != null) {
13053            mUnscaledDrawingCache.recycle();
13054            mUnscaledDrawingCache = null;
13055        }
13056    }
13057
13058    /**
13059     * Setting a solid background color for the drawing cache's bitmaps will improve
13060     * performance and memory usage. Note, though that this should only be used if this
13061     * view will always be drawn on top of a solid color.
13062     *
13063     * @param color The background color to use for the drawing cache's bitmap
13064     *
13065     * @see #setDrawingCacheEnabled(boolean)
13066     * @see #buildDrawingCache()
13067     * @see #getDrawingCache()
13068     */
13069    public void setDrawingCacheBackgroundColor(int color) {
13070        if (color != mDrawingCacheBackgroundColor) {
13071            mDrawingCacheBackgroundColor = color;
13072            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13073        }
13074    }
13075
13076    /**
13077     * @see #setDrawingCacheBackgroundColor(int)
13078     *
13079     * @return The background color to used for the drawing cache's bitmap
13080     */
13081    public int getDrawingCacheBackgroundColor() {
13082        return mDrawingCacheBackgroundColor;
13083    }
13084
13085    /**
13086     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13087     *
13088     * @see #buildDrawingCache(boolean)
13089     */
13090    public void buildDrawingCache() {
13091        buildDrawingCache(false);
13092    }
13093
13094    /**
13095     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13096     *
13097     * <p>If you call {@link #buildDrawingCache()} manually without calling
13098     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13099     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13100     *
13101     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13102     * this method will create a bitmap of the same size as this view. Because this bitmap
13103     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13104     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13105     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13106     * size than the view. This implies that your application must be able to handle this
13107     * size.</p>
13108     *
13109     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13110     * you do not need the drawing cache bitmap, calling this method will increase memory
13111     * usage and cause the view to be rendered in software once, thus negatively impacting
13112     * performance.</p>
13113     *
13114     * @see #getDrawingCache()
13115     * @see #destroyDrawingCache()
13116     */
13117    public void buildDrawingCache(boolean autoScale) {
13118        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13119                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13120            mCachingFailed = false;
13121
13122            int width = mRight - mLeft;
13123            int height = mBottom - mTop;
13124
13125            final AttachInfo attachInfo = mAttachInfo;
13126            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13127
13128            if (autoScale && scalingRequired) {
13129                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13130                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13131            }
13132
13133            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13134            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13135            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13136
13137            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13138            final long drawingCacheSize =
13139                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13140            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13141                if (width > 0 && height > 0) {
13142                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13143                            + projectedBitmapSize + " bytes, only "
13144                            + drawingCacheSize + " available");
13145                }
13146                destroyDrawingCache();
13147                mCachingFailed = true;
13148                return;
13149            }
13150
13151            boolean clear = true;
13152            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13153
13154            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13155                Bitmap.Config quality;
13156                if (!opaque) {
13157                    // Never pick ARGB_4444 because it looks awful
13158                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13159                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13160                        case DRAWING_CACHE_QUALITY_AUTO:
13161                            quality = Bitmap.Config.ARGB_8888;
13162                            break;
13163                        case DRAWING_CACHE_QUALITY_LOW:
13164                            quality = Bitmap.Config.ARGB_8888;
13165                            break;
13166                        case DRAWING_CACHE_QUALITY_HIGH:
13167                            quality = Bitmap.Config.ARGB_8888;
13168                            break;
13169                        default:
13170                            quality = Bitmap.Config.ARGB_8888;
13171                            break;
13172                    }
13173                } else {
13174                    // Optimization for translucent windows
13175                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13176                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13177                }
13178
13179                // Try to cleanup memory
13180                if (bitmap != null) bitmap.recycle();
13181
13182                try {
13183                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13184                            width, height, quality);
13185                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13186                    if (autoScale) {
13187                        mDrawingCache = bitmap;
13188                    } else {
13189                        mUnscaledDrawingCache = bitmap;
13190                    }
13191                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13192                } catch (OutOfMemoryError e) {
13193                    // If there is not enough memory to create the bitmap cache, just
13194                    // ignore the issue as bitmap caches are not required to draw the
13195                    // view hierarchy
13196                    if (autoScale) {
13197                        mDrawingCache = null;
13198                    } else {
13199                        mUnscaledDrawingCache = null;
13200                    }
13201                    mCachingFailed = true;
13202                    return;
13203                }
13204
13205                clear = drawingCacheBackgroundColor != 0;
13206            }
13207
13208            Canvas canvas;
13209            if (attachInfo != null) {
13210                canvas = attachInfo.mCanvas;
13211                if (canvas == null) {
13212                    canvas = new Canvas();
13213                }
13214                canvas.setBitmap(bitmap);
13215                // Temporarily clobber the cached Canvas in case one of our children
13216                // is also using a drawing cache. Without this, the children would
13217                // steal the canvas by attaching their own bitmap to it and bad, bad
13218                // thing would happen (invisible views, corrupted drawings, etc.)
13219                attachInfo.mCanvas = null;
13220            } else {
13221                // This case should hopefully never or seldom happen
13222                canvas = new Canvas(bitmap);
13223            }
13224
13225            if (clear) {
13226                bitmap.eraseColor(drawingCacheBackgroundColor);
13227            }
13228
13229            computeScroll();
13230            final int restoreCount = canvas.save();
13231
13232            if (autoScale && scalingRequired) {
13233                final float scale = attachInfo.mApplicationScale;
13234                canvas.scale(scale, scale);
13235            }
13236
13237            canvas.translate(-mScrollX, -mScrollY);
13238
13239            mPrivateFlags |= PFLAG_DRAWN;
13240            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13241                    mLayerType != LAYER_TYPE_NONE) {
13242                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13243            }
13244
13245            // Fast path for layouts with no backgrounds
13246            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13247                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13248                dispatchDraw(canvas);
13249                if (mOverlay != null && !mOverlay.isEmpty()) {
13250                    mOverlay.getOverlayView().draw(canvas);
13251                }
13252            } else {
13253                draw(canvas);
13254            }
13255
13256            canvas.restoreToCount(restoreCount);
13257            canvas.setBitmap(null);
13258
13259            if (attachInfo != null) {
13260                // Restore the cached Canvas for our siblings
13261                attachInfo.mCanvas = canvas;
13262            }
13263        }
13264    }
13265
13266    /**
13267     * Create a snapshot of the view into a bitmap.  We should probably make
13268     * some form of this public, but should think about the API.
13269     */
13270    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13271        int width = mRight - mLeft;
13272        int height = mBottom - mTop;
13273
13274        final AttachInfo attachInfo = mAttachInfo;
13275        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13276        width = (int) ((width * scale) + 0.5f);
13277        height = (int) ((height * scale) + 0.5f);
13278
13279        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13280                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13281        if (bitmap == null) {
13282            throw new OutOfMemoryError();
13283        }
13284
13285        Resources resources = getResources();
13286        if (resources != null) {
13287            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13288        }
13289
13290        Canvas canvas;
13291        if (attachInfo != null) {
13292            canvas = attachInfo.mCanvas;
13293            if (canvas == null) {
13294                canvas = new Canvas();
13295            }
13296            canvas.setBitmap(bitmap);
13297            // Temporarily clobber the cached Canvas in case one of our children
13298            // is also using a drawing cache. Without this, the children would
13299            // steal the canvas by attaching their own bitmap to it and bad, bad
13300            // things would happen (invisible views, corrupted drawings, etc.)
13301            attachInfo.mCanvas = null;
13302        } else {
13303            // This case should hopefully never or seldom happen
13304            canvas = new Canvas(bitmap);
13305        }
13306
13307        if ((backgroundColor & 0xff000000) != 0) {
13308            bitmap.eraseColor(backgroundColor);
13309        }
13310
13311        computeScroll();
13312        final int restoreCount = canvas.save();
13313        canvas.scale(scale, scale);
13314        canvas.translate(-mScrollX, -mScrollY);
13315
13316        // Temporarily remove the dirty mask
13317        int flags = mPrivateFlags;
13318        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13319
13320        // Fast path for layouts with no backgrounds
13321        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13322            dispatchDraw(canvas);
13323        } else {
13324            draw(canvas);
13325        }
13326
13327        mPrivateFlags = flags;
13328
13329        canvas.restoreToCount(restoreCount);
13330        canvas.setBitmap(null);
13331
13332        if (attachInfo != null) {
13333            // Restore the cached Canvas for our siblings
13334            attachInfo.mCanvas = canvas;
13335        }
13336
13337        return bitmap;
13338    }
13339
13340    /**
13341     * Indicates whether this View is currently in edit mode. A View is usually
13342     * in edit mode when displayed within a developer tool. For instance, if
13343     * this View is being drawn by a visual user interface builder, this method
13344     * should return true.
13345     *
13346     * Subclasses should check the return value of this method to provide
13347     * different behaviors if their normal behavior might interfere with the
13348     * host environment. For instance: the class spawns a thread in its
13349     * constructor, the drawing code relies on device-specific features, etc.
13350     *
13351     * This method is usually checked in the drawing code of custom widgets.
13352     *
13353     * @return True if this View is in edit mode, false otherwise.
13354     */
13355    public boolean isInEditMode() {
13356        return false;
13357    }
13358
13359    /**
13360     * If the View draws content inside its padding and enables fading edges,
13361     * it needs to support padding offsets. Padding offsets are added to the
13362     * fading edges to extend the length of the fade so that it covers pixels
13363     * drawn inside the padding.
13364     *
13365     * Subclasses of this class should override this method if they need
13366     * to draw content inside the padding.
13367     *
13368     * @return True if padding offset must be applied, false otherwise.
13369     *
13370     * @see #getLeftPaddingOffset()
13371     * @see #getRightPaddingOffset()
13372     * @see #getTopPaddingOffset()
13373     * @see #getBottomPaddingOffset()
13374     *
13375     * @since CURRENT
13376     */
13377    protected boolean isPaddingOffsetRequired() {
13378        return false;
13379    }
13380
13381    /**
13382     * Amount by which to extend the left fading region. Called only when
13383     * {@link #isPaddingOffsetRequired()} returns true.
13384     *
13385     * @return The left padding offset in pixels.
13386     *
13387     * @see #isPaddingOffsetRequired()
13388     *
13389     * @since CURRENT
13390     */
13391    protected int getLeftPaddingOffset() {
13392        return 0;
13393    }
13394
13395    /**
13396     * Amount by which to extend the right fading region. Called only when
13397     * {@link #isPaddingOffsetRequired()} returns true.
13398     *
13399     * @return The right padding offset in pixels.
13400     *
13401     * @see #isPaddingOffsetRequired()
13402     *
13403     * @since CURRENT
13404     */
13405    protected int getRightPaddingOffset() {
13406        return 0;
13407    }
13408
13409    /**
13410     * Amount by which to extend the top fading region. Called only when
13411     * {@link #isPaddingOffsetRequired()} returns true.
13412     *
13413     * @return The top padding offset in pixels.
13414     *
13415     * @see #isPaddingOffsetRequired()
13416     *
13417     * @since CURRENT
13418     */
13419    protected int getTopPaddingOffset() {
13420        return 0;
13421    }
13422
13423    /**
13424     * Amount by which to extend the bottom fading region. Called only when
13425     * {@link #isPaddingOffsetRequired()} returns true.
13426     *
13427     * @return The bottom padding offset in pixels.
13428     *
13429     * @see #isPaddingOffsetRequired()
13430     *
13431     * @since CURRENT
13432     */
13433    protected int getBottomPaddingOffset() {
13434        return 0;
13435    }
13436
13437    /**
13438     * @hide
13439     * @param offsetRequired
13440     */
13441    protected int getFadeTop(boolean offsetRequired) {
13442        int top = mPaddingTop;
13443        if (offsetRequired) top += getTopPaddingOffset();
13444        return top;
13445    }
13446
13447    /**
13448     * @hide
13449     * @param offsetRequired
13450     */
13451    protected int getFadeHeight(boolean offsetRequired) {
13452        int padding = mPaddingTop;
13453        if (offsetRequired) padding += getTopPaddingOffset();
13454        return mBottom - mTop - mPaddingBottom - padding;
13455    }
13456
13457    /**
13458     * <p>Indicates whether this view is attached to a hardware accelerated
13459     * window or not.</p>
13460     *
13461     * <p>Even if this method returns true, it does not mean that every call
13462     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13463     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13464     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13465     * window is hardware accelerated,
13466     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13467     * return false, and this method will return true.</p>
13468     *
13469     * @return True if the view is attached to a window and the window is
13470     *         hardware accelerated; false in any other case.
13471     */
13472    public boolean isHardwareAccelerated() {
13473        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13474    }
13475
13476    /**
13477     * Sets a rectangular area on this view to which the view will be clipped
13478     * when it is drawn. Setting the value to null will remove the clip bounds
13479     * and the view will draw normally, using its full bounds.
13480     *
13481     * @param clipBounds The rectangular area, in the local coordinates of
13482     * this view, to which future drawing operations will be clipped.
13483     */
13484    public void setClipBounds(Rect clipBounds) {
13485        if (clipBounds != null) {
13486            if (clipBounds.equals(mClipBounds)) {
13487                return;
13488            }
13489            if (mClipBounds == null) {
13490                invalidate();
13491                mClipBounds = new Rect(clipBounds);
13492            } else {
13493                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13494                        Math.min(mClipBounds.top, clipBounds.top),
13495                        Math.max(mClipBounds.right, clipBounds.right),
13496                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13497                mClipBounds.set(clipBounds);
13498            }
13499        } else {
13500            if (mClipBounds != null) {
13501                invalidate();
13502                mClipBounds = null;
13503            }
13504        }
13505    }
13506
13507    /**
13508     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13509     *
13510     * @return A copy of the current clip bounds if clip bounds are set,
13511     * otherwise null.
13512     */
13513    public Rect getClipBounds() {
13514        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13515    }
13516
13517    /**
13518     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13519     * case of an active Animation being run on the view.
13520     */
13521    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13522            Animation a, boolean scalingRequired) {
13523        Transformation invalidationTransform;
13524        final int flags = parent.mGroupFlags;
13525        final boolean initialized = a.isInitialized();
13526        if (!initialized) {
13527            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13528            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13529            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13530            onAnimationStart();
13531        }
13532
13533        final Transformation t = parent.getChildTransformation();
13534        boolean more = a.getTransformation(drawingTime, t, 1f);
13535        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13536            if (parent.mInvalidationTransformation == null) {
13537                parent.mInvalidationTransformation = new Transformation();
13538            }
13539            invalidationTransform = parent.mInvalidationTransformation;
13540            a.getTransformation(drawingTime, invalidationTransform, 1f);
13541        } else {
13542            invalidationTransform = t;
13543        }
13544
13545        if (more) {
13546            if (!a.willChangeBounds()) {
13547                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13548                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13549                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13550                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13551                    // The child need to draw an animation, potentially offscreen, so
13552                    // make sure we do not cancel invalidate requests
13553                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13554                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13555                }
13556            } else {
13557                if (parent.mInvalidateRegion == null) {
13558                    parent.mInvalidateRegion = new RectF();
13559                }
13560                final RectF region = parent.mInvalidateRegion;
13561                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13562                        invalidationTransform);
13563
13564                // The child need to draw an animation, potentially offscreen, so
13565                // make sure we do not cancel invalidate requests
13566                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13567
13568                final int left = mLeft + (int) region.left;
13569                final int top = mTop + (int) region.top;
13570                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13571                        top + (int) (region.height() + .5f));
13572            }
13573        }
13574        return more;
13575    }
13576
13577    /**
13578     * This method is called by getDisplayList() when a display list is created or re-rendered.
13579     * It sets or resets the current value of all properties on that display list (resetting is
13580     * necessary when a display list is being re-created, because we need to make sure that
13581     * previously-set transform values
13582     */
13583    void setDisplayListProperties(DisplayList displayList) {
13584        if (displayList != null) {
13585            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13586            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13587            if (mParent instanceof ViewGroup) {
13588                displayList.setClipToBounds(
13589                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13590            }
13591            float alpha = 1;
13592            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13593                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13594                ViewGroup parentVG = (ViewGroup) mParent;
13595                final Transformation t = parentVG.getChildTransformation();
13596                if (parentVG.getChildStaticTransformation(this, t)) {
13597                    final int transformType = t.getTransformationType();
13598                    if (transformType != Transformation.TYPE_IDENTITY) {
13599                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13600                            alpha = t.getAlpha();
13601                        }
13602                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13603                            displayList.setMatrix(t.getMatrix());
13604                        }
13605                    }
13606                }
13607            }
13608            if (mTransformationInfo != null) {
13609                alpha *= mTransformationInfo.mAlpha;
13610                if (alpha < 1) {
13611                    final int multipliedAlpha = (int) (255 * alpha);
13612                    if (onSetAlpha(multipliedAlpha)) {
13613                        alpha = 1;
13614                    }
13615                }
13616                displayList.setTransformationInfo(alpha,
13617                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13618                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13619                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13620                        mTransformationInfo.mScaleY);
13621                if (mTransformationInfo.mCamera == null) {
13622                    mTransformationInfo.mCamera = new Camera();
13623                    mTransformationInfo.matrix3D = new Matrix();
13624                }
13625                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13626                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13627                    displayList.setPivotX(getPivotX());
13628                    displayList.setPivotY(getPivotY());
13629                }
13630            } else if (alpha < 1) {
13631                displayList.setAlpha(alpha);
13632            }
13633        }
13634    }
13635
13636    /**
13637     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13638     * This draw() method is an implementation detail and is not intended to be overridden or
13639     * to be called from anywhere else other than ViewGroup.drawChild().
13640     */
13641    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13642        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13643        boolean more = false;
13644        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13645        final int flags = parent.mGroupFlags;
13646
13647        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13648            parent.getChildTransformation().clear();
13649            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13650        }
13651
13652        Transformation transformToApply = null;
13653        boolean concatMatrix = false;
13654
13655        boolean scalingRequired = false;
13656        boolean caching;
13657        int layerType = getLayerType();
13658
13659        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13660        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13661                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13662            caching = true;
13663            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13664            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13665        } else {
13666            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13667        }
13668
13669        final Animation a = getAnimation();
13670        if (a != null) {
13671            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13672            concatMatrix = a.willChangeTransformationMatrix();
13673            if (concatMatrix) {
13674                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13675            }
13676            transformToApply = parent.getChildTransformation();
13677        } else {
13678            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13679                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13680                // No longer animating: clear out old animation matrix
13681                mDisplayList.setAnimationMatrix(null);
13682                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13683            }
13684            if (!useDisplayListProperties &&
13685                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13686                final Transformation t = parent.getChildTransformation();
13687                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
13688                if (hasTransform) {
13689                    final int transformType = t.getTransformationType();
13690                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
13691                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13692                }
13693            }
13694        }
13695
13696        concatMatrix |= !childHasIdentityMatrix;
13697
13698        // Sets the flag as early as possible to allow draw() implementations
13699        // to call invalidate() successfully when doing animations
13700        mPrivateFlags |= PFLAG_DRAWN;
13701
13702        if (!concatMatrix &&
13703                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13704                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13705                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13706                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13707            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13708            return more;
13709        }
13710        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13711
13712        if (hardwareAccelerated) {
13713            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13714            // retain the flag's value temporarily in the mRecreateDisplayList flag
13715            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13716            mPrivateFlags &= ~PFLAG_INVALIDATED;
13717        }
13718
13719        DisplayList displayList = null;
13720        Bitmap cache = null;
13721        boolean hasDisplayList = false;
13722        if (caching) {
13723            if (!hardwareAccelerated) {
13724                if (layerType != LAYER_TYPE_NONE) {
13725                    layerType = LAYER_TYPE_SOFTWARE;
13726                    buildDrawingCache(true);
13727                }
13728                cache = getDrawingCache(true);
13729            } else {
13730                switch (layerType) {
13731                    case LAYER_TYPE_SOFTWARE:
13732                        if (useDisplayListProperties) {
13733                            hasDisplayList = canHaveDisplayList();
13734                        } else {
13735                            buildDrawingCache(true);
13736                            cache = getDrawingCache(true);
13737                        }
13738                        break;
13739                    case LAYER_TYPE_HARDWARE:
13740                        if (useDisplayListProperties) {
13741                            hasDisplayList = canHaveDisplayList();
13742                        }
13743                        break;
13744                    case LAYER_TYPE_NONE:
13745                        // Delay getting the display list until animation-driven alpha values are
13746                        // set up and possibly passed on to the view
13747                        hasDisplayList = canHaveDisplayList();
13748                        break;
13749                }
13750            }
13751        }
13752        useDisplayListProperties &= hasDisplayList;
13753        if (useDisplayListProperties) {
13754            displayList = getDisplayList();
13755            if (!displayList.isValid()) {
13756                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13757                // to getDisplayList(), the display list will be marked invalid and we should not
13758                // try to use it again.
13759                displayList = null;
13760                hasDisplayList = false;
13761                useDisplayListProperties = false;
13762            }
13763        }
13764
13765        int sx = 0;
13766        int sy = 0;
13767        if (!hasDisplayList) {
13768            computeScroll();
13769            sx = mScrollX;
13770            sy = mScrollY;
13771        }
13772
13773        final boolean hasNoCache = cache == null || hasDisplayList;
13774        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13775                layerType != LAYER_TYPE_HARDWARE;
13776
13777        int restoreTo = -1;
13778        if (!useDisplayListProperties || transformToApply != null) {
13779            restoreTo = canvas.save();
13780        }
13781        if (offsetForScroll) {
13782            canvas.translate(mLeft - sx, mTop - sy);
13783        } else {
13784            if (!useDisplayListProperties) {
13785                canvas.translate(mLeft, mTop);
13786            }
13787            if (scalingRequired) {
13788                if (useDisplayListProperties) {
13789                    // TODO: Might not need this if we put everything inside the DL
13790                    restoreTo = canvas.save();
13791                }
13792                // mAttachInfo cannot be null, otherwise scalingRequired == false
13793                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13794                canvas.scale(scale, scale);
13795            }
13796        }
13797
13798        float alpha = useDisplayListProperties ? 1 : getAlpha();
13799        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13800                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13801            if (transformToApply != null || !childHasIdentityMatrix) {
13802                int transX = 0;
13803                int transY = 0;
13804
13805                if (offsetForScroll) {
13806                    transX = -sx;
13807                    transY = -sy;
13808                }
13809
13810                if (transformToApply != null) {
13811                    if (concatMatrix) {
13812                        if (useDisplayListProperties) {
13813                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13814                        } else {
13815                            // Undo the scroll translation, apply the transformation matrix,
13816                            // then redo the scroll translate to get the correct result.
13817                            canvas.translate(-transX, -transY);
13818                            canvas.concat(transformToApply.getMatrix());
13819                            canvas.translate(transX, transY);
13820                        }
13821                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13822                    }
13823
13824                    float transformAlpha = transformToApply.getAlpha();
13825                    if (transformAlpha < 1) {
13826                        alpha *= transformAlpha;
13827                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13828                    }
13829                }
13830
13831                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13832                    canvas.translate(-transX, -transY);
13833                    canvas.concat(getMatrix());
13834                    canvas.translate(transX, transY);
13835                }
13836            }
13837
13838            // Deal with alpha if it is or used to be <1
13839            if (alpha < 1 ||
13840                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13841                if (alpha < 1) {
13842                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13843                } else {
13844                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13845                }
13846                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13847                if (hasNoCache) {
13848                    final int multipliedAlpha = (int) (255 * alpha);
13849                    if (!onSetAlpha(multipliedAlpha)) {
13850                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13851                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13852                                layerType != LAYER_TYPE_NONE) {
13853                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13854                        }
13855                        if (useDisplayListProperties) {
13856                            displayList.setAlpha(alpha * getAlpha());
13857                        } else  if (layerType == LAYER_TYPE_NONE) {
13858                            final int scrollX = hasDisplayList ? 0 : sx;
13859                            final int scrollY = hasDisplayList ? 0 : sy;
13860                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13861                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13862                        }
13863                    } else {
13864                        // Alpha is handled by the child directly, clobber the layer's alpha
13865                        mPrivateFlags |= PFLAG_ALPHA_SET;
13866                    }
13867                }
13868            }
13869        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13870            onSetAlpha(255);
13871            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13872        }
13873
13874        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13875                !useDisplayListProperties && cache == null) {
13876            if (offsetForScroll) {
13877                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13878            } else {
13879                if (!scalingRequired || cache == null) {
13880                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13881                } else {
13882                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13883                }
13884            }
13885        }
13886
13887        if (!useDisplayListProperties && hasDisplayList) {
13888            displayList = getDisplayList();
13889            if (!displayList.isValid()) {
13890                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13891                // to getDisplayList(), the display list will be marked invalid and we should not
13892                // try to use it again.
13893                displayList = null;
13894                hasDisplayList = false;
13895            }
13896        }
13897
13898        if (hasNoCache) {
13899            boolean layerRendered = false;
13900            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13901                final HardwareLayer layer = getHardwareLayer();
13902                if (layer != null && layer.isValid()) {
13903                    mLayerPaint.setAlpha((int) (alpha * 255));
13904                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13905                    layerRendered = true;
13906                } else {
13907                    final int scrollX = hasDisplayList ? 0 : sx;
13908                    final int scrollY = hasDisplayList ? 0 : sy;
13909                    canvas.saveLayer(scrollX, scrollY,
13910                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13911                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13912                }
13913            }
13914
13915            if (!layerRendered) {
13916                if (!hasDisplayList) {
13917                    // Fast path for layouts with no backgrounds
13918                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13919                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13920                        dispatchDraw(canvas);
13921                    } else {
13922                        draw(canvas);
13923                    }
13924                } else {
13925                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13926                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13927                }
13928            }
13929        } else if (cache != null) {
13930            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13931            Paint cachePaint;
13932
13933            if (layerType == LAYER_TYPE_NONE) {
13934                cachePaint = parent.mCachePaint;
13935                if (cachePaint == null) {
13936                    cachePaint = new Paint();
13937                    cachePaint.setDither(false);
13938                    parent.mCachePaint = cachePaint;
13939                }
13940                if (alpha < 1) {
13941                    cachePaint.setAlpha((int) (alpha * 255));
13942                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13943                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13944                    cachePaint.setAlpha(255);
13945                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13946                }
13947            } else {
13948                cachePaint = mLayerPaint;
13949                cachePaint.setAlpha((int) (alpha * 255));
13950            }
13951            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13952        }
13953
13954        if (restoreTo >= 0) {
13955            canvas.restoreToCount(restoreTo);
13956        }
13957
13958        if (a != null && !more) {
13959            if (!hardwareAccelerated && !a.getFillAfter()) {
13960                onSetAlpha(255);
13961            }
13962            parent.finishAnimatingView(this, a);
13963        }
13964
13965        if (more && hardwareAccelerated) {
13966            // invalidation is the trigger to recreate display lists, so if we're using
13967            // display lists to render, force an invalidate to allow the animation to
13968            // continue drawing another frame
13969            parent.invalidate(true);
13970            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13971                // alpha animations should cause the child to recreate its display list
13972                invalidate(true);
13973            }
13974        }
13975
13976        mRecreateDisplayList = false;
13977
13978        return more;
13979    }
13980
13981    /**
13982     * Manually render this view (and all of its children) to the given Canvas.
13983     * The view must have already done a full layout before this function is
13984     * called.  When implementing a view, implement
13985     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13986     * If you do need to override this method, call the superclass version.
13987     *
13988     * @param canvas The Canvas to which the View is rendered.
13989     */
13990    public void draw(Canvas canvas) {
13991        if (mClipBounds != null) {
13992            canvas.clipRect(mClipBounds);
13993        }
13994        final int privateFlags = mPrivateFlags;
13995        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13996                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13997        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13998
13999        /*
14000         * Draw traversal performs several drawing steps which must be executed
14001         * in the appropriate order:
14002         *
14003         *      1. Draw the background
14004         *      2. If necessary, save the canvas' layers to prepare for fading
14005         *      3. Draw view's content
14006         *      4. Draw children
14007         *      5. If necessary, draw the fading edges and restore layers
14008         *      6. Draw decorations (scrollbars for instance)
14009         */
14010
14011        // Step 1, draw the background, if needed
14012        int saveCount;
14013
14014        if (!dirtyOpaque) {
14015            final Drawable background = mBackground;
14016            if (background != null) {
14017                final int scrollX = mScrollX;
14018                final int scrollY = mScrollY;
14019
14020                if (mBackgroundSizeChanged) {
14021                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14022                    mBackgroundSizeChanged = false;
14023                }
14024
14025                if ((scrollX | scrollY) == 0) {
14026                    background.draw(canvas);
14027                } else {
14028                    canvas.translate(scrollX, scrollY);
14029                    background.draw(canvas);
14030                    canvas.translate(-scrollX, -scrollY);
14031                }
14032            }
14033        }
14034
14035        // skip step 2 & 5 if possible (common case)
14036        final int viewFlags = mViewFlags;
14037        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14038        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14039        if (!verticalEdges && !horizontalEdges) {
14040            // Step 3, draw the content
14041            if (!dirtyOpaque) onDraw(canvas);
14042
14043            // Step 4, draw the children
14044            dispatchDraw(canvas);
14045
14046            // Step 6, draw decorations (scrollbars)
14047            onDrawScrollBars(canvas);
14048
14049            if (mOverlay != null && !mOverlay.isEmpty()) {
14050                mOverlay.getOverlayView().dispatchDraw(canvas);
14051            }
14052
14053            // we're done...
14054            return;
14055        }
14056
14057        /*
14058         * Here we do the full fledged routine...
14059         * (this is an uncommon case where speed matters less,
14060         * this is why we repeat some of the tests that have been
14061         * done above)
14062         */
14063
14064        boolean drawTop = false;
14065        boolean drawBottom = false;
14066        boolean drawLeft = false;
14067        boolean drawRight = false;
14068
14069        float topFadeStrength = 0.0f;
14070        float bottomFadeStrength = 0.0f;
14071        float leftFadeStrength = 0.0f;
14072        float rightFadeStrength = 0.0f;
14073
14074        // Step 2, save the canvas' layers
14075        int paddingLeft = mPaddingLeft;
14076
14077        final boolean offsetRequired = isPaddingOffsetRequired();
14078        if (offsetRequired) {
14079            paddingLeft += getLeftPaddingOffset();
14080        }
14081
14082        int left = mScrollX + paddingLeft;
14083        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14084        int top = mScrollY + getFadeTop(offsetRequired);
14085        int bottom = top + getFadeHeight(offsetRequired);
14086
14087        if (offsetRequired) {
14088            right += getRightPaddingOffset();
14089            bottom += getBottomPaddingOffset();
14090        }
14091
14092        final ScrollabilityCache scrollabilityCache = mScrollCache;
14093        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14094        int length = (int) fadeHeight;
14095
14096        // clip the fade length if top and bottom fades overlap
14097        // overlapping fades produce odd-looking artifacts
14098        if (verticalEdges && (top + length > bottom - length)) {
14099            length = (bottom - top) / 2;
14100        }
14101
14102        // also clip horizontal fades if necessary
14103        if (horizontalEdges && (left + length > right - length)) {
14104            length = (right - left) / 2;
14105        }
14106
14107        if (verticalEdges) {
14108            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14109            drawTop = topFadeStrength * fadeHeight > 1.0f;
14110            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14111            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14112        }
14113
14114        if (horizontalEdges) {
14115            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14116            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14117            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14118            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14119        }
14120
14121        saveCount = canvas.getSaveCount();
14122
14123        int solidColor = getSolidColor();
14124        if (solidColor == 0) {
14125            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14126
14127            if (drawTop) {
14128                canvas.saveLayer(left, top, right, top + length, null, flags);
14129            }
14130
14131            if (drawBottom) {
14132                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14133            }
14134
14135            if (drawLeft) {
14136                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14137            }
14138
14139            if (drawRight) {
14140                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14141            }
14142        } else {
14143            scrollabilityCache.setFadeColor(solidColor);
14144        }
14145
14146        // Step 3, draw the content
14147        if (!dirtyOpaque) onDraw(canvas);
14148
14149        // Step 4, draw the children
14150        dispatchDraw(canvas);
14151
14152        // Step 5, draw the fade effect and restore layers
14153        final Paint p = scrollabilityCache.paint;
14154        final Matrix matrix = scrollabilityCache.matrix;
14155        final Shader fade = scrollabilityCache.shader;
14156
14157        if (drawTop) {
14158            matrix.setScale(1, fadeHeight * topFadeStrength);
14159            matrix.postTranslate(left, top);
14160            fade.setLocalMatrix(matrix);
14161            canvas.drawRect(left, top, right, top + length, p);
14162        }
14163
14164        if (drawBottom) {
14165            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14166            matrix.postRotate(180);
14167            matrix.postTranslate(left, bottom);
14168            fade.setLocalMatrix(matrix);
14169            canvas.drawRect(left, bottom - length, right, bottom, p);
14170        }
14171
14172        if (drawLeft) {
14173            matrix.setScale(1, fadeHeight * leftFadeStrength);
14174            matrix.postRotate(-90);
14175            matrix.postTranslate(left, top);
14176            fade.setLocalMatrix(matrix);
14177            canvas.drawRect(left, top, left + length, bottom, p);
14178        }
14179
14180        if (drawRight) {
14181            matrix.setScale(1, fadeHeight * rightFadeStrength);
14182            matrix.postRotate(90);
14183            matrix.postTranslate(right, top);
14184            fade.setLocalMatrix(matrix);
14185            canvas.drawRect(right - length, top, right, bottom, p);
14186        }
14187
14188        canvas.restoreToCount(saveCount);
14189
14190        // Step 6, draw decorations (scrollbars)
14191        onDrawScrollBars(canvas);
14192
14193        if (mOverlay != null && !mOverlay.isEmpty()) {
14194            mOverlay.getOverlayView().dispatchDraw(canvas);
14195        }
14196    }
14197
14198    /**
14199     * Returns the overlay for this view, creating it if it does not yet exist.
14200     * Adding drawables to the overlay will cause them to be displayed whenever
14201     * the view itself is redrawn. Objects in the overlay should be actively
14202     * managed: remove them when they should not be displayed anymore. The
14203     * overlay will always have the same size as its host view.
14204     *
14205     * <p>Note: Overlays do not currently work correctly with {@link
14206     * SurfaceView} or {@link TextureView}; contents in overlays for these
14207     * types of views may not display correctly.</p>
14208     *
14209     * @return The ViewOverlay object for this view.
14210     * @see ViewOverlay
14211     */
14212    public ViewOverlay getOverlay() {
14213        if (mOverlay == null) {
14214            mOverlay = new ViewOverlay(mContext, this);
14215        }
14216        return mOverlay;
14217    }
14218
14219    /**
14220     * Override this if your view is known to always be drawn on top of a solid color background,
14221     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14222     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14223     * should be set to 0xFF.
14224     *
14225     * @see #setVerticalFadingEdgeEnabled(boolean)
14226     * @see #setHorizontalFadingEdgeEnabled(boolean)
14227     *
14228     * @return The known solid color background for this view, or 0 if the color may vary
14229     */
14230    @ViewDebug.ExportedProperty(category = "drawing")
14231    public int getSolidColor() {
14232        return 0;
14233    }
14234
14235    /**
14236     * Build a human readable string representation of the specified view flags.
14237     *
14238     * @param flags the view flags to convert to a string
14239     * @return a String representing the supplied flags
14240     */
14241    private static String printFlags(int flags) {
14242        String output = "";
14243        int numFlags = 0;
14244        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14245            output += "TAKES_FOCUS";
14246            numFlags++;
14247        }
14248
14249        switch (flags & VISIBILITY_MASK) {
14250        case INVISIBLE:
14251            if (numFlags > 0) {
14252                output += " ";
14253            }
14254            output += "INVISIBLE";
14255            // USELESS HERE numFlags++;
14256            break;
14257        case GONE:
14258            if (numFlags > 0) {
14259                output += " ";
14260            }
14261            output += "GONE";
14262            // USELESS HERE numFlags++;
14263            break;
14264        default:
14265            break;
14266        }
14267        return output;
14268    }
14269
14270    /**
14271     * Build a human readable string representation of the specified private
14272     * view flags.
14273     *
14274     * @param privateFlags the private view flags to convert to a string
14275     * @return a String representing the supplied flags
14276     */
14277    private static String printPrivateFlags(int privateFlags) {
14278        String output = "";
14279        int numFlags = 0;
14280
14281        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14282            output += "WANTS_FOCUS";
14283            numFlags++;
14284        }
14285
14286        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14287            if (numFlags > 0) {
14288                output += " ";
14289            }
14290            output += "FOCUSED";
14291            numFlags++;
14292        }
14293
14294        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14295            if (numFlags > 0) {
14296                output += " ";
14297            }
14298            output += "SELECTED";
14299            numFlags++;
14300        }
14301
14302        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14303            if (numFlags > 0) {
14304                output += " ";
14305            }
14306            output += "IS_ROOT_NAMESPACE";
14307            numFlags++;
14308        }
14309
14310        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14311            if (numFlags > 0) {
14312                output += " ";
14313            }
14314            output += "HAS_BOUNDS";
14315            numFlags++;
14316        }
14317
14318        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14319            if (numFlags > 0) {
14320                output += " ";
14321            }
14322            output += "DRAWN";
14323            // USELESS HERE numFlags++;
14324        }
14325        return output;
14326    }
14327
14328    /**
14329     * <p>Indicates whether or not this view's layout will be requested during
14330     * the next hierarchy layout pass.</p>
14331     *
14332     * @return true if the layout will be forced during next layout pass
14333     */
14334    public boolean isLayoutRequested() {
14335        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14336    }
14337
14338    /**
14339     * Return true if o is a ViewGroup that is laying out using optical bounds.
14340     * @hide
14341     */
14342    public static boolean isLayoutModeOptical(Object o) {
14343        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14344    }
14345
14346    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14347        Insets parentInsets = mParent instanceof View ?
14348                ((View) mParent).getOpticalInsets() : Insets.NONE;
14349        Insets childInsets = getOpticalInsets();
14350        return setFrame(
14351                left   + parentInsets.left - childInsets.left,
14352                top    + parentInsets.top  - childInsets.top,
14353                right  + parentInsets.left + childInsets.right,
14354                bottom + parentInsets.top  + childInsets.bottom);
14355    }
14356
14357    /**
14358     * Assign a size and position to a view and all of its
14359     * descendants
14360     *
14361     * <p>This is the second phase of the layout mechanism.
14362     * (The first is measuring). In this phase, each parent calls
14363     * layout on all of its children to position them.
14364     * This is typically done using the child measurements
14365     * that were stored in the measure pass().</p>
14366     *
14367     * <p>Derived classes should not override this method.
14368     * Derived classes with children should override
14369     * onLayout. In that method, they should
14370     * call layout on each of their children.</p>
14371     *
14372     * @param l Left position, relative to parent
14373     * @param t Top position, relative to parent
14374     * @param r Right position, relative to parent
14375     * @param b Bottom position, relative to parent
14376     */
14377    @SuppressWarnings({"unchecked"})
14378    public void layout(int l, int t, int r, int b) {
14379        int oldL = mLeft;
14380        int oldT = mTop;
14381        int oldB = mBottom;
14382        int oldR = mRight;
14383        boolean changed = isLayoutModeOptical(mParent) ?
14384                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14385        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14386            onLayout(changed, l, t, r, b);
14387            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14388
14389            ListenerInfo li = mListenerInfo;
14390            if (li != null && li.mOnLayoutChangeListeners != null) {
14391                ArrayList<OnLayoutChangeListener> listenersCopy =
14392                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14393                int numListeners = listenersCopy.size();
14394                for (int i = 0; i < numListeners; ++i) {
14395                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14396                }
14397            }
14398        }
14399        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14400        mPrivateFlags3 |= PFLAG3_HAS_LAYOUT;
14401    }
14402
14403    /**
14404     * Called from layout when this view should
14405     * assign a size and position to each of its children.
14406     *
14407     * Derived classes with children should override
14408     * this method and call layout on each of
14409     * their children.
14410     * @param changed This is a new size or position for this view
14411     * @param left Left position, relative to parent
14412     * @param top Top position, relative to parent
14413     * @param right Right position, relative to parent
14414     * @param bottom Bottom position, relative to parent
14415     */
14416    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14417    }
14418
14419    /**
14420     * Assign a size and position to this view.
14421     *
14422     * This is called from layout.
14423     *
14424     * @param left Left position, relative to parent
14425     * @param top Top position, relative to parent
14426     * @param right Right position, relative to parent
14427     * @param bottom Bottom position, relative to parent
14428     * @return true if the new size and position are different than the
14429     *         previous ones
14430     * {@hide}
14431     */
14432    protected boolean setFrame(int left, int top, int right, int bottom) {
14433        boolean changed = false;
14434
14435        if (DBG) {
14436            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14437                    + right + "," + bottom + ")");
14438        }
14439
14440        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14441            changed = true;
14442
14443            // Remember our drawn bit
14444            int drawn = mPrivateFlags & PFLAG_DRAWN;
14445
14446            int oldWidth = mRight - mLeft;
14447            int oldHeight = mBottom - mTop;
14448            int newWidth = right - left;
14449            int newHeight = bottom - top;
14450            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14451
14452            // Invalidate our old position
14453            invalidate(sizeChanged);
14454
14455            mLeft = left;
14456            mTop = top;
14457            mRight = right;
14458            mBottom = bottom;
14459            if (mDisplayList != null) {
14460                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14461            }
14462
14463            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14464
14465
14466            if (sizeChanged) {
14467                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14468                    // A change in dimension means an auto-centered pivot point changes, too
14469                    if (mTransformationInfo != null) {
14470                        mTransformationInfo.mMatrixDirty = true;
14471                    }
14472                }
14473                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14474            }
14475
14476            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14477                // If we are visible, force the DRAWN bit to on so that
14478                // this invalidate will go through (at least to our parent).
14479                // This is because someone may have invalidated this view
14480                // before this call to setFrame came in, thereby clearing
14481                // the DRAWN bit.
14482                mPrivateFlags |= PFLAG_DRAWN;
14483                invalidate(sizeChanged);
14484                // parent display list may need to be recreated based on a change in the bounds
14485                // of any child
14486                invalidateParentCaches();
14487            }
14488
14489            // Reset drawn bit to original value (invalidate turns it off)
14490            mPrivateFlags |= drawn;
14491
14492            mBackgroundSizeChanged = true;
14493
14494            notifySubtreeAccessibilityStateChangedIfNeeded();
14495        }
14496        return changed;
14497    }
14498
14499    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14500        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14501        if (mOverlay != null) {
14502            mOverlay.getOverlayView().setRight(newWidth);
14503            mOverlay.getOverlayView().setBottom(newHeight);
14504        }
14505    }
14506
14507    /**
14508     * Finalize inflating a view from XML.  This is called as the last phase
14509     * of inflation, after all child views have been added.
14510     *
14511     * <p>Even if the subclass overrides onFinishInflate, they should always be
14512     * sure to call the super method, so that we get called.
14513     */
14514    protected void onFinishInflate() {
14515    }
14516
14517    /**
14518     * Returns the resources associated with this view.
14519     *
14520     * @return Resources object.
14521     */
14522    public Resources getResources() {
14523        return mResources;
14524    }
14525
14526    /**
14527     * Invalidates the specified Drawable.
14528     *
14529     * @param drawable the drawable to invalidate
14530     */
14531    public void invalidateDrawable(Drawable drawable) {
14532        if (verifyDrawable(drawable)) {
14533            final Rect dirty = drawable.getBounds();
14534            final int scrollX = mScrollX;
14535            final int scrollY = mScrollY;
14536
14537            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14538                    dirty.right + scrollX, dirty.bottom + scrollY);
14539        }
14540    }
14541
14542    /**
14543     * Schedules an action on a drawable to occur at a specified time.
14544     *
14545     * @param who the recipient of the action
14546     * @param what the action to run on the drawable
14547     * @param when the time at which the action must occur. Uses the
14548     *        {@link SystemClock#uptimeMillis} timebase.
14549     */
14550    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14551        if (verifyDrawable(who) && what != null) {
14552            final long delay = when - SystemClock.uptimeMillis();
14553            if (mAttachInfo != null) {
14554                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14555                        Choreographer.CALLBACK_ANIMATION, what, who,
14556                        Choreographer.subtractFrameDelay(delay));
14557            } else {
14558                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14559            }
14560        }
14561    }
14562
14563    /**
14564     * Cancels a scheduled action on a drawable.
14565     *
14566     * @param who the recipient of the action
14567     * @param what the action to cancel
14568     */
14569    public void unscheduleDrawable(Drawable who, Runnable what) {
14570        if (verifyDrawable(who) && what != null) {
14571            if (mAttachInfo != null) {
14572                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14573                        Choreographer.CALLBACK_ANIMATION, what, who);
14574            } else {
14575                ViewRootImpl.getRunQueue().removeCallbacks(what);
14576            }
14577        }
14578    }
14579
14580    /**
14581     * Unschedule any events associated with the given Drawable.  This can be
14582     * used when selecting a new Drawable into a view, so that the previous
14583     * one is completely unscheduled.
14584     *
14585     * @param who The Drawable to unschedule.
14586     *
14587     * @see #drawableStateChanged
14588     */
14589    public void unscheduleDrawable(Drawable who) {
14590        if (mAttachInfo != null && who != null) {
14591            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14592                    Choreographer.CALLBACK_ANIMATION, null, who);
14593        }
14594    }
14595
14596    /**
14597     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14598     * that the View directionality can and will be resolved before its Drawables.
14599     *
14600     * Will call {@link View#onResolveDrawables} when resolution is done.
14601     *
14602     * @hide
14603     */
14604    protected void resolveDrawables() {
14605        if (canResolveLayoutDirection()) {
14606            if (mBackground != null) {
14607                mBackground.setLayoutDirection(getLayoutDirection());
14608            }
14609            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14610            onResolveDrawables(getLayoutDirection());
14611        }
14612    }
14613
14614    /**
14615     * Called when layout direction has been resolved.
14616     *
14617     * The default implementation does nothing.
14618     *
14619     * @param layoutDirection The resolved layout direction.
14620     *
14621     * @see #LAYOUT_DIRECTION_LTR
14622     * @see #LAYOUT_DIRECTION_RTL
14623     *
14624     * @hide
14625     */
14626    public void onResolveDrawables(int layoutDirection) {
14627    }
14628
14629    /**
14630     * @hide
14631     */
14632    protected void resetResolvedDrawables() {
14633        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14634    }
14635
14636    private boolean isDrawablesResolved() {
14637        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14638    }
14639
14640    /**
14641     * If your view subclass is displaying its own Drawable objects, it should
14642     * override this function and return true for any Drawable it is
14643     * displaying.  This allows animations for those drawables to be
14644     * scheduled.
14645     *
14646     * <p>Be sure to call through to the super class when overriding this
14647     * function.
14648     *
14649     * @param who The Drawable to verify.  Return true if it is one you are
14650     *            displaying, else return the result of calling through to the
14651     *            super class.
14652     *
14653     * @return boolean If true than the Drawable is being displayed in the
14654     *         view; else false and it is not allowed to animate.
14655     *
14656     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14657     * @see #drawableStateChanged()
14658     */
14659    protected boolean verifyDrawable(Drawable who) {
14660        return who == mBackground;
14661    }
14662
14663    /**
14664     * This function is called whenever the state of the view changes in such
14665     * a way that it impacts the state of drawables being shown.
14666     *
14667     * <p>Be sure to call through to the superclass when overriding this
14668     * function.
14669     *
14670     * @see Drawable#setState(int[])
14671     */
14672    protected void drawableStateChanged() {
14673        Drawable d = mBackground;
14674        if (d != null && d.isStateful()) {
14675            d.setState(getDrawableState());
14676        }
14677    }
14678
14679    /**
14680     * Call this to force a view to update its drawable state. This will cause
14681     * drawableStateChanged to be called on this view. Views that are interested
14682     * in the new state should call getDrawableState.
14683     *
14684     * @see #drawableStateChanged
14685     * @see #getDrawableState
14686     */
14687    public void refreshDrawableState() {
14688        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14689        drawableStateChanged();
14690
14691        ViewParent parent = mParent;
14692        if (parent != null) {
14693            parent.childDrawableStateChanged(this);
14694        }
14695    }
14696
14697    /**
14698     * Return an array of resource IDs of the drawable states representing the
14699     * current state of the view.
14700     *
14701     * @return The current drawable state
14702     *
14703     * @see Drawable#setState(int[])
14704     * @see #drawableStateChanged()
14705     * @see #onCreateDrawableState(int)
14706     */
14707    public final int[] getDrawableState() {
14708        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14709            return mDrawableState;
14710        } else {
14711            mDrawableState = onCreateDrawableState(0);
14712            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14713            return mDrawableState;
14714        }
14715    }
14716
14717    /**
14718     * Generate the new {@link android.graphics.drawable.Drawable} state for
14719     * this view. This is called by the view
14720     * system when the cached Drawable state is determined to be invalid.  To
14721     * retrieve the current state, you should use {@link #getDrawableState}.
14722     *
14723     * @param extraSpace if non-zero, this is the number of extra entries you
14724     * would like in the returned array in which you can place your own
14725     * states.
14726     *
14727     * @return Returns an array holding the current {@link Drawable} state of
14728     * the view.
14729     *
14730     * @see #mergeDrawableStates(int[], int[])
14731     */
14732    protected int[] onCreateDrawableState(int extraSpace) {
14733        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14734                mParent instanceof View) {
14735            return ((View) mParent).onCreateDrawableState(extraSpace);
14736        }
14737
14738        int[] drawableState;
14739
14740        int privateFlags = mPrivateFlags;
14741
14742        int viewStateIndex = 0;
14743        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14744        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14745        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14746        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14747        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14748        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14749        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14750                HardwareRenderer.isAvailable()) {
14751            // This is set if HW acceleration is requested, even if the current
14752            // process doesn't allow it.  This is just to allow app preview
14753            // windows to better match their app.
14754            viewStateIndex |= VIEW_STATE_ACCELERATED;
14755        }
14756        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14757
14758        final int privateFlags2 = mPrivateFlags2;
14759        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14760        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14761
14762        drawableState = VIEW_STATE_SETS[viewStateIndex];
14763
14764        //noinspection ConstantIfStatement
14765        if (false) {
14766            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14767            Log.i("View", toString()
14768                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14769                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14770                    + " fo=" + hasFocus()
14771                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14772                    + " wf=" + hasWindowFocus()
14773                    + ": " + Arrays.toString(drawableState));
14774        }
14775
14776        if (extraSpace == 0) {
14777            return drawableState;
14778        }
14779
14780        final int[] fullState;
14781        if (drawableState != null) {
14782            fullState = new int[drawableState.length + extraSpace];
14783            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14784        } else {
14785            fullState = new int[extraSpace];
14786        }
14787
14788        return fullState;
14789    }
14790
14791    /**
14792     * Merge your own state values in <var>additionalState</var> into the base
14793     * state values <var>baseState</var> that were returned by
14794     * {@link #onCreateDrawableState(int)}.
14795     *
14796     * @param baseState The base state values returned by
14797     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14798     * own additional state values.
14799     *
14800     * @param additionalState The additional state values you would like
14801     * added to <var>baseState</var>; this array is not modified.
14802     *
14803     * @return As a convenience, the <var>baseState</var> array you originally
14804     * passed into the function is returned.
14805     *
14806     * @see #onCreateDrawableState(int)
14807     */
14808    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14809        final int N = baseState.length;
14810        int i = N - 1;
14811        while (i >= 0 && baseState[i] == 0) {
14812            i--;
14813        }
14814        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14815        return baseState;
14816    }
14817
14818    /**
14819     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14820     * on all Drawable objects associated with this view.
14821     */
14822    public void jumpDrawablesToCurrentState() {
14823        if (mBackground != null) {
14824            mBackground.jumpToCurrentState();
14825        }
14826    }
14827
14828    /**
14829     * Sets the background color for this view.
14830     * @param color the color of the background
14831     */
14832    @RemotableViewMethod
14833    public void setBackgroundColor(int color) {
14834        if (mBackground instanceof ColorDrawable) {
14835            ((ColorDrawable) mBackground.mutate()).setColor(color);
14836            computeOpaqueFlags();
14837            mBackgroundResource = 0;
14838        } else {
14839            setBackground(new ColorDrawable(color));
14840        }
14841    }
14842
14843    /**
14844     * Set the background to a given resource. The resource should refer to
14845     * a Drawable object or 0 to remove the background.
14846     * @param resid The identifier of the resource.
14847     *
14848     * @attr ref android.R.styleable#View_background
14849     */
14850    @RemotableViewMethod
14851    public void setBackgroundResource(int resid) {
14852        if (resid != 0 && resid == mBackgroundResource) {
14853            return;
14854        }
14855
14856        Drawable d= null;
14857        if (resid != 0) {
14858            d = mResources.getDrawable(resid);
14859        }
14860        setBackground(d);
14861
14862        mBackgroundResource = resid;
14863    }
14864
14865    /**
14866     * Set the background to a given Drawable, or remove the background. If the
14867     * background has padding, this View's padding is set to the background's
14868     * padding. However, when a background is removed, this View's padding isn't
14869     * touched. If setting the padding is desired, please use
14870     * {@link #setPadding(int, int, int, int)}.
14871     *
14872     * @param background The Drawable to use as the background, or null to remove the
14873     *        background
14874     */
14875    public void setBackground(Drawable background) {
14876        //noinspection deprecation
14877        setBackgroundDrawable(background);
14878    }
14879
14880    /**
14881     * @deprecated use {@link #setBackground(Drawable)} instead
14882     */
14883    @Deprecated
14884    public void setBackgroundDrawable(Drawable background) {
14885        computeOpaqueFlags();
14886
14887        if (background == mBackground) {
14888            return;
14889        }
14890
14891        boolean requestLayout = false;
14892
14893        mBackgroundResource = 0;
14894
14895        /*
14896         * Regardless of whether we're setting a new background or not, we want
14897         * to clear the previous drawable.
14898         */
14899        if (mBackground != null) {
14900            mBackground.setCallback(null);
14901            unscheduleDrawable(mBackground);
14902        }
14903
14904        if (background != null) {
14905            Rect padding = sThreadLocal.get();
14906            if (padding == null) {
14907                padding = new Rect();
14908                sThreadLocal.set(padding);
14909            }
14910            resetResolvedDrawables();
14911            background.setLayoutDirection(getLayoutDirection());
14912            if (background.getPadding(padding)) {
14913                resetResolvedPadding();
14914                switch (background.getLayoutDirection()) {
14915                    case LAYOUT_DIRECTION_RTL:
14916                        mUserPaddingLeftInitial = padding.right;
14917                        mUserPaddingRightInitial = padding.left;
14918                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14919                        break;
14920                    case LAYOUT_DIRECTION_LTR:
14921                    default:
14922                        mUserPaddingLeftInitial = padding.left;
14923                        mUserPaddingRightInitial = padding.right;
14924                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14925                }
14926            }
14927
14928            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14929            // if it has a different minimum size, we should layout again
14930            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14931                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14932                requestLayout = true;
14933            }
14934
14935            background.setCallback(this);
14936            if (background.isStateful()) {
14937                background.setState(getDrawableState());
14938            }
14939            background.setVisible(getVisibility() == VISIBLE, false);
14940            mBackground = background;
14941
14942            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14943                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14944                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14945                requestLayout = true;
14946            }
14947        } else {
14948            /* Remove the background */
14949            mBackground = null;
14950
14951            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14952                /*
14953                 * This view ONLY drew the background before and we're removing
14954                 * the background, so now it won't draw anything
14955                 * (hence we SKIP_DRAW)
14956                 */
14957                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14958                mPrivateFlags |= PFLAG_SKIP_DRAW;
14959            }
14960
14961            /*
14962             * When the background is set, we try to apply its padding to this
14963             * View. When the background is removed, we don't touch this View's
14964             * padding. This is noted in the Javadocs. Hence, we don't need to
14965             * requestLayout(), the invalidate() below is sufficient.
14966             */
14967
14968            // The old background's minimum size could have affected this
14969            // View's layout, so let's requestLayout
14970            requestLayout = true;
14971        }
14972
14973        computeOpaqueFlags();
14974
14975        if (requestLayout) {
14976            requestLayout();
14977        }
14978
14979        mBackgroundSizeChanged = true;
14980        invalidate(true);
14981    }
14982
14983    /**
14984     * Gets the background drawable
14985     *
14986     * @return The drawable used as the background for this view, if any.
14987     *
14988     * @see #setBackground(Drawable)
14989     *
14990     * @attr ref android.R.styleable#View_background
14991     */
14992    public Drawable getBackground() {
14993        return mBackground;
14994    }
14995
14996    /**
14997     * Sets the padding. The view may add on the space required to display
14998     * the scrollbars, depending on the style and visibility of the scrollbars.
14999     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15000     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15001     * from the values set in this call.
15002     *
15003     * @attr ref android.R.styleable#View_padding
15004     * @attr ref android.R.styleable#View_paddingBottom
15005     * @attr ref android.R.styleable#View_paddingLeft
15006     * @attr ref android.R.styleable#View_paddingRight
15007     * @attr ref android.R.styleable#View_paddingTop
15008     * @param left the left padding in pixels
15009     * @param top the top padding in pixels
15010     * @param right the right padding in pixels
15011     * @param bottom the bottom padding in pixels
15012     */
15013    public void setPadding(int left, int top, int right, int bottom) {
15014        resetResolvedPadding();
15015
15016        mUserPaddingStart = UNDEFINED_PADDING;
15017        mUserPaddingEnd = UNDEFINED_PADDING;
15018
15019        mUserPaddingLeftInitial = left;
15020        mUserPaddingRightInitial = right;
15021
15022        internalSetPadding(left, top, right, bottom);
15023    }
15024
15025    /**
15026     * @hide
15027     */
15028    protected void internalSetPadding(int left, int top, int right, int bottom) {
15029        mUserPaddingLeft = left;
15030        mUserPaddingRight = right;
15031        mUserPaddingBottom = bottom;
15032
15033        final int viewFlags = mViewFlags;
15034        boolean changed = false;
15035
15036        // Common case is there are no scroll bars.
15037        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15038            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15039                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15040                        ? 0 : getVerticalScrollbarWidth();
15041                switch (mVerticalScrollbarPosition) {
15042                    case SCROLLBAR_POSITION_DEFAULT:
15043                        if (isLayoutRtl()) {
15044                            left += offset;
15045                        } else {
15046                            right += offset;
15047                        }
15048                        break;
15049                    case SCROLLBAR_POSITION_RIGHT:
15050                        right += offset;
15051                        break;
15052                    case SCROLLBAR_POSITION_LEFT:
15053                        left += offset;
15054                        break;
15055                }
15056            }
15057            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15058                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15059                        ? 0 : getHorizontalScrollbarHeight();
15060            }
15061        }
15062
15063        if (mPaddingLeft != left) {
15064            changed = true;
15065            mPaddingLeft = left;
15066        }
15067        if (mPaddingTop != top) {
15068            changed = true;
15069            mPaddingTop = top;
15070        }
15071        if (mPaddingRight != right) {
15072            changed = true;
15073            mPaddingRight = right;
15074        }
15075        if (mPaddingBottom != bottom) {
15076            changed = true;
15077            mPaddingBottom = bottom;
15078        }
15079
15080        if (changed) {
15081            requestLayout();
15082        }
15083    }
15084
15085    /**
15086     * Sets the relative padding. The view may add on the space required to display
15087     * the scrollbars, depending on the style and visibility of the scrollbars.
15088     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15089     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15090     * from the values set in this call.
15091     *
15092     * @attr ref android.R.styleable#View_padding
15093     * @attr ref android.R.styleable#View_paddingBottom
15094     * @attr ref android.R.styleable#View_paddingStart
15095     * @attr ref android.R.styleable#View_paddingEnd
15096     * @attr ref android.R.styleable#View_paddingTop
15097     * @param start the start padding in pixels
15098     * @param top the top padding in pixels
15099     * @param end the end padding in pixels
15100     * @param bottom the bottom padding in pixels
15101     */
15102    public void setPaddingRelative(int start, int top, int end, int bottom) {
15103        resetResolvedPadding();
15104
15105        mUserPaddingStart = start;
15106        mUserPaddingEnd = end;
15107
15108        switch(getLayoutDirection()) {
15109            case LAYOUT_DIRECTION_RTL:
15110                mUserPaddingLeftInitial = end;
15111                mUserPaddingRightInitial = start;
15112                internalSetPadding(end, top, start, bottom);
15113                break;
15114            case LAYOUT_DIRECTION_LTR:
15115            default:
15116                mUserPaddingLeftInitial = start;
15117                mUserPaddingRightInitial = end;
15118                internalSetPadding(start, top, end, bottom);
15119        }
15120    }
15121
15122    /**
15123     * Returns the top padding of this view.
15124     *
15125     * @return the top padding in pixels
15126     */
15127    public int getPaddingTop() {
15128        return mPaddingTop;
15129    }
15130
15131    /**
15132     * Returns the bottom padding of this view. If there are inset and enabled
15133     * scrollbars, this value may include the space required to display the
15134     * scrollbars as well.
15135     *
15136     * @return the bottom padding in pixels
15137     */
15138    public int getPaddingBottom() {
15139        return mPaddingBottom;
15140    }
15141
15142    /**
15143     * Returns the left padding of this view. If there are inset and enabled
15144     * scrollbars, this value may include the space required to display the
15145     * scrollbars as well.
15146     *
15147     * @return the left padding in pixels
15148     */
15149    public int getPaddingLeft() {
15150        if (!isPaddingResolved()) {
15151            resolvePadding();
15152        }
15153        return mPaddingLeft;
15154    }
15155
15156    /**
15157     * Returns the start padding of this view depending on its resolved layout direction.
15158     * If there are inset and enabled scrollbars, this value may include the space
15159     * required to display the scrollbars as well.
15160     *
15161     * @return the start padding in pixels
15162     */
15163    public int getPaddingStart() {
15164        if (!isPaddingResolved()) {
15165            resolvePadding();
15166        }
15167        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15168                mPaddingRight : mPaddingLeft;
15169    }
15170
15171    /**
15172     * Returns the right padding of this view. If there are inset and enabled
15173     * scrollbars, this value may include the space required to display the
15174     * scrollbars as well.
15175     *
15176     * @return the right padding in pixels
15177     */
15178    public int getPaddingRight() {
15179        if (!isPaddingResolved()) {
15180            resolvePadding();
15181        }
15182        return mPaddingRight;
15183    }
15184
15185    /**
15186     * Returns the end padding of this view depending on its resolved layout direction.
15187     * If there are inset and enabled scrollbars, this value may include the space
15188     * required to display the scrollbars as well.
15189     *
15190     * @return the end padding in pixels
15191     */
15192    public int getPaddingEnd() {
15193        if (!isPaddingResolved()) {
15194            resolvePadding();
15195        }
15196        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15197                mPaddingLeft : mPaddingRight;
15198    }
15199
15200    /**
15201     * Return if the padding as been set thru relative values
15202     * {@link #setPaddingRelative(int, int, int, int)} or thru
15203     * @attr ref android.R.styleable#View_paddingStart or
15204     * @attr ref android.R.styleable#View_paddingEnd
15205     *
15206     * @return true if the padding is relative or false if it is not.
15207     */
15208    public boolean isPaddingRelative() {
15209        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15210    }
15211
15212    Insets computeOpticalInsets() {
15213        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15214    }
15215
15216    /**
15217     * @hide
15218     */
15219    public void resetPaddingToInitialValues() {
15220        if (isRtlCompatibilityMode()) {
15221            mPaddingLeft = mUserPaddingLeftInitial;
15222            mPaddingRight = mUserPaddingRightInitial;
15223            return;
15224        }
15225        if (isLayoutRtl()) {
15226            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15227            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15228        } else {
15229            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15230            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15231        }
15232    }
15233
15234    /**
15235     * @hide
15236     */
15237    public Insets getOpticalInsets() {
15238        if (mLayoutInsets == null) {
15239            mLayoutInsets = computeOpticalInsets();
15240        }
15241        return mLayoutInsets;
15242    }
15243
15244    /**
15245     * Changes the selection state of this view. A view can be selected or not.
15246     * Note that selection is not the same as focus. Views are typically
15247     * selected in the context of an AdapterView like ListView or GridView;
15248     * the selected view is the view that is highlighted.
15249     *
15250     * @param selected true if the view must be selected, false otherwise
15251     */
15252    public void setSelected(boolean selected) {
15253        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15254            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15255            if (!selected) resetPressedState();
15256            invalidate(true);
15257            refreshDrawableState();
15258            dispatchSetSelected(selected);
15259            notifyViewAccessibilityStateChangedIfNeeded();
15260        }
15261    }
15262
15263    /**
15264     * Dispatch setSelected to all of this View's children.
15265     *
15266     * @see #setSelected(boolean)
15267     *
15268     * @param selected The new selected state
15269     */
15270    protected void dispatchSetSelected(boolean selected) {
15271    }
15272
15273    /**
15274     * Indicates the selection state of this view.
15275     *
15276     * @return true if the view is selected, false otherwise
15277     */
15278    @ViewDebug.ExportedProperty
15279    public boolean isSelected() {
15280        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15281    }
15282
15283    /**
15284     * Changes the activated state of this view. A view can be activated or not.
15285     * Note that activation is not the same as selection.  Selection is
15286     * a transient property, representing the view (hierarchy) the user is
15287     * currently interacting with.  Activation is a longer-term state that the
15288     * user can move views in and out of.  For example, in a list view with
15289     * single or multiple selection enabled, the views in the current selection
15290     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15291     * here.)  The activated state is propagated down to children of the view it
15292     * is set on.
15293     *
15294     * @param activated true if the view must be activated, false otherwise
15295     */
15296    public void setActivated(boolean activated) {
15297        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15298            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15299            invalidate(true);
15300            refreshDrawableState();
15301            dispatchSetActivated(activated);
15302        }
15303    }
15304
15305    /**
15306     * Dispatch setActivated to all of this View's children.
15307     *
15308     * @see #setActivated(boolean)
15309     *
15310     * @param activated The new activated state
15311     */
15312    protected void dispatchSetActivated(boolean activated) {
15313    }
15314
15315    /**
15316     * Indicates the activation state of this view.
15317     *
15318     * @return true if the view is activated, false otherwise
15319     */
15320    @ViewDebug.ExportedProperty
15321    public boolean isActivated() {
15322        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15323    }
15324
15325    /**
15326     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15327     * observer can be used to get notifications when global events, like
15328     * layout, happen.
15329     *
15330     * The returned ViewTreeObserver observer is not guaranteed to remain
15331     * valid for the lifetime of this View. If the caller of this method keeps
15332     * a long-lived reference to ViewTreeObserver, it should always check for
15333     * the return value of {@link ViewTreeObserver#isAlive()}.
15334     *
15335     * @return The ViewTreeObserver for this view's hierarchy.
15336     */
15337    public ViewTreeObserver getViewTreeObserver() {
15338        if (mAttachInfo != null) {
15339            return mAttachInfo.mTreeObserver;
15340        }
15341        if (mFloatingTreeObserver == null) {
15342            mFloatingTreeObserver = new ViewTreeObserver();
15343        }
15344        return mFloatingTreeObserver;
15345    }
15346
15347    /**
15348     * <p>Finds the topmost view in the current view hierarchy.</p>
15349     *
15350     * @return the topmost view containing this view
15351     */
15352    public View getRootView() {
15353        if (mAttachInfo != null) {
15354            final View v = mAttachInfo.mRootView;
15355            if (v != null) {
15356                return v;
15357            }
15358        }
15359
15360        View parent = this;
15361
15362        while (parent.mParent != null && parent.mParent instanceof View) {
15363            parent = (View) parent.mParent;
15364        }
15365
15366        return parent;
15367    }
15368
15369    /**
15370     * <p>Computes the coordinates of this view on the screen. The argument
15371     * must be an array of two integers. After the method returns, the array
15372     * contains the x and y location in that order.</p>
15373     *
15374     * @param location an array of two integers in which to hold the coordinates
15375     */
15376    public void getLocationOnScreen(int[] location) {
15377        getLocationInWindow(location);
15378
15379        final AttachInfo info = mAttachInfo;
15380        if (info != null) {
15381            location[0] += info.mWindowLeft;
15382            location[1] += info.mWindowTop;
15383        }
15384    }
15385
15386    /**
15387     * <p>Computes the coordinates of this view in its window. The argument
15388     * must be an array of two integers. After the method returns, the array
15389     * contains the x and y location in that order.</p>
15390     *
15391     * @param location an array of two integers in which to hold the coordinates
15392     */
15393    public void getLocationInWindow(int[] location) {
15394        if (location == null || location.length < 2) {
15395            throw new IllegalArgumentException("location must be an array of two integers");
15396        }
15397
15398        if (mAttachInfo == null) {
15399            // When the view is not attached to a window, this method does not make sense
15400            location[0] = location[1] = 0;
15401            return;
15402        }
15403
15404        float[] position = mAttachInfo.mTmpTransformLocation;
15405        position[0] = position[1] = 0.0f;
15406
15407        if (!hasIdentityMatrix()) {
15408            getMatrix().mapPoints(position);
15409        }
15410
15411        position[0] += mLeft;
15412        position[1] += mTop;
15413
15414        ViewParent viewParent = mParent;
15415        while (viewParent instanceof View) {
15416            final View view = (View) viewParent;
15417
15418            position[0] -= view.mScrollX;
15419            position[1] -= view.mScrollY;
15420
15421            if (!view.hasIdentityMatrix()) {
15422                view.getMatrix().mapPoints(position);
15423            }
15424
15425            position[0] += view.mLeft;
15426            position[1] += view.mTop;
15427
15428            viewParent = view.mParent;
15429         }
15430
15431        if (viewParent instanceof ViewRootImpl) {
15432            // *cough*
15433            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15434            position[1] -= vr.mCurScrollY;
15435        }
15436
15437        location[0] = (int) (position[0] + 0.5f);
15438        location[1] = (int) (position[1] + 0.5f);
15439    }
15440
15441    /**
15442     * {@hide}
15443     * @param id the id of the view to be found
15444     * @return the view of the specified id, null if cannot be found
15445     */
15446    protected View findViewTraversal(int id) {
15447        if (id == mID) {
15448            return this;
15449        }
15450        return null;
15451    }
15452
15453    /**
15454     * {@hide}
15455     * @param tag the tag of the view to be found
15456     * @return the view of specified tag, null if cannot be found
15457     */
15458    protected View findViewWithTagTraversal(Object tag) {
15459        if (tag != null && tag.equals(mTag)) {
15460            return this;
15461        }
15462        return null;
15463    }
15464
15465    /**
15466     * {@hide}
15467     * @param predicate The predicate to evaluate.
15468     * @param childToSkip If not null, ignores this child during the recursive traversal.
15469     * @return The first view that matches the predicate or null.
15470     */
15471    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15472        if (predicate.apply(this)) {
15473            return this;
15474        }
15475        return null;
15476    }
15477
15478    /**
15479     * Look for a child view with the given id.  If this view has the given
15480     * id, return this view.
15481     *
15482     * @param id The id to search for.
15483     * @return The view that has the given id in the hierarchy or null
15484     */
15485    public final View findViewById(int id) {
15486        if (id < 0) {
15487            return null;
15488        }
15489        return findViewTraversal(id);
15490    }
15491
15492    /**
15493     * Finds a view by its unuque and stable accessibility id.
15494     *
15495     * @param accessibilityId The searched accessibility id.
15496     * @return The found view.
15497     */
15498    final View findViewByAccessibilityId(int accessibilityId) {
15499        if (accessibilityId < 0) {
15500            return null;
15501        }
15502        return findViewByAccessibilityIdTraversal(accessibilityId);
15503    }
15504
15505    /**
15506     * Performs the traversal to find a view by its unuque and stable accessibility id.
15507     *
15508     * <strong>Note:</strong>This method does not stop at the root namespace
15509     * boundary since the user can touch the screen at an arbitrary location
15510     * potentially crossing the root namespace bounday which will send an
15511     * accessibility event to accessibility services and they should be able
15512     * to obtain the event source. Also accessibility ids are guaranteed to be
15513     * unique in the window.
15514     *
15515     * @param accessibilityId The accessibility id.
15516     * @return The found view.
15517     *
15518     * @hide
15519     */
15520    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15521        if (getAccessibilityViewId() == accessibilityId) {
15522            return this;
15523        }
15524        return null;
15525    }
15526
15527    /**
15528     * Look for a child view with the given tag.  If this view has the given
15529     * tag, return this view.
15530     *
15531     * @param tag The tag to search for, using "tag.equals(getTag())".
15532     * @return The View that has the given tag in the hierarchy or null
15533     */
15534    public final View findViewWithTag(Object tag) {
15535        if (tag == null) {
15536            return null;
15537        }
15538        return findViewWithTagTraversal(tag);
15539    }
15540
15541    /**
15542     * {@hide}
15543     * Look for a child view that matches the specified predicate.
15544     * If this view matches the predicate, return this view.
15545     *
15546     * @param predicate The predicate to evaluate.
15547     * @return The first view that matches the predicate or null.
15548     */
15549    public final View findViewByPredicate(Predicate<View> predicate) {
15550        return findViewByPredicateTraversal(predicate, null);
15551    }
15552
15553    /**
15554     * {@hide}
15555     * Look for a child view that matches the specified predicate,
15556     * starting with the specified view and its descendents and then
15557     * recusively searching the ancestors and siblings of that view
15558     * until this view is reached.
15559     *
15560     * This method is useful in cases where the predicate does not match
15561     * a single unique view (perhaps multiple views use the same id)
15562     * and we are trying to find the view that is "closest" in scope to the
15563     * starting view.
15564     *
15565     * @param start The view to start from.
15566     * @param predicate The predicate to evaluate.
15567     * @return The first view that matches the predicate or null.
15568     */
15569    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15570        View childToSkip = null;
15571        for (;;) {
15572            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15573            if (view != null || start == this) {
15574                return view;
15575            }
15576
15577            ViewParent parent = start.getParent();
15578            if (parent == null || !(parent instanceof View)) {
15579                return null;
15580            }
15581
15582            childToSkip = start;
15583            start = (View) parent;
15584        }
15585    }
15586
15587    /**
15588     * Sets the identifier for this view. The identifier does not have to be
15589     * unique in this view's hierarchy. The identifier should be a positive
15590     * number.
15591     *
15592     * @see #NO_ID
15593     * @see #getId()
15594     * @see #findViewById(int)
15595     *
15596     * @param id a number used to identify the view
15597     *
15598     * @attr ref android.R.styleable#View_id
15599     */
15600    public void setId(int id) {
15601        mID = id;
15602        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15603            mID = generateViewId();
15604        }
15605    }
15606
15607    /**
15608     * {@hide}
15609     *
15610     * @param isRoot true if the view belongs to the root namespace, false
15611     *        otherwise
15612     */
15613    public void setIsRootNamespace(boolean isRoot) {
15614        if (isRoot) {
15615            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15616        } else {
15617            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15618        }
15619    }
15620
15621    /**
15622     * {@hide}
15623     *
15624     * @return true if the view belongs to the root namespace, false otherwise
15625     */
15626    public boolean isRootNamespace() {
15627        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15628    }
15629
15630    /**
15631     * Returns this view's identifier.
15632     *
15633     * @return a positive integer used to identify the view or {@link #NO_ID}
15634     *         if the view has no ID
15635     *
15636     * @see #setId(int)
15637     * @see #findViewById(int)
15638     * @attr ref android.R.styleable#View_id
15639     */
15640    @ViewDebug.CapturedViewProperty
15641    public int getId() {
15642        return mID;
15643    }
15644
15645    /**
15646     * Returns this view's tag.
15647     *
15648     * @return the Object stored in this view as a tag
15649     *
15650     * @see #setTag(Object)
15651     * @see #getTag(int)
15652     */
15653    @ViewDebug.ExportedProperty
15654    public Object getTag() {
15655        return mTag;
15656    }
15657
15658    /**
15659     * Sets the tag associated with this view. A tag can be used to mark
15660     * a view in its hierarchy and does not have to be unique within the
15661     * hierarchy. Tags can also be used to store data within a view without
15662     * resorting to another data structure.
15663     *
15664     * @param tag an Object to tag the view with
15665     *
15666     * @see #getTag()
15667     * @see #setTag(int, Object)
15668     */
15669    public void setTag(final Object tag) {
15670        mTag = tag;
15671    }
15672
15673    /**
15674     * Returns the tag associated with this view and the specified key.
15675     *
15676     * @param key The key identifying the tag
15677     *
15678     * @return the Object stored in this view as a tag
15679     *
15680     * @see #setTag(int, Object)
15681     * @see #getTag()
15682     */
15683    public Object getTag(int key) {
15684        if (mKeyedTags != null) return mKeyedTags.get(key);
15685        return null;
15686    }
15687
15688    /**
15689     * Sets a tag associated with this view and a key. A tag can be used
15690     * to mark a view in its hierarchy and does not have to be unique within
15691     * the hierarchy. Tags can also be used to store data within a view
15692     * without resorting to another data structure.
15693     *
15694     * The specified key should be an id declared in the resources of the
15695     * application to ensure it is unique (see the <a
15696     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15697     * Keys identified as belonging to
15698     * the Android framework or not associated with any package will cause
15699     * an {@link IllegalArgumentException} to be thrown.
15700     *
15701     * @param key The key identifying the tag
15702     * @param tag An Object to tag the view with
15703     *
15704     * @throws IllegalArgumentException If they specified key is not valid
15705     *
15706     * @see #setTag(Object)
15707     * @see #getTag(int)
15708     */
15709    public void setTag(int key, final Object tag) {
15710        // If the package id is 0x00 or 0x01, it's either an undefined package
15711        // or a framework id
15712        if ((key >>> 24) < 2) {
15713            throw new IllegalArgumentException("The key must be an application-specific "
15714                    + "resource id.");
15715        }
15716
15717        setKeyedTag(key, tag);
15718    }
15719
15720    /**
15721     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15722     * framework id.
15723     *
15724     * @hide
15725     */
15726    public void setTagInternal(int key, Object tag) {
15727        if ((key >>> 24) != 0x1) {
15728            throw new IllegalArgumentException("The key must be a framework-specific "
15729                    + "resource id.");
15730        }
15731
15732        setKeyedTag(key, tag);
15733    }
15734
15735    private void setKeyedTag(int key, Object tag) {
15736        if (mKeyedTags == null) {
15737            mKeyedTags = new SparseArray<Object>(2);
15738        }
15739
15740        mKeyedTags.put(key, tag);
15741    }
15742
15743    /**
15744     * Prints information about this view in the log output, with the tag
15745     * {@link #VIEW_LOG_TAG}.
15746     *
15747     * @hide
15748     */
15749    public void debug() {
15750        debug(0);
15751    }
15752
15753    /**
15754     * Prints information about this view in the log output, with the tag
15755     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15756     * indentation defined by the <code>depth</code>.
15757     *
15758     * @param depth the indentation level
15759     *
15760     * @hide
15761     */
15762    protected void debug(int depth) {
15763        String output = debugIndent(depth - 1);
15764
15765        output += "+ " + this;
15766        int id = getId();
15767        if (id != -1) {
15768            output += " (id=" + id + ")";
15769        }
15770        Object tag = getTag();
15771        if (tag != null) {
15772            output += " (tag=" + tag + ")";
15773        }
15774        Log.d(VIEW_LOG_TAG, output);
15775
15776        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15777            output = debugIndent(depth) + " FOCUSED";
15778            Log.d(VIEW_LOG_TAG, output);
15779        }
15780
15781        output = debugIndent(depth);
15782        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15783                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15784                + "} ";
15785        Log.d(VIEW_LOG_TAG, output);
15786
15787        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15788                || mPaddingBottom != 0) {
15789            output = debugIndent(depth);
15790            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15791                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15792            Log.d(VIEW_LOG_TAG, output);
15793        }
15794
15795        output = debugIndent(depth);
15796        output += "mMeasureWidth=" + mMeasuredWidth +
15797                " mMeasureHeight=" + mMeasuredHeight;
15798        Log.d(VIEW_LOG_TAG, output);
15799
15800        output = debugIndent(depth);
15801        if (mLayoutParams == null) {
15802            output += "BAD! no layout params";
15803        } else {
15804            output = mLayoutParams.debug(output);
15805        }
15806        Log.d(VIEW_LOG_TAG, output);
15807
15808        output = debugIndent(depth);
15809        output += "flags={";
15810        output += View.printFlags(mViewFlags);
15811        output += "}";
15812        Log.d(VIEW_LOG_TAG, output);
15813
15814        output = debugIndent(depth);
15815        output += "privateFlags={";
15816        output += View.printPrivateFlags(mPrivateFlags);
15817        output += "}";
15818        Log.d(VIEW_LOG_TAG, output);
15819    }
15820
15821    /**
15822     * Creates a string of whitespaces used for indentation.
15823     *
15824     * @param depth the indentation level
15825     * @return a String containing (depth * 2 + 3) * 2 white spaces
15826     *
15827     * @hide
15828     */
15829    protected static String debugIndent(int depth) {
15830        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15831        for (int i = 0; i < (depth * 2) + 3; i++) {
15832            spaces.append(' ').append(' ');
15833        }
15834        return spaces.toString();
15835    }
15836
15837    /**
15838     * <p>Return the offset of the widget's text baseline from the widget's top
15839     * boundary. If this widget does not support baseline alignment, this
15840     * method returns -1. </p>
15841     *
15842     * @return the offset of the baseline within the widget's bounds or -1
15843     *         if baseline alignment is not supported
15844     */
15845    @ViewDebug.ExportedProperty(category = "layout")
15846    public int getBaseline() {
15847        return -1;
15848    }
15849
15850    /**
15851     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15852     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15853     * a layout pass.
15854     *
15855     * @return whether the view hierarchy is currently undergoing a layout pass
15856     */
15857    public boolean isInLayout() {
15858        ViewRootImpl viewRoot = getViewRootImpl();
15859        return (viewRoot != null && viewRoot.isInLayout());
15860    }
15861
15862    /**
15863     * Call this when something has changed which has invalidated the
15864     * layout of this view. This will schedule a layout pass of the view
15865     * tree. This should not be called while the view hierarchy is currently in a layout
15866     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15867     * end of the current layout pass (and then layout will run again) or after the current
15868     * frame is drawn and the next layout occurs.
15869     *
15870     * <p>Subclasses which override this method should call the superclass method to
15871     * handle possible request-during-layout errors correctly.</p>
15872     */
15873    public void requestLayout() {
15874        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15875            // Only trigger request-during-layout logic if this is the view requesting it,
15876            // not the views in its parent hierarchy
15877            ViewRootImpl viewRoot = getViewRootImpl();
15878            if (viewRoot != null && viewRoot.isInLayout()) {
15879                if (!viewRoot.requestLayoutDuringLayout(this)) {
15880                    return;
15881                }
15882            }
15883            mAttachInfo.mViewRequestingLayout = this;
15884        }
15885
15886        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15887        mPrivateFlags |= PFLAG_INVALIDATED;
15888
15889        if (mParent != null && !mParent.isLayoutRequested()) {
15890            mParent.requestLayout();
15891        }
15892        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15893            mAttachInfo.mViewRequestingLayout = null;
15894        }
15895    }
15896
15897    /**
15898     * Forces this view to be laid out during the next layout pass.
15899     * This method does not call requestLayout() or forceLayout()
15900     * on the parent.
15901     */
15902    public void forceLayout() {
15903        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15904        mPrivateFlags |= PFLAG_INVALIDATED;
15905    }
15906
15907    /**
15908     * <p>
15909     * This is called to find out how big a view should be. The parent
15910     * supplies constraint information in the width and height parameters.
15911     * </p>
15912     *
15913     * <p>
15914     * The actual measurement work of a view is performed in
15915     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15916     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15917     * </p>
15918     *
15919     *
15920     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15921     *        parent
15922     * @param heightMeasureSpec Vertical space requirements as imposed by the
15923     *        parent
15924     *
15925     * @see #onMeasure(int, int)
15926     */
15927    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15928        boolean optical = isLayoutModeOptical(this);
15929        if (optical != isLayoutModeOptical(mParent)) {
15930            Insets insets = getOpticalInsets();
15931            int oWidth  = insets.left + insets.right;
15932            int oHeight = insets.top  + insets.bottom;
15933            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15934            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15935        }
15936        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15937                widthMeasureSpec != mOldWidthMeasureSpec ||
15938                heightMeasureSpec != mOldHeightMeasureSpec) {
15939
15940            // first clears the measured dimension flag
15941            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15942
15943            resolveRtlPropertiesIfNeeded();
15944
15945            // measure ourselves, this should set the measured dimension flag back
15946            onMeasure(widthMeasureSpec, heightMeasureSpec);
15947
15948            // flag not set, setMeasuredDimension() was not invoked, we raise
15949            // an exception to warn the developer
15950            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15951                throw new IllegalStateException("onMeasure() did not set the"
15952                        + " measured dimension by calling"
15953                        + " setMeasuredDimension()");
15954            }
15955
15956            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15957        }
15958
15959        mOldWidthMeasureSpec = widthMeasureSpec;
15960        mOldHeightMeasureSpec = heightMeasureSpec;
15961    }
15962
15963    /**
15964     * <p>
15965     * Measure the view and its content to determine the measured width and the
15966     * measured height. This method is invoked by {@link #measure(int, int)} and
15967     * should be overriden by subclasses to provide accurate and efficient
15968     * measurement of their contents.
15969     * </p>
15970     *
15971     * <p>
15972     * <strong>CONTRACT:</strong> When overriding this method, you
15973     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15974     * measured width and height of this view. Failure to do so will trigger an
15975     * <code>IllegalStateException</code>, thrown by
15976     * {@link #measure(int, int)}. Calling the superclass'
15977     * {@link #onMeasure(int, int)} is a valid use.
15978     * </p>
15979     *
15980     * <p>
15981     * The base class implementation of measure defaults to the background size,
15982     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15983     * override {@link #onMeasure(int, int)} to provide better measurements of
15984     * their content.
15985     * </p>
15986     *
15987     * <p>
15988     * If this method is overridden, it is the subclass's responsibility to make
15989     * sure the measured height and width are at least the view's minimum height
15990     * and width ({@link #getSuggestedMinimumHeight()} and
15991     * {@link #getSuggestedMinimumWidth()}).
15992     * </p>
15993     *
15994     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15995     *                         The requirements are encoded with
15996     *                         {@link android.view.View.MeasureSpec}.
15997     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15998     *                         The requirements are encoded with
15999     *                         {@link android.view.View.MeasureSpec}.
16000     *
16001     * @see #getMeasuredWidth()
16002     * @see #getMeasuredHeight()
16003     * @see #setMeasuredDimension(int, int)
16004     * @see #getSuggestedMinimumHeight()
16005     * @see #getSuggestedMinimumWidth()
16006     * @see android.view.View.MeasureSpec#getMode(int)
16007     * @see android.view.View.MeasureSpec#getSize(int)
16008     */
16009    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16010        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16011                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16012    }
16013
16014    /**
16015     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16016     * measured width and measured height. Failing to do so will trigger an
16017     * exception at measurement time.</p>
16018     *
16019     * @param measuredWidth The measured width of this view.  May be a complex
16020     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16021     * {@link #MEASURED_STATE_TOO_SMALL}.
16022     * @param measuredHeight The measured height of this view.  May be a complex
16023     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16024     * {@link #MEASURED_STATE_TOO_SMALL}.
16025     */
16026    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16027        boolean optical = isLayoutModeOptical(this);
16028        if (optical != isLayoutModeOptical(mParent)) {
16029            Insets insets = getOpticalInsets();
16030            int opticalWidth  = insets.left + insets.right;
16031            int opticalHeight = insets.top  + insets.bottom;
16032
16033            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16034            measuredHeight += optical ? opticalHeight : -opticalHeight;
16035        }
16036        mMeasuredWidth = measuredWidth;
16037        mMeasuredHeight = measuredHeight;
16038
16039        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16040    }
16041
16042    /**
16043     * Merge two states as returned by {@link #getMeasuredState()}.
16044     * @param curState The current state as returned from a view or the result
16045     * of combining multiple views.
16046     * @param newState The new view state to combine.
16047     * @return Returns a new integer reflecting the combination of the two
16048     * states.
16049     */
16050    public static int combineMeasuredStates(int curState, int newState) {
16051        return curState | newState;
16052    }
16053
16054    /**
16055     * Version of {@link #resolveSizeAndState(int, int, int)}
16056     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16057     */
16058    public static int resolveSize(int size, int measureSpec) {
16059        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16060    }
16061
16062    /**
16063     * Utility to reconcile a desired size and state, with constraints imposed
16064     * by a MeasureSpec.  Will take the desired size, unless a different size
16065     * is imposed by the constraints.  The returned value is a compound integer,
16066     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16067     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16068     * size is smaller than the size the view wants to be.
16069     *
16070     * @param size How big the view wants to be
16071     * @param measureSpec Constraints imposed by the parent
16072     * @return Size information bit mask as defined by
16073     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16074     */
16075    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16076        int result = size;
16077        int specMode = MeasureSpec.getMode(measureSpec);
16078        int specSize =  MeasureSpec.getSize(measureSpec);
16079        switch (specMode) {
16080        case MeasureSpec.UNSPECIFIED:
16081            result = size;
16082            break;
16083        case MeasureSpec.AT_MOST:
16084            if (specSize < size) {
16085                result = specSize | MEASURED_STATE_TOO_SMALL;
16086            } else {
16087                result = size;
16088            }
16089            break;
16090        case MeasureSpec.EXACTLY:
16091            result = specSize;
16092            break;
16093        }
16094        return result | (childMeasuredState&MEASURED_STATE_MASK);
16095    }
16096
16097    /**
16098     * Utility to return a default size. Uses the supplied size if the
16099     * MeasureSpec imposed no constraints. Will get larger if allowed
16100     * by the MeasureSpec.
16101     *
16102     * @param size Default size for this view
16103     * @param measureSpec Constraints imposed by the parent
16104     * @return The size this view should be.
16105     */
16106    public static int getDefaultSize(int size, int measureSpec) {
16107        int result = size;
16108        int specMode = MeasureSpec.getMode(measureSpec);
16109        int specSize = MeasureSpec.getSize(measureSpec);
16110
16111        switch (specMode) {
16112        case MeasureSpec.UNSPECIFIED:
16113            result = size;
16114            break;
16115        case MeasureSpec.AT_MOST:
16116        case MeasureSpec.EXACTLY:
16117            result = specSize;
16118            break;
16119        }
16120        return result;
16121    }
16122
16123    /**
16124     * Returns the suggested minimum height that the view should use. This
16125     * returns the maximum of the view's minimum height
16126     * and the background's minimum height
16127     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16128     * <p>
16129     * When being used in {@link #onMeasure(int, int)}, the caller should still
16130     * ensure the returned height is within the requirements of the parent.
16131     *
16132     * @return The suggested minimum height of the view.
16133     */
16134    protected int getSuggestedMinimumHeight() {
16135        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16136
16137    }
16138
16139    /**
16140     * Returns the suggested minimum width that the view should use. This
16141     * returns the maximum of the view's minimum width)
16142     * and the background's minimum width
16143     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16144     * <p>
16145     * When being used in {@link #onMeasure(int, int)}, the caller should still
16146     * ensure the returned width is within the requirements of the parent.
16147     *
16148     * @return The suggested minimum width of the view.
16149     */
16150    protected int getSuggestedMinimumWidth() {
16151        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16152    }
16153
16154    /**
16155     * Returns the minimum height of the view.
16156     *
16157     * @return the minimum height the view will try to be.
16158     *
16159     * @see #setMinimumHeight(int)
16160     *
16161     * @attr ref android.R.styleable#View_minHeight
16162     */
16163    public int getMinimumHeight() {
16164        return mMinHeight;
16165    }
16166
16167    /**
16168     * Sets the minimum height of the view. It is not guaranteed the view will
16169     * be able to achieve this minimum height (for example, if its parent layout
16170     * constrains it with less available height).
16171     *
16172     * @param minHeight The minimum height the view will try to be.
16173     *
16174     * @see #getMinimumHeight()
16175     *
16176     * @attr ref android.R.styleable#View_minHeight
16177     */
16178    public void setMinimumHeight(int minHeight) {
16179        mMinHeight = minHeight;
16180        requestLayout();
16181    }
16182
16183    /**
16184     * Returns the minimum width of the view.
16185     *
16186     * @return the minimum width the view will try to be.
16187     *
16188     * @see #setMinimumWidth(int)
16189     *
16190     * @attr ref android.R.styleable#View_minWidth
16191     */
16192    public int getMinimumWidth() {
16193        return mMinWidth;
16194    }
16195
16196    /**
16197     * Sets the minimum width of the view. It is not guaranteed the view will
16198     * be able to achieve this minimum width (for example, if its parent layout
16199     * constrains it with less available width).
16200     *
16201     * @param minWidth The minimum width the view will try to be.
16202     *
16203     * @see #getMinimumWidth()
16204     *
16205     * @attr ref android.R.styleable#View_minWidth
16206     */
16207    public void setMinimumWidth(int minWidth) {
16208        mMinWidth = minWidth;
16209        requestLayout();
16210
16211    }
16212
16213    /**
16214     * Get the animation currently associated with this view.
16215     *
16216     * @return The animation that is currently playing or
16217     *         scheduled to play for this view.
16218     */
16219    public Animation getAnimation() {
16220        return mCurrentAnimation;
16221    }
16222
16223    /**
16224     * Start the specified animation now.
16225     *
16226     * @param animation the animation to start now
16227     */
16228    public void startAnimation(Animation animation) {
16229        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16230        setAnimation(animation);
16231        invalidateParentCaches();
16232        invalidate(true);
16233    }
16234
16235    /**
16236     * Cancels any animations for this view.
16237     */
16238    public void clearAnimation() {
16239        if (mCurrentAnimation != null) {
16240            mCurrentAnimation.detach();
16241        }
16242        mCurrentAnimation = null;
16243        invalidateParentIfNeeded();
16244    }
16245
16246    /**
16247     * Sets the next animation to play for this view.
16248     * If you want the animation to play immediately, use
16249     * {@link #startAnimation(android.view.animation.Animation)} instead.
16250     * This method provides allows fine-grained
16251     * control over the start time and invalidation, but you
16252     * must make sure that 1) the animation has a start time set, and
16253     * 2) the view's parent (which controls animations on its children)
16254     * will be invalidated when the animation is supposed to
16255     * start.
16256     *
16257     * @param animation The next animation, or null.
16258     */
16259    public void setAnimation(Animation animation) {
16260        mCurrentAnimation = animation;
16261
16262        if (animation != null) {
16263            // If the screen is off assume the animation start time is now instead of
16264            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16265            // would cause the animation to start when the screen turns back on
16266            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16267                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16268                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16269            }
16270            animation.reset();
16271        }
16272    }
16273
16274    /**
16275     * Invoked by a parent ViewGroup to notify the start of the animation
16276     * currently associated with this view. If you override this method,
16277     * always call super.onAnimationStart();
16278     *
16279     * @see #setAnimation(android.view.animation.Animation)
16280     * @see #getAnimation()
16281     */
16282    protected void onAnimationStart() {
16283        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16284    }
16285
16286    /**
16287     * Invoked by a parent ViewGroup to notify the end of the animation
16288     * currently associated with this view. If you override this method,
16289     * always call super.onAnimationEnd();
16290     *
16291     * @see #setAnimation(android.view.animation.Animation)
16292     * @see #getAnimation()
16293     */
16294    protected void onAnimationEnd() {
16295        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16296    }
16297
16298    /**
16299     * Invoked if there is a Transform that involves alpha. Subclass that can
16300     * draw themselves with the specified alpha should return true, and then
16301     * respect that alpha when their onDraw() is called. If this returns false
16302     * then the view may be redirected to draw into an offscreen buffer to
16303     * fulfill the request, which will look fine, but may be slower than if the
16304     * subclass handles it internally. The default implementation returns false.
16305     *
16306     * @param alpha The alpha (0..255) to apply to the view's drawing
16307     * @return true if the view can draw with the specified alpha.
16308     */
16309    protected boolean onSetAlpha(int alpha) {
16310        return false;
16311    }
16312
16313    /**
16314     * This is used by the RootView to perform an optimization when
16315     * the view hierarchy contains one or several SurfaceView.
16316     * SurfaceView is always considered transparent, but its children are not,
16317     * therefore all View objects remove themselves from the global transparent
16318     * region (passed as a parameter to this function).
16319     *
16320     * @param region The transparent region for this ViewAncestor (window).
16321     *
16322     * @return Returns true if the effective visibility of the view at this
16323     * point is opaque, regardless of the transparent region; returns false
16324     * if it is possible for underlying windows to be seen behind the view.
16325     *
16326     * {@hide}
16327     */
16328    public boolean gatherTransparentRegion(Region region) {
16329        final AttachInfo attachInfo = mAttachInfo;
16330        if (region != null && attachInfo != null) {
16331            final int pflags = mPrivateFlags;
16332            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16333                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16334                // remove it from the transparent region.
16335                final int[] location = attachInfo.mTransparentLocation;
16336                getLocationInWindow(location);
16337                region.op(location[0], location[1], location[0] + mRight - mLeft,
16338                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16339            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16340                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16341                // exists, so we remove the background drawable's non-transparent
16342                // parts from this transparent region.
16343                applyDrawableToTransparentRegion(mBackground, region);
16344            }
16345        }
16346        return true;
16347    }
16348
16349    /**
16350     * Play a sound effect for this view.
16351     *
16352     * <p>The framework will play sound effects for some built in actions, such as
16353     * clicking, but you may wish to play these effects in your widget,
16354     * for instance, for internal navigation.
16355     *
16356     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16357     * {@link #isSoundEffectsEnabled()} is true.
16358     *
16359     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16360     */
16361    public void playSoundEffect(int soundConstant) {
16362        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16363            return;
16364        }
16365        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16366    }
16367
16368    /**
16369     * BZZZTT!!1!
16370     *
16371     * <p>Provide haptic feedback to the user for this view.
16372     *
16373     * <p>The framework will provide haptic feedback for some built in actions,
16374     * such as long presses, but you may wish to provide feedback for your
16375     * own widget.
16376     *
16377     * <p>The feedback will only be performed if
16378     * {@link #isHapticFeedbackEnabled()} is true.
16379     *
16380     * @param feedbackConstant One of the constants defined in
16381     * {@link HapticFeedbackConstants}
16382     */
16383    public boolean performHapticFeedback(int feedbackConstant) {
16384        return performHapticFeedback(feedbackConstant, 0);
16385    }
16386
16387    /**
16388     * BZZZTT!!1!
16389     *
16390     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16391     *
16392     * @param feedbackConstant One of the constants defined in
16393     * {@link HapticFeedbackConstants}
16394     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16395     */
16396    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16397        if (mAttachInfo == null) {
16398            return false;
16399        }
16400        //noinspection SimplifiableIfStatement
16401        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16402                && !isHapticFeedbackEnabled()) {
16403            return false;
16404        }
16405        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16406                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16407    }
16408
16409    /**
16410     * Request that the visibility of the status bar or other screen/window
16411     * decorations be changed.
16412     *
16413     * <p>This method is used to put the over device UI into temporary modes
16414     * where the user's attention is focused more on the application content,
16415     * by dimming or hiding surrounding system affordances.  This is typically
16416     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16417     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16418     * to be placed behind the action bar (and with these flags other system
16419     * affordances) so that smooth transitions between hiding and showing them
16420     * can be done.
16421     *
16422     * <p>Two representative examples of the use of system UI visibility is
16423     * implementing a content browsing application (like a magazine reader)
16424     * and a video playing application.
16425     *
16426     * <p>The first code shows a typical implementation of a View in a content
16427     * browsing application.  In this implementation, the application goes
16428     * into a content-oriented mode by hiding the status bar and action bar,
16429     * and putting the navigation elements into lights out mode.  The user can
16430     * then interact with content while in this mode.  Such an application should
16431     * provide an easy way for the user to toggle out of the mode (such as to
16432     * check information in the status bar or access notifications).  In the
16433     * implementation here, this is done simply by tapping on the content.
16434     *
16435     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16436     *      content}
16437     *
16438     * <p>This second code sample shows a typical implementation of a View
16439     * in a video playing application.  In this situation, while the video is
16440     * playing the application would like to go into a complete full-screen mode,
16441     * to use as much of the display as possible for the video.  When in this state
16442     * the user can not interact with the application; the system intercepts
16443     * touching on the screen to pop the UI out of full screen mode.  See
16444     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16445     *
16446     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16447     *      content}
16448     *
16449     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16450     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16451     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16452     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16453     */
16454    public void setSystemUiVisibility(int visibility) {
16455        if (visibility != mSystemUiVisibility) {
16456            mSystemUiVisibility = visibility;
16457            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16458                mParent.recomputeViewAttributes(this);
16459            }
16460        }
16461    }
16462
16463    /**
16464     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16465     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16466     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16467     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16468     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16469     */
16470    public int getSystemUiVisibility() {
16471        return mSystemUiVisibility;
16472    }
16473
16474    /**
16475     * Returns the current system UI visibility that is currently set for
16476     * the entire window.  This is the combination of the
16477     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16478     * views in the window.
16479     */
16480    public int getWindowSystemUiVisibility() {
16481        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16482    }
16483
16484    /**
16485     * Override to find out when the window's requested system UI visibility
16486     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16487     * This is different from the callbacks recieved through
16488     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16489     * in that this is only telling you about the local request of the window,
16490     * not the actual values applied by the system.
16491     */
16492    public void onWindowSystemUiVisibilityChanged(int visible) {
16493    }
16494
16495    /**
16496     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16497     * the view hierarchy.
16498     */
16499    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16500        onWindowSystemUiVisibilityChanged(visible);
16501    }
16502
16503    /**
16504     * Set a listener to receive callbacks when the visibility of the system bar changes.
16505     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16506     */
16507    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16508        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16509        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16510            mParent.recomputeViewAttributes(this);
16511        }
16512    }
16513
16514    /**
16515     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16516     * the view hierarchy.
16517     */
16518    public void dispatchSystemUiVisibilityChanged(int visibility) {
16519        ListenerInfo li = mListenerInfo;
16520        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16521            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16522                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16523        }
16524    }
16525
16526    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16527        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16528        if (val != mSystemUiVisibility) {
16529            setSystemUiVisibility(val);
16530            return true;
16531        }
16532        return false;
16533    }
16534
16535    /** @hide */
16536    public void setDisabledSystemUiVisibility(int flags) {
16537        if (mAttachInfo != null) {
16538            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16539                mAttachInfo.mDisabledSystemUiVisibility = flags;
16540                if (mParent != null) {
16541                    mParent.recomputeViewAttributes(this);
16542                }
16543            }
16544        }
16545    }
16546
16547    /**
16548     * Creates an image that the system displays during the drag and drop
16549     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16550     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16551     * appearance as the given View. The default also positions the center of the drag shadow
16552     * directly under the touch point. If no View is provided (the constructor with no parameters
16553     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16554     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16555     * default is an invisible drag shadow.
16556     * <p>
16557     * You are not required to use the View you provide to the constructor as the basis of the
16558     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16559     * anything you want as the drag shadow.
16560     * </p>
16561     * <p>
16562     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16563     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16564     *  size and position of the drag shadow. It uses this data to construct a
16565     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16566     *  so that your application can draw the shadow image in the Canvas.
16567     * </p>
16568     *
16569     * <div class="special reference">
16570     * <h3>Developer Guides</h3>
16571     * <p>For a guide to implementing drag and drop features, read the
16572     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16573     * </div>
16574     */
16575    public static class DragShadowBuilder {
16576        private final WeakReference<View> mView;
16577
16578        /**
16579         * Constructs a shadow image builder based on a View. By default, the resulting drag
16580         * shadow will have the same appearance and dimensions as the View, with the touch point
16581         * over the center of the View.
16582         * @param view A View. Any View in scope can be used.
16583         */
16584        public DragShadowBuilder(View view) {
16585            mView = new WeakReference<View>(view);
16586        }
16587
16588        /**
16589         * Construct a shadow builder object with no associated View.  This
16590         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16591         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16592         * to supply the drag shadow's dimensions and appearance without
16593         * reference to any View object. If they are not overridden, then the result is an
16594         * invisible drag shadow.
16595         */
16596        public DragShadowBuilder() {
16597            mView = new WeakReference<View>(null);
16598        }
16599
16600        /**
16601         * Returns the View object that had been passed to the
16602         * {@link #View.DragShadowBuilder(View)}
16603         * constructor.  If that View parameter was {@code null} or if the
16604         * {@link #View.DragShadowBuilder()}
16605         * constructor was used to instantiate the builder object, this method will return
16606         * null.
16607         *
16608         * @return The View object associate with this builder object.
16609         */
16610        @SuppressWarnings({"JavadocReference"})
16611        final public View getView() {
16612            return mView.get();
16613        }
16614
16615        /**
16616         * Provides the metrics for the shadow image. These include the dimensions of
16617         * the shadow image, and the point within that shadow that should
16618         * be centered under the touch location while dragging.
16619         * <p>
16620         * The default implementation sets the dimensions of the shadow to be the
16621         * same as the dimensions of the View itself and centers the shadow under
16622         * the touch point.
16623         * </p>
16624         *
16625         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16626         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16627         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16628         * image.
16629         *
16630         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16631         * shadow image that should be underneath the touch point during the drag and drop
16632         * operation. Your application must set {@link android.graphics.Point#x} to the
16633         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16634         */
16635        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16636            final View view = mView.get();
16637            if (view != null) {
16638                shadowSize.set(view.getWidth(), view.getHeight());
16639                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16640            } else {
16641                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16642            }
16643        }
16644
16645        /**
16646         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16647         * based on the dimensions it received from the
16648         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16649         *
16650         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16651         */
16652        public void onDrawShadow(Canvas canvas) {
16653            final View view = mView.get();
16654            if (view != null) {
16655                view.draw(canvas);
16656            } else {
16657                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16658            }
16659        }
16660    }
16661
16662    /**
16663     * Starts a drag and drop operation. When your application calls this method, it passes a
16664     * {@link android.view.View.DragShadowBuilder} object to the system. The
16665     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16666     * to get metrics for the drag shadow, and then calls the object's
16667     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16668     * <p>
16669     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16670     *  drag events to all the View objects in your application that are currently visible. It does
16671     *  this either by calling the View object's drag listener (an implementation of
16672     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16673     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16674     *  Both are passed a {@link android.view.DragEvent} object that has a
16675     *  {@link android.view.DragEvent#getAction()} value of
16676     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16677     * </p>
16678     * <p>
16679     * Your application can invoke startDrag() on any attached View object. The View object does not
16680     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16681     * be related to the View the user selected for dragging.
16682     * </p>
16683     * @param data A {@link android.content.ClipData} object pointing to the data to be
16684     * transferred by the drag and drop operation.
16685     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16686     * drag shadow.
16687     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16688     * drop operation. This Object is put into every DragEvent object sent by the system during the
16689     * current drag.
16690     * <p>
16691     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16692     * to the target Views. For example, it can contain flags that differentiate between a
16693     * a copy operation and a move operation.
16694     * </p>
16695     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16696     * so the parameter should be set to 0.
16697     * @return {@code true} if the method completes successfully, or
16698     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16699     * do a drag, and so no drag operation is in progress.
16700     */
16701    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16702            Object myLocalState, int flags) {
16703        if (ViewDebug.DEBUG_DRAG) {
16704            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16705        }
16706        boolean okay = false;
16707
16708        Point shadowSize = new Point();
16709        Point shadowTouchPoint = new Point();
16710        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16711
16712        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16713                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16714            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16715        }
16716
16717        if (ViewDebug.DEBUG_DRAG) {
16718            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16719                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16720        }
16721        Surface surface = new Surface();
16722        try {
16723            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16724                    flags, shadowSize.x, shadowSize.y, surface);
16725            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16726                    + " surface=" + surface);
16727            if (token != null) {
16728                Canvas canvas = surface.lockCanvas(null);
16729                try {
16730                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16731                    shadowBuilder.onDrawShadow(canvas);
16732                } finally {
16733                    surface.unlockCanvasAndPost(canvas);
16734                }
16735
16736                final ViewRootImpl root = getViewRootImpl();
16737
16738                // Cache the local state object for delivery with DragEvents
16739                root.setLocalDragState(myLocalState);
16740
16741                // repurpose 'shadowSize' for the last touch point
16742                root.getLastTouchPoint(shadowSize);
16743
16744                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16745                        shadowSize.x, shadowSize.y,
16746                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16747                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16748
16749                // Off and running!  Release our local surface instance; the drag
16750                // shadow surface is now managed by the system process.
16751                surface.release();
16752            }
16753        } catch (Exception e) {
16754            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16755            surface.destroy();
16756        }
16757
16758        return okay;
16759    }
16760
16761    /**
16762     * Handles drag events sent by the system following a call to
16763     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16764     *<p>
16765     * When the system calls this method, it passes a
16766     * {@link android.view.DragEvent} object. A call to
16767     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16768     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16769     * operation.
16770     * @param event The {@link android.view.DragEvent} sent by the system.
16771     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16772     * in DragEvent, indicating the type of drag event represented by this object.
16773     * @return {@code true} if the method was successful, otherwise {@code false}.
16774     * <p>
16775     *  The method should return {@code true} in response to an action type of
16776     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16777     *  operation.
16778     * </p>
16779     * <p>
16780     *  The method should also return {@code true} in response to an action type of
16781     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16782     *  {@code false} if it didn't.
16783     * </p>
16784     */
16785    public boolean onDragEvent(DragEvent event) {
16786        return false;
16787    }
16788
16789    /**
16790     * Detects if this View is enabled and has a drag event listener.
16791     * If both are true, then it calls the drag event listener with the
16792     * {@link android.view.DragEvent} it received. If the drag event listener returns
16793     * {@code true}, then dispatchDragEvent() returns {@code true}.
16794     * <p>
16795     * For all other cases, the method calls the
16796     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16797     * method and returns its result.
16798     * </p>
16799     * <p>
16800     * This ensures that a drag event is always consumed, even if the View does not have a drag
16801     * event listener. However, if the View has a listener and the listener returns true, then
16802     * onDragEvent() is not called.
16803     * </p>
16804     */
16805    public boolean dispatchDragEvent(DragEvent event) {
16806        //noinspection SimplifiableIfStatement
16807        ListenerInfo li = mListenerInfo;
16808        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16809                && li.mOnDragListener.onDrag(this, event)) {
16810            return true;
16811        }
16812        return onDragEvent(event);
16813    }
16814
16815    boolean canAcceptDrag() {
16816        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16817    }
16818
16819    /**
16820     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16821     * it is ever exposed at all.
16822     * @hide
16823     */
16824    public void onCloseSystemDialogs(String reason) {
16825    }
16826
16827    /**
16828     * Given a Drawable whose bounds have been set to draw into this view,
16829     * update a Region being computed for
16830     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16831     * that any non-transparent parts of the Drawable are removed from the
16832     * given transparent region.
16833     *
16834     * @param dr The Drawable whose transparency is to be applied to the region.
16835     * @param region A Region holding the current transparency information,
16836     * where any parts of the region that are set are considered to be
16837     * transparent.  On return, this region will be modified to have the
16838     * transparency information reduced by the corresponding parts of the
16839     * Drawable that are not transparent.
16840     * {@hide}
16841     */
16842    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16843        if (DBG) {
16844            Log.i("View", "Getting transparent region for: " + this);
16845        }
16846        final Region r = dr.getTransparentRegion();
16847        final Rect db = dr.getBounds();
16848        final AttachInfo attachInfo = mAttachInfo;
16849        if (r != null && attachInfo != null) {
16850            final int w = getRight()-getLeft();
16851            final int h = getBottom()-getTop();
16852            if (db.left > 0) {
16853                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16854                r.op(0, 0, db.left, h, Region.Op.UNION);
16855            }
16856            if (db.right < w) {
16857                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16858                r.op(db.right, 0, w, h, Region.Op.UNION);
16859            }
16860            if (db.top > 0) {
16861                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16862                r.op(0, 0, w, db.top, Region.Op.UNION);
16863            }
16864            if (db.bottom < h) {
16865                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16866                r.op(0, db.bottom, w, h, Region.Op.UNION);
16867            }
16868            final int[] location = attachInfo.mTransparentLocation;
16869            getLocationInWindow(location);
16870            r.translate(location[0], location[1]);
16871            region.op(r, Region.Op.INTERSECT);
16872        } else {
16873            region.op(db, Region.Op.DIFFERENCE);
16874        }
16875    }
16876
16877    private void checkForLongClick(int delayOffset) {
16878        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16879            mHasPerformedLongPress = false;
16880
16881            if (mPendingCheckForLongPress == null) {
16882                mPendingCheckForLongPress = new CheckForLongPress();
16883            }
16884            mPendingCheckForLongPress.rememberWindowAttachCount();
16885            postDelayed(mPendingCheckForLongPress,
16886                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16887        }
16888    }
16889
16890    /**
16891     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16892     * LayoutInflater} class, which provides a full range of options for view inflation.
16893     *
16894     * @param context The Context object for your activity or application.
16895     * @param resource The resource ID to inflate
16896     * @param root A view group that will be the parent.  Used to properly inflate the
16897     * layout_* parameters.
16898     * @see LayoutInflater
16899     */
16900    public static View inflate(Context context, int resource, ViewGroup root) {
16901        LayoutInflater factory = LayoutInflater.from(context);
16902        return factory.inflate(resource, root);
16903    }
16904
16905    /**
16906     * Scroll the view with standard behavior for scrolling beyond the normal
16907     * content boundaries. Views that call this method should override
16908     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16909     * results of an over-scroll operation.
16910     *
16911     * Views can use this method to handle any touch or fling-based scrolling.
16912     *
16913     * @param deltaX Change in X in pixels
16914     * @param deltaY Change in Y in pixels
16915     * @param scrollX Current X scroll value in pixels before applying deltaX
16916     * @param scrollY Current Y scroll value in pixels before applying deltaY
16917     * @param scrollRangeX Maximum content scroll range along the X axis
16918     * @param scrollRangeY Maximum content scroll range along the Y axis
16919     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16920     *          along the X axis.
16921     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16922     *          along the Y axis.
16923     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16924     * @return true if scrolling was clamped to an over-scroll boundary along either
16925     *          axis, false otherwise.
16926     */
16927    @SuppressWarnings({"UnusedParameters"})
16928    protected boolean overScrollBy(int deltaX, int deltaY,
16929            int scrollX, int scrollY,
16930            int scrollRangeX, int scrollRangeY,
16931            int maxOverScrollX, int maxOverScrollY,
16932            boolean isTouchEvent) {
16933        final int overScrollMode = mOverScrollMode;
16934        final boolean canScrollHorizontal =
16935                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16936        final boolean canScrollVertical =
16937                computeVerticalScrollRange() > computeVerticalScrollExtent();
16938        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16939                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16940        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16941                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16942
16943        int newScrollX = scrollX + deltaX;
16944        if (!overScrollHorizontal) {
16945            maxOverScrollX = 0;
16946        }
16947
16948        int newScrollY = scrollY + deltaY;
16949        if (!overScrollVertical) {
16950            maxOverScrollY = 0;
16951        }
16952
16953        // Clamp values if at the limits and record
16954        final int left = -maxOverScrollX;
16955        final int right = maxOverScrollX + scrollRangeX;
16956        final int top = -maxOverScrollY;
16957        final int bottom = maxOverScrollY + scrollRangeY;
16958
16959        boolean clampedX = false;
16960        if (newScrollX > right) {
16961            newScrollX = right;
16962            clampedX = true;
16963        } else if (newScrollX < left) {
16964            newScrollX = left;
16965            clampedX = true;
16966        }
16967
16968        boolean clampedY = false;
16969        if (newScrollY > bottom) {
16970            newScrollY = bottom;
16971            clampedY = true;
16972        } else if (newScrollY < top) {
16973            newScrollY = top;
16974            clampedY = true;
16975        }
16976
16977        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16978
16979        return clampedX || clampedY;
16980    }
16981
16982    /**
16983     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16984     * respond to the results of an over-scroll operation.
16985     *
16986     * @param scrollX New X scroll value in pixels
16987     * @param scrollY New Y scroll value in pixels
16988     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16989     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16990     */
16991    protected void onOverScrolled(int scrollX, int scrollY,
16992            boolean clampedX, boolean clampedY) {
16993        // Intentionally empty.
16994    }
16995
16996    /**
16997     * Returns the over-scroll mode for this view. The result will be
16998     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16999     * (allow over-scrolling only if the view content is larger than the container),
17000     * or {@link #OVER_SCROLL_NEVER}.
17001     *
17002     * @return This view's over-scroll mode.
17003     */
17004    public int getOverScrollMode() {
17005        return mOverScrollMode;
17006    }
17007
17008    /**
17009     * Set the over-scroll mode for this view. Valid over-scroll modes are
17010     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17011     * (allow over-scrolling only if the view content is larger than the container),
17012     * or {@link #OVER_SCROLL_NEVER}.
17013     *
17014     * Setting the over-scroll mode of a view will have an effect only if the
17015     * view is capable of scrolling.
17016     *
17017     * @param overScrollMode The new over-scroll mode for this view.
17018     */
17019    public void setOverScrollMode(int overScrollMode) {
17020        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17021                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17022                overScrollMode != OVER_SCROLL_NEVER) {
17023            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17024        }
17025        mOverScrollMode = overScrollMode;
17026    }
17027
17028    /**
17029     * Gets a scale factor that determines the distance the view should scroll
17030     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17031     * @return The vertical scroll scale factor.
17032     * @hide
17033     */
17034    protected float getVerticalScrollFactor() {
17035        if (mVerticalScrollFactor == 0) {
17036            TypedValue outValue = new TypedValue();
17037            if (!mContext.getTheme().resolveAttribute(
17038                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17039                throw new IllegalStateException(
17040                        "Expected theme to define listPreferredItemHeight.");
17041            }
17042            mVerticalScrollFactor = outValue.getDimension(
17043                    mContext.getResources().getDisplayMetrics());
17044        }
17045        return mVerticalScrollFactor;
17046    }
17047
17048    /**
17049     * Gets a scale factor that determines the distance the view should scroll
17050     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17051     * @return The horizontal scroll scale factor.
17052     * @hide
17053     */
17054    protected float getHorizontalScrollFactor() {
17055        // TODO: Should use something else.
17056        return getVerticalScrollFactor();
17057    }
17058
17059    /**
17060     * Return the value specifying the text direction or policy that was set with
17061     * {@link #setTextDirection(int)}.
17062     *
17063     * @return the defined text direction. It can be one of:
17064     *
17065     * {@link #TEXT_DIRECTION_INHERIT},
17066     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17067     * {@link #TEXT_DIRECTION_ANY_RTL},
17068     * {@link #TEXT_DIRECTION_LTR},
17069     * {@link #TEXT_DIRECTION_RTL},
17070     * {@link #TEXT_DIRECTION_LOCALE}
17071     *
17072     * @attr ref android.R.styleable#View_textDirection
17073     *
17074     * @hide
17075     */
17076    @ViewDebug.ExportedProperty(category = "text", mapping = {
17077            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17078            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17079            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17080            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17081            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17082            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17083    })
17084    public int getRawTextDirection() {
17085        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17086    }
17087
17088    /**
17089     * Set the text direction.
17090     *
17091     * @param textDirection the direction to set. Should be one of:
17092     *
17093     * {@link #TEXT_DIRECTION_INHERIT},
17094     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17095     * {@link #TEXT_DIRECTION_ANY_RTL},
17096     * {@link #TEXT_DIRECTION_LTR},
17097     * {@link #TEXT_DIRECTION_RTL},
17098     * {@link #TEXT_DIRECTION_LOCALE}
17099     *
17100     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17101     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17102     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17103     *
17104     * @attr ref android.R.styleable#View_textDirection
17105     */
17106    public void setTextDirection(int textDirection) {
17107        if (getRawTextDirection() != textDirection) {
17108            // Reset the current text direction and the resolved one
17109            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17110            resetResolvedTextDirection();
17111            // Set the new text direction
17112            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17113            // Do resolution
17114            resolveTextDirection();
17115            // Notify change
17116            onRtlPropertiesChanged(getLayoutDirection());
17117            // Refresh
17118            requestLayout();
17119            invalidate(true);
17120        }
17121    }
17122
17123    /**
17124     * Return the resolved text direction.
17125     *
17126     * @return the resolved text direction. Returns one of:
17127     *
17128     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17129     * {@link #TEXT_DIRECTION_ANY_RTL},
17130     * {@link #TEXT_DIRECTION_LTR},
17131     * {@link #TEXT_DIRECTION_RTL},
17132     * {@link #TEXT_DIRECTION_LOCALE}
17133     *
17134     * @attr ref android.R.styleable#View_textDirection
17135     */
17136    @ViewDebug.ExportedProperty(category = "text", mapping = {
17137            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17138            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17139            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17140            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17141            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17142            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17143    })
17144    public int getTextDirection() {
17145        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17146    }
17147
17148    /**
17149     * Resolve the text direction.
17150     *
17151     * @return true if resolution has been done, false otherwise.
17152     *
17153     * @hide
17154     */
17155    public boolean resolveTextDirection() {
17156        // Reset any previous text direction resolution
17157        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17158
17159        if (hasRtlSupport()) {
17160            // Set resolved text direction flag depending on text direction flag
17161            final int textDirection = getRawTextDirection();
17162            switch(textDirection) {
17163                case TEXT_DIRECTION_INHERIT:
17164                    if (!canResolveTextDirection()) {
17165                        // We cannot do the resolution if there is no parent, so use the default one
17166                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17167                        // Resolution will need to happen again later
17168                        return false;
17169                    }
17170
17171                    // Parent has not yet resolved, so we still return the default
17172                    if (!mParent.isTextDirectionResolved()) {
17173                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17174                        // Resolution will need to happen again later
17175                        return false;
17176                    }
17177
17178                    // Set current resolved direction to the same value as the parent's one
17179                    final int parentResolvedDirection = mParent.getTextDirection();
17180                    switch (parentResolvedDirection) {
17181                        case TEXT_DIRECTION_FIRST_STRONG:
17182                        case TEXT_DIRECTION_ANY_RTL:
17183                        case TEXT_DIRECTION_LTR:
17184                        case TEXT_DIRECTION_RTL:
17185                        case TEXT_DIRECTION_LOCALE:
17186                            mPrivateFlags2 |=
17187                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17188                            break;
17189                        default:
17190                            // Default resolved direction is "first strong" heuristic
17191                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17192                    }
17193                    break;
17194                case TEXT_DIRECTION_FIRST_STRONG:
17195                case TEXT_DIRECTION_ANY_RTL:
17196                case TEXT_DIRECTION_LTR:
17197                case TEXT_DIRECTION_RTL:
17198                case TEXT_DIRECTION_LOCALE:
17199                    // Resolved direction is the same as text direction
17200                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17201                    break;
17202                default:
17203                    // Default resolved direction is "first strong" heuristic
17204                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17205            }
17206        } else {
17207            // Default resolved direction is "first strong" heuristic
17208            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17209        }
17210
17211        // Set to resolved
17212        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17213        return true;
17214    }
17215
17216    /**
17217     * Check if text direction resolution can be done.
17218     *
17219     * @return true if text direction resolution can be done otherwise return false.
17220     *
17221     * @hide
17222     */
17223    public boolean canResolveTextDirection() {
17224        switch (getRawTextDirection()) {
17225            case TEXT_DIRECTION_INHERIT:
17226                return (mParent != null) && mParent.canResolveTextDirection();
17227            default:
17228                return true;
17229        }
17230    }
17231
17232    /**
17233     * Reset resolved text direction. Text direction will be resolved during a call to
17234     * {@link #onMeasure(int, int)}.
17235     *
17236     * @hide
17237     */
17238    public void resetResolvedTextDirection() {
17239        // Reset any previous text direction resolution
17240        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17241        // Set to default value
17242        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17243    }
17244
17245    /**
17246     * @return true if text direction is inherited.
17247     *
17248     * @hide
17249     */
17250    public boolean isTextDirectionInherited() {
17251        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17252    }
17253
17254    /**
17255     * @return true if text direction is resolved.
17256     *
17257     * @hide
17258     */
17259    public boolean isTextDirectionResolved() {
17260        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17261    }
17262
17263    /**
17264     * Return the value specifying the text alignment or policy that was set with
17265     * {@link #setTextAlignment(int)}.
17266     *
17267     * @return the defined text alignment. It can be one of:
17268     *
17269     * {@link #TEXT_ALIGNMENT_INHERIT},
17270     * {@link #TEXT_ALIGNMENT_GRAVITY},
17271     * {@link #TEXT_ALIGNMENT_CENTER},
17272     * {@link #TEXT_ALIGNMENT_TEXT_START},
17273     * {@link #TEXT_ALIGNMENT_TEXT_END},
17274     * {@link #TEXT_ALIGNMENT_VIEW_START},
17275     * {@link #TEXT_ALIGNMENT_VIEW_END}
17276     *
17277     * @attr ref android.R.styleable#View_textAlignment
17278     *
17279     * @hide
17280     */
17281    @ViewDebug.ExportedProperty(category = "text", mapping = {
17282            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17283            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17284            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17285            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17286            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17287            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17288            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17289    })
17290    public int getRawTextAlignment() {
17291        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17292    }
17293
17294    /**
17295     * Set the text alignment.
17296     *
17297     * @param textAlignment The text alignment to set. Should be one of
17298     *
17299     * {@link #TEXT_ALIGNMENT_INHERIT},
17300     * {@link #TEXT_ALIGNMENT_GRAVITY},
17301     * {@link #TEXT_ALIGNMENT_CENTER},
17302     * {@link #TEXT_ALIGNMENT_TEXT_START},
17303     * {@link #TEXT_ALIGNMENT_TEXT_END},
17304     * {@link #TEXT_ALIGNMENT_VIEW_START},
17305     * {@link #TEXT_ALIGNMENT_VIEW_END}
17306     *
17307     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17308     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17309     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17310     *
17311     * @attr ref android.R.styleable#View_textAlignment
17312     */
17313    public void setTextAlignment(int textAlignment) {
17314        if (textAlignment != getRawTextAlignment()) {
17315            // Reset the current and resolved text alignment
17316            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17317            resetResolvedTextAlignment();
17318            // Set the new text alignment
17319            mPrivateFlags2 |=
17320                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17321            // Do resolution
17322            resolveTextAlignment();
17323            // Notify change
17324            onRtlPropertiesChanged(getLayoutDirection());
17325            // Refresh
17326            requestLayout();
17327            invalidate(true);
17328        }
17329    }
17330
17331    /**
17332     * Return the resolved text alignment.
17333     *
17334     * @return the resolved text alignment. Returns one of:
17335     *
17336     * {@link #TEXT_ALIGNMENT_GRAVITY},
17337     * {@link #TEXT_ALIGNMENT_CENTER},
17338     * {@link #TEXT_ALIGNMENT_TEXT_START},
17339     * {@link #TEXT_ALIGNMENT_TEXT_END},
17340     * {@link #TEXT_ALIGNMENT_VIEW_START},
17341     * {@link #TEXT_ALIGNMENT_VIEW_END}
17342     *
17343     * @attr ref android.R.styleable#View_textAlignment
17344     */
17345    @ViewDebug.ExportedProperty(category = "text", mapping = {
17346            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17347            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17348            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17349            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17350            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17351            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17352            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17353    })
17354    public int getTextAlignment() {
17355        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17356                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17357    }
17358
17359    /**
17360     * Resolve the text alignment.
17361     *
17362     * @return true if resolution has been done, false otherwise.
17363     *
17364     * @hide
17365     */
17366    public boolean resolveTextAlignment() {
17367        // Reset any previous text alignment resolution
17368        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17369
17370        if (hasRtlSupport()) {
17371            // Set resolved text alignment flag depending on text alignment flag
17372            final int textAlignment = getRawTextAlignment();
17373            switch (textAlignment) {
17374                case TEXT_ALIGNMENT_INHERIT:
17375                    // Check if we can resolve the text alignment
17376                    if (!canResolveTextAlignment()) {
17377                        // We cannot do the resolution if there is no parent so use the default
17378                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17379                        // Resolution will need to happen again later
17380                        return false;
17381                    }
17382
17383                    // Parent has not yet resolved, so we still return the default
17384                    if (!mParent.isTextAlignmentResolved()) {
17385                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17386                        // Resolution will need to happen again later
17387                        return false;
17388                    }
17389
17390                    final int parentResolvedTextAlignment = mParent.getTextAlignment();
17391                    switch (parentResolvedTextAlignment) {
17392                        case TEXT_ALIGNMENT_GRAVITY:
17393                        case TEXT_ALIGNMENT_TEXT_START:
17394                        case TEXT_ALIGNMENT_TEXT_END:
17395                        case TEXT_ALIGNMENT_CENTER:
17396                        case TEXT_ALIGNMENT_VIEW_START:
17397                        case TEXT_ALIGNMENT_VIEW_END:
17398                            // Resolved text alignment is the same as the parent resolved
17399                            // text alignment
17400                            mPrivateFlags2 |=
17401                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17402                            break;
17403                        default:
17404                            // Use default resolved text alignment
17405                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17406                    }
17407                    break;
17408                case TEXT_ALIGNMENT_GRAVITY:
17409                case TEXT_ALIGNMENT_TEXT_START:
17410                case TEXT_ALIGNMENT_TEXT_END:
17411                case TEXT_ALIGNMENT_CENTER:
17412                case TEXT_ALIGNMENT_VIEW_START:
17413                case TEXT_ALIGNMENT_VIEW_END:
17414                    // Resolved text alignment is the same as text alignment
17415                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17416                    break;
17417                default:
17418                    // Use default resolved text alignment
17419                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17420            }
17421        } else {
17422            // Use default resolved text alignment
17423            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17424        }
17425
17426        // Set the resolved
17427        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17428        return true;
17429    }
17430
17431    /**
17432     * Check if text alignment resolution can be done.
17433     *
17434     * @return true if text alignment resolution can be done otherwise return false.
17435     *
17436     * @hide
17437     */
17438    public boolean canResolveTextAlignment() {
17439        switch (getRawTextAlignment()) {
17440            case TEXT_DIRECTION_INHERIT:
17441                return (mParent != null) && mParent.canResolveTextAlignment();
17442            default:
17443                return true;
17444        }
17445    }
17446
17447    /**
17448     * Reset resolved text alignment. Text alignment will be resolved during a call to
17449     * {@link #onMeasure(int, int)}.
17450     *
17451     * @hide
17452     */
17453    public void resetResolvedTextAlignment() {
17454        // Reset any previous text alignment resolution
17455        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17456        // Set to default
17457        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17458    }
17459
17460    /**
17461     * @return true if text alignment is inherited.
17462     *
17463     * @hide
17464     */
17465    public boolean isTextAlignmentInherited() {
17466        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17467    }
17468
17469    /**
17470     * @return true if text alignment is resolved.
17471     *
17472     * @hide
17473     */
17474    public boolean isTextAlignmentResolved() {
17475        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17476    }
17477
17478    /**
17479     * Generate a value suitable for use in {@link #setId(int)}.
17480     * This value will not collide with ID values generated at build time by aapt for R.id.
17481     *
17482     * @return a generated ID value
17483     */
17484    public static int generateViewId() {
17485        for (;;) {
17486            final int result = sNextGeneratedId.get();
17487            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17488            int newValue = result + 1;
17489            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17490            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17491                return result;
17492            }
17493        }
17494    }
17495
17496    //
17497    // Properties
17498    //
17499    /**
17500     * A Property wrapper around the <code>alpha</code> functionality handled by the
17501     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17502     */
17503    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17504        @Override
17505        public void setValue(View object, float value) {
17506            object.setAlpha(value);
17507        }
17508
17509        @Override
17510        public Float get(View object) {
17511            return object.getAlpha();
17512        }
17513    };
17514
17515    /**
17516     * A Property wrapper around the <code>translationX</code> functionality handled by the
17517     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17518     */
17519    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17520        @Override
17521        public void setValue(View object, float value) {
17522            object.setTranslationX(value);
17523        }
17524
17525                @Override
17526        public Float get(View object) {
17527            return object.getTranslationX();
17528        }
17529    };
17530
17531    /**
17532     * A Property wrapper around the <code>translationY</code> functionality handled by the
17533     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17534     */
17535    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17536        @Override
17537        public void setValue(View object, float value) {
17538            object.setTranslationY(value);
17539        }
17540
17541        @Override
17542        public Float get(View object) {
17543            return object.getTranslationY();
17544        }
17545    };
17546
17547    /**
17548     * A Property wrapper around the <code>x</code> functionality handled by the
17549     * {@link View#setX(float)} and {@link View#getX()} methods.
17550     */
17551    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17552        @Override
17553        public void setValue(View object, float value) {
17554            object.setX(value);
17555        }
17556
17557        @Override
17558        public Float get(View object) {
17559            return object.getX();
17560        }
17561    };
17562
17563    /**
17564     * A Property wrapper around the <code>y</code> functionality handled by the
17565     * {@link View#setY(float)} and {@link View#getY()} methods.
17566     */
17567    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17568        @Override
17569        public void setValue(View object, float value) {
17570            object.setY(value);
17571        }
17572
17573        @Override
17574        public Float get(View object) {
17575            return object.getY();
17576        }
17577    };
17578
17579    /**
17580     * A Property wrapper around the <code>rotation</code> functionality handled by the
17581     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17582     */
17583    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17584        @Override
17585        public void setValue(View object, float value) {
17586            object.setRotation(value);
17587        }
17588
17589        @Override
17590        public Float get(View object) {
17591            return object.getRotation();
17592        }
17593    };
17594
17595    /**
17596     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17597     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17598     */
17599    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17600        @Override
17601        public void setValue(View object, float value) {
17602            object.setRotationX(value);
17603        }
17604
17605        @Override
17606        public Float get(View object) {
17607            return object.getRotationX();
17608        }
17609    };
17610
17611    /**
17612     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17613     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17614     */
17615    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17616        @Override
17617        public void setValue(View object, float value) {
17618            object.setRotationY(value);
17619        }
17620
17621        @Override
17622        public Float get(View object) {
17623            return object.getRotationY();
17624        }
17625    };
17626
17627    /**
17628     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17629     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17630     */
17631    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17632        @Override
17633        public void setValue(View object, float value) {
17634            object.setScaleX(value);
17635        }
17636
17637        @Override
17638        public Float get(View object) {
17639            return object.getScaleX();
17640        }
17641    };
17642
17643    /**
17644     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17645     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17646     */
17647    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17648        @Override
17649        public void setValue(View object, float value) {
17650            object.setScaleY(value);
17651        }
17652
17653        @Override
17654        public Float get(View object) {
17655            return object.getScaleY();
17656        }
17657    };
17658
17659    /**
17660     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17661     * Each MeasureSpec represents a requirement for either the width or the height.
17662     * A MeasureSpec is comprised of a size and a mode. There are three possible
17663     * modes:
17664     * <dl>
17665     * <dt>UNSPECIFIED</dt>
17666     * <dd>
17667     * The parent has not imposed any constraint on the child. It can be whatever size
17668     * it wants.
17669     * </dd>
17670     *
17671     * <dt>EXACTLY</dt>
17672     * <dd>
17673     * The parent has determined an exact size for the child. The child is going to be
17674     * given those bounds regardless of how big it wants to be.
17675     * </dd>
17676     *
17677     * <dt>AT_MOST</dt>
17678     * <dd>
17679     * The child can be as large as it wants up to the specified size.
17680     * </dd>
17681     * </dl>
17682     *
17683     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17684     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17685     */
17686    public static class MeasureSpec {
17687        private static final int MODE_SHIFT = 30;
17688        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17689
17690        /**
17691         * Measure specification mode: The parent has not imposed any constraint
17692         * on the child. It can be whatever size it wants.
17693         */
17694        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17695
17696        /**
17697         * Measure specification mode: The parent has determined an exact size
17698         * for the child. The child is going to be given those bounds regardless
17699         * of how big it wants to be.
17700         */
17701        public static final int EXACTLY     = 1 << MODE_SHIFT;
17702
17703        /**
17704         * Measure specification mode: The child can be as large as it wants up
17705         * to the specified size.
17706         */
17707        public static final int AT_MOST     = 2 << MODE_SHIFT;
17708
17709        /**
17710         * Creates a measure specification based on the supplied size and mode.
17711         *
17712         * The mode must always be one of the following:
17713         * <ul>
17714         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17715         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17716         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17717         * </ul>
17718         *
17719         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17720         * implementation was such that the order of arguments did not matter
17721         * and overflow in either value could impact the resulting MeasureSpec.
17722         * {@link android.widget.RelativeLayout} was affected by this bug.
17723         * Apps targeting API levels greater than 17 will get the fixed, more strict
17724         * behavior.</p>
17725         *
17726         * @param size the size of the measure specification
17727         * @param mode the mode of the measure specification
17728         * @return the measure specification based on size and mode
17729         */
17730        public static int makeMeasureSpec(int size, int mode) {
17731            if (sUseBrokenMakeMeasureSpec) {
17732                return size + mode;
17733            } else {
17734                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17735            }
17736        }
17737
17738        /**
17739         * Extracts the mode from the supplied measure specification.
17740         *
17741         * @param measureSpec the measure specification to extract the mode from
17742         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17743         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17744         *         {@link android.view.View.MeasureSpec#EXACTLY}
17745         */
17746        public static int getMode(int measureSpec) {
17747            return (measureSpec & MODE_MASK);
17748        }
17749
17750        /**
17751         * Extracts the size from the supplied measure specification.
17752         *
17753         * @param measureSpec the measure specification to extract the size from
17754         * @return the size in pixels defined in the supplied measure specification
17755         */
17756        public static int getSize(int measureSpec) {
17757            return (measureSpec & ~MODE_MASK);
17758        }
17759
17760        static int adjust(int measureSpec, int delta) {
17761            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17762        }
17763
17764        /**
17765         * Returns a String representation of the specified measure
17766         * specification.
17767         *
17768         * @param measureSpec the measure specification to convert to a String
17769         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17770         */
17771        public static String toString(int measureSpec) {
17772            int mode = getMode(measureSpec);
17773            int size = getSize(measureSpec);
17774
17775            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17776
17777            if (mode == UNSPECIFIED)
17778                sb.append("UNSPECIFIED ");
17779            else if (mode == EXACTLY)
17780                sb.append("EXACTLY ");
17781            else if (mode == AT_MOST)
17782                sb.append("AT_MOST ");
17783            else
17784                sb.append(mode).append(" ");
17785
17786            sb.append(size);
17787            return sb.toString();
17788        }
17789    }
17790
17791    class CheckForLongPress implements Runnable {
17792
17793        private int mOriginalWindowAttachCount;
17794
17795        public void run() {
17796            if (isPressed() && (mParent != null)
17797                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17798                if (performLongClick()) {
17799                    mHasPerformedLongPress = true;
17800                }
17801            }
17802        }
17803
17804        public void rememberWindowAttachCount() {
17805            mOriginalWindowAttachCount = mWindowAttachCount;
17806        }
17807    }
17808
17809    private final class CheckForTap implements Runnable {
17810        public void run() {
17811            mPrivateFlags &= ~PFLAG_PREPRESSED;
17812            setPressed(true);
17813            checkForLongClick(ViewConfiguration.getTapTimeout());
17814        }
17815    }
17816
17817    private final class PerformClick implements Runnable {
17818        public void run() {
17819            performClick();
17820        }
17821    }
17822
17823    /** @hide */
17824    public void hackTurnOffWindowResizeAnim(boolean off) {
17825        mAttachInfo.mTurnOffWindowResizeAnim = off;
17826    }
17827
17828    /**
17829     * This method returns a ViewPropertyAnimator object, which can be used to animate
17830     * specific properties on this View.
17831     *
17832     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17833     */
17834    public ViewPropertyAnimator animate() {
17835        if (mAnimator == null) {
17836            mAnimator = new ViewPropertyAnimator(this);
17837        }
17838        return mAnimator;
17839    }
17840
17841    /**
17842     * Set the current Scene that this view is in. The current scene is set only
17843     * on the root view of a scene, not for every view in that hierarchy. This
17844     * information is used by Scene to determine whether there is a previous
17845     * scene which should be exited before the new scene is entered.
17846     *
17847     * @param scene The new scene being set on the view
17848     *
17849     * @hide
17850     */
17851    public void setCurrentScene(Scene scene) {
17852        mCurrentScene = scene;
17853    }
17854
17855    /**
17856     * Gets the current {@link Scene} set on this view. A scene is set on a view
17857     * only if that view is the scene root.
17858     *
17859     * @return The current Scene set on this view. A value of null indicates that
17860     * no Scene is current set.
17861     */
17862    public Scene getCurrentScene() {
17863        return mCurrentScene;
17864    }
17865
17866    /**
17867     * Interface definition for a callback to be invoked when a hardware key event is
17868     * dispatched to this view. The callback will be invoked before the key event is
17869     * given to the view. This is only useful for hardware keyboards; a software input
17870     * method has no obligation to trigger this listener.
17871     */
17872    public interface OnKeyListener {
17873        /**
17874         * Called when a hardware key is dispatched to a view. This allows listeners to
17875         * get a chance to respond before the target view.
17876         * <p>Key presses in software keyboards will generally NOT trigger this method,
17877         * although some may elect to do so in some situations. Do not assume a
17878         * software input method has to be key-based; even if it is, it may use key presses
17879         * in a different way than you expect, so there is no way to reliably catch soft
17880         * input key presses.
17881         *
17882         * @param v The view the key has been dispatched to.
17883         * @param keyCode The code for the physical key that was pressed
17884         * @param event The KeyEvent object containing full information about
17885         *        the event.
17886         * @return True if the listener has consumed the event, false otherwise.
17887         */
17888        boolean onKey(View v, int keyCode, KeyEvent event);
17889    }
17890
17891    /**
17892     * Interface definition for a callback to be invoked when a touch event is
17893     * dispatched to this view. The callback will be invoked before the touch
17894     * event is given to the view.
17895     */
17896    public interface OnTouchListener {
17897        /**
17898         * Called when a touch event is dispatched to a view. This allows listeners to
17899         * get a chance to respond before the target view.
17900         *
17901         * @param v The view the touch event has been dispatched to.
17902         * @param event The MotionEvent object containing full information about
17903         *        the event.
17904         * @return True if the listener has consumed the event, false otherwise.
17905         */
17906        boolean onTouch(View v, MotionEvent event);
17907    }
17908
17909    /**
17910     * Interface definition for a callback to be invoked when a hover event is
17911     * dispatched to this view. The callback will be invoked before the hover
17912     * event is given to the view.
17913     */
17914    public interface OnHoverListener {
17915        /**
17916         * Called when a hover event is dispatched to a view. This allows listeners to
17917         * get a chance to respond before the target view.
17918         *
17919         * @param v The view the hover event has been dispatched to.
17920         * @param event The MotionEvent object containing full information about
17921         *        the event.
17922         * @return True if the listener has consumed the event, false otherwise.
17923         */
17924        boolean onHover(View v, MotionEvent event);
17925    }
17926
17927    /**
17928     * Interface definition for a callback to be invoked when a generic motion event is
17929     * dispatched to this view. The callback will be invoked before the generic motion
17930     * event is given to the view.
17931     */
17932    public interface OnGenericMotionListener {
17933        /**
17934         * Called when a generic motion event is dispatched to a view. This allows listeners to
17935         * get a chance to respond before the target view.
17936         *
17937         * @param v The view the generic motion event has been dispatched to.
17938         * @param event The MotionEvent object containing full information about
17939         *        the event.
17940         * @return True if the listener has consumed the event, false otherwise.
17941         */
17942        boolean onGenericMotion(View v, MotionEvent event);
17943    }
17944
17945    /**
17946     * Interface definition for a callback to be invoked when a view has been clicked and held.
17947     */
17948    public interface OnLongClickListener {
17949        /**
17950         * Called when a view has been clicked and held.
17951         *
17952         * @param v The view that was clicked and held.
17953         *
17954         * @return true if the callback consumed the long click, false otherwise.
17955         */
17956        boolean onLongClick(View v);
17957    }
17958
17959    /**
17960     * Interface definition for a callback to be invoked when a drag is being dispatched
17961     * to this view.  The callback will be invoked before the hosting view's own
17962     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17963     * onDrag(event) behavior, it should return 'false' from this callback.
17964     *
17965     * <div class="special reference">
17966     * <h3>Developer Guides</h3>
17967     * <p>For a guide to implementing drag and drop features, read the
17968     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17969     * </div>
17970     */
17971    public interface OnDragListener {
17972        /**
17973         * Called when a drag event is dispatched to a view. This allows listeners
17974         * to get a chance to override base View behavior.
17975         *
17976         * @param v The View that received the drag event.
17977         * @param event The {@link android.view.DragEvent} object for the drag event.
17978         * @return {@code true} if the drag event was handled successfully, or {@code false}
17979         * if the drag event was not handled. Note that {@code false} will trigger the View
17980         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17981         */
17982        boolean onDrag(View v, DragEvent event);
17983    }
17984
17985    /**
17986     * Interface definition for a callback to be invoked when the focus state of
17987     * a view changed.
17988     */
17989    public interface OnFocusChangeListener {
17990        /**
17991         * Called when the focus state of a view has changed.
17992         *
17993         * @param v The view whose state has changed.
17994         * @param hasFocus The new focus state of v.
17995         */
17996        void onFocusChange(View v, boolean hasFocus);
17997    }
17998
17999    /**
18000     * Interface definition for a callback to be invoked when a view is clicked.
18001     */
18002    public interface OnClickListener {
18003        /**
18004         * Called when a view has been clicked.
18005         *
18006         * @param v The view that was clicked.
18007         */
18008        void onClick(View v);
18009    }
18010
18011    /**
18012     * Interface definition for a callback to be invoked when the context menu
18013     * for this view is being built.
18014     */
18015    public interface OnCreateContextMenuListener {
18016        /**
18017         * Called when the context menu for this view is being built. It is not
18018         * safe to hold onto the menu after this method returns.
18019         *
18020         * @param menu The context menu that is being built
18021         * @param v The view for which the context menu is being built
18022         * @param menuInfo Extra information about the item for which the
18023         *            context menu should be shown. This information will vary
18024         *            depending on the class of v.
18025         */
18026        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18027    }
18028
18029    /**
18030     * Interface definition for a callback to be invoked when the status bar changes
18031     * visibility.  This reports <strong>global</strong> changes to the system UI
18032     * state, not what the application is requesting.
18033     *
18034     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18035     */
18036    public interface OnSystemUiVisibilityChangeListener {
18037        /**
18038         * Called when the status bar changes visibility because of a call to
18039         * {@link View#setSystemUiVisibility(int)}.
18040         *
18041         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18042         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18043         * This tells you the <strong>global</strong> state of these UI visibility
18044         * flags, not what your app is currently applying.
18045         */
18046        public void onSystemUiVisibilityChange(int visibility);
18047    }
18048
18049    /**
18050     * Interface definition for a callback to be invoked when this view is attached
18051     * or detached from its window.
18052     */
18053    public interface OnAttachStateChangeListener {
18054        /**
18055         * Called when the view is attached to a window.
18056         * @param v The view that was attached
18057         */
18058        public void onViewAttachedToWindow(View v);
18059        /**
18060         * Called when the view is detached from a window.
18061         * @param v The view that was detached
18062         */
18063        public void onViewDetachedFromWindow(View v);
18064    }
18065
18066    private final class UnsetPressedState implements Runnable {
18067        public void run() {
18068            setPressed(false);
18069        }
18070    }
18071
18072    /**
18073     * Base class for derived classes that want to save and restore their own
18074     * state in {@link android.view.View#onSaveInstanceState()}.
18075     */
18076    public static class BaseSavedState extends AbsSavedState {
18077        /**
18078         * Constructor used when reading from a parcel. Reads the state of the superclass.
18079         *
18080         * @param source
18081         */
18082        public BaseSavedState(Parcel source) {
18083            super(source);
18084        }
18085
18086        /**
18087         * Constructor called by derived classes when creating their SavedState objects
18088         *
18089         * @param superState The state of the superclass of this view
18090         */
18091        public BaseSavedState(Parcelable superState) {
18092            super(superState);
18093        }
18094
18095        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18096                new Parcelable.Creator<BaseSavedState>() {
18097            public BaseSavedState createFromParcel(Parcel in) {
18098                return new BaseSavedState(in);
18099            }
18100
18101            public BaseSavedState[] newArray(int size) {
18102                return new BaseSavedState[size];
18103            }
18104        };
18105    }
18106
18107    /**
18108     * A set of information given to a view when it is attached to its parent
18109     * window.
18110     */
18111    static class AttachInfo {
18112        interface Callbacks {
18113            void playSoundEffect(int effectId);
18114            boolean performHapticFeedback(int effectId, boolean always);
18115        }
18116
18117        /**
18118         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18119         * to a Handler. This class contains the target (View) to invalidate and
18120         * the coordinates of the dirty rectangle.
18121         *
18122         * For performance purposes, this class also implements a pool of up to
18123         * POOL_LIMIT objects that get reused. This reduces memory allocations
18124         * whenever possible.
18125         */
18126        static class InvalidateInfo {
18127            private static final int POOL_LIMIT = 10;
18128
18129            private static final SynchronizedPool<InvalidateInfo> sPool =
18130                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18131
18132            View target;
18133
18134            int left;
18135            int top;
18136            int right;
18137            int bottom;
18138
18139            public static InvalidateInfo obtain() {
18140                InvalidateInfo instance = sPool.acquire();
18141                return (instance != null) ? instance : new InvalidateInfo();
18142            }
18143
18144            public void recycle() {
18145                target = null;
18146                sPool.release(this);
18147            }
18148        }
18149
18150        final IWindowSession mSession;
18151
18152        final IWindow mWindow;
18153
18154        final IBinder mWindowToken;
18155
18156        final Display mDisplay;
18157
18158        final Callbacks mRootCallbacks;
18159
18160        HardwareCanvas mHardwareCanvas;
18161
18162        IWindowId mIWindowId;
18163        WindowId mWindowId;
18164
18165        /**
18166         * The top view of the hierarchy.
18167         */
18168        View mRootView;
18169
18170        IBinder mPanelParentWindowToken;
18171        Surface mSurface;
18172
18173        boolean mHardwareAccelerated;
18174        boolean mHardwareAccelerationRequested;
18175        HardwareRenderer mHardwareRenderer;
18176
18177        boolean mScreenOn;
18178
18179        /**
18180         * Scale factor used by the compatibility mode
18181         */
18182        float mApplicationScale;
18183
18184        /**
18185         * Indicates whether the application is in compatibility mode
18186         */
18187        boolean mScalingRequired;
18188
18189        /**
18190         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18191         */
18192        boolean mTurnOffWindowResizeAnim;
18193
18194        /**
18195         * Left position of this view's window
18196         */
18197        int mWindowLeft;
18198
18199        /**
18200         * Top position of this view's window
18201         */
18202        int mWindowTop;
18203
18204        /**
18205         * Indicates whether views need to use 32-bit drawing caches
18206         */
18207        boolean mUse32BitDrawingCache;
18208
18209        /**
18210         * For windows that are full-screen but using insets to layout inside
18211         * of the screen areas, these are the current insets to appear inside
18212         * the overscan area of the display.
18213         */
18214        final Rect mOverscanInsets = new Rect();
18215
18216        /**
18217         * For windows that are full-screen but using insets to layout inside
18218         * of the screen decorations, these are the current insets for the
18219         * content of the window.
18220         */
18221        final Rect mContentInsets = new Rect();
18222
18223        /**
18224         * For windows that are full-screen but using insets to layout inside
18225         * of the screen decorations, these are the current insets for the
18226         * actual visible parts of the window.
18227         */
18228        final Rect mVisibleInsets = new Rect();
18229
18230        /**
18231         * The internal insets given by this window.  This value is
18232         * supplied by the client (through
18233         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18234         * be given to the window manager when changed to be used in laying
18235         * out windows behind it.
18236         */
18237        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18238                = new ViewTreeObserver.InternalInsetsInfo();
18239
18240        /**
18241         * All views in the window's hierarchy that serve as scroll containers,
18242         * used to determine if the window can be resized or must be panned
18243         * to adjust for a soft input area.
18244         */
18245        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18246
18247        final KeyEvent.DispatcherState mKeyDispatchState
18248                = new KeyEvent.DispatcherState();
18249
18250        /**
18251         * Indicates whether the view's window currently has the focus.
18252         */
18253        boolean mHasWindowFocus;
18254
18255        /**
18256         * The current visibility of the window.
18257         */
18258        int mWindowVisibility;
18259
18260        /**
18261         * Indicates the time at which drawing started to occur.
18262         */
18263        long mDrawingTime;
18264
18265        /**
18266         * Indicates whether or not ignoring the DIRTY_MASK flags.
18267         */
18268        boolean mIgnoreDirtyState;
18269
18270        /**
18271         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18272         * to avoid clearing that flag prematurely.
18273         */
18274        boolean mSetIgnoreDirtyState = false;
18275
18276        /**
18277         * Indicates whether the view's window is currently in touch mode.
18278         */
18279        boolean mInTouchMode;
18280
18281        /**
18282         * Indicates that ViewAncestor should trigger a global layout change
18283         * the next time it performs a traversal
18284         */
18285        boolean mRecomputeGlobalAttributes;
18286
18287        /**
18288         * Always report new attributes at next traversal.
18289         */
18290        boolean mForceReportNewAttributes;
18291
18292        /**
18293         * Set during a traveral if any views want to keep the screen on.
18294         */
18295        boolean mKeepScreenOn;
18296
18297        /**
18298         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18299         */
18300        int mSystemUiVisibility;
18301
18302        /**
18303         * Hack to force certain system UI visibility flags to be cleared.
18304         */
18305        int mDisabledSystemUiVisibility;
18306
18307        /**
18308         * Last global system UI visibility reported by the window manager.
18309         */
18310        int mGlobalSystemUiVisibility;
18311
18312        /**
18313         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18314         * attached.
18315         */
18316        boolean mHasSystemUiListeners;
18317
18318        /**
18319         * Set if the window has requested to extend into the overscan region
18320         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18321         */
18322        boolean mOverscanRequested;
18323
18324        /**
18325         * Set if the visibility of any views has changed.
18326         */
18327        boolean mViewVisibilityChanged;
18328
18329        /**
18330         * Set to true if a view has been scrolled.
18331         */
18332        boolean mViewScrollChanged;
18333
18334        /**
18335         * Global to the view hierarchy used as a temporary for dealing with
18336         * x/y points in the transparent region computations.
18337         */
18338        final int[] mTransparentLocation = new int[2];
18339
18340        /**
18341         * Global to the view hierarchy used as a temporary for dealing with
18342         * x/y points in the ViewGroup.invalidateChild implementation.
18343         */
18344        final int[] mInvalidateChildLocation = new int[2];
18345
18346
18347        /**
18348         * Global to the view hierarchy used as a temporary for dealing with
18349         * x/y location when view is transformed.
18350         */
18351        final float[] mTmpTransformLocation = new float[2];
18352
18353        /**
18354         * The view tree observer used to dispatch global events like
18355         * layout, pre-draw, touch mode change, etc.
18356         */
18357        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18358
18359        /**
18360         * A Canvas used by the view hierarchy to perform bitmap caching.
18361         */
18362        Canvas mCanvas;
18363
18364        /**
18365         * The view root impl.
18366         */
18367        final ViewRootImpl mViewRootImpl;
18368
18369        /**
18370         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18371         * handler can be used to pump events in the UI events queue.
18372         */
18373        final Handler mHandler;
18374
18375        /**
18376         * Temporary for use in computing invalidate rectangles while
18377         * calling up the hierarchy.
18378         */
18379        final Rect mTmpInvalRect = new Rect();
18380
18381        /**
18382         * Temporary for use in computing hit areas with transformed views
18383         */
18384        final RectF mTmpTransformRect = new RectF();
18385
18386        /**
18387         * Temporary for use in transforming invalidation rect
18388         */
18389        final Matrix mTmpMatrix = new Matrix();
18390
18391        /**
18392         * Temporary for use in transforming invalidation rect
18393         */
18394        final Transformation mTmpTransformation = new Transformation();
18395
18396        /**
18397         * Temporary list for use in collecting focusable descendents of a view.
18398         */
18399        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18400
18401        /**
18402         * The id of the window for accessibility purposes.
18403         */
18404        int mAccessibilityWindowId = View.NO_ID;
18405
18406        /**
18407         * Flags related to accessibility processing.
18408         *
18409         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18410         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18411         */
18412        int mAccessibilityFetchFlags;
18413
18414        /**
18415         * The drawable for highlighting accessibility focus.
18416         */
18417        Drawable mAccessibilityFocusDrawable;
18418
18419        /**
18420         * Show where the margins, bounds and layout bounds are for each view.
18421         */
18422        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18423
18424        /**
18425         * Point used to compute visible regions.
18426         */
18427        final Point mPoint = new Point();
18428
18429        /**
18430         * Used to track which View originated a requestLayout() call, used when
18431         * requestLayout() is called during layout.
18432         */
18433        View mViewRequestingLayout;
18434
18435        /**
18436         * Creates a new set of attachment information with the specified
18437         * events handler and thread.
18438         *
18439         * @param handler the events handler the view must use
18440         */
18441        AttachInfo(IWindowSession session, IWindow window, Display display,
18442                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18443            mSession = session;
18444            mWindow = window;
18445            mWindowToken = window.asBinder();
18446            mDisplay = display;
18447            mViewRootImpl = viewRootImpl;
18448            mHandler = handler;
18449            mRootCallbacks = effectPlayer;
18450        }
18451    }
18452
18453    /**
18454     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18455     * is supported. This avoids keeping too many unused fields in most
18456     * instances of View.</p>
18457     */
18458    private static class ScrollabilityCache implements Runnable {
18459
18460        /**
18461         * Scrollbars are not visible
18462         */
18463        public static final int OFF = 0;
18464
18465        /**
18466         * Scrollbars are visible
18467         */
18468        public static final int ON = 1;
18469
18470        /**
18471         * Scrollbars are fading away
18472         */
18473        public static final int FADING = 2;
18474
18475        public boolean fadeScrollBars;
18476
18477        public int fadingEdgeLength;
18478        public int scrollBarDefaultDelayBeforeFade;
18479        public int scrollBarFadeDuration;
18480
18481        public int scrollBarSize;
18482        public ScrollBarDrawable scrollBar;
18483        public float[] interpolatorValues;
18484        public View host;
18485
18486        public final Paint paint;
18487        public final Matrix matrix;
18488        public Shader shader;
18489
18490        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18491
18492        private static final float[] OPAQUE = { 255 };
18493        private static final float[] TRANSPARENT = { 0.0f };
18494
18495        /**
18496         * When fading should start. This time moves into the future every time
18497         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18498         */
18499        public long fadeStartTime;
18500
18501
18502        /**
18503         * The current state of the scrollbars: ON, OFF, or FADING
18504         */
18505        public int state = OFF;
18506
18507        private int mLastColor;
18508
18509        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18510            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18511            scrollBarSize = configuration.getScaledScrollBarSize();
18512            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18513            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18514
18515            paint = new Paint();
18516            matrix = new Matrix();
18517            // use use a height of 1, and then wack the matrix each time we
18518            // actually use it.
18519            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18520            paint.setShader(shader);
18521            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18522
18523            this.host = host;
18524        }
18525
18526        public void setFadeColor(int color) {
18527            if (color != mLastColor) {
18528                mLastColor = color;
18529
18530                if (color != 0) {
18531                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18532                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18533                    paint.setShader(shader);
18534                    // Restore the default transfer mode (src_over)
18535                    paint.setXfermode(null);
18536                } else {
18537                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18538                    paint.setShader(shader);
18539                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18540                }
18541            }
18542        }
18543
18544        public void run() {
18545            long now = AnimationUtils.currentAnimationTimeMillis();
18546            if (now >= fadeStartTime) {
18547
18548                // the animation fades the scrollbars out by changing
18549                // the opacity (alpha) from fully opaque to fully
18550                // transparent
18551                int nextFrame = (int) now;
18552                int framesCount = 0;
18553
18554                Interpolator interpolator = scrollBarInterpolator;
18555
18556                // Start opaque
18557                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18558
18559                // End transparent
18560                nextFrame += scrollBarFadeDuration;
18561                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18562
18563                state = FADING;
18564
18565                // Kick off the fade animation
18566                host.invalidate(true);
18567            }
18568        }
18569    }
18570
18571    /**
18572     * Resuable callback for sending
18573     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18574     */
18575    private class SendViewScrolledAccessibilityEvent implements Runnable {
18576        public volatile boolean mIsPending;
18577
18578        public void run() {
18579            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18580            mIsPending = false;
18581        }
18582    }
18583
18584    /**
18585     * <p>
18586     * This class represents a delegate that can be registered in a {@link View}
18587     * to enhance accessibility support via composition rather via inheritance.
18588     * It is specifically targeted to widget developers that extend basic View
18589     * classes i.e. classes in package android.view, that would like their
18590     * applications to be backwards compatible.
18591     * </p>
18592     * <div class="special reference">
18593     * <h3>Developer Guides</h3>
18594     * <p>For more information about making applications accessible, read the
18595     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18596     * developer guide.</p>
18597     * </div>
18598     * <p>
18599     * A scenario in which a developer would like to use an accessibility delegate
18600     * is overriding a method introduced in a later API version then the minimal API
18601     * version supported by the application. For example, the method
18602     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18603     * in API version 4 when the accessibility APIs were first introduced. If a
18604     * developer would like his application to run on API version 4 devices (assuming
18605     * all other APIs used by the application are version 4 or lower) and take advantage
18606     * of this method, instead of overriding the method which would break the application's
18607     * backwards compatibility, he can override the corresponding method in this
18608     * delegate and register the delegate in the target View if the API version of
18609     * the system is high enough i.e. the API version is same or higher to the API
18610     * version that introduced
18611     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18612     * </p>
18613     * <p>
18614     * Here is an example implementation:
18615     * </p>
18616     * <code><pre><p>
18617     * if (Build.VERSION.SDK_INT >= 14) {
18618     *     // If the API version is equal of higher than the version in
18619     *     // which onInitializeAccessibilityNodeInfo was introduced we
18620     *     // register a delegate with a customized implementation.
18621     *     View view = findViewById(R.id.view_id);
18622     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18623     *         public void onInitializeAccessibilityNodeInfo(View host,
18624     *                 AccessibilityNodeInfo info) {
18625     *             // Let the default implementation populate the info.
18626     *             super.onInitializeAccessibilityNodeInfo(host, info);
18627     *             // Set some other information.
18628     *             info.setEnabled(host.isEnabled());
18629     *         }
18630     *     });
18631     * }
18632     * </code></pre></p>
18633     * <p>
18634     * This delegate contains methods that correspond to the accessibility methods
18635     * in View. If a delegate has been specified the implementation in View hands
18636     * off handling to the corresponding method in this delegate. The default
18637     * implementation the delegate methods behaves exactly as the corresponding
18638     * method in View for the case of no accessibility delegate been set. Hence,
18639     * to customize the behavior of a View method, clients can override only the
18640     * corresponding delegate method without altering the behavior of the rest
18641     * accessibility related methods of the host view.
18642     * </p>
18643     */
18644    public static class AccessibilityDelegate {
18645
18646        /**
18647         * Sends an accessibility event of the given type. If accessibility is not
18648         * enabled this method has no effect.
18649         * <p>
18650         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18651         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18652         * been set.
18653         * </p>
18654         *
18655         * @param host The View hosting the delegate.
18656         * @param eventType The type of the event to send.
18657         *
18658         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18659         */
18660        public void sendAccessibilityEvent(View host, int eventType) {
18661            host.sendAccessibilityEventInternal(eventType);
18662        }
18663
18664        /**
18665         * Performs the specified accessibility action on the view. For
18666         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18667         * <p>
18668         * The default implementation behaves as
18669         * {@link View#performAccessibilityAction(int, Bundle)
18670         *  View#performAccessibilityAction(int, Bundle)} for the case of
18671         *  no accessibility delegate been set.
18672         * </p>
18673         *
18674         * @param action The action to perform.
18675         * @return Whether the action was performed.
18676         *
18677         * @see View#performAccessibilityAction(int, Bundle)
18678         *      View#performAccessibilityAction(int, Bundle)
18679         */
18680        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18681            return host.performAccessibilityActionInternal(action, args);
18682        }
18683
18684        /**
18685         * Sends an accessibility event. This method behaves exactly as
18686         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18687         * empty {@link AccessibilityEvent} and does not perform a check whether
18688         * accessibility is enabled.
18689         * <p>
18690         * The default implementation behaves as
18691         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18692         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18693         * the case of no accessibility delegate been set.
18694         * </p>
18695         *
18696         * @param host The View hosting the delegate.
18697         * @param event The event to send.
18698         *
18699         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18700         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18701         */
18702        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18703            host.sendAccessibilityEventUncheckedInternal(event);
18704        }
18705
18706        /**
18707         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18708         * to its children for adding their text content to the event.
18709         * <p>
18710         * The default implementation behaves as
18711         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18712         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18713         * the case of no accessibility delegate been set.
18714         * </p>
18715         *
18716         * @param host The View hosting the delegate.
18717         * @param event The event.
18718         * @return True if the event population was completed.
18719         *
18720         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18721         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18722         */
18723        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18724            return host.dispatchPopulateAccessibilityEventInternal(event);
18725        }
18726
18727        /**
18728         * Gives a chance to the host View to populate the accessibility event with its
18729         * text content.
18730         * <p>
18731         * The default implementation behaves as
18732         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18733         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18734         * the case of no accessibility delegate been set.
18735         * </p>
18736         *
18737         * @param host The View hosting the delegate.
18738         * @param event The accessibility event which to populate.
18739         *
18740         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18741         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18742         */
18743        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18744            host.onPopulateAccessibilityEventInternal(event);
18745        }
18746
18747        /**
18748         * Initializes an {@link AccessibilityEvent} with information about the
18749         * the host View which is the event source.
18750         * <p>
18751         * The default implementation behaves as
18752         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18753         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18754         * the case of no accessibility delegate been set.
18755         * </p>
18756         *
18757         * @param host The View hosting the delegate.
18758         * @param event The event to initialize.
18759         *
18760         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18761         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18762         */
18763        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18764            host.onInitializeAccessibilityEventInternal(event);
18765        }
18766
18767        /**
18768         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18769         * <p>
18770         * The default implementation behaves as
18771         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18772         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18773         * the case of no accessibility delegate been set.
18774         * </p>
18775         *
18776         * @param host The View hosting the delegate.
18777         * @param info The instance to initialize.
18778         *
18779         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18780         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18781         */
18782        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18783            host.onInitializeAccessibilityNodeInfoInternal(info);
18784        }
18785
18786        /**
18787         * Called when a child of the host View has requested sending an
18788         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18789         * to augment the event.
18790         * <p>
18791         * The default implementation behaves as
18792         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18793         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18794         * the case of no accessibility delegate been set.
18795         * </p>
18796         *
18797         * @param host The View hosting the delegate.
18798         * @param child The child which requests sending the event.
18799         * @param event The event to be sent.
18800         * @return True if the event should be sent
18801         *
18802         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18803         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18804         */
18805        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18806                AccessibilityEvent event) {
18807            return host.onRequestSendAccessibilityEventInternal(child, event);
18808        }
18809
18810        /**
18811         * Gets the provider for managing a virtual view hierarchy rooted at this View
18812         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18813         * that explore the window content.
18814         * <p>
18815         * The default implementation behaves as
18816         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18817         * the case of no accessibility delegate been set.
18818         * </p>
18819         *
18820         * @return The provider.
18821         *
18822         * @see AccessibilityNodeProvider
18823         */
18824        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18825            return null;
18826        }
18827
18828        /**
18829         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
18830         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
18831         * This method is responsible for obtaining an accessibility node info from a
18832         * pool of reusable instances and calling
18833         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
18834         * view to initialize the former.
18835         * <p>
18836         * <strong>Note:</strong> The client is responsible for recycling the obtained
18837         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
18838         * creation.
18839         * </p>
18840         * <p>
18841         * The default implementation behaves as
18842         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
18843         * the case of no accessibility delegate been set.
18844         * </p>
18845         * @return A populated {@link AccessibilityNodeInfo}.
18846         *
18847         * @see AccessibilityNodeInfo
18848         *
18849         * @hide
18850         */
18851        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
18852            return host.createAccessibilityNodeInfoInternal();
18853        }
18854    }
18855
18856    private class MatchIdPredicate implements Predicate<View> {
18857        public int mId;
18858
18859        @Override
18860        public boolean apply(View view) {
18861            return (view.mID == mId);
18862        }
18863    }
18864
18865    private class MatchLabelForPredicate implements Predicate<View> {
18866        private int mLabeledId;
18867
18868        @Override
18869        public boolean apply(View view) {
18870            return (view.mLabelForId == mLabeledId);
18871        }
18872    }
18873
18874    private class SendViewStateChangedAccessibilityEvent implements Runnable {
18875        private boolean mPosted;
18876        private long mLastEventTimeMillis;
18877
18878        public void run() {
18879            mPosted = false;
18880            mLastEventTimeMillis = SystemClock.uptimeMillis();
18881            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
18882                AccessibilityEvent event = AccessibilityEvent.obtain();
18883                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
18884                event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE);
18885                sendAccessibilityEventUnchecked(event);
18886            }
18887        }
18888
18889        public void runOrPost() {
18890            if (mPosted) {
18891                return;
18892            }
18893            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
18894            final long minEventIntevalMillis =
18895                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
18896            if (timeSinceLastMillis >= minEventIntevalMillis) {
18897                removeCallbacks(this);
18898                run();
18899            } else {
18900                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
18901                mPosted = true;
18902            }
18903        }
18904    }
18905
18906    /**
18907     * Dump all private flags in readable format, useful for documentation and
18908     * sanity checking.
18909     */
18910    private static void dumpFlags() {
18911        final HashMap<String, String> found = Maps.newHashMap();
18912        try {
18913            for (Field field : View.class.getDeclaredFields()) {
18914                final int modifiers = field.getModifiers();
18915                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18916                    if (field.getType().equals(int.class)) {
18917                        final int value = field.getInt(null);
18918                        dumpFlag(found, field.getName(), value);
18919                    } else if (field.getType().equals(int[].class)) {
18920                        final int[] values = (int[]) field.get(null);
18921                        for (int i = 0; i < values.length; i++) {
18922                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18923                        }
18924                    }
18925                }
18926            }
18927        } catch (IllegalAccessException e) {
18928            throw new RuntimeException(e);
18929        }
18930
18931        final ArrayList<String> keys = Lists.newArrayList();
18932        keys.addAll(found.keySet());
18933        Collections.sort(keys);
18934        for (String key : keys) {
18935            Log.d(VIEW_LOG_TAG, found.get(key));
18936        }
18937    }
18938
18939    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18940        // Sort flags by prefix, then by bits, always keeping unique keys
18941        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18942        final int prefix = name.indexOf('_');
18943        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18944        final String output = bits + " " + name;
18945        found.put(key, output);
18946    }
18947}
18948