View.java revision 06f37728b92450035a256504fe4e289d058861ef
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.annotation.IntDef;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.content.ClipData;
23import android.content.Context;
24import android.content.res.Configuration;
25import android.content.res.Resources;
26import android.content.res.TypedArray;
27import android.graphics.Bitmap;
28import android.graphics.Camera;
29import android.graphics.Canvas;
30import android.graphics.Insets;
31import android.graphics.Interpolator;
32import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.PixelFormat;
36import android.graphics.Point;
37import android.graphics.PorterDuff;
38import android.graphics.PorterDuffXfermode;
39import android.graphics.Rect;
40import android.graphics.RectF;
41import android.graphics.Region;
42import android.graphics.Shader;
43import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.hardware.display.DisplayManagerGlobal;
46import android.os.Bundle;
47import android.os.Handler;
48import android.os.IBinder;
49import android.os.Parcel;
50import android.os.Parcelable;
51import android.os.RemoteException;
52import android.os.SystemClock;
53import android.os.SystemProperties;
54import android.text.TextUtils;
55import android.util.AttributeSet;
56import android.util.FloatProperty;
57import android.util.LayoutDirection;
58import android.util.Log;
59import android.util.LongSparseLongArray;
60import android.util.Pools.SynchronizedPool;
61import android.util.Property;
62import android.util.SparseArray;
63import android.util.SuperNotCalledException;
64import android.util.TypedValue;
65import android.view.ContextMenu.ContextMenuInfo;
66import android.view.AccessibilityIterators.TextSegmentIterator;
67import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
68import android.view.AccessibilityIterators.WordTextSegmentIterator;
69import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
70import android.view.accessibility.AccessibilityEvent;
71import android.view.accessibility.AccessibilityEventSource;
72import android.view.accessibility.AccessibilityManager;
73import android.view.accessibility.AccessibilityNodeInfo;
74import android.view.accessibility.AccessibilityNodeProvider;
75import android.view.animation.Animation;
76import android.view.animation.AnimationUtils;
77import android.view.animation.Transformation;
78import android.view.inputmethod.EditorInfo;
79import android.view.inputmethod.InputConnection;
80import android.view.inputmethod.InputMethodManager;
81import android.widget.ScrollBarDrawable;
82
83import static android.os.Build.VERSION_CODES.*;
84import static java.lang.Math.max;
85
86import com.android.internal.R;
87import com.android.internal.util.Predicate;
88import com.android.internal.view.menu.MenuBuilder;
89import com.google.android.collect.Lists;
90import com.google.android.collect.Maps;
91
92import java.lang.annotation.Retention;
93import java.lang.annotation.RetentionPolicy;
94import java.lang.ref.WeakReference;
95import java.lang.reflect.Field;
96import java.lang.reflect.InvocationTargetException;
97import java.lang.reflect.Method;
98import java.lang.reflect.Modifier;
99import java.util.ArrayList;
100import java.util.Arrays;
101import java.util.Collections;
102import java.util.HashMap;
103import java.util.Locale;
104import java.util.concurrent.CopyOnWriteArrayList;
105import java.util.concurrent.atomic.AtomicInteger;
106
107/**
108 * <p>
109 * This class represents the basic building block for user interface components. A View
110 * occupies a rectangular area on the screen and is responsible for drawing and
111 * event handling. View is the base class for <em>widgets</em>, which are
112 * used to create interactive UI components (buttons, text fields, etc.). The
113 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
114 * are invisible containers that hold other Views (or other ViewGroups) and define
115 * their layout properties.
116 * </p>
117 *
118 * <div class="special reference">
119 * <h3>Developer Guides</h3>
120 * <p>For information about using this class to develop your application's user interface,
121 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
122 * </div>
123 *
124 * <a name="Using"></a>
125 * <h3>Using Views</h3>
126 * <p>
127 * All of the views in a window are arranged in a single tree. You can add views
128 * either from code or by specifying a tree of views in one or more XML layout
129 * files. There are many specialized subclasses of views that act as controls or
130 * are capable of displaying text, images, or other content.
131 * </p>
132 * <p>
133 * Once you have created a tree of views, there are typically a few types of
134 * common operations you may wish to perform:
135 * <ul>
136 * <li><strong>Set properties:</strong> for example setting the text of a
137 * {@link android.widget.TextView}. The available properties and the methods
138 * that set them will vary among the different subclasses of views. Note that
139 * properties that are known at build time can be set in the XML layout
140 * files.</li>
141 * <li><strong>Set focus:</strong> The framework will handled moving focus in
142 * response to user input. To force focus to a specific view, call
143 * {@link #requestFocus}.</li>
144 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
145 * that will be notified when something interesting happens to the view. For
146 * example, all views will let you set a listener to be notified when the view
147 * gains or loses focus. You can register such a listener using
148 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
149 * Other view subclasses offer more specialized listeners. For example, a Button
150 * exposes a listener to notify clients when the button is clicked.</li>
151 * <li><strong>Set visibility:</strong> You can hide or show views using
152 * {@link #setVisibility(int)}.</li>
153 * </ul>
154 * </p>
155 * <p><em>
156 * Note: The Android framework is responsible for measuring, laying out and
157 * drawing views. You should not call methods that perform these actions on
158 * views yourself unless you are actually implementing a
159 * {@link android.view.ViewGroup}.
160 * </em></p>
161 *
162 * <a name="Lifecycle"></a>
163 * <h3>Implementing a Custom View</h3>
164 *
165 * <p>
166 * To implement a custom view, you will usually begin by providing overrides for
167 * some of the standard methods that the framework calls on all views. You do
168 * not need to override all of these methods. In fact, you can start by just
169 * overriding {@link #onDraw(android.graphics.Canvas)}.
170 * <table border="2" width="85%" align="center" cellpadding="5">
171 *     <thead>
172 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
173 *     </thead>
174 *
175 *     <tbody>
176 *     <tr>
177 *         <td rowspan="2">Creation</td>
178 *         <td>Constructors</td>
179 *         <td>There is a form of the constructor that are called when the view
180 *         is created from code and a form that is called when the view is
181 *         inflated from a layout file. The second form should parse and apply
182 *         any attributes defined in the layout file.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onFinishInflate()}</code></td>
187 *         <td>Called after a view and all of its children has been inflated
188 *         from XML.</td>
189 *     </tr>
190 *
191 *     <tr>
192 *         <td rowspan="3">Layout</td>
193 *         <td><code>{@link #onMeasure(int, int)}</code></td>
194 *         <td>Called to determine the size requirements for this view and all
195 *         of its children.
196 *         </td>
197 *     </tr>
198 *     <tr>
199 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
200 *         <td>Called when this view should assign a size and position to all
201 *         of its children.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
206 *         <td>Called when the size of this view has changed.
207 *         </td>
208 *     </tr>
209 *
210 *     <tr>
211 *         <td>Drawing</td>
212 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
213 *         <td>Called when the view should render its content.
214 *         </td>
215 *     </tr>
216 *
217 *     <tr>
218 *         <td rowspan="4">Event processing</td>
219 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
220 *         <td>Called when a new hardware key event occurs.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
225 *         <td>Called when a hardware key up event occurs.
226 *         </td>
227 *     </tr>
228 *     <tr>
229 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
230 *         <td>Called when a trackball motion event occurs.
231 *         </td>
232 *     </tr>
233 *     <tr>
234 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
235 *         <td>Called when a touch screen motion event occurs.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="2">Focus</td>
241 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
242 *         <td>Called when the view gains or loses focus.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
248 *         <td>Called when the window containing the view gains or loses focus.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td rowspan="3">Attaching</td>
254 *         <td><code>{@link #onAttachedToWindow()}</code></td>
255 *         <td>Called when the view is attached to a window.
256 *         </td>
257 *     </tr>
258 *
259 *     <tr>
260 *         <td><code>{@link #onDetachedFromWindow}</code></td>
261 *         <td>Called when the view is detached from its window.
262 *         </td>
263 *     </tr>
264 *
265 *     <tr>
266 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
267 *         <td>Called when the visibility of the window containing the view
268 *         has changed.
269 *         </td>
270 *     </tr>
271 *     </tbody>
272 *
273 * </table>
274 * </p>
275 *
276 * <a name="IDs"></a>
277 * <h3>IDs</h3>
278 * Views may have an integer id associated with them. These ids are typically
279 * assigned in the layout XML files, and are used to find specific views within
280 * the view tree. A common pattern is to:
281 * <ul>
282 * <li>Define a Button in the layout file and assign it a unique ID.
283 * <pre>
284 * &lt;Button
285 *     android:id="@+id/my_button"
286 *     android:layout_width="wrap_content"
287 *     android:layout_height="wrap_content"
288 *     android:text="@string/my_button_text"/&gt;
289 * </pre></li>
290 * <li>From the onCreate method of an Activity, find the Button
291 * <pre class="prettyprint">
292 *      Button myButton = (Button) findViewById(R.id.my_button);
293 * </pre></li>
294 * </ul>
295 * <p>
296 * View IDs need not be unique throughout the tree, but it is good practice to
297 * ensure that they are at least unique within the part of the tree you are
298 * searching.
299 * </p>
300 *
301 * <a name="Position"></a>
302 * <h3>Position</h3>
303 * <p>
304 * The geometry of a view is that of a rectangle. A view has a location,
305 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
306 * two dimensions, expressed as a width and a height. The unit for location
307 * and dimensions is the pixel.
308 * </p>
309 *
310 * <p>
311 * It is possible to retrieve the location of a view by invoking the methods
312 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
313 * coordinate of the rectangle representing the view. The latter returns the
314 * top, or Y, coordinate of the rectangle representing the view. These methods
315 * both return the location of the view relative to its parent. For instance,
316 * when getLeft() returns 20, that means the view is located 20 pixels to the
317 * right of the left edge of its direct parent.
318 * </p>
319 *
320 * <p>
321 * In addition, several convenience methods are offered to avoid unnecessary
322 * computations, namely {@link #getRight()} and {@link #getBottom()}.
323 * These methods return the coordinates of the right and bottom edges of the
324 * rectangle representing the view. For instance, calling {@link #getRight()}
325 * is similar to the following computation: <code>getLeft() + getWidth()</code>
326 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
327 * </p>
328 *
329 * <a name="SizePaddingMargins"></a>
330 * <h3>Size, padding and margins</h3>
331 * <p>
332 * The size of a view is expressed with a width and a height. A view actually
333 * possess two pairs of width and height values.
334 * </p>
335 *
336 * <p>
337 * The first pair is known as <em>measured width</em> and
338 * <em>measured height</em>. These dimensions define how big a view wants to be
339 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
340 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
341 * and {@link #getMeasuredHeight()}.
342 * </p>
343 *
344 * <p>
345 * The second pair is simply known as <em>width</em> and <em>height</em>, or
346 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
347 * dimensions define the actual size of the view on screen, at drawing time and
348 * after layout. These values may, but do not have to, be different from the
349 * measured width and height. The width and height can be obtained by calling
350 * {@link #getWidth()} and {@link #getHeight()}.
351 * </p>
352 *
353 * <p>
354 * To measure its dimensions, a view takes into account its padding. The padding
355 * is expressed in pixels for the left, top, right and bottom parts of the view.
356 * Padding can be used to offset the content of the view by a specific amount of
357 * pixels. For instance, a left padding of 2 will push the view's content by
358 * 2 pixels to the right of the left edge. Padding can be set using the
359 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
360 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
361 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
362 * {@link #getPaddingEnd()}.
363 * </p>
364 *
365 * <p>
366 * Even though a view can define a padding, it does not provide any support for
367 * margins. However, view groups provide such a support. Refer to
368 * {@link android.view.ViewGroup} and
369 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
370 * </p>
371 *
372 * <a name="Layout"></a>
373 * <h3>Layout</h3>
374 * <p>
375 * Layout is a two pass process: a measure pass and a layout pass. The measuring
376 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
377 * of the view tree. Each view pushes dimension specifications down the tree
378 * during the recursion. At the end of the measure pass, every view has stored
379 * its measurements. The second pass happens in
380 * {@link #layout(int,int,int,int)} and is also top-down. During
381 * this pass each parent is responsible for positioning all of its children
382 * using the sizes computed in the measure pass.
383 * </p>
384 *
385 * <p>
386 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
387 * {@link #getMeasuredHeight()} values must be set, along with those for all of
388 * that view's descendants. A view's measured width and measured height values
389 * must respect the constraints imposed by the view's parents. This guarantees
390 * that at the end of the measure pass, all parents accept all of their
391 * children's measurements. A parent view may call measure() more than once on
392 * its children. For example, the parent may measure each child once with
393 * unspecified dimensions to find out how big they want to be, then call
394 * measure() on them again with actual numbers if the sum of all the children's
395 * unconstrained sizes is too big or too small.
396 * </p>
397 *
398 * <p>
399 * The measure pass uses two classes to communicate dimensions. The
400 * {@link MeasureSpec} class is used by views to tell their parents how they
401 * want to be measured and positioned. The base LayoutParams class just
402 * describes how big the view wants to be for both width and height. For each
403 * dimension, it can specify one of:
404 * <ul>
405 * <li> an exact number
406 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
407 * (minus padding)
408 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
409 * enclose its content (plus padding).
410 * </ul>
411 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
412 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
413 * an X and Y value.
414 * </p>
415 *
416 * <p>
417 * MeasureSpecs are used to push requirements down the tree from parent to
418 * child. A MeasureSpec can be in one of three modes:
419 * <ul>
420 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
421 * of a child view. For example, a LinearLayout may call measure() on its child
422 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
423 * tall the child view wants to be given a width of 240 pixels.
424 * <li>EXACTLY: This is used by the parent to impose an exact size on the
425 * child. The child must use this size, and guarantee that all of its
426 * descendants will fit within this size.
427 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
428 * child. The child must gurantee that it and all of its descendants will fit
429 * within this size.
430 * </ul>
431 * </p>
432 *
433 * <p>
434 * To intiate a layout, call {@link #requestLayout}. This method is typically
435 * called by a view on itself when it believes that is can no longer fit within
436 * its current bounds.
437 * </p>
438 *
439 * <a name="Drawing"></a>
440 * <h3>Drawing</h3>
441 * <p>
442 * Drawing is handled by walking the tree and rendering each view that
443 * intersects the invalid region. Because the tree is traversed in-order,
444 * this means that parents will draw before (i.e., behind) their children, with
445 * siblings drawn in the order they appear in the tree.
446 * If you set a background drawable for a View, then the View will draw it for you
447 * before calling back to its <code>onDraw()</code> method.
448 * </p>
449 *
450 * <p>
451 * Note that the framework will not draw views that are not in the invalid region.
452 * </p>
453 *
454 * <p>
455 * To force a view to draw, call {@link #invalidate()}.
456 * </p>
457 *
458 * <a name="EventHandlingThreading"></a>
459 * <h3>Event Handling and Threading</h3>
460 * <p>
461 * The basic cycle of a view is as follows:
462 * <ol>
463 * <li>An event comes in and is dispatched to the appropriate view. The view
464 * handles the event and notifies any listeners.</li>
465 * <li>If in the course of processing the event, the view's bounds may need
466 * to be changed, the view will call {@link #requestLayout()}.</li>
467 * <li>Similarly, if in the course of processing the event the view's appearance
468 * may need to be changed, the view will call {@link #invalidate()}.</li>
469 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
470 * the framework will take care of measuring, laying out, and drawing the tree
471 * as appropriate.</li>
472 * </ol>
473 * </p>
474 *
475 * <p><em>Note: The entire view tree is single threaded. You must always be on
476 * the UI thread when calling any method on any view.</em>
477 * If you are doing work on other threads and want to update the state of a view
478 * from that thread, you should use a {@link Handler}.
479 * </p>
480 *
481 * <a name="FocusHandling"></a>
482 * <h3>Focus Handling</h3>
483 * <p>
484 * The framework will handle routine focus movement in response to user input.
485 * This includes changing the focus as views are removed or hidden, or as new
486 * views become available. Views indicate their willingness to take focus
487 * through the {@link #isFocusable} method. To change whether a view can take
488 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
489 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
490 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
491 * </p>
492 * <p>
493 * Focus movement is based on an algorithm which finds the nearest neighbor in a
494 * given direction. In rare cases, the default algorithm may not match the
495 * intended behavior of the developer. In these situations, you can provide
496 * explicit overrides by using these XML attributes in the layout file:
497 * <pre>
498 * nextFocusDown
499 * nextFocusLeft
500 * nextFocusRight
501 * nextFocusUp
502 * </pre>
503 * </p>
504 *
505 *
506 * <p>
507 * To get a particular view to take focus, call {@link #requestFocus()}.
508 * </p>
509 *
510 * <a name="TouchMode"></a>
511 * <h3>Touch Mode</h3>
512 * <p>
513 * When a user is navigating a user interface via directional keys such as a D-pad, it is
514 * necessary to give focus to actionable items such as buttons so the user can see
515 * what will take input.  If the device has touch capabilities, however, and the user
516 * begins interacting with the interface by touching it, it is no longer necessary to
517 * always highlight, or give focus to, a particular view.  This motivates a mode
518 * for interaction named 'touch mode'.
519 * </p>
520 * <p>
521 * For a touch capable device, once the user touches the screen, the device
522 * will enter touch mode.  From this point onward, only views for which
523 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
524 * Other views that are touchable, like buttons, will not take focus when touched; they will
525 * only fire the on click listeners.
526 * </p>
527 * <p>
528 * Any time a user hits a directional key, such as a D-pad direction, the view device will
529 * exit touch mode, and find a view to take focus, so that the user may resume interacting
530 * with the user interface without touching the screen again.
531 * </p>
532 * <p>
533 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
534 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
535 * </p>
536 *
537 * <a name="Scrolling"></a>
538 * <h3>Scrolling</h3>
539 * <p>
540 * The framework provides basic support for views that wish to internally
541 * scroll their content. This includes keeping track of the X and Y scroll
542 * offset as well as mechanisms for drawing scrollbars. See
543 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
544 * {@link #awakenScrollBars()} for more details.
545 * </p>
546 *
547 * <a name="Tags"></a>
548 * <h3>Tags</h3>
549 * <p>
550 * Unlike IDs, tags are not used to identify views. Tags are essentially an
551 * extra piece of information that can be associated with a view. They are most
552 * often used as a convenience to store data related to views in the views
553 * themselves rather than by putting them in a separate structure.
554 * </p>
555 *
556 * <a name="Properties"></a>
557 * <h3>Properties</h3>
558 * <p>
559 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
560 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
561 * available both in the {@link Property} form as well as in similarly-named setter/getter
562 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
563 * be used to set persistent state associated with these rendering-related properties on the view.
564 * The properties and methods can also be used in conjunction with
565 * {@link android.animation.Animator Animator}-based animations, described more in the
566 * <a href="#Animation">Animation</a> section.
567 * </p>
568 *
569 * <a name="Animation"></a>
570 * <h3>Animation</h3>
571 * <p>
572 * Starting with Android 3.0, the preferred way of animating views is to use the
573 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
574 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
575 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
576 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
577 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
578 * makes animating these View properties particularly easy and efficient.
579 * </p>
580 * <p>
581 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
582 * You can attach an {@link Animation} object to a view using
583 * {@link #setAnimation(Animation)} or
584 * {@link #startAnimation(Animation)}. The animation can alter the scale,
585 * rotation, translation and alpha of a view over time. If the animation is
586 * attached to a view that has children, the animation will affect the entire
587 * subtree rooted by that node. When an animation is started, the framework will
588 * take care of redrawing the appropriate views until the animation completes.
589 * </p>
590 *
591 * <a name="Security"></a>
592 * <h3>Security</h3>
593 * <p>
594 * Sometimes it is essential that an application be able to verify that an action
595 * is being performed with the full knowledge and consent of the user, such as
596 * granting a permission request, making a purchase or clicking on an advertisement.
597 * Unfortunately, a malicious application could try to spoof the user into
598 * performing these actions, unaware, by concealing the intended purpose of the view.
599 * As a remedy, the framework offers a touch filtering mechanism that can be used to
600 * improve the security of views that provide access to sensitive functionality.
601 * </p><p>
602 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
603 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
604 * will discard touches that are received whenever the view's window is obscured by
605 * another visible window.  As a result, the view will not receive touches whenever a
606 * toast, dialog or other window appears above the view's window.
607 * </p><p>
608 * For more fine-grained control over security, consider overriding the
609 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
610 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
611 * </p>
612 *
613 * @attr ref android.R.styleable#View_alpha
614 * @attr ref android.R.styleable#View_background
615 * @attr ref android.R.styleable#View_clickable
616 * @attr ref android.R.styleable#View_contentDescription
617 * @attr ref android.R.styleable#View_drawingCacheQuality
618 * @attr ref android.R.styleable#View_duplicateParentState
619 * @attr ref android.R.styleable#View_id
620 * @attr ref android.R.styleable#View_requiresFadingEdge
621 * @attr ref android.R.styleable#View_fadeScrollbars
622 * @attr ref android.R.styleable#View_fadingEdgeLength
623 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
624 * @attr ref android.R.styleable#View_fitsSystemWindows
625 * @attr ref android.R.styleable#View_isScrollContainer
626 * @attr ref android.R.styleable#View_focusable
627 * @attr ref android.R.styleable#View_focusableInTouchMode
628 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
629 * @attr ref android.R.styleable#View_keepScreenOn
630 * @attr ref android.R.styleable#View_layerType
631 * @attr ref android.R.styleable#View_layoutDirection
632 * @attr ref android.R.styleable#View_longClickable
633 * @attr ref android.R.styleable#View_minHeight
634 * @attr ref android.R.styleable#View_minWidth
635 * @attr ref android.R.styleable#View_nextFocusDown
636 * @attr ref android.R.styleable#View_nextFocusLeft
637 * @attr ref android.R.styleable#View_nextFocusRight
638 * @attr ref android.R.styleable#View_nextFocusUp
639 * @attr ref android.R.styleable#View_onClick
640 * @attr ref android.R.styleable#View_padding
641 * @attr ref android.R.styleable#View_paddingBottom
642 * @attr ref android.R.styleable#View_paddingLeft
643 * @attr ref android.R.styleable#View_paddingRight
644 * @attr ref android.R.styleable#View_paddingTop
645 * @attr ref android.R.styleable#View_paddingStart
646 * @attr ref android.R.styleable#View_paddingEnd
647 * @attr ref android.R.styleable#View_saveEnabled
648 * @attr ref android.R.styleable#View_rotation
649 * @attr ref android.R.styleable#View_rotationX
650 * @attr ref android.R.styleable#View_rotationY
651 * @attr ref android.R.styleable#View_scaleX
652 * @attr ref android.R.styleable#View_scaleY
653 * @attr ref android.R.styleable#View_scrollX
654 * @attr ref android.R.styleable#View_scrollY
655 * @attr ref android.R.styleable#View_scrollbarSize
656 * @attr ref android.R.styleable#View_scrollbarStyle
657 * @attr ref android.R.styleable#View_scrollbars
658 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
659 * @attr ref android.R.styleable#View_scrollbarFadeDuration
660 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
661 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
662 * @attr ref android.R.styleable#View_scrollbarThumbVertical
663 * @attr ref android.R.styleable#View_scrollbarTrackVertical
664 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
665 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
666 * @attr ref android.R.styleable#View_soundEffectsEnabled
667 * @attr ref android.R.styleable#View_tag
668 * @attr ref android.R.styleable#View_textAlignment
669 * @attr ref android.R.styleable#View_textDirection
670 * @attr ref android.R.styleable#View_transformPivotX
671 * @attr ref android.R.styleable#View_transformPivotY
672 * @attr ref android.R.styleable#View_translationX
673 * @attr ref android.R.styleable#View_translationY
674 * @attr ref android.R.styleable#View_visibility
675 *
676 * @see android.view.ViewGroup
677 */
678public class View implements Drawable.Callback, KeyEvent.Callback,
679        AccessibilityEventSource {
680    private static final boolean DBG = false;
681
682    /**
683     * The logging tag used by this class with android.util.Log.
684     */
685    protected static final String VIEW_LOG_TAG = "View";
686
687    /**
688     * When set to true, apps will draw debugging information about their layouts.
689     *
690     * @hide
691     */
692    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
693
694    /**
695     * Used to mark a View that has no ID.
696     */
697    public static final int NO_ID = -1;
698
699    /**
700     * Signals that compatibility booleans have been initialized according to
701     * target SDK versions.
702     */
703    private static boolean sCompatibilityDone = false;
704
705    /**
706     * Use the old (broken) way of building MeasureSpecs.
707     */
708    private static boolean sUseBrokenMakeMeasureSpec = false;
709
710    /**
711     * Ignore any optimizations using the measure cache.
712     */
713    private static boolean sIgnoreMeasureCache = false;
714
715    /**
716     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
717     * calling setFlags.
718     */
719    private static final int NOT_FOCUSABLE = 0x00000000;
720
721    /**
722     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
723     * setFlags.
724     */
725    private static final int FOCUSABLE = 0x00000001;
726
727    /**
728     * Mask for use with setFlags indicating bits used for focus.
729     */
730    private static final int FOCUSABLE_MASK = 0x00000001;
731
732    /**
733     * This view will adjust its padding to fit sytem windows (e.g. status bar)
734     */
735    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
736
737    /** @hide */
738    @IntDef({VISIBLE, INVISIBLE, GONE})
739    @Retention(RetentionPolicy.SOURCE)
740    public @interface Visibility {}
741
742    /**
743     * This view is visible.
744     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
745     * android:visibility}.
746     */
747    public static final int VISIBLE = 0x00000000;
748
749    /**
750     * This view is invisible, but it still takes up space for layout purposes.
751     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
752     * android:visibility}.
753     */
754    public static final int INVISIBLE = 0x00000004;
755
756    /**
757     * This view is invisible, and it doesn't take any space for layout
758     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
759     * android:visibility}.
760     */
761    public static final int GONE = 0x00000008;
762
763    /**
764     * Mask for use with setFlags indicating bits used for visibility.
765     * {@hide}
766     */
767    static final int VISIBILITY_MASK = 0x0000000C;
768
769    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
770
771    /**
772     * This view is enabled. Interpretation varies by subclass.
773     * Use with ENABLED_MASK when calling setFlags.
774     * {@hide}
775     */
776    static final int ENABLED = 0x00000000;
777
778    /**
779     * This view is disabled. Interpretation varies by subclass.
780     * Use with ENABLED_MASK when calling setFlags.
781     * {@hide}
782     */
783    static final int DISABLED = 0x00000020;
784
785   /**
786    * Mask for use with setFlags indicating bits used for indicating whether
787    * this view is enabled
788    * {@hide}
789    */
790    static final int ENABLED_MASK = 0x00000020;
791
792    /**
793     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
794     * called and further optimizations will be performed. It is okay to have
795     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
796     * {@hide}
797     */
798    static final int WILL_NOT_DRAW = 0x00000080;
799
800    /**
801     * Mask for use with setFlags indicating bits used for indicating whether
802     * this view is will draw
803     * {@hide}
804     */
805    static final int DRAW_MASK = 0x00000080;
806
807    /**
808     * <p>This view doesn't show scrollbars.</p>
809     * {@hide}
810     */
811    static final int SCROLLBARS_NONE = 0x00000000;
812
813    /**
814     * <p>This view shows horizontal scrollbars.</p>
815     * {@hide}
816     */
817    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
818
819    /**
820     * <p>This view shows vertical scrollbars.</p>
821     * {@hide}
822     */
823    static final int SCROLLBARS_VERTICAL = 0x00000200;
824
825    /**
826     * <p>Mask for use with setFlags indicating bits used for indicating which
827     * scrollbars are enabled.</p>
828     * {@hide}
829     */
830    static final int SCROLLBARS_MASK = 0x00000300;
831
832    /**
833     * Indicates that the view should filter touches when its window is obscured.
834     * Refer to the class comments for more information about this security feature.
835     * {@hide}
836     */
837    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
838
839    /**
840     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
841     * that they are optional and should be skipped if the window has
842     * requested system UI flags that ignore those insets for layout.
843     */
844    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
845
846    /**
847     * <p>This view doesn't show fading edges.</p>
848     * {@hide}
849     */
850    static final int FADING_EDGE_NONE = 0x00000000;
851
852    /**
853     * <p>This view shows horizontal fading edges.</p>
854     * {@hide}
855     */
856    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
857
858    /**
859     * <p>This view shows vertical fading edges.</p>
860     * {@hide}
861     */
862    static final int FADING_EDGE_VERTICAL = 0x00002000;
863
864    /**
865     * <p>Mask for use with setFlags indicating bits used for indicating which
866     * fading edges are enabled.</p>
867     * {@hide}
868     */
869    static final int FADING_EDGE_MASK = 0x00003000;
870
871    /**
872     * <p>Indicates this view can be clicked. When clickable, a View reacts
873     * to clicks by notifying the OnClickListener.<p>
874     * {@hide}
875     */
876    static final int CLICKABLE = 0x00004000;
877
878    /**
879     * <p>Indicates this view is caching its drawing into a bitmap.</p>
880     * {@hide}
881     */
882    static final int DRAWING_CACHE_ENABLED = 0x00008000;
883
884    /**
885     * <p>Indicates that no icicle should be saved for this view.<p>
886     * {@hide}
887     */
888    static final int SAVE_DISABLED = 0x000010000;
889
890    /**
891     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
892     * property.</p>
893     * {@hide}
894     */
895    static final int SAVE_DISABLED_MASK = 0x000010000;
896
897    /**
898     * <p>Indicates that no drawing cache should ever be created for this view.<p>
899     * {@hide}
900     */
901    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
902
903    /**
904     * <p>Indicates this view can take / keep focus when int touch mode.</p>
905     * {@hide}
906     */
907    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
908
909    /** @hide */
910    @Retention(RetentionPolicy.SOURCE)
911    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
912    public @interface DrawingCacheQuality {}
913
914    /**
915     * <p>Enables low quality mode for the drawing cache.</p>
916     */
917    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
918
919    /**
920     * <p>Enables high quality mode for the drawing cache.</p>
921     */
922    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
923
924    /**
925     * <p>Enables automatic quality mode for the drawing cache.</p>
926     */
927    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
928
929    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
930            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
931    };
932
933    /**
934     * <p>Mask for use with setFlags indicating bits used for the cache
935     * quality property.</p>
936     * {@hide}
937     */
938    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
939
940    /**
941     * <p>
942     * Indicates this view can be long clicked. When long clickable, a View
943     * reacts to long clicks by notifying the OnLongClickListener or showing a
944     * context menu.
945     * </p>
946     * {@hide}
947     */
948    static final int LONG_CLICKABLE = 0x00200000;
949
950    /**
951     * <p>Indicates that this view gets its drawable states from its direct parent
952     * and ignores its original internal states.</p>
953     *
954     * @hide
955     */
956    static final int DUPLICATE_PARENT_STATE = 0x00400000;
957
958    /** @hide */
959    @IntDef({
960        SCROLLBARS_INSIDE_OVERLAY,
961        SCROLLBARS_INSIDE_INSET,
962        SCROLLBARS_OUTSIDE_OVERLAY,
963        SCROLLBARS_OUTSIDE_INSET
964    })
965    @Retention(RetentionPolicy.SOURCE)
966    public @interface ScrollBarStyle {}
967
968    /**
969     * The scrollbar style to display the scrollbars inside the content area,
970     * without increasing the padding. The scrollbars will be overlaid with
971     * translucency on the view's content.
972     */
973    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
974
975    /**
976     * The scrollbar style to display the scrollbars inside the padded area,
977     * increasing the padding of the view. The scrollbars will not overlap the
978     * content area of the view.
979     */
980    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
981
982    /**
983     * The scrollbar style to display the scrollbars at the edge of the view,
984     * without increasing the padding. The scrollbars will be overlaid with
985     * translucency.
986     */
987    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
988
989    /**
990     * The scrollbar style to display the scrollbars at the edge of the view,
991     * increasing the padding of the view. The scrollbars will only overlap the
992     * background, if any.
993     */
994    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
995
996    /**
997     * Mask to check if the scrollbar style is overlay or inset.
998     * {@hide}
999     */
1000    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1001
1002    /**
1003     * Mask to check if the scrollbar style is inside or outside.
1004     * {@hide}
1005     */
1006    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1007
1008    /**
1009     * Mask for scrollbar style.
1010     * {@hide}
1011     */
1012    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1013
1014    /**
1015     * View flag indicating that the screen should remain on while the
1016     * window containing this view is visible to the user.  This effectively
1017     * takes care of automatically setting the WindowManager's
1018     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1019     */
1020    public static final int KEEP_SCREEN_ON = 0x04000000;
1021
1022    /**
1023     * View flag indicating whether this view should have sound effects enabled
1024     * for events such as clicking and touching.
1025     */
1026    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1027
1028    /**
1029     * View flag indicating whether this view should have haptic feedback
1030     * enabled for events such as long presses.
1031     */
1032    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1033
1034    /**
1035     * <p>Indicates that the view hierarchy should stop saving state when
1036     * it reaches this view.  If state saving is initiated immediately at
1037     * the view, it will be allowed.
1038     * {@hide}
1039     */
1040    static final int PARENT_SAVE_DISABLED = 0x20000000;
1041
1042    /**
1043     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1044     * {@hide}
1045     */
1046    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1047
1048    /** @hide */
1049    @IntDef(flag = true,
1050            value = {
1051                FOCUSABLES_ALL,
1052                FOCUSABLES_TOUCH_MODE
1053            })
1054    @Retention(RetentionPolicy.SOURCE)
1055    public @interface FocusableMode {}
1056
1057    /**
1058     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1059     * should add all focusable Views regardless if they are focusable in touch mode.
1060     */
1061    public static final int FOCUSABLES_ALL = 0x00000000;
1062
1063    /**
1064     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1065     * should add only Views focusable in touch mode.
1066     */
1067    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1068
1069    /** @hide */
1070    @IntDef({
1071            FOCUS_BACKWARD,
1072            FOCUS_FORWARD,
1073            FOCUS_LEFT,
1074            FOCUS_UP,
1075            FOCUS_RIGHT,
1076            FOCUS_DOWN
1077    })
1078    @Retention(RetentionPolicy.SOURCE)
1079    public @interface FocusDirection {}
1080
1081    /** @hide */
1082    @IntDef({
1083            FOCUS_LEFT,
1084            FOCUS_UP,
1085            FOCUS_RIGHT,
1086            FOCUS_DOWN
1087    })
1088    @Retention(RetentionPolicy.SOURCE)
1089    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1090
1091    /**
1092     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1093     * item.
1094     */
1095    public static final int FOCUS_BACKWARD = 0x00000001;
1096
1097    /**
1098     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1099     * item.
1100     */
1101    public static final int FOCUS_FORWARD = 0x00000002;
1102
1103    /**
1104     * Use with {@link #focusSearch(int)}. Move focus to the left.
1105     */
1106    public static final int FOCUS_LEFT = 0x00000011;
1107
1108    /**
1109     * Use with {@link #focusSearch(int)}. Move focus up.
1110     */
1111    public static final int FOCUS_UP = 0x00000021;
1112
1113    /**
1114     * Use with {@link #focusSearch(int)}. Move focus to the right.
1115     */
1116    public static final int FOCUS_RIGHT = 0x00000042;
1117
1118    /**
1119     * Use with {@link #focusSearch(int)}. Move focus down.
1120     */
1121    public static final int FOCUS_DOWN = 0x00000082;
1122
1123    /**
1124     * Bits of {@link #getMeasuredWidthAndState()} and
1125     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1126     */
1127    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1128
1129    /**
1130     * Bits of {@link #getMeasuredWidthAndState()} and
1131     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1132     */
1133    public static final int MEASURED_STATE_MASK = 0xff000000;
1134
1135    /**
1136     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1137     * for functions that combine both width and height into a single int,
1138     * such as {@link #getMeasuredState()} and the childState argument of
1139     * {@link #resolveSizeAndState(int, int, int)}.
1140     */
1141    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1142
1143    /**
1144     * Bit of {@link #getMeasuredWidthAndState()} and
1145     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1146     * is smaller that the space the view would like to have.
1147     */
1148    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1149
1150    /**
1151     * Base View state sets
1152     */
1153    // Singles
1154    /**
1155     * Indicates the view has no states set. States are used with
1156     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1157     * view depending on its state.
1158     *
1159     * @see android.graphics.drawable.Drawable
1160     * @see #getDrawableState()
1161     */
1162    protected static final int[] EMPTY_STATE_SET;
1163    /**
1164     * Indicates the view is enabled. States are used with
1165     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1166     * view depending on its state.
1167     *
1168     * @see android.graphics.drawable.Drawable
1169     * @see #getDrawableState()
1170     */
1171    protected static final int[] ENABLED_STATE_SET;
1172    /**
1173     * Indicates the view is focused. States are used with
1174     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1175     * view depending on its state.
1176     *
1177     * @see android.graphics.drawable.Drawable
1178     * @see #getDrawableState()
1179     */
1180    protected static final int[] FOCUSED_STATE_SET;
1181    /**
1182     * Indicates the view is selected. States are used with
1183     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1184     * view depending on its state.
1185     *
1186     * @see android.graphics.drawable.Drawable
1187     * @see #getDrawableState()
1188     */
1189    protected static final int[] SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is pressed. States are used with
1192     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1193     * view depending on its state.
1194     *
1195     * @see android.graphics.drawable.Drawable
1196     * @see #getDrawableState()
1197     */
1198    protected static final int[] PRESSED_STATE_SET;
1199    /**
1200     * Indicates the view's window has focus. States are used with
1201     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1202     * view depending on its state.
1203     *
1204     * @see android.graphics.drawable.Drawable
1205     * @see #getDrawableState()
1206     */
1207    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1208    // Doubles
1209    /**
1210     * Indicates the view is enabled and has the focus.
1211     *
1212     * @see #ENABLED_STATE_SET
1213     * @see #FOCUSED_STATE_SET
1214     */
1215    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1216    /**
1217     * Indicates the view is enabled and selected.
1218     *
1219     * @see #ENABLED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     */
1222    protected static final int[] ENABLED_SELECTED_STATE_SET;
1223    /**
1224     * Indicates the view is enabled and that its window has focus.
1225     *
1226     * @see #ENABLED_STATE_SET
1227     * @see #WINDOW_FOCUSED_STATE_SET
1228     */
1229    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is focused and selected.
1232     *
1233     * @see #FOCUSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     */
1236    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1237    /**
1238     * Indicates the view has the focus and that its window has the focus.
1239     *
1240     * @see #FOCUSED_STATE_SET
1241     * @see #WINDOW_FOCUSED_STATE_SET
1242     */
1243    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1244    /**
1245     * Indicates the view is selected and that its window has the focus.
1246     *
1247     * @see #SELECTED_STATE_SET
1248     * @see #WINDOW_FOCUSED_STATE_SET
1249     */
1250    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1251    // Triples
1252    /**
1253     * Indicates the view is enabled, focused and selected.
1254     *
1255     * @see #ENABLED_STATE_SET
1256     * @see #FOCUSED_STATE_SET
1257     * @see #SELECTED_STATE_SET
1258     */
1259    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1260    /**
1261     * Indicates the view is enabled, focused and its window has the focus.
1262     *
1263     * @see #ENABLED_STATE_SET
1264     * @see #FOCUSED_STATE_SET
1265     * @see #WINDOW_FOCUSED_STATE_SET
1266     */
1267    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1268    /**
1269     * Indicates the view is enabled, selected and its window has the focus.
1270     *
1271     * @see #ENABLED_STATE_SET
1272     * @see #SELECTED_STATE_SET
1273     * @see #WINDOW_FOCUSED_STATE_SET
1274     */
1275    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1276    /**
1277     * Indicates the view is focused, selected and its window has the focus.
1278     *
1279     * @see #FOCUSED_STATE_SET
1280     * @see #SELECTED_STATE_SET
1281     * @see #WINDOW_FOCUSED_STATE_SET
1282     */
1283    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1284    /**
1285     * Indicates the view is enabled, focused, selected and its window
1286     * has the focus.
1287     *
1288     * @see #ENABLED_STATE_SET
1289     * @see #FOCUSED_STATE_SET
1290     * @see #SELECTED_STATE_SET
1291     * @see #WINDOW_FOCUSED_STATE_SET
1292     */
1293    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1294    /**
1295     * Indicates the view is pressed and its window has the focus.
1296     *
1297     * @see #PRESSED_STATE_SET
1298     * @see #WINDOW_FOCUSED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed and selected.
1303     *
1304     * @see #PRESSED_STATE_SET
1305     * @see #SELECTED_STATE_SET
1306     */
1307    protected static final int[] PRESSED_SELECTED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed, selected and its window has the focus.
1310     *
1311     * @see #PRESSED_STATE_SET
1312     * @see #SELECTED_STATE_SET
1313     * @see #WINDOW_FOCUSED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed and focused.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #FOCUSED_STATE_SET
1321     */
1322    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1323    /**
1324     * Indicates the view is pressed, focused and its window has the focus.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #FOCUSED_STATE_SET
1328     * @see #WINDOW_FOCUSED_STATE_SET
1329     */
1330    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1331    /**
1332     * Indicates the view is pressed, focused and selected.
1333     *
1334     * @see #PRESSED_STATE_SET
1335     * @see #SELECTED_STATE_SET
1336     * @see #FOCUSED_STATE_SET
1337     */
1338    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1339    /**
1340     * Indicates the view is pressed, focused, selected and its window has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #FOCUSED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1348    /**
1349     * Indicates the view is pressed and enabled.
1350     *
1351     * @see #PRESSED_STATE_SET
1352     * @see #ENABLED_STATE_SET
1353     */
1354    protected static final int[] PRESSED_ENABLED_STATE_SET;
1355    /**
1356     * Indicates the view is pressed, enabled and its window has the focus.
1357     *
1358     * @see #PRESSED_STATE_SET
1359     * @see #ENABLED_STATE_SET
1360     * @see #WINDOW_FOCUSED_STATE_SET
1361     */
1362    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1363    /**
1364     * Indicates the view is pressed, enabled and selected.
1365     *
1366     * @see #PRESSED_STATE_SET
1367     * @see #ENABLED_STATE_SET
1368     * @see #SELECTED_STATE_SET
1369     */
1370    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1371    /**
1372     * Indicates the view is pressed, enabled, selected and its window has the
1373     * focus.
1374     *
1375     * @see #PRESSED_STATE_SET
1376     * @see #ENABLED_STATE_SET
1377     * @see #SELECTED_STATE_SET
1378     * @see #WINDOW_FOCUSED_STATE_SET
1379     */
1380    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1381    /**
1382     * Indicates the view is pressed, enabled and focused.
1383     *
1384     * @see #PRESSED_STATE_SET
1385     * @see #ENABLED_STATE_SET
1386     * @see #FOCUSED_STATE_SET
1387     */
1388    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1389    /**
1390     * Indicates the view is pressed, enabled, focused and its window has the
1391     * focus.
1392     *
1393     * @see #PRESSED_STATE_SET
1394     * @see #ENABLED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     * @see #WINDOW_FOCUSED_STATE_SET
1397     */
1398    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1399    /**
1400     * Indicates the view is pressed, enabled, focused and selected.
1401     *
1402     * @see #PRESSED_STATE_SET
1403     * @see #ENABLED_STATE_SET
1404     * @see #SELECTED_STATE_SET
1405     * @see #FOCUSED_STATE_SET
1406     */
1407    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1408    /**
1409     * Indicates the view is pressed, enabled, focused, selected and its window
1410     * has the focus.
1411     *
1412     * @see #PRESSED_STATE_SET
1413     * @see #ENABLED_STATE_SET
1414     * @see #SELECTED_STATE_SET
1415     * @see #FOCUSED_STATE_SET
1416     * @see #WINDOW_FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1419
1420    /**
1421     * The order here is very important to {@link #getDrawableState()}
1422     */
1423    private static final int[][] VIEW_STATE_SETS;
1424
1425    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1426    static final int VIEW_STATE_SELECTED = 1 << 1;
1427    static final int VIEW_STATE_FOCUSED = 1 << 2;
1428    static final int VIEW_STATE_ENABLED = 1 << 3;
1429    static final int VIEW_STATE_PRESSED = 1 << 4;
1430    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1431    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1432    static final int VIEW_STATE_HOVERED = 1 << 7;
1433    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1434    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1435
1436    static final int[] VIEW_STATE_IDS = new int[] {
1437        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1438        R.attr.state_selected,          VIEW_STATE_SELECTED,
1439        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1440        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1441        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1442        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1443        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1444        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1445        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1446        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1447    };
1448
1449    static {
1450        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1451            throw new IllegalStateException(
1452                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1453        }
1454        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1455        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1456            int viewState = R.styleable.ViewDrawableStates[i];
1457            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1458                if (VIEW_STATE_IDS[j] == viewState) {
1459                    orderedIds[i * 2] = viewState;
1460                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1461                }
1462            }
1463        }
1464        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1465        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1466        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1467            int numBits = Integer.bitCount(i);
1468            int[] set = new int[numBits];
1469            int pos = 0;
1470            for (int j = 0; j < orderedIds.length; j += 2) {
1471                if ((i & orderedIds[j+1]) != 0) {
1472                    set[pos++] = orderedIds[j];
1473                }
1474            }
1475            VIEW_STATE_SETS[i] = set;
1476        }
1477
1478        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1479        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1480        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1481        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1482                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1483        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1484        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1485                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1486        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1488        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1490                | VIEW_STATE_FOCUSED];
1491        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1492        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1494        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1495                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1496        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1498                | VIEW_STATE_ENABLED];
1499        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1501        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1503                | VIEW_STATE_ENABLED];
1504        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1505                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1506                | VIEW_STATE_ENABLED];
1507        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1508                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1509                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1510
1511        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1512        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1514        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1515                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1516        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1518                | VIEW_STATE_PRESSED];
1519        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1520                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1521        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1523                | VIEW_STATE_PRESSED];
1524        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1525                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1526                | VIEW_STATE_PRESSED];
1527        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1528                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1529                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1530        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1532        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1533                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1534                | VIEW_STATE_PRESSED];
1535        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1537                | VIEW_STATE_PRESSED];
1538        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1539                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1540                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1541        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1543                | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1546                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1547        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1549                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1552                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1553                | VIEW_STATE_PRESSED];
1554    }
1555
1556    /**
1557     * Accessibility event types that are dispatched for text population.
1558     */
1559    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1560            AccessibilityEvent.TYPE_VIEW_CLICKED
1561            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1562            | AccessibilityEvent.TYPE_VIEW_SELECTED
1563            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1564            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1565            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1566            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1567            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1568            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1569            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1570            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1571
1572    /**
1573     * Temporary Rect currently for use in setBackground().  This will probably
1574     * be extended in the future to hold our own class with more than just
1575     * a Rect. :)
1576     */
1577    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1578
1579    /**
1580     * Map used to store views' tags.
1581     */
1582    private SparseArray<Object> mKeyedTags;
1583
1584    /**
1585     * The next available accessibility id.
1586     */
1587    private static int sNextAccessibilityViewId;
1588
1589    /**
1590     * The animation currently associated with this view.
1591     * @hide
1592     */
1593    protected Animation mCurrentAnimation = null;
1594
1595    /**
1596     * Width as measured during measure pass.
1597     * {@hide}
1598     */
1599    @ViewDebug.ExportedProperty(category = "measurement")
1600    int mMeasuredWidth;
1601
1602    /**
1603     * Height as measured during measure pass.
1604     * {@hide}
1605     */
1606    @ViewDebug.ExportedProperty(category = "measurement")
1607    int mMeasuredHeight;
1608
1609    /**
1610     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1611     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1612     * its display list. This flag, used only when hw accelerated, allows us to clear the
1613     * flag while retaining this information until it's needed (at getDisplayList() time and
1614     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1615     *
1616     * {@hide}
1617     */
1618    boolean mRecreateDisplayList = false;
1619
1620    /**
1621     * The view's identifier.
1622     * {@hide}
1623     *
1624     * @see #setId(int)
1625     * @see #getId()
1626     */
1627    @ViewDebug.ExportedProperty(resolveId = true)
1628    int mID = NO_ID;
1629
1630    /**
1631     * The stable ID of this view for accessibility purposes.
1632     */
1633    int mAccessibilityViewId = NO_ID;
1634
1635    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1636
1637    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1638
1639    /**
1640     * The view's tag.
1641     * {@hide}
1642     *
1643     * @see #setTag(Object)
1644     * @see #getTag()
1645     */
1646    protected Object mTag;
1647
1648    // for mPrivateFlags:
1649    /** {@hide} */
1650    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1651    /** {@hide} */
1652    static final int PFLAG_FOCUSED                     = 0x00000002;
1653    /** {@hide} */
1654    static final int PFLAG_SELECTED                    = 0x00000004;
1655    /** {@hide} */
1656    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1657    /** {@hide} */
1658    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1659    /** {@hide} */
1660    static final int PFLAG_DRAWN                       = 0x00000020;
1661    /**
1662     * When this flag is set, this view is running an animation on behalf of its
1663     * children and should therefore not cancel invalidate requests, even if they
1664     * lie outside of this view's bounds.
1665     *
1666     * {@hide}
1667     */
1668    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1669    /** {@hide} */
1670    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1671    /** {@hide} */
1672    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1673    /** {@hide} */
1674    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1675    /** {@hide} */
1676    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1677    /** {@hide} */
1678    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1679    /** {@hide} */
1680    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1681    /** {@hide} */
1682    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1683
1684    private static final int PFLAG_PRESSED             = 0x00004000;
1685
1686    /** {@hide} */
1687    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1688    /**
1689     * Flag used to indicate that this view should be drawn once more (and only once
1690     * more) after its animation has completed.
1691     * {@hide}
1692     */
1693    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1694
1695    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1696
1697    /**
1698     * Indicates that the View returned true when onSetAlpha() was called and that
1699     * the alpha must be restored.
1700     * {@hide}
1701     */
1702    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1703
1704    /**
1705     * Set by {@link #setScrollContainer(boolean)}.
1706     */
1707    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1708
1709    /**
1710     * Set by {@link #setScrollContainer(boolean)}.
1711     */
1712    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1713
1714    /**
1715     * View flag indicating whether this view was invalidated (fully or partially.)
1716     *
1717     * @hide
1718     */
1719    static final int PFLAG_DIRTY                       = 0x00200000;
1720
1721    /**
1722     * View flag indicating whether this view was invalidated by an opaque
1723     * invalidate request.
1724     *
1725     * @hide
1726     */
1727    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1728
1729    /**
1730     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1731     *
1732     * @hide
1733     */
1734    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1735
1736    /**
1737     * Indicates whether the background is opaque.
1738     *
1739     * @hide
1740     */
1741    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1742
1743    /**
1744     * Indicates whether the scrollbars are opaque.
1745     *
1746     * @hide
1747     */
1748    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1749
1750    /**
1751     * Indicates whether the view is opaque.
1752     *
1753     * @hide
1754     */
1755    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1756
1757    /**
1758     * Indicates a prepressed state;
1759     * the short time between ACTION_DOWN and recognizing
1760     * a 'real' press. Prepressed is used to recognize quick taps
1761     * even when they are shorter than ViewConfiguration.getTapTimeout().
1762     *
1763     * @hide
1764     */
1765    private static final int PFLAG_PREPRESSED          = 0x02000000;
1766
1767    /**
1768     * Indicates whether the view is temporarily detached.
1769     *
1770     * @hide
1771     */
1772    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1773
1774    /**
1775     * Indicates that we should awaken scroll bars once attached
1776     *
1777     * @hide
1778     */
1779    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1780
1781    /**
1782     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1783     * @hide
1784     */
1785    private static final int PFLAG_HOVERED             = 0x10000000;
1786
1787    /**
1788     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1789     * for transform operations
1790     *
1791     * @hide
1792     */
1793    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1794
1795    /** {@hide} */
1796    static final int PFLAG_ACTIVATED                   = 0x40000000;
1797
1798    /**
1799     * Indicates that this view was specifically invalidated, not just dirtied because some
1800     * child view was invalidated. The flag is used to determine when we need to recreate
1801     * a view's display list (as opposed to just returning a reference to its existing
1802     * display list).
1803     *
1804     * @hide
1805     */
1806    static final int PFLAG_INVALIDATED                 = 0x80000000;
1807
1808    /**
1809     * Masks for mPrivateFlags2, as generated by dumpFlags():
1810     *
1811     * |-------|-------|-------|-------|
1812     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1813     *                                1  PFLAG2_DRAG_HOVERED
1814     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1815     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1816     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1817     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1818     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1819     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1820     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1821     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1822     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1823     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1824     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1825     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1826     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1827     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1828     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1829     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1830     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1831     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1832     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1833     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1834     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1835     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1836     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1837     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1838     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1839     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1840     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1841     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1842     *    1                              PFLAG2_PADDING_RESOLVED
1843     *   1                               PFLAG2_DRAWABLE_RESOLVED
1844     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1845     * |-------|-------|-------|-------|
1846     */
1847
1848    /**
1849     * Indicates that this view has reported that it can accept the current drag's content.
1850     * Cleared when the drag operation concludes.
1851     * @hide
1852     */
1853    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1854
1855    /**
1856     * Indicates that this view is currently directly under the drag location in a
1857     * drag-and-drop operation involving content that it can accept.  Cleared when
1858     * the drag exits the view, or when the drag operation concludes.
1859     * @hide
1860     */
1861    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1862
1863    /** @hide */
1864    @IntDef({
1865        LAYOUT_DIRECTION_LTR,
1866        LAYOUT_DIRECTION_RTL,
1867        LAYOUT_DIRECTION_INHERIT,
1868        LAYOUT_DIRECTION_LOCALE
1869    })
1870    @Retention(RetentionPolicy.SOURCE)
1871    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1872    public @interface LayoutDir {}
1873
1874    /** @hide */
1875    @IntDef({
1876        LAYOUT_DIRECTION_LTR,
1877        LAYOUT_DIRECTION_RTL
1878    })
1879    @Retention(RetentionPolicy.SOURCE)
1880    public @interface ResolvedLayoutDir {}
1881
1882    /**
1883     * Horizontal layout direction of this view is from Left to Right.
1884     * Use with {@link #setLayoutDirection}.
1885     */
1886    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1887
1888    /**
1889     * Horizontal layout direction of this view is from Right to Left.
1890     * Use with {@link #setLayoutDirection}.
1891     */
1892    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1893
1894    /**
1895     * Horizontal layout direction of this view is inherited from its parent.
1896     * Use with {@link #setLayoutDirection}.
1897     */
1898    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1899
1900    /**
1901     * Horizontal layout direction of this view is from deduced from the default language
1902     * script for the locale. Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1905
1906    /**
1907     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1908     * @hide
1909     */
1910    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1911
1912    /**
1913     * Mask for use with private flags indicating bits used for horizontal layout direction.
1914     * @hide
1915     */
1916    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1917
1918    /**
1919     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1920     * right-to-left direction.
1921     * @hide
1922     */
1923    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1924
1925    /**
1926     * Indicates whether the view horizontal layout direction has been resolved.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1933     * @hide
1934     */
1935    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1936            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1937
1938    /*
1939     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1940     * flag value.
1941     * @hide
1942     */
1943    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1944            LAYOUT_DIRECTION_LTR,
1945            LAYOUT_DIRECTION_RTL,
1946            LAYOUT_DIRECTION_INHERIT,
1947            LAYOUT_DIRECTION_LOCALE
1948    };
1949
1950    /**
1951     * Default horizontal layout direction.
1952     */
1953    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1954
1955    /**
1956     * Default horizontal layout direction.
1957     * @hide
1958     */
1959    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1960
1961    /**
1962     * Text direction is inherited thru {@link ViewGroup}
1963     */
1964    public static final int TEXT_DIRECTION_INHERIT = 0;
1965
1966    /**
1967     * Text direction is using "first strong algorithm". The first strong directional character
1968     * determines the paragraph direction. If there is no strong directional character, the
1969     * paragraph direction is the view's resolved layout direction.
1970     */
1971    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1972
1973    /**
1974     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1975     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1976     * If there are neither, the paragraph direction is the view's resolved layout direction.
1977     */
1978    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1979
1980    /**
1981     * Text direction is forced to LTR.
1982     */
1983    public static final int TEXT_DIRECTION_LTR = 3;
1984
1985    /**
1986     * Text direction is forced to RTL.
1987     */
1988    public static final int TEXT_DIRECTION_RTL = 4;
1989
1990    /**
1991     * Text direction is coming from the system Locale.
1992     */
1993    public static final int TEXT_DIRECTION_LOCALE = 5;
1994
1995    /**
1996     * Default text direction is inherited
1997     */
1998    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1999
2000    /**
2001     * Default resolved text direction
2002     * @hide
2003     */
2004    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2005
2006    /**
2007     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2008     * @hide
2009     */
2010    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2011
2012    /**
2013     * Mask for use with private flags indicating bits used for text direction.
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2017            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2018
2019    /**
2020     * Array of text direction flags for mapping attribute "textDirection" to correct
2021     * flag value.
2022     * @hide
2023     */
2024    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2025            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2026            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2027            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2028            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2029            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2030            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2031    };
2032
2033    /**
2034     * Indicates whether the view text direction has been resolved.
2035     * @hide
2036     */
2037    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2038            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2039
2040    /**
2041     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2042     * @hide
2043     */
2044    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2045
2046    /**
2047     * Mask for use with private flags indicating bits used for resolved text direction.
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2051            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2052
2053    /**
2054     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2055     * @hide
2056     */
2057    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2058            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2059
2060    /** @hide */
2061    @IntDef({
2062        TEXT_ALIGNMENT_INHERIT,
2063        TEXT_ALIGNMENT_GRAVITY,
2064        TEXT_ALIGNMENT_CENTER,
2065        TEXT_ALIGNMENT_TEXT_START,
2066        TEXT_ALIGNMENT_TEXT_END,
2067        TEXT_ALIGNMENT_VIEW_START,
2068        TEXT_ALIGNMENT_VIEW_END
2069    })
2070    @Retention(RetentionPolicy.SOURCE)
2071    public @interface TextAlignment {}
2072
2073    /**
2074     * Default text alignment. The text alignment of this View is inherited from its parent.
2075     * Use with {@link #setTextAlignment(int)}
2076     */
2077    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2078
2079    /**
2080     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2081     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2082     *
2083     * Use with {@link #setTextAlignment(int)}
2084     */
2085    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2086
2087    /**
2088     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2089     *
2090     * Use with {@link #setTextAlignment(int)}
2091     */
2092    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2093
2094    /**
2095     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2096     *
2097     * Use with {@link #setTextAlignment(int)}
2098     */
2099    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2100
2101    /**
2102     * Center the paragraph, e.g. ALIGN_CENTER.
2103     *
2104     * Use with {@link #setTextAlignment(int)}
2105     */
2106    public static final int TEXT_ALIGNMENT_CENTER = 4;
2107
2108    /**
2109     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2110     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2111     *
2112     * Use with {@link #setTextAlignment(int)}
2113     */
2114    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2115
2116    /**
2117     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2118     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2119     *
2120     * Use with {@link #setTextAlignment(int)}
2121     */
2122    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2123
2124    /**
2125     * Default text alignment is inherited
2126     */
2127    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2128
2129    /**
2130     * Default resolved text alignment
2131     * @hide
2132     */
2133    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2134
2135    /**
2136      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2137      * @hide
2138      */
2139    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2140
2141    /**
2142      * Mask for use with private flags indicating bits used for text alignment.
2143      * @hide
2144      */
2145    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2146
2147    /**
2148     * Array of text direction flags for mapping attribute "textAlignment" to correct
2149     * flag value.
2150     * @hide
2151     */
2152    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2153            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2154            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2155            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2156            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2157            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2158            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2159            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2160    };
2161
2162    /**
2163     * Indicates whether the view text alignment has been resolved.
2164     * @hide
2165     */
2166    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2167
2168    /**
2169     * Bit shift to get the resolved text alignment.
2170     * @hide
2171     */
2172    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2173
2174    /**
2175     * Mask for use with private flags indicating bits used for text alignment.
2176     * @hide
2177     */
2178    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2179            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2180
2181    /**
2182     * Indicates whether if the view text alignment has been resolved to gravity
2183     */
2184    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2185            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2186
2187    // Accessiblity constants for mPrivateFlags2
2188
2189    /**
2190     * Shift for the bits in {@link #mPrivateFlags2} related to the
2191     * "importantForAccessibility" attribute.
2192     */
2193    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2194
2195    /**
2196     * Automatically determine whether a view is important for accessibility.
2197     */
2198    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2199
2200    /**
2201     * The view is important for accessibility.
2202     */
2203    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2204
2205    /**
2206     * The view is not important for accessibility.
2207     */
2208    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2209
2210    /**
2211     * The view is not important for accessibility, nor are any of its
2212     * descendant views.
2213     */
2214    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2215
2216    /**
2217     * The default whether the view is important for accessibility.
2218     */
2219    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2220
2221    /**
2222     * Mask for obtainig the bits which specify how to determine
2223     * whether a view is important for accessibility.
2224     */
2225    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2226        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2227        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2228        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2229
2230    /**
2231     * Shift for the bits in {@link #mPrivateFlags2} related to the
2232     * "accessibilityLiveRegion" attribute.
2233     */
2234    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2235
2236    /**
2237     * Live region mode specifying that accessibility services should not
2238     * automatically announce changes to this view. This is the default live
2239     * region mode for most views.
2240     * <p>
2241     * Use with {@link #setAccessibilityLiveRegion(int)}.
2242     */
2243    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2244
2245    /**
2246     * Live region mode specifying that accessibility services should announce
2247     * changes to this view.
2248     * <p>
2249     * Use with {@link #setAccessibilityLiveRegion(int)}.
2250     */
2251    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2252
2253    /**
2254     * Live region mode specifying that accessibility services should interrupt
2255     * ongoing speech to immediately announce changes to this view.
2256     * <p>
2257     * Use with {@link #setAccessibilityLiveRegion(int)}.
2258     */
2259    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2260
2261    /**
2262     * The default whether the view is important for accessibility.
2263     */
2264    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2265
2266    /**
2267     * Mask for obtaining the bits which specify a view's accessibility live
2268     * region mode.
2269     */
2270    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2271            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2272            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2273
2274    /**
2275     * Flag indicating whether a view has accessibility focus.
2276     */
2277    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2278
2279    /**
2280     * Flag whether the accessibility state of the subtree rooted at this view changed.
2281     */
2282    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2283
2284    /**
2285     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2286     * is used to check whether later changes to the view's transform should invalidate the
2287     * view to force the quickReject test to run again.
2288     */
2289    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2290
2291    /**
2292     * Flag indicating that start/end padding has been resolved into left/right padding
2293     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2294     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2295     * during measurement. In some special cases this is required such as when an adapter-based
2296     * view measures prospective children without attaching them to a window.
2297     */
2298    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2299
2300    /**
2301     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2302     */
2303    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2304
2305    /**
2306     * Indicates that the view is tracking some sort of transient state
2307     * that the app should not need to be aware of, but that the framework
2308     * should take special care to preserve.
2309     */
2310    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2311
2312    /**
2313     * Group of bits indicating that RTL properties resolution is done.
2314     */
2315    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2316            PFLAG2_TEXT_DIRECTION_RESOLVED |
2317            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2318            PFLAG2_PADDING_RESOLVED |
2319            PFLAG2_DRAWABLE_RESOLVED;
2320
2321    // There are a couple of flags left in mPrivateFlags2
2322
2323    /* End of masks for mPrivateFlags2 */
2324
2325    /* Masks for mPrivateFlags3 */
2326
2327    /**
2328     * Flag indicating that view has a transform animation set on it. This is used to track whether
2329     * an animation is cleared between successive frames, in order to tell the associated
2330     * DisplayList to clear its animation matrix.
2331     */
2332    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2333
2334    /**
2335     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2336     * animation is cleared between successive frames, in order to tell the associated
2337     * DisplayList to restore its alpha value.
2338     */
2339    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2340
2341    /**
2342     * Flag indicating that the view has been through at least one layout since it
2343     * was last attached to a window.
2344     */
2345    static final int PFLAG3_IS_LAID_OUT = 0x4;
2346
2347    /**
2348     * Flag indicating that a call to measure() was skipped and should be done
2349     * instead when layout() is invoked.
2350     */
2351    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2352
2353    /**
2354     * Flag indicating that an overridden method correctly  called down to
2355     * the superclass implementation as required by the API spec.
2356     */
2357    static final int PFLAG3_CALLED_SUPER = 0x10;
2358
2359
2360    /* End of masks for mPrivateFlags3 */
2361
2362    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2363
2364    /**
2365     * Always allow a user to over-scroll this view, provided it is a
2366     * view that can scroll.
2367     *
2368     * @see #getOverScrollMode()
2369     * @see #setOverScrollMode(int)
2370     */
2371    public static final int OVER_SCROLL_ALWAYS = 0;
2372
2373    /**
2374     * Allow a user to over-scroll this view only if the content is large
2375     * enough to meaningfully scroll, provided it is a view that can scroll.
2376     *
2377     * @see #getOverScrollMode()
2378     * @see #setOverScrollMode(int)
2379     */
2380    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2381
2382    /**
2383     * Never allow a user to over-scroll this view.
2384     *
2385     * @see #getOverScrollMode()
2386     * @see #setOverScrollMode(int)
2387     */
2388    public static final int OVER_SCROLL_NEVER = 2;
2389
2390    /**
2391     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2392     * requested the system UI (status bar) to be visible (the default).
2393     *
2394     * @see #setSystemUiVisibility(int)
2395     */
2396    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2397
2398    /**
2399     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2400     * system UI to enter an unobtrusive "low profile" mode.
2401     *
2402     * <p>This is for use in games, book readers, video players, or any other
2403     * "immersive" application where the usual system chrome is deemed too distracting.
2404     *
2405     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2406     *
2407     * @see #setSystemUiVisibility(int)
2408     */
2409    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2410
2411    /**
2412     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2413     * system navigation be temporarily hidden.
2414     *
2415     * <p>This is an even less obtrusive state than that called for by
2416     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2417     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2418     * those to disappear. This is useful (in conjunction with the
2419     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2420     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2421     * window flags) for displaying content using every last pixel on the display.
2422     *
2423     * <p>There is a limitation: because navigation controls are so important, the least user
2424     * interaction will cause them to reappear immediately.  When this happens, both
2425     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2426     * so that both elements reappear at the same time.
2427     *
2428     * @see #setSystemUiVisibility(int)
2429     */
2430    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2431
2432    /**
2433     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2434     * into the normal fullscreen mode so that its content can take over the screen
2435     * while still allowing the user to interact with the application.
2436     *
2437     * <p>This has the same visual effect as
2438     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2439     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2440     * meaning that non-critical screen decorations (such as the status bar) will be
2441     * hidden while the user is in the View's window, focusing the experience on
2442     * that content.  Unlike the window flag, if you are using ActionBar in
2443     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2444     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2445     * hide the action bar.
2446     *
2447     * <p>This approach to going fullscreen is best used over the window flag when
2448     * it is a transient state -- that is, the application does this at certain
2449     * points in its user interaction where it wants to allow the user to focus
2450     * on content, but not as a continuous state.  For situations where the application
2451     * would like to simply stay full screen the entire time (such as a game that
2452     * wants to take over the screen), the
2453     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2454     * is usually a better approach.  The state set here will be removed by the system
2455     * in various situations (such as the user moving to another application) like
2456     * the other system UI states.
2457     *
2458     * <p>When using this flag, the application should provide some easy facility
2459     * for the user to go out of it.  A common example would be in an e-book
2460     * reader, where tapping on the screen brings back whatever screen and UI
2461     * decorations that had been hidden while the user was immersed in reading
2462     * the book.
2463     *
2464     * @see #setSystemUiVisibility(int)
2465     */
2466    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2467
2468    /**
2469     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2470     * flags, we would like a stable view of the content insets given to
2471     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2472     * will always represent the worst case that the application can expect
2473     * as a continuous state.  In the stock Android UI this is the space for
2474     * the system bar, nav bar, and status bar, but not more transient elements
2475     * such as an input method.
2476     *
2477     * The stable layout your UI sees is based on the system UI modes you can
2478     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2479     * then you will get a stable layout for changes of the
2480     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2481     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2482     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2483     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2484     * with a stable layout.  (Note that you should avoid using
2485     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2486     *
2487     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2488     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2489     * then a hidden status bar will be considered a "stable" state for purposes
2490     * here.  This allows your UI to continually hide the status bar, while still
2491     * using the system UI flags to hide the action bar while still retaining
2492     * a stable layout.  Note that changing the window fullscreen flag will never
2493     * provide a stable layout for a clean transition.
2494     *
2495     * <p>If you are using ActionBar in
2496     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2497     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2498     * insets it adds to those given to the application.
2499     */
2500    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2501
2502    /**
2503     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2504     * to be layed out as if it has requested
2505     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2506     * allows it to avoid artifacts when switching in and out of that mode, at
2507     * the expense that some of its user interface may be covered by screen
2508     * decorations when they are shown.  You can perform layout of your inner
2509     * UI elements to account for the navigation system UI through the
2510     * {@link #fitSystemWindows(Rect)} method.
2511     */
2512    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2513
2514    /**
2515     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2516     * to be layed out as if it has requested
2517     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2518     * allows it to avoid artifacts when switching in and out of that mode, at
2519     * the expense that some of its user interface may be covered by screen
2520     * decorations when they are shown.  You can perform layout of your inner
2521     * UI elements to account for non-fullscreen system UI through the
2522     * {@link #fitSystemWindows(Rect)} method.
2523     */
2524    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2525
2526    /**
2527     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2528     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2529     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2530     * user interaction.
2531     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2532     * has an effect when used in combination with that flag.</p>
2533     */
2534    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2535
2536    /**
2537     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2538     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2539     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2540     * experience while also hiding the system bars.  If this flag is not set,
2541     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2542     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2543     * if the user swipes from the top of the screen.
2544     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2545     * system gestures, such as swiping from the top of the screen.  These transient system bars
2546     * will overlay app’s content, may have some degree of transparency, and will automatically
2547     * hide after a short timeout.
2548     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2549     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2550     * with one or both of those flags.</p>
2551     */
2552    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2553
2554    /**
2555     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2556     */
2557    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2558
2559    /**
2560     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2561     */
2562    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2563
2564    /**
2565     * @hide
2566     *
2567     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2568     * out of the public fields to keep the undefined bits out of the developer's way.
2569     *
2570     * Flag to make the status bar not expandable.  Unless you also
2571     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2572     */
2573    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2574
2575    /**
2576     * @hide
2577     *
2578     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2579     * out of the public fields to keep the undefined bits out of the developer's way.
2580     *
2581     * Flag to hide notification icons and scrolling ticker text.
2582     */
2583    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2584
2585    /**
2586     * @hide
2587     *
2588     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2589     * out of the public fields to keep the undefined bits out of the developer's way.
2590     *
2591     * Flag to disable incoming notification alerts.  This will not block
2592     * icons, but it will block sound, vibrating and other visual or aural notifications.
2593     */
2594    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2595
2596    /**
2597     * @hide
2598     *
2599     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2600     * out of the public fields to keep the undefined bits out of the developer's way.
2601     *
2602     * Flag to hide only the scrolling ticker.  Note that
2603     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2604     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2605     */
2606    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2607
2608    /**
2609     * @hide
2610     *
2611     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2612     * out of the public fields to keep the undefined bits out of the developer's way.
2613     *
2614     * Flag to hide the center system info area.
2615     */
2616    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2617
2618    /**
2619     * @hide
2620     *
2621     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2622     * out of the public fields to keep the undefined bits out of the developer's way.
2623     *
2624     * Flag to hide only the home button.  Don't use this
2625     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2626     */
2627    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2628
2629    /**
2630     * @hide
2631     *
2632     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2633     * out of the public fields to keep the undefined bits out of the developer's way.
2634     *
2635     * Flag to hide only the back button. Don't use this
2636     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2637     */
2638    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2639
2640    /**
2641     * @hide
2642     *
2643     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2644     * out of the public fields to keep the undefined bits out of the developer's way.
2645     *
2646     * Flag to hide only the clock.  You might use this if your activity has
2647     * its own clock making the status bar's clock redundant.
2648     */
2649    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2650
2651    /**
2652     * @hide
2653     *
2654     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2655     * out of the public fields to keep the undefined bits out of the developer's way.
2656     *
2657     * Flag to hide only the recent apps button. Don't use this
2658     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2659     */
2660    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2661
2662    /**
2663     * @hide
2664     *
2665     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2666     * out of the public fields to keep the undefined bits out of the developer's way.
2667     *
2668     * Flag to disable the global search gesture. Don't use this
2669     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2670     */
2671    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2672
2673    /**
2674     * @hide
2675     *
2676     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2677     * out of the public fields to keep the undefined bits out of the developer's way.
2678     *
2679     * Flag to specify that the status bar is displayed in transient mode.
2680     */
2681    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2682
2683    /**
2684     * @hide
2685     *
2686     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2687     * out of the public fields to keep the undefined bits out of the developer's way.
2688     *
2689     * Flag to specify that the navigation bar is displayed in transient mode.
2690     */
2691    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2692
2693    /**
2694     * @hide
2695     *
2696     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2697     * out of the public fields to keep the undefined bits out of the developer's way.
2698     *
2699     * Flag to specify that the hidden status bar would like to be shown.
2700     */
2701    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2702
2703    /**
2704     * @hide
2705     *
2706     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2707     * out of the public fields to keep the undefined bits out of the developer's way.
2708     *
2709     * Flag to specify that the hidden navigation bar would like to be shown.
2710     */
2711    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2712
2713    /**
2714     * @hide
2715     *
2716     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2717     * out of the public fields to keep the undefined bits out of the developer's way.
2718     *
2719     * Flag to specify that the status bar is displayed in translucent mode.
2720     */
2721    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2722
2723    /**
2724     * @hide
2725     *
2726     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2727     * out of the public fields to keep the undefined bits out of the developer's way.
2728     *
2729     * Flag to specify that the navigation bar is displayed in translucent mode.
2730     */
2731    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2732
2733    /**
2734     * @hide
2735     */
2736    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2737
2738    /**
2739     * These are the system UI flags that can be cleared by events outside
2740     * of an application.  Currently this is just the ability to tap on the
2741     * screen while hiding the navigation bar to have it return.
2742     * @hide
2743     */
2744    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2745            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2746            | SYSTEM_UI_FLAG_FULLSCREEN;
2747
2748    /**
2749     * Flags that can impact the layout in relation to system UI.
2750     */
2751    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2752            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2753            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2754
2755    /** @hide */
2756    @IntDef(flag = true,
2757            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2758    @Retention(RetentionPolicy.SOURCE)
2759    public @interface FindViewFlags {}
2760
2761    /**
2762     * Find views that render the specified text.
2763     *
2764     * @see #findViewsWithText(ArrayList, CharSequence, int)
2765     */
2766    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2767
2768    /**
2769     * Find find views that contain the specified content description.
2770     *
2771     * @see #findViewsWithText(ArrayList, CharSequence, int)
2772     */
2773    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2774
2775    /**
2776     * Find views that contain {@link AccessibilityNodeProvider}. Such
2777     * a View is a root of virtual view hierarchy and may contain the searched
2778     * text. If this flag is set Views with providers are automatically
2779     * added and it is a responsibility of the client to call the APIs of
2780     * the provider to determine whether the virtual tree rooted at this View
2781     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2782     * representing the virtual views with this text.
2783     *
2784     * @see #findViewsWithText(ArrayList, CharSequence, int)
2785     *
2786     * @hide
2787     */
2788    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2789
2790    /**
2791     * The undefined cursor position.
2792     *
2793     * @hide
2794     */
2795    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2796
2797    /**
2798     * Indicates that the screen has changed state and is now off.
2799     *
2800     * @see #onScreenStateChanged(int)
2801     */
2802    public static final int SCREEN_STATE_OFF = 0x0;
2803
2804    /**
2805     * Indicates that the screen has changed state and is now on.
2806     *
2807     * @see #onScreenStateChanged(int)
2808     */
2809    public static final int SCREEN_STATE_ON = 0x1;
2810
2811    /**
2812     * Controls the over-scroll mode for this view.
2813     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2814     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2815     * and {@link #OVER_SCROLL_NEVER}.
2816     */
2817    private int mOverScrollMode;
2818
2819    /**
2820     * The parent this view is attached to.
2821     * {@hide}
2822     *
2823     * @see #getParent()
2824     */
2825    protected ViewParent mParent;
2826
2827    /**
2828     * {@hide}
2829     */
2830    AttachInfo mAttachInfo;
2831
2832    /**
2833     * {@hide}
2834     */
2835    @ViewDebug.ExportedProperty(flagMapping = {
2836        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2837                name = "FORCE_LAYOUT"),
2838        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2839                name = "LAYOUT_REQUIRED"),
2840        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2841            name = "DRAWING_CACHE_INVALID", outputIf = false),
2842        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2843        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2844        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2845        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2846    })
2847    int mPrivateFlags;
2848    int mPrivateFlags2;
2849    int mPrivateFlags3;
2850
2851    /**
2852     * This view's request for the visibility of the status bar.
2853     * @hide
2854     */
2855    @ViewDebug.ExportedProperty(flagMapping = {
2856        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2857                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2858                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2859        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2860                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2861                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2862        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2863                                equals = SYSTEM_UI_FLAG_VISIBLE,
2864                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2865    })
2866    int mSystemUiVisibility;
2867
2868    /**
2869     * Reference count for transient state.
2870     * @see #setHasTransientState(boolean)
2871     */
2872    int mTransientStateCount = 0;
2873
2874    /**
2875     * Count of how many windows this view has been attached to.
2876     */
2877    int mWindowAttachCount;
2878
2879    /**
2880     * The layout parameters associated with this view and used by the parent
2881     * {@link android.view.ViewGroup} to determine how this view should be
2882     * laid out.
2883     * {@hide}
2884     */
2885    protected ViewGroup.LayoutParams mLayoutParams;
2886
2887    /**
2888     * The view flags hold various views states.
2889     * {@hide}
2890     */
2891    @ViewDebug.ExportedProperty
2892    int mViewFlags;
2893
2894    static class TransformationInfo {
2895        /**
2896         * The transform matrix for the View. This transform is calculated internally
2897         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2898         * is used by default. Do *not* use this variable directly; instead call
2899         * getMatrix(), which will automatically recalculate the matrix if necessary
2900         * to get the correct matrix based on the latest rotation and scale properties.
2901         */
2902        private final Matrix mMatrix = new Matrix();
2903
2904        /**
2905         * The transform matrix for the View. This transform is calculated internally
2906         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2907         * is used by default. Do *not* use this variable directly; instead call
2908         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2909         * to get the correct matrix based on the latest rotation and scale properties.
2910         */
2911        private Matrix mInverseMatrix;
2912
2913        /**
2914         * An internal variable that tracks whether we need to recalculate the
2915         * transform matrix, based on whether the rotation or scaleX/Y properties
2916         * have changed since the matrix was last calculated.
2917         */
2918        boolean mMatrixDirty = false;
2919
2920        /**
2921         * An internal variable that tracks whether we need to recalculate the
2922         * transform matrix, based on whether the rotation or scaleX/Y properties
2923         * have changed since the matrix was last calculated.
2924         */
2925        private boolean mInverseMatrixDirty = true;
2926
2927        /**
2928         * A variable that tracks whether we need to recalculate the
2929         * transform matrix, based on whether the rotation or scaleX/Y properties
2930         * have changed since the matrix was last calculated. This variable
2931         * is only valid after a call to updateMatrix() or to a function that
2932         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2933         */
2934        private boolean mMatrixIsIdentity = true;
2935
2936        /**
2937         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2938         */
2939        private Camera mCamera = null;
2940
2941        /**
2942         * This matrix is used when computing the matrix for 3D rotations.
2943         */
2944        private Matrix matrix3D = null;
2945
2946        /**
2947         * These prev values are used to recalculate a centered pivot point when necessary. The
2948         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2949         * set), so thes values are only used then as well.
2950         */
2951        private int mPrevWidth = -1;
2952        private int mPrevHeight = -1;
2953
2954        /**
2955         * The degrees rotation around the vertical axis through the pivot point.
2956         */
2957        @ViewDebug.ExportedProperty
2958        float mRotationY = 0f;
2959
2960        /**
2961         * The degrees rotation around the horizontal axis through the pivot point.
2962         */
2963        @ViewDebug.ExportedProperty
2964        float mRotationX = 0f;
2965
2966        /**
2967         * The degrees rotation around the pivot point.
2968         */
2969        @ViewDebug.ExportedProperty
2970        float mRotation = 0f;
2971
2972        /**
2973         * The amount of translation of the object away from its left property (post-layout).
2974         */
2975        @ViewDebug.ExportedProperty
2976        float mTranslationX = 0f;
2977
2978        /**
2979         * The amount of translation of the object away from its top property (post-layout).
2980         */
2981        @ViewDebug.ExportedProperty
2982        float mTranslationY = 0f;
2983
2984        /**
2985         * The amount of scale in the x direction around the pivot point. A
2986         * value of 1 means no scaling is applied.
2987         */
2988        @ViewDebug.ExportedProperty
2989        float mScaleX = 1f;
2990
2991        /**
2992         * The amount of scale in the y direction around the pivot point. A
2993         * value of 1 means no scaling is applied.
2994         */
2995        @ViewDebug.ExportedProperty
2996        float mScaleY = 1f;
2997
2998        /**
2999         * The x location of the point around which the view is rotated and scaled.
3000         */
3001        @ViewDebug.ExportedProperty
3002        float mPivotX = 0f;
3003
3004        /**
3005         * The y location of the point around which the view is rotated and scaled.
3006         */
3007        @ViewDebug.ExportedProperty
3008        float mPivotY = 0f;
3009
3010        /**
3011         * The opacity of the View. This is a value from 0 to 1, where 0 means
3012         * completely transparent and 1 means completely opaque.
3013         */
3014        @ViewDebug.ExportedProperty
3015        float mAlpha = 1f;
3016
3017        /**
3018         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3019         * property only used by transitions, which is composited with the other alpha
3020         * values to calculate the final visual alpha value.
3021         */
3022        float mTransitionAlpha = 1f;
3023    }
3024
3025    TransformationInfo mTransformationInfo;
3026
3027    /**
3028     * Current clip bounds. to which all drawing of this view are constrained.
3029     */
3030    private Rect mClipBounds = null;
3031
3032    private boolean mLastIsOpaque;
3033
3034    /**
3035     * Convenience value to check for float values that are close enough to zero to be considered
3036     * zero.
3037     */
3038    private static final float NONZERO_EPSILON = .001f;
3039
3040    /**
3041     * The distance in pixels from the left edge of this view's parent
3042     * to the left edge of this view.
3043     * {@hide}
3044     */
3045    @ViewDebug.ExportedProperty(category = "layout")
3046    protected int mLeft;
3047    /**
3048     * The distance in pixels from the left edge of this view's parent
3049     * to the right edge of this view.
3050     * {@hide}
3051     */
3052    @ViewDebug.ExportedProperty(category = "layout")
3053    protected int mRight;
3054    /**
3055     * The distance in pixels from the top edge of this view's parent
3056     * to the top edge of this view.
3057     * {@hide}
3058     */
3059    @ViewDebug.ExportedProperty(category = "layout")
3060    protected int mTop;
3061    /**
3062     * The distance in pixels from the top edge of this view's parent
3063     * to the bottom edge of this view.
3064     * {@hide}
3065     */
3066    @ViewDebug.ExportedProperty(category = "layout")
3067    protected int mBottom;
3068
3069    /**
3070     * The offset, in pixels, by which the content of this view is scrolled
3071     * horizontally.
3072     * {@hide}
3073     */
3074    @ViewDebug.ExportedProperty(category = "scrolling")
3075    protected int mScrollX;
3076    /**
3077     * The offset, in pixels, by which the content of this view is scrolled
3078     * vertically.
3079     * {@hide}
3080     */
3081    @ViewDebug.ExportedProperty(category = "scrolling")
3082    protected int mScrollY;
3083
3084    /**
3085     * The left padding in pixels, that is the distance in pixels between the
3086     * left edge of this view and the left edge of its content.
3087     * {@hide}
3088     */
3089    @ViewDebug.ExportedProperty(category = "padding")
3090    protected int mPaddingLeft = 0;
3091    /**
3092     * The right padding in pixels, that is the distance in pixels between the
3093     * right edge of this view and the right edge of its content.
3094     * {@hide}
3095     */
3096    @ViewDebug.ExportedProperty(category = "padding")
3097    protected int mPaddingRight = 0;
3098    /**
3099     * The top padding in pixels, that is the distance in pixels between the
3100     * top edge of this view and the top edge of its content.
3101     * {@hide}
3102     */
3103    @ViewDebug.ExportedProperty(category = "padding")
3104    protected int mPaddingTop;
3105    /**
3106     * The bottom padding in pixels, that is the distance in pixels between the
3107     * bottom edge of this view and the bottom edge of its content.
3108     * {@hide}
3109     */
3110    @ViewDebug.ExportedProperty(category = "padding")
3111    protected int mPaddingBottom;
3112
3113    /**
3114     * The layout insets in pixels, that is the distance in pixels between the
3115     * visible edges of this view its bounds.
3116     */
3117    private Insets mLayoutInsets;
3118
3119    /**
3120     * Briefly describes the view and is primarily used for accessibility support.
3121     */
3122    private CharSequence mContentDescription;
3123
3124    /**
3125     * Specifies the id of a view for which this view serves as a label for
3126     * accessibility purposes.
3127     */
3128    private int mLabelForId = View.NO_ID;
3129
3130    /**
3131     * Predicate for matching labeled view id with its label for
3132     * accessibility purposes.
3133     */
3134    private MatchLabelForPredicate mMatchLabelForPredicate;
3135
3136    /**
3137     * Predicate for matching a view by its id.
3138     */
3139    private MatchIdPredicate mMatchIdPredicate;
3140
3141    /**
3142     * Cache the paddingRight set by the user to append to the scrollbar's size.
3143     *
3144     * @hide
3145     */
3146    @ViewDebug.ExportedProperty(category = "padding")
3147    protected int mUserPaddingRight;
3148
3149    /**
3150     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3151     *
3152     * @hide
3153     */
3154    @ViewDebug.ExportedProperty(category = "padding")
3155    protected int mUserPaddingBottom;
3156
3157    /**
3158     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3159     *
3160     * @hide
3161     */
3162    @ViewDebug.ExportedProperty(category = "padding")
3163    protected int mUserPaddingLeft;
3164
3165    /**
3166     * Cache the paddingStart set by the user to append to the scrollbar's size.
3167     *
3168     */
3169    @ViewDebug.ExportedProperty(category = "padding")
3170    int mUserPaddingStart;
3171
3172    /**
3173     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3174     *
3175     */
3176    @ViewDebug.ExportedProperty(category = "padding")
3177    int mUserPaddingEnd;
3178
3179    /**
3180     * Cache initial left padding.
3181     *
3182     * @hide
3183     */
3184    int mUserPaddingLeftInitial;
3185
3186    /**
3187     * Cache initial right padding.
3188     *
3189     * @hide
3190     */
3191    int mUserPaddingRightInitial;
3192
3193    /**
3194     * Default undefined padding
3195     */
3196    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3197
3198    /**
3199     * Cache if a left padding has been defined
3200     */
3201    private boolean mLeftPaddingDefined = false;
3202
3203    /**
3204     * Cache if a right padding has been defined
3205     */
3206    private boolean mRightPaddingDefined = false;
3207
3208    /**
3209     * @hide
3210     */
3211    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3212    /**
3213     * @hide
3214     */
3215    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3216
3217    private LongSparseLongArray mMeasureCache;
3218
3219    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3220    private Drawable mBackground;
3221
3222    private int mBackgroundResource;
3223    private boolean mBackgroundSizeChanged;
3224
3225    static class ListenerInfo {
3226        /**
3227         * Listener used to dispatch focus change events.
3228         * This field should be made private, so it is hidden from the SDK.
3229         * {@hide}
3230         */
3231        protected OnFocusChangeListener mOnFocusChangeListener;
3232
3233        /**
3234         * Listeners for layout change events.
3235         */
3236        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3237
3238        /**
3239         * Listeners for attach events.
3240         */
3241        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3242
3243        /**
3244         * Listener used to dispatch click events.
3245         * This field should be made private, so it is hidden from the SDK.
3246         * {@hide}
3247         */
3248        public OnClickListener mOnClickListener;
3249
3250        /**
3251         * Listener used to dispatch long click events.
3252         * This field should be made private, so it is hidden from the SDK.
3253         * {@hide}
3254         */
3255        protected OnLongClickListener mOnLongClickListener;
3256
3257        /**
3258         * Listener used to build the context menu.
3259         * This field should be made private, so it is hidden from the SDK.
3260         * {@hide}
3261         */
3262        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3263
3264        private OnKeyListener mOnKeyListener;
3265
3266        private OnTouchListener mOnTouchListener;
3267
3268        private OnHoverListener mOnHoverListener;
3269
3270        private OnGenericMotionListener mOnGenericMotionListener;
3271
3272        private OnDragListener mOnDragListener;
3273
3274        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3275    }
3276
3277    ListenerInfo mListenerInfo;
3278
3279    /**
3280     * The application environment this view lives in.
3281     * This field should be made private, so it is hidden from the SDK.
3282     * {@hide}
3283     */
3284    protected Context mContext;
3285
3286    private final Resources mResources;
3287
3288    private ScrollabilityCache mScrollCache;
3289
3290    private int[] mDrawableState = null;
3291
3292    /**
3293     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3294     * the user may specify which view to go to next.
3295     */
3296    private int mNextFocusLeftId = View.NO_ID;
3297
3298    /**
3299     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3300     * the user may specify which view to go to next.
3301     */
3302    private int mNextFocusRightId = View.NO_ID;
3303
3304    /**
3305     * When this view has focus and the next focus is {@link #FOCUS_UP},
3306     * the user may specify which view to go to next.
3307     */
3308    private int mNextFocusUpId = View.NO_ID;
3309
3310    /**
3311     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3312     * the user may specify which view to go to next.
3313     */
3314    private int mNextFocusDownId = View.NO_ID;
3315
3316    /**
3317     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3318     * the user may specify which view to go to next.
3319     */
3320    int mNextFocusForwardId = View.NO_ID;
3321
3322    private CheckForLongPress mPendingCheckForLongPress;
3323    private CheckForTap mPendingCheckForTap = null;
3324    private PerformClick mPerformClick;
3325    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3326
3327    private UnsetPressedState mUnsetPressedState;
3328
3329    /**
3330     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3331     * up event while a long press is invoked as soon as the long press duration is reached, so
3332     * a long press could be performed before the tap is checked, in which case the tap's action
3333     * should not be invoked.
3334     */
3335    private boolean mHasPerformedLongPress;
3336
3337    /**
3338     * The minimum height of the view. We'll try our best to have the height
3339     * of this view to at least this amount.
3340     */
3341    @ViewDebug.ExportedProperty(category = "measurement")
3342    private int mMinHeight;
3343
3344    /**
3345     * The minimum width of the view. We'll try our best to have the width
3346     * of this view to at least this amount.
3347     */
3348    @ViewDebug.ExportedProperty(category = "measurement")
3349    private int mMinWidth;
3350
3351    /**
3352     * The delegate to handle touch events that are physically in this view
3353     * but should be handled by another view.
3354     */
3355    private TouchDelegate mTouchDelegate = null;
3356
3357    /**
3358     * Solid color to use as a background when creating the drawing cache. Enables
3359     * the cache to use 16 bit bitmaps instead of 32 bit.
3360     */
3361    private int mDrawingCacheBackgroundColor = 0;
3362
3363    /**
3364     * Special tree observer used when mAttachInfo is null.
3365     */
3366    private ViewTreeObserver mFloatingTreeObserver;
3367
3368    /**
3369     * Cache the touch slop from the context that created the view.
3370     */
3371    private int mTouchSlop;
3372
3373    /**
3374     * Object that handles automatic animation of view properties.
3375     */
3376    private ViewPropertyAnimator mAnimator = null;
3377
3378    /**
3379     * Flag indicating that a drag can cross window boundaries.  When
3380     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3381     * with this flag set, all visible applications will be able to participate
3382     * in the drag operation and receive the dragged content.
3383     *
3384     * @hide
3385     */
3386    public static final int DRAG_FLAG_GLOBAL = 1;
3387
3388    /**
3389     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3390     */
3391    private float mVerticalScrollFactor;
3392
3393    /**
3394     * Position of the vertical scroll bar.
3395     */
3396    private int mVerticalScrollbarPosition;
3397
3398    /**
3399     * Position the scroll bar at the default position as determined by the system.
3400     */
3401    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3402
3403    /**
3404     * Position the scroll bar along the left edge.
3405     */
3406    public static final int SCROLLBAR_POSITION_LEFT = 1;
3407
3408    /**
3409     * Position the scroll bar along the right edge.
3410     */
3411    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3412
3413    /**
3414     * Indicates that the view does not have a layer.
3415     *
3416     * @see #getLayerType()
3417     * @see #setLayerType(int, android.graphics.Paint)
3418     * @see #LAYER_TYPE_SOFTWARE
3419     * @see #LAYER_TYPE_HARDWARE
3420     */
3421    public static final int LAYER_TYPE_NONE = 0;
3422
3423    /**
3424     * <p>Indicates that the view has a software layer. A software layer is backed
3425     * by a bitmap and causes the view to be rendered using Android's software
3426     * rendering pipeline, even if hardware acceleration is enabled.</p>
3427     *
3428     * <p>Software layers have various usages:</p>
3429     * <p>When the application is not using hardware acceleration, a software layer
3430     * is useful to apply a specific color filter and/or blending mode and/or
3431     * translucency to a view and all its children.</p>
3432     * <p>When the application is using hardware acceleration, a software layer
3433     * is useful to render drawing primitives not supported by the hardware
3434     * accelerated pipeline. It can also be used to cache a complex view tree
3435     * into a texture and reduce the complexity of drawing operations. For instance,
3436     * when animating a complex view tree with a translation, a software layer can
3437     * be used to render the view tree only once.</p>
3438     * <p>Software layers should be avoided when the affected view tree updates
3439     * often. Every update will require to re-render the software layer, which can
3440     * potentially be slow (particularly when hardware acceleration is turned on
3441     * since the layer will have to be uploaded into a hardware texture after every
3442     * update.)</p>
3443     *
3444     * @see #getLayerType()
3445     * @see #setLayerType(int, android.graphics.Paint)
3446     * @see #LAYER_TYPE_NONE
3447     * @see #LAYER_TYPE_HARDWARE
3448     */
3449    public static final int LAYER_TYPE_SOFTWARE = 1;
3450
3451    /**
3452     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3453     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3454     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3455     * rendering pipeline, but only if hardware acceleration is turned on for the
3456     * view hierarchy. When hardware acceleration is turned off, hardware layers
3457     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3458     *
3459     * <p>A hardware layer is useful to apply a specific color filter and/or
3460     * blending mode and/or translucency to a view and all its children.</p>
3461     * <p>A hardware layer can be used to cache a complex view tree into a
3462     * texture and reduce the complexity of drawing operations. For instance,
3463     * when animating a complex view tree with a translation, a hardware layer can
3464     * be used to render the view tree only once.</p>
3465     * <p>A hardware layer can also be used to increase the rendering quality when
3466     * rotation transformations are applied on a view. It can also be used to
3467     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3468     *
3469     * @see #getLayerType()
3470     * @see #setLayerType(int, android.graphics.Paint)
3471     * @see #LAYER_TYPE_NONE
3472     * @see #LAYER_TYPE_SOFTWARE
3473     */
3474    public static final int LAYER_TYPE_HARDWARE = 2;
3475
3476    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3477            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3478            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3479            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3480    })
3481    int mLayerType = LAYER_TYPE_NONE;
3482    Paint mLayerPaint;
3483    Rect mLocalDirtyRect;
3484    private HardwareLayer mHardwareLayer;
3485
3486    /**
3487     * Set to true when drawing cache is enabled and cannot be created.
3488     *
3489     * @hide
3490     */
3491    public boolean mCachingFailed;
3492    private Bitmap mDrawingCache;
3493    private Bitmap mUnscaledDrawingCache;
3494
3495    DisplayList mDisplayList;
3496
3497    /**
3498     * Set to true when the view is sending hover accessibility events because it
3499     * is the innermost hovered view.
3500     */
3501    private boolean mSendingHoverAccessibilityEvents;
3502
3503    /**
3504     * Delegate for injecting accessibility functionality.
3505     */
3506    AccessibilityDelegate mAccessibilityDelegate;
3507
3508    /**
3509     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3510     * and add/remove objects to/from the overlay directly through the Overlay methods.
3511     */
3512    ViewOverlay mOverlay;
3513
3514    /**
3515     * Consistency verifier for debugging purposes.
3516     * @hide
3517     */
3518    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3519            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3520                    new InputEventConsistencyVerifier(this, 0) : null;
3521
3522    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3523
3524    /**
3525     * Simple constructor to use when creating a view from code.
3526     *
3527     * @param context The Context the view is running in, through which it can
3528     *        access the current theme, resources, etc.
3529     */
3530    public View(Context context) {
3531        mContext = context;
3532        mResources = context != null ? context.getResources() : null;
3533        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3534        // Set some flags defaults
3535        mPrivateFlags2 =
3536                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3537                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3538                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3539                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3540                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3541                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3542        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3543        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3544        mUserPaddingStart = UNDEFINED_PADDING;
3545        mUserPaddingEnd = UNDEFINED_PADDING;
3546
3547        if (!sCompatibilityDone && context != null) {
3548            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3549
3550            // Older apps may need this compatibility hack for measurement.
3551            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3552
3553            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3554            // of whether a layout was requested on that View.
3555            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3556
3557            sCompatibilityDone = true;
3558        }
3559    }
3560
3561    /**
3562     * Constructor that is called when inflating a view from XML. This is called
3563     * when a view is being constructed from an XML file, supplying attributes
3564     * that were specified in the XML file. This version uses a default style of
3565     * 0, so the only attribute values applied are those in the Context's Theme
3566     * and the given AttributeSet.
3567     *
3568     * <p>
3569     * The method onFinishInflate() will be called after all children have been
3570     * added.
3571     *
3572     * @param context The Context the view is running in, through which it can
3573     *        access the current theme, resources, etc.
3574     * @param attrs The attributes of the XML tag that is inflating the view.
3575     * @see #View(Context, AttributeSet, int)
3576     */
3577    public View(Context context, AttributeSet attrs) {
3578        this(context, attrs, 0);
3579    }
3580
3581    /**
3582     * Perform inflation from XML and apply a class-specific base style from a
3583     * theme attribute. This constructor of View allows subclasses to use their
3584     * own base style when they are inflating. For example, a Button class's
3585     * constructor would call this version of the super class constructor and
3586     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3587     * allows the theme's button style to modify all of the base view attributes
3588     * (in particular its background) as well as the Button class's attributes.
3589     *
3590     * @param context The Context the view is running in, through which it can
3591     *        access the current theme, resources, etc.
3592     * @param attrs The attributes of the XML tag that is inflating the view.
3593     * @param defStyleAttr An attribute in the current theme that contains a
3594     *        reference to a style resource that supplies default values for
3595     *        the view. Can be 0 to not look for defaults.
3596     * @see #View(Context, AttributeSet)
3597     */
3598    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3599        this(context, attrs, defStyleAttr, 0);
3600    }
3601
3602    /**
3603     * Perform inflation from XML and apply a class-specific base style from a
3604     * theme attribute or style resource. This constructor of View allows
3605     * subclasses to use their own base style when they are inflating.
3606     * <p>
3607     * When determining the final value of a particular attribute, there are
3608     * four inputs that come into play:
3609     * <ol>
3610     * <li>Any attribute values in the given AttributeSet.
3611     * <li>The style resource specified in the AttributeSet (named "style").
3612     * <li>The default style specified by <var>defStyleAttr</var>.
3613     * <li>The default style specified by <var>defStyleRes</var>.
3614     * <li>The base values in this theme.
3615     * </ol>
3616     * <p>
3617     * Each of these inputs is considered in-order, with the first listed taking
3618     * precedence over the following ones. In other words, if in the
3619     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3620     * , then the button's text will <em>always</em> be black, regardless of
3621     * what is specified in any of the styles.
3622     *
3623     * @param context The Context the view is running in, through which it can
3624     *        access the current theme, resources, etc.
3625     * @param attrs The attributes of the XML tag that is inflating the view.
3626     * @param defStyleAttr An attribute in the current theme that contains a
3627     *        reference to a style resource that supplies default values for
3628     *        the view. Can be 0 to not look for defaults.
3629     * @param defStyleRes A resource identifier of a style resource that
3630     *        supplies default values for the view, used only if
3631     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3632     *        to not look for defaults.
3633     * @see #View(Context, AttributeSet, int)
3634     */
3635    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3636        this(context);
3637
3638        final TypedArray a = context.obtainStyledAttributes(
3639                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3640
3641        Drawable background = null;
3642
3643        int leftPadding = -1;
3644        int topPadding = -1;
3645        int rightPadding = -1;
3646        int bottomPadding = -1;
3647        int startPadding = UNDEFINED_PADDING;
3648        int endPadding = UNDEFINED_PADDING;
3649
3650        int padding = -1;
3651
3652        int viewFlagValues = 0;
3653        int viewFlagMasks = 0;
3654
3655        boolean setScrollContainer = false;
3656
3657        int x = 0;
3658        int y = 0;
3659
3660        float tx = 0;
3661        float ty = 0;
3662        float rotation = 0;
3663        float rotationX = 0;
3664        float rotationY = 0;
3665        float sx = 1f;
3666        float sy = 1f;
3667        boolean transformSet = false;
3668
3669        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3670        int overScrollMode = mOverScrollMode;
3671        boolean initializeScrollbars = false;
3672
3673        boolean startPaddingDefined = false;
3674        boolean endPaddingDefined = false;
3675        boolean leftPaddingDefined = false;
3676        boolean rightPaddingDefined = false;
3677
3678        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3679
3680        final int N = a.getIndexCount();
3681        for (int i = 0; i < N; i++) {
3682            int attr = a.getIndex(i);
3683            switch (attr) {
3684                case com.android.internal.R.styleable.View_background:
3685                    background = a.getDrawable(attr);
3686                    break;
3687                case com.android.internal.R.styleable.View_padding:
3688                    padding = a.getDimensionPixelSize(attr, -1);
3689                    mUserPaddingLeftInitial = padding;
3690                    mUserPaddingRightInitial = padding;
3691                    leftPaddingDefined = true;
3692                    rightPaddingDefined = true;
3693                    break;
3694                 case com.android.internal.R.styleable.View_paddingLeft:
3695                    leftPadding = a.getDimensionPixelSize(attr, -1);
3696                    mUserPaddingLeftInitial = leftPadding;
3697                    leftPaddingDefined = true;
3698                    break;
3699                case com.android.internal.R.styleable.View_paddingTop:
3700                    topPadding = a.getDimensionPixelSize(attr, -1);
3701                    break;
3702                case com.android.internal.R.styleable.View_paddingRight:
3703                    rightPadding = a.getDimensionPixelSize(attr, -1);
3704                    mUserPaddingRightInitial = rightPadding;
3705                    rightPaddingDefined = true;
3706                    break;
3707                case com.android.internal.R.styleable.View_paddingBottom:
3708                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3709                    break;
3710                case com.android.internal.R.styleable.View_paddingStart:
3711                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3712                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3713                    break;
3714                case com.android.internal.R.styleable.View_paddingEnd:
3715                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3716                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3717                    break;
3718                case com.android.internal.R.styleable.View_scrollX:
3719                    x = a.getDimensionPixelOffset(attr, 0);
3720                    break;
3721                case com.android.internal.R.styleable.View_scrollY:
3722                    y = a.getDimensionPixelOffset(attr, 0);
3723                    break;
3724                case com.android.internal.R.styleable.View_alpha:
3725                    setAlpha(a.getFloat(attr, 1f));
3726                    break;
3727                case com.android.internal.R.styleable.View_transformPivotX:
3728                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3729                    break;
3730                case com.android.internal.R.styleable.View_transformPivotY:
3731                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3732                    break;
3733                case com.android.internal.R.styleable.View_translationX:
3734                    tx = a.getDimensionPixelOffset(attr, 0);
3735                    transformSet = true;
3736                    break;
3737                case com.android.internal.R.styleable.View_translationY:
3738                    ty = a.getDimensionPixelOffset(attr, 0);
3739                    transformSet = true;
3740                    break;
3741                case com.android.internal.R.styleable.View_rotation:
3742                    rotation = a.getFloat(attr, 0);
3743                    transformSet = true;
3744                    break;
3745                case com.android.internal.R.styleable.View_rotationX:
3746                    rotationX = a.getFloat(attr, 0);
3747                    transformSet = true;
3748                    break;
3749                case com.android.internal.R.styleable.View_rotationY:
3750                    rotationY = a.getFloat(attr, 0);
3751                    transformSet = true;
3752                    break;
3753                case com.android.internal.R.styleable.View_scaleX:
3754                    sx = a.getFloat(attr, 1f);
3755                    transformSet = true;
3756                    break;
3757                case com.android.internal.R.styleable.View_scaleY:
3758                    sy = a.getFloat(attr, 1f);
3759                    transformSet = true;
3760                    break;
3761                case com.android.internal.R.styleable.View_id:
3762                    mID = a.getResourceId(attr, NO_ID);
3763                    break;
3764                case com.android.internal.R.styleable.View_tag:
3765                    mTag = a.getText(attr);
3766                    break;
3767                case com.android.internal.R.styleable.View_fitsSystemWindows:
3768                    if (a.getBoolean(attr, false)) {
3769                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3770                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3771                    }
3772                    break;
3773                case com.android.internal.R.styleable.View_focusable:
3774                    if (a.getBoolean(attr, false)) {
3775                        viewFlagValues |= FOCUSABLE;
3776                        viewFlagMasks |= FOCUSABLE_MASK;
3777                    }
3778                    break;
3779                case com.android.internal.R.styleable.View_focusableInTouchMode:
3780                    if (a.getBoolean(attr, false)) {
3781                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3782                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3783                    }
3784                    break;
3785                case com.android.internal.R.styleable.View_clickable:
3786                    if (a.getBoolean(attr, false)) {
3787                        viewFlagValues |= CLICKABLE;
3788                        viewFlagMasks |= CLICKABLE;
3789                    }
3790                    break;
3791                case com.android.internal.R.styleable.View_longClickable:
3792                    if (a.getBoolean(attr, false)) {
3793                        viewFlagValues |= LONG_CLICKABLE;
3794                        viewFlagMasks |= LONG_CLICKABLE;
3795                    }
3796                    break;
3797                case com.android.internal.R.styleable.View_saveEnabled:
3798                    if (!a.getBoolean(attr, true)) {
3799                        viewFlagValues |= SAVE_DISABLED;
3800                        viewFlagMasks |= SAVE_DISABLED_MASK;
3801                    }
3802                    break;
3803                case com.android.internal.R.styleable.View_duplicateParentState:
3804                    if (a.getBoolean(attr, false)) {
3805                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3806                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3807                    }
3808                    break;
3809                case com.android.internal.R.styleable.View_visibility:
3810                    final int visibility = a.getInt(attr, 0);
3811                    if (visibility != 0) {
3812                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3813                        viewFlagMasks |= VISIBILITY_MASK;
3814                    }
3815                    break;
3816                case com.android.internal.R.styleable.View_layoutDirection:
3817                    // Clear any layout direction flags (included resolved bits) already set
3818                    mPrivateFlags2 &=
3819                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3820                    // Set the layout direction flags depending on the value of the attribute
3821                    final int layoutDirection = a.getInt(attr, -1);
3822                    final int value = (layoutDirection != -1) ?
3823                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3824                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3825                    break;
3826                case com.android.internal.R.styleable.View_drawingCacheQuality:
3827                    final int cacheQuality = a.getInt(attr, 0);
3828                    if (cacheQuality != 0) {
3829                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3830                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3831                    }
3832                    break;
3833                case com.android.internal.R.styleable.View_contentDescription:
3834                    setContentDescription(a.getString(attr));
3835                    break;
3836                case com.android.internal.R.styleable.View_labelFor:
3837                    setLabelFor(a.getResourceId(attr, NO_ID));
3838                    break;
3839                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3840                    if (!a.getBoolean(attr, true)) {
3841                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3842                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3843                    }
3844                    break;
3845                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3846                    if (!a.getBoolean(attr, true)) {
3847                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3848                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3849                    }
3850                    break;
3851                case R.styleable.View_scrollbars:
3852                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3853                    if (scrollbars != SCROLLBARS_NONE) {
3854                        viewFlagValues |= scrollbars;
3855                        viewFlagMasks |= SCROLLBARS_MASK;
3856                        initializeScrollbars = true;
3857                    }
3858                    break;
3859                //noinspection deprecation
3860                case R.styleable.View_fadingEdge:
3861                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3862                        // Ignore the attribute starting with ICS
3863                        break;
3864                    }
3865                    // With builds < ICS, fall through and apply fading edges
3866                case R.styleable.View_requiresFadingEdge:
3867                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3868                    if (fadingEdge != FADING_EDGE_NONE) {
3869                        viewFlagValues |= fadingEdge;
3870                        viewFlagMasks |= FADING_EDGE_MASK;
3871                        initializeFadingEdge(a);
3872                    }
3873                    break;
3874                case R.styleable.View_scrollbarStyle:
3875                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3876                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3877                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3878                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3879                    }
3880                    break;
3881                case R.styleable.View_isScrollContainer:
3882                    setScrollContainer = true;
3883                    if (a.getBoolean(attr, false)) {
3884                        setScrollContainer(true);
3885                    }
3886                    break;
3887                case com.android.internal.R.styleable.View_keepScreenOn:
3888                    if (a.getBoolean(attr, false)) {
3889                        viewFlagValues |= KEEP_SCREEN_ON;
3890                        viewFlagMasks |= KEEP_SCREEN_ON;
3891                    }
3892                    break;
3893                case R.styleable.View_filterTouchesWhenObscured:
3894                    if (a.getBoolean(attr, false)) {
3895                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3896                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3897                    }
3898                    break;
3899                case R.styleable.View_nextFocusLeft:
3900                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3901                    break;
3902                case R.styleable.View_nextFocusRight:
3903                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3904                    break;
3905                case R.styleable.View_nextFocusUp:
3906                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3907                    break;
3908                case R.styleable.View_nextFocusDown:
3909                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3910                    break;
3911                case R.styleable.View_nextFocusForward:
3912                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3913                    break;
3914                case R.styleable.View_minWidth:
3915                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3916                    break;
3917                case R.styleable.View_minHeight:
3918                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3919                    break;
3920                case R.styleable.View_onClick:
3921                    if (context.isRestricted()) {
3922                        throw new IllegalStateException("The android:onClick attribute cannot "
3923                                + "be used within a restricted context");
3924                    }
3925
3926                    final String handlerName = a.getString(attr);
3927                    if (handlerName != null) {
3928                        setOnClickListener(new OnClickListener() {
3929                            private Method mHandler;
3930
3931                            public void onClick(View v) {
3932                                if (mHandler == null) {
3933                                    try {
3934                                        mHandler = getContext().getClass().getMethod(handlerName,
3935                                                View.class);
3936                                    } catch (NoSuchMethodException e) {
3937                                        int id = getId();
3938                                        String idText = id == NO_ID ? "" : " with id '"
3939                                                + getContext().getResources().getResourceEntryName(
3940                                                    id) + "'";
3941                                        throw new IllegalStateException("Could not find a method " +
3942                                                handlerName + "(View) in the activity "
3943                                                + getContext().getClass() + " for onClick handler"
3944                                                + " on view " + View.this.getClass() + idText, e);
3945                                    }
3946                                }
3947
3948                                try {
3949                                    mHandler.invoke(getContext(), View.this);
3950                                } catch (IllegalAccessException e) {
3951                                    throw new IllegalStateException("Could not execute non "
3952                                            + "public method of the activity", e);
3953                                } catch (InvocationTargetException e) {
3954                                    throw new IllegalStateException("Could not execute "
3955                                            + "method of the activity", e);
3956                                }
3957                            }
3958                        });
3959                    }
3960                    break;
3961                case R.styleable.View_overScrollMode:
3962                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3963                    break;
3964                case R.styleable.View_verticalScrollbarPosition:
3965                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3966                    break;
3967                case R.styleable.View_layerType:
3968                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3969                    break;
3970                case R.styleable.View_textDirection:
3971                    // Clear any text direction flag already set
3972                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3973                    // Set the text direction flags depending on the value of the attribute
3974                    final int textDirection = a.getInt(attr, -1);
3975                    if (textDirection != -1) {
3976                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3977                    }
3978                    break;
3979                case R.styleable.View_textAlignment:
3980                    // Clear any text alignment flag already set
3981                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3982                    // Set the text alignment flag depending on the value of the attribute
3983                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3984                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3985                    break;
3986                case R.styleable.View_importantForAccessibility:
3987                    setImportantForAccessibility(a.getInt(attr,
3988                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3989                    break;
3990                case R.styleable.View_accessibilityLiveRegion:
3991                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
3992                    break;
3993            }
3994        }
3995
3996        setOverScrollMode(overScrollMode);
3997
3998        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3999        // the resolved layout direction). Those cached values will be used later during padding
4000        // resolution.
4001        mUserPaddingStart = startPadding;
4002        mUserPaddingEnd = endPadding;
4003
4004        if (background != null) {
4005            setBackground(background);
4006        }
4007
4008        // setBackground above will record that padding is currently provided by the background.
4009        // If we have padding specified via xml, record that here instead and use it.
4010        mLeftPaddingDefined = leftPaddingDefined;
4011        mRightPaddingDefined = rightPaddingDefined;
4012
4013        if (padding >= 0) {
4014            leftPadding = padding;
4015            topPadding = padding;
4016            rightPadding = padding;
4017            bottomPadding = padding;
4018            mUserPaddingLeftInitial = padding;
4019            mUserPaddingRightInitial = padding;
4020        }
4021
4022        if (isRtlCompatibilityMode()) {
4023            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4024            // left / right padding are used if defined (meaning here nothing to do). If they are not
4025            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4026            // start / end and resolve them as left / right (layout direction is not taken into account).
4027            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4028            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4029            // defined.
4030            if (!mLeftPaddingDefined && startPaddingDefined) {
4031                leftPadding = startPadding;
4032            }
4033            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4034            if (!mRightPaddingDefined && endPaddingDefined) {
4035                rightPadding = endPadding;
4036            }
4037            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4038        } else {
4039            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4040            // values defined. Otherwise, left /right values are used.
4041            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4042            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4043            // defined.
4044            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4045
4046            if (mLeftPaddingDefined && !hasRelativePadding) {
4047                mUserPaddingLeftInitial = leftPadding;
4048            }
4049            if (mRightPaddingDefined && !hasRelativePadding) {
4050                mUserPaddingRightInitial = rightPadding;
4051            }
4052        }
4053
4054        internalSetPadding(
4055                mUserPaddingLeftInitial,
4056                topPadding >= 0 ? topPadding : mPaddingTop,
4057                mUserPaddingRightInitial,
4058                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4059
4060        if (viewFlagMasks != 0) {
4061            setFlags(viewFlagValues, viewFlagMasks);
4062        }
4063
4064        if (initializeScrollbars) {
4065            initializeScrollbars(a);
4066        }
4067
4068        a.recycle();
4069
4070        // Needs to be called after mViewFlags is set
4071        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4072            recomputePadding();
4073        }
4074
4075        if (x != 0 || y != 0) {
4076            scrollTo(x, y);
4077        }
4078
4079        if (transformSet) {
4080            setTranslationX(tx);
4081            setTranslationY(ty);
4082            setRotation(rotation);
4083            setRotationX(rotationX);
4084            setRotationY(rotationY);
4085            setScaleX(sx);
4086            setScaleY(sy);
4087        }
4088
4089        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4090            setScrollContainer(true);
4091        }
4092
4093        computeOpaqueFlags();
4094    }
4095
4096    /**
4097     * Non-public constructor for use in testing
4098     */
4099    View() {
4100        mResources = null;
4101    }
4102
4103    public String toString() {
4104        StringBuilder out = new StringBuilder(128);
4105        out.append(getClass().getName());
4106        out.append('{');
4107        out.append(Integer.toHexString(System.identityHashCode(this)));
4108        out.append(' ');
4109        switch (mViewFlags&VISIBILITY_MASK) {
4110            case VISIBLE: out.append('V'); break;
4111            case INVISIBLE: out.append('I'); break;
4112            case GONE: out.append('G'); break;
4113            default: out.append('.'); break;
4114        }
4115        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4116        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4117        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4118        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4119        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4120        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4121        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4122        out.append(' ');
4123        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4124        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4125        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4126        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4127            out.append('p');
4128        } else {
4129            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4130        }
4131        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4132        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4133        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4134        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4135        out.append(' ');
4136        out.append(mLeft);
4137        out.append(',');
4138        out.append(mTop);
4139        out.append('-');
4140        out.append(mRight);
4141        out.append(',');
4142        out.append(mBottom);
4143        final int id = getId();
4144        if (id != NO_ID) {
4145            out.append(" #");
4146            out.append(Integer.toHexString(id));
4147            final Resources r = mResources;
4148            if (id != 0 && r != null) {
4149                try {
4150                    String pkgname;
4151                    switch (id&0xff000000) {
4152                        case 0x7f000000:
4153                            pkgname="app";
4154                            break;
4155                        case 0x01000000:
4156                            pkgname="android";
4157                            break;
4158                        default:
4159                            pkgname = r.getResourcePackageName(id);
4160                            break;
4161                    }
4162                    String typename = r.getResourceTypeName(id);
4163                    String entryname = r.getResourceEntryName(id);
4164                    out.append(" ");
4165                    out.append(pkgname);
4166                    out.append(":");
4167                    out.append(typename);
4168                    out.append("/");
4169                    out.append(entryname);
4170                } catch (Resources.NotFoundException e) {
4171                }
4172            }
4173        }
4174        out.append("}");
4175        return out.toString();
4176    }
4177
4178    /**
4179     * <p>
4180     * Initializes the fading edges from a given set of styled attributes. This
4181     * method should be called by subclasses that need fading edges and when an
4182     * instance of these subclasses is created programmatically rather than
4183     * being inflated from XML. This method is automatically called when the XML
4184     * is inflated.
4185     * </p>
4186     *
4187     * @param a the styled attributes set to initialize the fading edges from
4188     */
4189    protected void initializeFadingEdge(TypedArray a) {
4190        initScrollCache();
4191
4192        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4193                R.styleable.View_fadingEdgeLength,
4194                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4195    }
4196
4197    /**
4198     * Returns the size of the vertical faded edges used to indicate that more
4199     * content in this view is visible.
4200     *
4201     * @return The size in pixels of the vertical faded edge or 0 if vertical
4202     *         faded edges are not enabled for this view.
4203     * @attr ref android.R.styleable#View_fadingEdgeLength
4204     */
4205    public int getVerticalFadingEdgeLength() {
4206        if (isVerticalFadingEdgeEnabled()) {
4207            ScrollabilityCache cache = mScrollCache;
4208            if (cache != null) {
4209                return cache.fadingEdgeLength;
4210            }
4211        }
4212        return 0;
4213    }
4214
4215    /**
4216     * Set the size of the faded edge used to indicate that more content in this
4217     * view is available.  Will not change whether the fading edge is enabled; use
4218     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4219     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4220     * for the vertical or horizontal fading edges.
4221     *
4222     * @param length The size in pixels of the faded edge used to indicate that more
4223     *        content in this view is visible.
4224     */
4225    public void setFadingEdgeLength(int length) {
4226        initScrollCache();
4227        mScrollCache.fadingEdgeLength = length;
4228    }
4229
4230    /**
4231     * Returns the size of the horizontal faded edges used to indicate that more
4232     * content in this view is visible.
4233     *
4234     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4235     *         faded edges are not enabled for this view.
4236     * @attr ref android.R.styleable#View_fadingEdgeLength
4237     */
4238    public int getHorizontalFadingEdgeLength() {
4239        if (isHorizontalFadingEdgeEnabled()) {
4240            ScrollabilityCache cache = mScrollCache;
4241            if (cache != null) {
4242                return cache.fadingEdgeLength;
4243            }
4244        }
4245        return 0;
4246    }
4247
4248    /**
4249     * Returns the width of the vertical scrollbar.
4250     *
4251     * @return The width in pixels of the vertical scrollbar or 0 if there
4252     *         is no vertical scrollbar.
4253     */
4254    public int getVerticalScrollbarWidth() {
4255        ScrollabilityCache cache = mScrollCache;
4256        if (cache != null) {
4257            ScrollBarDrawable scrollBar = cache.scrollBar;
4258            if (scrollBar != null) {
4259                int size = scrollBar.getSize(true);
4260                if (size <= 0) {
4261                    size = cache.scrollBarSize;
4262                }
4263                return size;
4264            }
4265            return 0;
4266        }
4267        return 0;
4268    }
4269
4270    /**
4271     * Returns the height of the horizontal scrollbar.
4272     *
4273     * @return The height in pixels of the horizontal scrollbar or 0 if
4274     *         there is no horizontal scrollbar.
4275     */
4276    protected int getHorizontalScrollbarHeight() {
4277        ScrollabilityCache cache = mScrollCache;
4278        if (cache != null) {
4279            ScrollBarDrawable scrollBar = cache.scrollBar;
4280            if (scrollBar != null) {
4281                int size = scrollBar.getSize(false);
4282                if (size <= 0) {
4283                    size = cache.scrollBarSize;
4284                }
4285                return size;
4286            }
4287            return 0;
4288        }
4289        return 0;
4290    }
4291
4292    /**
4293     * <p>
4294     * Initializes the scrollbars from a given set of styled attributes. This
4295     * method should be called by subclasses that need scrollbars and when an
4296     * instance of these subclasses is created programmatically rather than
4297     * being inflated from XML. This method is automatically called when the XML
4298     * is inflated.
4299     * </p>
4300     *
4301     * @param a the styled attributes set to initialize the scrollbars from
4302     */
4303    protected void initializeScrollbars(TypedArray a) {
4304        initScrollCache();
4305
4306        final ScrollabilityCache scrollabilityCache = mScrollCache;
4307
4308        if (scrollabilityCache.scrollBar == null) {
4309            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4310        }
4311
4312        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4313
4314        if (!fadeScrollbars) {
4315            scrollabilityCache.state = ScrollabilityCache.ON;
4316        }
4317        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4318
4319
4320        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4321                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4322                        .getScrollBarFadeDuration());
4323        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4324                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4325                ViewConfiguration.getScrollDefaultDelay());
4326
4327
4328        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4329                com.android.internal.R.styleable.View_scrollbarSize,
4330                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4331
4332        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4333        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4334
4335        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4336        if (thumb != null) {
4337            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4338        }
4339
4340        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4341                false);
4342        if (alwaysDraw) {
4343            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4344        }
4345
4346        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4347        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4348
4349        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4350        if (thumb != null) {
4351            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4352        }
4353
4354        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4355                false);
4356        if (alwaysDraw) {
4357            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4358        }
4359
4360        // Apply layout direction to the new Drawables if needed
4361        final int layoutDirection = getLayoutDirection();
4362        if (track != null) {
4363            track.setLayoutDirection(layoutDirection);
4364        }
4365        if (thumb != null) {
4366            thumb.setLayoutDirection(layoutDirection);
4367        }
4368
4369        // Re-apply user/background padding so that scrollbar(s) get added
4370        resolvePadding();
4371    }
4372
4373    /**
4374     * <p>
4375     * Initalizes the scrollability cache if necessary.
4376     * </p>
4377     */
4378    private void initScrollCache() {
4379        if (mScrollCache == null) {
4380            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4381        }
4382    }
4383
4384    private ScrollabilityCache getScrollCache() {
4385        initScrollCache();
4386        return mScrollCache;
4387    }
4388
4389    /**
4390     * Set the position of the vertical scroll bar. Should be one of
4391     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4392     * {@link #SCROLLBAR_POSITION_RIGHT}.
4393     *
4394     * @param position Where the vertical scroll bar should be positioned.
4395     */
4396    public void setVerticalScrollbarPosition(int position) {
4397        if (mVerticalScrollbarPosition != position) {
4398            mVerticalScrollbarPosition = position;
4399            computeOpaqueFlags();
4400            resolvePadding();
4401        }
4402    }
4403
4404    /**
4405     * @return The position where the vertical scroll bar will show, if applicable.
4406     * @see #setVerticalScrollbarPosition(int)
4407     */
4408    public int getVerticalScrollbarPosition() {
4409        return mVerticalScrollbarPosition;
4410    }
4411
4412    ListenerInfo getListenerInfo() {
4413        if (mListenerInfo != null) {
4414            return mListenerInfo;
4415        }
4416        mListenerInfo = new ListenerInfo();
4417        return mListenerInfo;
4418    }
4419
4420    /**
4421     * Register a callback to be invoked when focus of this view changed.
4422     *
4423     * @param l The callback that will run.
4424     */
4425    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4426        getListenerInfo().mOnFocusChangeListener = l;
4427    }
4428
4429    /**
4430     * Add a listener that will be called when the bounds of the view change due to
4431     * layout processing.
4432     *
4433     * @param listener The listener that will be called when layout bounds change.
4434     */
4435    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4436        ListenerInfo li = getListenerInfo();
4437        if (li.mOnLayoutChangeListeners == null) {
4438            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4439        }
4440        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4441            li.mOnLayoutChangeListeners.add(listener);
4442        }
4443    }
4444
4445    /**
4446     * Remove a listener for layout changes.
4447     *
4448     * @param listener The listener for layout bounds change.
4449     */
4450    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4451        ListenerInfo li = mListenerInfo;
4452        if (li == null || li.mOnLayoutChangeListeners == null) {
4453            return;
4454        }
4455        li.mOnLayoutChangeListeners.remove(listener);
4456    }
4457
4458    /**
4459     * Add a listener for attach state changes.
4460     *
4461     * This listener will be called whenever this view is attached or detached
4462     * from a window. Remove the listener using
4463     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4464     *
4465     * @param listener Listener to attach
4466     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4467     */
4468    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4469        ListenerInfo li = getListenerInfo();
4470        if (li.mOnAttachStateChangeListeners == null) {
4471            li.mOnAttachStateChangeListeners
4472                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4473        }
4474        li.mOnAttachStateChangeListeners.add(listener);
4475    }
4476
4477    /**
4478     * Remove a listener for attach state changes. The listener will receive no further
4479     * notification of window attach/detach events.
4480     *
4481     * @param listener Listener to remove
4482     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4483     */
4484    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4485        ListenerInfo li = mListenerInfo;
4486        if (li == null || li.mOnAttachStateChangeListeners == null) {
4487            return;
4488        }
4489        li.mOnAttachStateChangeListeners.remove(listener);
4490    }
4491
4492    /**
4493     * Returns the focus-change callback registered for this view.
4494     *
4495     * @return The callback, or null if one is not registered.
4496     */
4497    public OnFocusChangeListener getOnFocusChangeListener() {
4498        ListenerInfo li = mListenerInfo;
4499        return li != null ? li.mOnFocusChangeListener : null;
4500    }
4501
4502    /**
4503     * Register a callback to be invoked when this view is clicked. If this view is not
4504     * clickable, it becomes clickable.
4505     *
4506     * @param l The callback that will run
4507     *
4508     * @see #setClickable(boolean)
4509     */
4510    public void setOnClickListener(OnClickListener l) {
4511        if (!isClickable()) {
4512            setClickable(true);
4513        }
4514        getListenerInfo().mOnClickListener = l;
4515    }
4516
4517    /**
4518     * Return whether this view has an attached OnClickListener.  Returns
4519     * true if there is a listener, false if there is none.
4520     */
4521    public boolean hasOnClickListeners() {
4522        ListenerInfo li = mListenerInfo;
4523        return (li != null && li.mOnClickListener != null);
4524    }
4525
4526    /**
4527     * Register a callback to be invoked when this view is clicked and held. If this view is not
4528     * long clickable, it becomes long clickable.
4529     *
4530     * @param l The callback that will run
4531     *
4532     * @see #setLongClickable(boolean)
4533     */
4534    public void setOnLongClickListener(OnLongClickListener l) {
4535        if (!isLongClickable()) {
4536            setLongClickable(true);
4537        }
4538        getListenerInfo().mOnLongClickListener = l;
4539    }
4540
4541    /**
4542     * Register a callback to be invoked when the context menu for this view is
4543     * being built. If this view is not long clickable, it becomes long clickable.
4544     *
4545     * @param l The callback that will run
4546     *
4547     */
4548    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4549        if (!isLongClickable()) {
4550            setLongClickable(true);
4551        }
4552        getListenerInfo().mOnCreateContextMenuListener = l;
4553    }
4554
4555    /**
4556     * Call this view's OnClickListener, if it is defined.  Performs all normal
4557     * actions associated with clicking: reporting accessibility event, playing
4558     * a sound, etc.
4559     *
4560     * @return True there was an assigned OnClickListener that was called, false
4561     *         otherwise is returned.
4562     */
4563    public boolean performClick() {
4564        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4565
4566        ListenerInfo li = mListenerInfo;
4567        if (li != null && li.mOnClickListener != null) {
4568            playSoundEffect(SoundEffectConstants.CLICK);
4569            li.mOnClickListener.onClick(this);
4570            return true;
4571        }
4572
4573        return false;
4574    }
4575
4576    /**
4577     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4578     * this only calls the listener, and does not do any associated clicking
4579     * actions like reporting an accessibility event.
4580     *
4581     * @return True there was an assigned OnClickListener that was called, false
4582     *         otherwise is returned.
4583     */
4584    public boolean callOnClick() {
4585        ListenerInfo li = mListenerInfo;
4586        if (li != null && li.mOnClickListener != null) {
4587            li.mOnClickListener.onClick(this);
4588            return true;
4589        }
4590        return false;
4591    }
4592
4593    /**
4594     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4595     * OnLongClickListener did not consume the event.
4596     *
4597     * @return True if one of the above receivers consumed the event, false otherwise.
4598     */
4599    public boolean performLongClick() {
4600        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4601
4602        boolean handled = false;
4603        ListenerInfo li = mListenerInfo;
4604        if (li != null && li.mOnLongClickListener != null) {
4605            handled = li.mOnLongClickListener.onLongClick(View.this);
4606        }
4607        if (!handled) {
4608            handled = showContextMenu();
4609        }
4610        if (handled) {
4611            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4612        }
4613        return handled;
4614    }
4615
4616    /**
4617     * Performs button-related actions during a touch down event.
4618     *
4619     * @param event The event.
4620     * @return True if the down was consumed.
4621     *
4622     * @hide
4623     */
4624    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4625        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4626            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4627                return true;
4628            }
4629        }
4630        return false;
4631    }
4632
4633    /**
4634     * Bring up the context menu for this view.
4635     *
4636     * @return Whether a context menu was displayed.
4637     */
4638    public boolean showContextMenu() {
4639        return getParent().showContextMenuForChild(this);
4640    }
4641
4642    /**
4643     * Bring up the context menu for this view, referring to the item under the specified point.
4644     *
4645     * @param x The referenced x coordinate.
4646     * @param y The referenced y coordinate.
4647     * @param metaState The keyboard modifiers that were pressed.
4648     * @return Whether a context menu was displayed.
4649     *
4650     * @hide
4651     */
4652    public boolean showContextMenu(float x, float y, int metaState) {
4653        return showContextMenu();
4654    }
4655
4656    /**
4657     * Start an action mode.
4658     *
4659     * @param callback Callback that will control the lifecycle of the action mode
4660     * @return The new action mode if it is started, null otherwise
4661     *
4662     * @see ActionMode
4663     */
4664    public ActionMode startActionMode(ActionMode.Callback callback) {
4665        ViewParent parent = getParent();
4666        if (parent == null) return null;
4667        return parent.startActionModeForChild(this, callback);
4668    }
4669
4670    /**
4671     * Register a callback to be invoked when a hardware key is pressed in this view.
4672     * Key presses in software input methods will generally not trigger the methods of
4673     * this listener.
4674     * @param l the key listener to attach to this view
4675     */
4676    public void setOnKeyListener(OnKeyListener l) {
4677        getListenerInfo().mOnKeyListener = l;
4678    }
4679
4680    /**
4681     * Register a callback to be invoked when a touch event is sent to this view.
4682     * @param l the touch listener to attach to this view
4683     */
4684    public void setOnTouchListener(OnTouchListener l) {
4685        getListenerInfo().mOnTouchListener = l;
4686    }
4687
4688    /**
4689     * Register a callback to be invoked when a generic motion event is sent to this view.
4690     * @param l the generic motion listener to attach to this view
4691     */
4692    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4693        getListenerInfo().mOnGenericMotionListener = l;
4694    }
4695
4696    /**
4697     * Register a callback to be invoked when a hover event is sent to this view.
4698     * @param l the hover listener to attach to this view
4699     */
4700    public void setOnHoverListener(OnHoverListener l) {
4701        getListenerInfo().mOnHoverListener = l;
4702    }
4703
4704    /**
4705     * Register a drag event listener callback object for this View. The parameter is
4706     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4707     * View, the system calls the
4708     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4709     * @param l An implementation of {@link android.view.View.OnDragListener}.
4710     */
4711    public void setOnDragListener(OnDragListener l) {
4712        getListenerInfo().mOnDragListener = l;
4713    }
4714
4715    /**
4716     * Give this view focus. This will cause
4717     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4718     *
4719     * Note: this does not check whether this {@link View} should get focus, it just
4720     * gives it focus no matter what.  It should only be called internally by framework
4721     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4722     *
4723     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4724     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4725     *        focus moved when requestFocus() is called. It may not always
4726     *        apply, in which case use the default View.FOCUS_DOWN.
4727     * @param previouslyFocusedRect The rectangle of the view that had focus
4728     *        prior in this View's coordinate system.
4729     */
4730    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4731        if (DBG) {
4732            System.out.println(this + " requestFocus()");
4733        }
4734
4735        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4736            mPrivateFlags |= PFLAG_FOCUSED;
4737
4738            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4739
4740            if (mParent != null) {
4741                mParent.requestChildFocus(this, this);
4742            }
4743
4744            if (mAttachInfo != null) {
4745                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4746            }
4747
4748            onFocusChanged(true, direction, previouslyFocusedRect);
4749            refreshDrawableState();
4750        }
4751    }
4752
4753    /**
4754     * Request that a rectangle of this view be visible on the screen,
4755     * scrolling if necessary just enough.
4756     *
4757     * <p>A View should call this if it maintains some notion of which part
4758     * of its content is interesting.  For example, a text editing view
4759     * should call this when its cursor moves.
4760     *
4761     * @param rectangle The rectangle.
4762     * @return Whether any parent scrolled.
4763     */
4764    public boolean requestRectangleOnScreen(Rect rectangle) {
4765        return requestRectangleOnScreen(rectangle, false);
4766    }
4767
4768    /**
4769     * Request that a rectangle of this view be visible on the screen,
4770     * scrolling if necessary just enough.
4771     *
4772     * <p>A View should call this if it maintains some notion of which part
4773     * of its content is interesting.  For example, a text editing view
4774     * should call this when its cursor moves.
4775     *
4776     * <p>When <code>immediate</code> is set to true, scrolling will not be
4777     * animated.
4778     *
4779     * @param rectangle The rectangle.
4780     * @param immediate True to forbid animated scrolling, false otherwise
4781     * @return Whether any parent scrolled.
4782     */
4783    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4784        if (mParent == null) {
4785            return false;
4786        }
4787
4788        View child = this;
4789
4790        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4791        position.set(rectangle);
4792
4793        ViewParent parent = mParent;
4794        boolean scrolled = false;
4795        while (parent != null) {
4796            rectangle.set((int) position.left, (int) position.top,
4797                    (int) position.right, (int) position.bottom);
4798
4799            scrolled |= parent.requestChildRectangleOnScreen(child,
4800                    rectangle, immediate);
4801
4802            if (!child.hasIdentityMatrix()) {
4803                child.getMatrix().mapRect(position);
4804            }
4805
4806            position.offset(child.mLeft, child.mTop);
4807
4808            if (!(parent instanceof View)) {
4809                break;
4810            }
4811
4812            View parentView = (View) parent;
4813
4814            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4815
4816            child = parentView;
4817            parent = child.getParent();
4818        }
4819
4820        return scrolled;
4821    }
4822
4823    /**
4824     * Called when this view wants to give up focus. If focus is cleared
4825     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4826     * <p>
4827     * <strong>Note:</strong> When a View clears focus the framework is trying
4828     * to give focus to the first focusable View from the top. Hence, if this
4829     * View is the first from the top that can take focus, then all callbacks
4830     * related to clearing focus will be invoked after wich the framework will
4831     * give focus to this view.
4832     * </p>
4833     */
4834    public void clearFocus() {
4835        if (DBG) {
4836            System.out.println(this + " clearFocus()");
4837        }
4838
4839        clearFocusInternal(true, true);
4840    }
4841
4842    /**
4843     * Clears focus from the view, optionally propagating the change up through
4844     * the parent hierarchy and requesting that the root view place new focus.
4845     *
4846     * @param propagate whether to propagate the change up through the parent
4847     *            hierarchy
4848     * @param refocus when propagate is true, specifies whether to request the
4849     *            root view place new focus
4850     */
4851    void clearFocusInternal(boolean propagate, boolean refocus) {
4852        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4853            mPrivateFlags &= ~PFLAG_FOCUSED;
4854
4855            if (propagate && mParent != null) {
4856                mParent.clearChildFocus(this);
4857            }
4858
4859            onFocusChanged(false, 0, null);
4860
4861            refreshDrawableState();
4862
4863            if (propagate && (!refocus || !rootViewRequestFocus())) {
4864                notifyGlobalFocusCleared(this);
4865            }
4866        }
4867    }
4868
4869    void notifyGlobalFocusCleared(View oldFocus) {
4870        if (oldFocus != null && mAttachInfo != null) {
4871            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4872        }
4873    }
4874
4875    boolean rootViewRequestFocus() {
4876        final View root = getRootView();
4877        return root != null && root.requestFocus();
4878    }
4879
4880    /**
4881     * Called internally by the view system when a new view is getting focus.
4882     * This is what clears the old focus.
4883     * <p>
4884     * <b>NOTE:</b> The parent view's focused child must be updated manually
4885     * after calling this method. Otherwise, the view hierarchy may be left in
4886     * an inconstent state.
4887     */
4888    void unFocus() {
4889        if (DBG) {
4890            System.out.println(this + " unFocus()");
4891        }
4892
4893        clearFocusInternal(false, false);
4894    }
4895
4896    /**
4897     * Returns true if this view has focus iteself, or is the ancestor of the
4898     * view that has focus.
4899     *
4900     * @return True if this view has or contains focus, false otherwise.
4901     */
4902    @ViewDebug.ExportedProperty(category = "focus")
4903    public boolean hasFocus() {
4904        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4905    }
4906
4907    /**
4908     * Returns true if this view is focusable or if it contains a reachable View
4909     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4910     * is a View whose parents do not block descendants focus.
4911     *
4912     * Only {@link #VISIBLE} views are considered focusable.
4913     *
4914     * @return True if the view is focusable or if the view contains a focusable
4915     *         View, false otherwise.
4916     *
4917     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4918     */
4919    public boolean hasFocusable() {
4920        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4921    }
4922
4923    /**
4924     * Called by the view system when the focus state of this view changes.
4925     * When the focus change event is caused by directional navigation, direction
4926     * and previouslyFocusedRect provide insight into where the focus is coming from.
4927     * When overriding, be sure to call up through to the super class so that
4928     * the standard focus handling will occur.
4929     *
4930     * @param gainFocus True if the View has focus; false otherwise.
4931     * @param direction The direction focus has moved when requestFocus()
4932     *                  is called to give this view focus. Values are
4933     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4934     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4935     *                  It may not always apply, in which case use the default.
4936     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4937     *        system, of the previously focused view.  If applicable, this will be
4938     *        passed in as finer grained information about where the focus is coming
4939     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4940     */
4941    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
4942            @Nullable Rect previouslyFocusedRect) {
4943        if (gainFocus) {
4944            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4945        } else {
4946            notifyViewAccessibilityStateChangedIfNeeded(
4947                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
4948        }
4949
4950        InputMethodManager imm = InputMethodManager.peekInstance();
4951        if (!gainFocus) {
4952            if (isPressed()) {
4953                setPressed(false);
4954            }
4955            if (imm != null && mAttachInfo != null
4956                    && mAttachInfo.mHasWindowFocus) {
4957                imm.focusOut(this);
4958            }
4959            onFocusLost();
4960        } else if (imm != null && mAttachInfo != null
4961                && mAttachInfo.mHasWindowFocus) {
4962            imm.focusIn(this);
4963        }
4964
4965        invalidate(true);
4966        ListenerInfo li = mListenerInfo;
4967        if (li != null && li.mOnFocusChangeListener != null) {
4968            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4969        }
4970
4971        if (mAttachInfo != null) {
4972            mAttachInfo.mKeyDispatchState.reset(this);
4973        }
4974    }
4975
4976    /**
4977     * Sends an accessibility event of the given type. If accessibility is
4978     * not enabled this method has no effect. The default implementation calls
4979     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4980     * to populate information about the event source (this View), then calls
4981     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4982     * populate the text content of the event source including its descendants,
4983     * and last calls
4984     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4985     * on its parent to resuest sending of the event to interested parties.
4986     * <p>
4987     * If an {@link AccessibilityDelegate} has been specified via calling
4988     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4989     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4990     * responsible for handling this call.
4991     * </p>
4992     *
4993     * @param eventType The type of the event to send, as defined by several types from
4994     * {@link android.view.accessibility.AccessibilityEvent}, such as
4995     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4996     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4997     *
4998     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4999     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5000     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5001     * @see AccessibilityDelegate
5002     */
5003    public void sendAccessibilityEvent(int eventType) {
5004        // Excluded views do not send accessibility events.
5005        if (!includeForAccessibility()) {
5006            return;
5007        }
5008        if (mAccessibilityDelegate != null) {
5009            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5010        } else {
5011            sendAccessibilityEventInternal(eventType);
5012        }
5013    }
5014
5015    /**
5016     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5017     * {@link AccessibilityEvent} to make an announcement which is related to some
5018     * sort of a context change for which none of the events representing UI transitions
5019     * is a good fit. For example, announcing a new page in a book. If accessibility
5020     * is not enabled this method does nothing.
5021     *
5022     * @param text The announcement text.
5023     */
5024    public void announceForAccessibility(CharSequence text) {
5025        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5026            AccessibilityEvent event = AccessibilityEvent.obtain(
5027                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5028            onInitializeAccessibilityEvent(event);
5029            event.getText().add(text);
5030            event.setContentDescription(null);
5031            mParent.requestSendAccessibilityEvent(this, event);
5032        }
5033    }
5034
5035    /**
5036     * @see #sendAccessibilityEvent(int)
5037     *
5038     * Note: Called from the default {@link AccessibilityDelegate}.
5039     */
5040    void sendAccessibilityEventInternal(int eventType) {
5041        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5042            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5043        }
5044    }
5045
5046    /**
5047     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5048     * takes as an argument an empty {@link AccessibilityEvent} and does not
5049     * perform a check whether accessibility is enabled.
5050     * <p>
5051     * If an {@link AccessibilityDelegate} has been specified via calling
5052     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5053     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5054     * is responsible for handling this call.
5055     * </p>
5056     *
5057     * @param event The event to send.
5058     *
5059     * @see #sendAccessibilityEvent(int)
5060     */
5061    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5062        if (mAccessibilityDelegate != null) {
5063            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5064        } else {
5065            sendAccessibilityEventUncheckedInternal(event);
5066        }
5067    }
5068
5069    /**
5070     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5071     *
5072     * Note: Called from the default {@link AccessibilityDelegate}.
5073     */
5074    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5075        if (!isShown()) {
5076            return;
5077        }
5078        onInitializeAccessibilityEvent(event);
5079        // Only a subset of accessibility events populates text content.
5080        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5081            dispatchPopulateAccessibilityEvent(event);
5082        }
5083        // In the beginning we called #isShown(), so we know that getParent() is not null.
5084        getParent().requestSendAccessibilityEvent(this, event);
5085    }
5086
5087    /**
5088     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5089     * to its children for adding their text content to the event. Note that the
5090     * event text is populated in a separate dispatch path since we add to the
5091     * event not only the text of the source but also the text of all its descendants.
5092     * A typical implementation will call
5093     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5094     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5095     * on each child. Override this method if custom population of the event text
5096     * content is required.
5097     * <p>
5098     * If an {@link AccessibilityDelegate} has been specified via calling
5099     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5100     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5101     * is responsible for handling this call.
5102     * </p>
5103     * <p>
5104     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5105     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5106     * </p>
5107     *
5108     * @param event The event.
5109     *
5110     * @return True if the event population was completed.
5111     */
5112    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5113        if (mAccessibilityDelegate != null) {
5114            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5115        } else {
5116            return dispatchPopulateAccessibilityEventInternal(event);
5117        }
5118    }
5119
5120    /**
5121     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5122     *
5123     * Note: Called from the default {@link AccessibilityDelegate}.
5124     */
5125    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5126        onPopulateAccessibilityEvent(event);
5127        return false;
5128    }
5129
5130    /**
5131     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5132     * giving a chance to this View to populate the accessibility event with its
5133     * text content. While this method is free to modify event
5134     * attributes other than text content, doing so should normally be performed in
5135     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5136     * <p>
5137     * Example: Adding formatted date string to an accessibility event in addition
5138     *          to the text added by the super implementation:
5139     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5140     *     super.onPopulateAccessibilityEvent(event);
5141     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5142     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5143     *         mCurrentDate.getTimeInMillis(), flags);
5144     *     event.getText().add(selectedDateUtterance);
5145     * }</pre>
5146     * <p>
5147     * If an {@link AccessibilityDelegate} has been specified via calling
5148     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5149     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5150     * is responsible for handling this call.
5151     * </p>
5152     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5153     * information to the event, in case the default implementation has basic information to add.
5154     * </p>
5155     *
5156     * @param event The accessibility event which to populate.
5157     *
5158     * @see #sendAccessibilityEvent(int)
5159     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5160     */
5161    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5162        if (mAccessibilityDelegate != null) {
5163            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5164        } else {
5165            onPopulateAccessibilityEventInternal(event);
5166        }
5167    }
5168
5169    /**
5170     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5171     *
5172     * Note: Called from the default {@link AccessibilityDelegate}.
5173     */
5174    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5175    }
5176
5177    /**
5178     * Initializes an {@link AccessibilityEvent} with information about
5179     * this View which is the event source. In other words, the source of
5180     * an accessibility event is the view whose state change triggered firing
5181     * the event.
5182     * <p>
5183     * Example: Setting the password property of an event in addition
5184     *          to properties set by the super implementation:
5185     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5186     *     super.onInitializeAccessibilityEvent(event);
5187     *     event.setPassword(true);
5188     * }</pre>
5189     * <p>
5190     * If an {@link AccessibilityDelegate} has been specified via calling
5191     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5192     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5193     * is responsible for handling this call.
5194     * </p>
5195     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5196     * information to the event, in case the default implementation has basic information to add.
5197     * </p>
5198     * @param event The event to initialize.
5199     *
5200     * @see #sendAccessibilityEvent(int)
5201     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5202     */
5203    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5204        if (mAccessibilityDelegate != null) {
5205            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5206        } else {
5207            onInitializeAccessibilityEventInternal(event);
5208        }
5209    }
5210
5211    /**
5212     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5213     *
5214     * Note: Called from the default {@link AccessibilityDelegate}.
5215     */
5216    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5217        event.setSource(this);
5218        event.setClassName(View.class.getName());
5219        event.setPackageName(getContext().getPackageName());
5220        event.setEnabled(isEnabled());
5221        event.setContentDescription(mContentDescription);
5222
5223        switch (event.getEventType()) {
5224            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5225                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5226                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5227                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5228                event.setItemCount(focusablesTempList.size());
5229                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5230                if (mAttachInfo != null) {
5231                    focusablesTempList.clear();
5232                }
5233            } break;
5234            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5235                CharSequence text = getIterableTextForAccessibility();
5236                if (text != null && text.length() > 0) {
5237                    event.setFromIndex(getAccessibilitySelectionStart());
5238                    event.setToIndex(getAccessibilitySelectionEnd());
5239                    event.setItemCount(text.length());
5240                }
5241            } break;
5242        }
5243    }
5244
5245    /**
5246     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5247     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5248     * This method is responsible for obtaining an accessibility node info from a
5249     * pool of reusable instances and calling
5250     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5251     * initialize the former.
5252     * <p>
5253     * Note: The client is responsible for recycling the obtained instance by calling
5254     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5255     * </p>
5256     *
5257     * @return A populated {@link AccessibilityNodeInfo}.
5258     *
5259     * @see AccessibilityNodeInfo
5260     */
5261    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5262        if (mAccessibilityDelegate != null) {
5263            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5264        } else {
5265            return createAccessibilityNodeInfoInternal();
5266        }
5267    }
5268
5269    /**
5270     * @see #createAccessibilityNodeInfo()
5271     */
5272    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5273        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5274        if (provider != null) {
5275            return provider.createAccessibilityNodeInfo(View.NO_ID);
5276        } else {
5277            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5278            onInitializeAccessibilityNodeInfo(info);
5279            return info;
5280        }
5281    }
5282
5283    /**
5284     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5285     * The base implementation sets:
5286     * <ul>
5287     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5288     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5289     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5290     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5291     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5292     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5293     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5294     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5295     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5296     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5297     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5298     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5299     * </ul>
5300     * <p>
5301     * Subclasses should override this method, call the super implementation,
5302     * and set additional attributes.
5303     * </p>
5304     * <p>
5305     * If an {@link AccessibilityDelegate} has been specified via calling
5306     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5307     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5308     * is responsible for handling this call.
5309     * </p>
5310     *
5311     * @param info The instance to initialize.
5312     */
5313    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5314        if (mAccessibilityDelegate != null) {
5315            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5316        } else {
5317            onInitializeAccessibilityNodeInfoInternal(info);
5318        }
5319    }
5320
5321    /**
5322     * Gets the location of this view in screen coordintates.
5323     *
5324     * @param outRect The output location
5325     */
5326    void getBoundsOnScreen(Rect outRect) {
5327        if (mAttachInfo == null) {
5328            return;
5329        }
5330
5331        RectF position = mAttachInfo.mTmpTransformRect;
5332        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5333
5334        if (!hasIdentityMatrix()) {
5335            getMatrix().mapRect(position);
5336        }
5337
5338        position.offset(mLeft, mTop);
5339
5340        ViewParent parent = mParent;
5341        while (parent instanceof View) {
5342            View parentView = (View) parent;
5343
5344            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5345
5346            if (!parentView.hasIdentityMatrix()) {
5347                parentView.getMatrix().mapRect(position);
5348            }
5349
5350            position.offset(parentView.mLeft, parentView.mTop);
5351
5352            parent = parentView.mParent;
5353        }
5354
5355        if (parent instanceof ViewRootImpl) {
5356            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5357            position.offset(0, -viewRootImpl.mCurScrollY);
5358        }
5359
5360        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5361
5362        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5363                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5364    }
5365
5366    /**
5367     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5368     *
5369     * Note: Called from the default {@link AccessibilityDelegate}.
5370     */
5371    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5372        Rect bounds = mAttachInfo.mTmpInvalRect;
5373
5374        getDrawingRect(bounds);
5375        info.setBoundsInParent(bounds);
5376
5377        getBoundsOnScreen(bounds);
5378        info.setBoundsInScreen(bounds);
5379
5380        ViewParent parent = getParentForAccessibility();
5381        if (parent instanceof View) {
5382            info.setParent((View) parent);
5383        }
5384
5385        if (mID != View.NO_ID) {
5386            View rootView = getRootView();
5387            if (rootView == null) {
5388                rootView = this;
5389            }
5390            View label = rootView.findLabelForView(this, mID);
5391            if (label != null) {
5392                info.setLabeledBy(label);
5393            }
5394
5395            if ((mAttachInfo.mAccessibilityFetchFlags
5396                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5397                    && Resources.resourceHasPackage(mID)) {
5398                try {
5399                    String viewId = getResources().getResourceName(mID);
5400                    info.setViewIdResourceName(viewId);
5401                } catch (Resources.NotFoundException nfe) {
5402                    /* ignore */
5403                }
5404            }
5405        }
5406
5407        if (mLabelForId != View.NO_ID) {
5408            View rootView = getRootView();
5409            if (rootView == null) {
5410                rootView = this;
5411            }
5412            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5413            if (labeled != null) {
5414                info.setLabelFor(labeled);
5415            }
5416        }
5417
5418        info.setVisibleToUser(isVisibleToUser());
5419
5420        info.setPackageName(mContext.getPackageName());
5421        info.setClassName(View.class.getName());
5422        info.setContentDescription(getContentDescription());
5423
5424        info.setEnabled(isEnabled());
5425        info.setClickable(isClickable());
5426        info.setFocusable(isFocusable());
5427        info.setFocused(isFocused());
5428        info.setAccessibilityFocused(isAccessibilityFocused());
5429        info.setSelected(isSelected());
5430        info.setLongClickable(isLongClickable());
5431        info.setLiveRegion(getAccessibilityLiveRegion());
5432
5433        // TODO: These make sense only if we are in an AdapterView but all
5434        // views can be selected. Maybe from accessibility perspective
5435        // we should report as selectable view in an AdapterView.
5436        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5437        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5438
5439        if (isFocusable()) {
5440            if (isFocused()) {
5441                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5442            } else {
5443                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5444            }
5445        }
5446
5447        if (!isAccessibilityFocused()) {
5448            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5449        } else {
5450            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5451        }
5452
5453        if (isClickable() && isEnabled()) {
5454            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5455        }
5456
5457        if (isLongClickable() && isEnabled()) {
5458            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5459        }
5460
5461        CharSequence text = getIterableTextForAccessibility();
5462        if (text != null && text.length() > 0) {
5463            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5464
5465            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5466            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5467            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5468            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5469                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5470                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5471        }
5472    }
5473
5474    private View findLabelForView(View view, int labeledId) {
5475        if (mMatchLabelForPredicate == null) {
5476            mMatchLabelForPredicate = new MatchLabelForPredicate();
5477        }
5478        mMatchLabelForPredicate.mLabeledId = labeledId;
5479        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5480    }
5481
5482    /**
5483     * Computes whether this view is visible to the user. Such a view is
5484     * attached, visible, all its predecessors are visible, it is not clipped
5485     * entirely by its predecessors, and has an alpha greater than zero.
5486     *
5487     * @return Whether the view is visible on the screen.
5488     *
5489     * @hide
5490     */
5491    protected boolean isVisibleToUser() {
5492        return isVisibleToUser(null);
5493    }
5494
5495    /**
5496     * Computes whether the given portion of this view is visible to the user.
5497     * Such a view is attached, visible, all its predecessors are visible,
5498     * has an alpha greater than zero, and the specified portion is not
5499     * clipped entirely by its predecessors.
5500     *
5501     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5502     *                    <code>null</code>, and the entire view will be tested in this case.
5503     *                    When <code>true</code> is returned by the function, the actual visible
5504     *                    region will be stored in this parameter; that is, if boundInView is fully
5505     *                    contained within the view, no modification will be made, otherwise regions
5506     *                    outside of the visible area of the view will be clipped.
5507     *
5508     * @return Whether the specified portion of the view is visible on the screen.
5509     *
5510     * @hide
5511     */
5512    protected boolean isVisibleToUser(Rect boundInView) {
5513        if (mAttachInfo != null) {
5514            // Attached to invisible window means this view is not visible.
5515            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5516                return false;
5517            }
5518            // An invisible predecessor or one with alpha zero means
5519            // that this view is not visible to the user.
5520            Object current = this;
5521            while (current instanceof View) {
5522                View view = (View) current;
5523                // We have attach info so this view is attached and there is no
5524                // need to check whether we reach to ViewRootImpl on the way up.
5525                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5526                        view.getVisibility() != VISIBLE) {
5527                    return false;
5528                }
5529                current = view.mParent;
5530            }
5531            // Check if the view is entirely covered by its predecessors.
5532            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5533            Point offset = mAttachInfo.mPoint;
5534            if (!getGlobalVisibleRect(visibleRect, offset)) {
5535                return false;
5536            }
5537            // Check if the visible portion intersects the rectangle of interest.
5538            if (boundInView != null) {
5539                visibleRect.offset(-offset.x, -offset.y);
5540                return boundInView.intersect(visibleRect);
5541            }
5542            return true;
5543        }
5544        return false;
5545    }
5546
5547    /**
5548     * Returns the delegate for implementing accessibility support via
5549     * composition. For more details see {@link AccessibilityDelegate}.
5550     *
5551     * @return The delegate, or null if none set.
5552     *
5553     * @hide
5554     */
5555    public AccessibilityDelegate getAccessibilityDelegate() {
5556        return mAccessibilityDelegate;
5557    }
5558
5559    /**
5560     * Sets a delegate for implementing accessibility support via composition as
5561     * opposed to inheritance. The delegate's primary use is for implementing
5562     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5563     *
5564     * @param delegate The delegate instance.
5565     *
5566     * @see AccessibilityDelegate
5567     */
5568    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5569        mAccessibilityDelegate = delegate;
5570    }
5571
5572    /**
5573     * Gets the provider for managing a virtual view hierarchy rooted at this View
5574     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5575     * that explore the window content.
5576     * <p>
5577     * If this method returns an instance, this instance is responsible for managing
5578     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5579     * View including the one representing the View itself. Similarly the returned
5580     * instance is responsible for performing accessibility actions on any virtual
5581     * view or the root view itself.
5582     * </p>
5583     * <p>
5584     * If an {@link AccessibilityDelegate} has been specified via calling
5585     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5586     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5587     * is responsible for handling this call.
5588     * </p>
5589     *
5590     * @return The provider.
5591     *
5592     * @see AccessibilityNodeProvider
5593     */
5594    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5595        if (mAccessibilityDelegate != null) {
5596            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5597        } else {
5598            return null;
5599        }
5600    }
5601
5602    /**
5603     * Gets the unique identifier of this view on the screen for accessibility purposes.
5604     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5605     *
5606     * @return The view accessibility id.
5607     *
5608     * @hide
5609     */
5610    public int getAccessibilityViewId() {
5611        if (mAccessibilityViewId == NO_ID) {
5612            mAccessibilityViewId = sNextAccessibilityViewId++;
5613        }
5614        return mAccessibilityViewId;
5615    }
5616
5617    /**
5618     * Gets the unique identifier of the window in which this View reseides.
5619     *
5620     * @return The window accessibility id.
5621     *
5622     * @hide
5623     */
5624    public int getAccessibilityWindowId() {
5625        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5626    }
5627
5628    /**
5629     * Gets the {@link View} description. It briefly describes the view and is
5630     * primarily used for accessibility support. Set this property to enable
5631     * better accessibility support for your application. This is especially
5632     * true for views that do not have textual representation (For example,
5633     * ImageButton).
5634     *
5635     * @return The content description.
5636     *
5637     * @attr ref android.R.styleable#View_contentDescription
5638     */
5639    @ViewDebug.ExportedProperty(category = "accessibility")
5640    public CharSequence getContentDescription() {
5641        return mContentDescription;
5642    }
5643
5644    /**
5645     * Sets the {@link View} description. It briefly describes the view and is
5646     * primarily used for accessibility support. Set this property to enable
5647     * better accessibility support for your application. This is especially
5648     * true for views that do not have textual representation (For example,
5649     * ImageButton).
5650     *
5651     * @param contentDescription The content description.
5652     *
5653     * @attr ref android.R.styleable#View_contentDescription
5654     */
5655    @RemotableViewMethod
5656    public void setContentDescription(CharSequence contentDescription) {
5657        if (mContentDescription == null) {
5658            if (contentDescription == null) {
5659                return;
5660            }
5661        } else if (mContentDescription.equals(contentDescription)) {
5662            return;
5663        }
5664        mContentDescription = contentDescription;
5665        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5666        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5667            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5668            notifySubtreeAccessibilityStateChangedIfNeeded();
5669        } else {
5670            notifyViewAccessibilityStateChangedIfNeeded(
5671                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5672        }
5673    }
5674
5675    /**
5676     * Gets the id of a view for which this view serves as a label for
5677     * accessibility purposes.
5678     *
5679     * @return The labeled view id.
5680     */
5681    @ViewDebug.ExportedProperty(category = "accessibility")
5682    public int getLabelFor() {
5683        return mLabelForId;
5684    }
5685
5686    /**
5687     * Sets the id of a view for which this view serves as a label for
5688     * accessibility purposes.
5689     *
5690     * @param id The labeled view id.
5691     */
5692    @RemotableViewMethod
5693    public void setLabelFor(int id) {
5694        mLabelForId = id;
5695        if (mLabelForId != View.NO_ID
5696                && mID == View.NO_ID) {
5697            mID = generateViewId();
5698        }
5699    }
5700
5701    /**
5702     * Invoked whenever this view loses focus, either by losing window focus or by losing
5703     * focus within its window. This method can be used to clear any state tied to the
5704     * focus. For instance, if a button is held pressed with the trackball and the window
5705     * loses focus, this method can be used to cancel the press.
5706     *
5707     * Subclasses of View overriding this method should always call super.onFocusLost().
5708     *
5709     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5710     * @see #onWindowFocusChanged(boolean)
5711     *
5712     * @hide pending API council approval
5713     */
5714    protected void onFocusLost() {
5715        resetPressedState();
5716    }
5717
5718    private void resetPressedState() {
5719        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5720            return;
5721        }
5722
5723        if (isPressed()) {
5724            setPressed(false);
5725
5726            if (!mHasPerformedLongPress) {
5727                removeLongPressCallback();
5728            }
5729        }
5730    }
5731
5732    /**
5733     * Returns true if this view has focus
5734     *
5735     * @return True if this view has focus, false otherwise.
5736     */
5737    @ViewDebug.ExportedProperty(category = "focus")
5738    public boolean isFocused() {
5739        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5740    }
5741
5742    /**
5743     * Find the view in the hierarchy rooted at this view that currently has
5744     * focus.
5745     *
5746     * @return The view that currently has focus, or null if no focused view can
5747     *         be found.
5748     */
5749    public View findFocus() {
5750        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5751    }
5752
5753    /**
5754     * Indicates whether this view is one of the set of scrollable containers in
5755     * its window.
5756     *
5757     * @return whether this view is one of the set of scrollable containers in
5758     * its window
5759     *
5760     * @attr ref android.R.styleable#View_isScrollContainer
5761     */
5762    public boolean isScrollContainer() {
5763        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5764    }
5765
5766    /**
5767     * Change whether this view is one of the set of scrollable containers in
5768     * its window.  This will be used to determine whether the window can
5769     * resize or must pan when a soft input area is open -- scrollable
5770     * containers allow the window to use resize mode since the container
5771     * will appropriately shrink.
5772     *
5773     * @attr ref android.R.styleable#View_isScrollContainer
5774     */
5775    public void setScrollContainer(boolean isScrollContainer) {
5776        if (isScrollContainer) {
5777            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5778                mAttachInfo.mScrollContainers.add(this);
5779                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5780            }
5781            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5782        } else {
5783            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5784                mAttachInfo.mScrollContainers.remove(this);
5785            }
5786            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5787        }
5788    }
5789
5790    /**
5791     * Returns the quality of the drawing cache.
5792     *
5793     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5794     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5795     *
5796     * @see #setDrawingCacheQuality(int)
5797     * @see #setDrawingCacheEnabled(boolean)
5798     * @see #isDrawingCacheEnabled()
5799     *
5800     * @attr ref android.R.styleable#View_drawingCacheQuality
5801     */
5802    @DrawingCacheQuality
5803    public int getDrawingCacheQuality() {
5804        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5805    }
5806
5807    /**
5808     * Set the drawing cache quality of this view. This value is used only when the
5809     * drawing cache is enabled
5810     *
5811     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5812     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5813     *
5814     * @see #getDrawingCacheQuality()
5815     * @see #setDrawingCacheEnabled(boolean)
5816     * @see #isDrawingCacheEnabled()
5817     *
5818     * @attr ref android.R.styleable#View_drawingCacheQuality
5819     */
5820    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5821        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5822    }
5823
5824    /**
5825     * Returns whether the screen should remain on, corresponding to the current
5826     * value of {@link #KEEP_SCREEN_ON}.
5827     *
5828     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5829     *
5830     * @see #setKeepScreenOn(boolean)
5831     *
5832     * @attr ref android.R.styleable#View_keepScreenOn
5833     */
5834    public boolean getKeepScreenOn() {
5835        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5836    }
5837
5838    /**
5839     * Controls whether the screen should remain on, modifying the
5840     * value of {@link #KEEP_SCREEN_ON}.
5841     *
5842     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5843     *
5844     * @see #getKeepScreenOn()
5845     *
5846     * @attr ref android.R.styleable#View_keepScreenOn
5847     */
5848    public void setKeepScreenOn(boolean keepScreenOn) {
5849        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5850    }
5851
5852    /**
5853     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5854     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5855     *
5856     * @attr ref android.R.styleable#View_nextFocusLeft
5857     */
5858    public int getNextFocusLeftId() {
5859        return mNextFocusLeftId;
5860    }
5861
5862    /**
5863     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5864     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5865     * decide automatically.
5866     *
5867     * @attr ref android.R.styleable#View_nextFocusLeft
5868     */
5869    public void setNextFocusLeftId(int nextFocusLeftId) {
5870        mNextFocusLeftId = nextFocusLeftId;
5871    }
5872
5873    /**
5874     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5875     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5876     *
5877     * @attr ref android.R.styleable#View_nextFocusRight
5878     */
5879    public int getNextFocusRightId() {
5880        return mNextFocusRightId;
5881    }
5882
5883    /**
5884     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5885     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5886     * decide automatically.
5887     *
5888     * @attr ref android.R.styleable#View_nextFocusRight
5889     */
5890    public void setNextFocusRightId(int nextFocusRightId) {
5891        mNextFocusRightId = nextFocusRightId;
5892    }
5893
5894    /**
5895     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5896     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5897     *
5898     * @attr ref android.R.styleable#View_nextFocusUp
5899     */
5900    public int getNextFocusUpId() {
5901        return mNextFocusUpId;
5902    }
5903
5904    /**
5905     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5906     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5907     * decide automatically.
5908     *
5909     * @attr ref android.R.styleable#View_nextFocusUp
5910     */
5911    public void setNextFocusUpId(int nextFocusUpId) {
5912        mNextFocusUpId = nextFocusUpId;
5913    }
5914
5915    /**
5916     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5917     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5918     *
5919     * @attr ref android.R.styleable#View_nextFocusDown
5920     */
5921    public int getNextFocusDownId() {
5922        return mNextFocusDownId;
5923    }
5924
5925    /**
5926     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5927     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5928     * decide automatically.
5929     *
5930     * @attr ref android.R.styleable#View_nextFocusDown
5931     */
5932    public void setNextFocusDownId(int nextFocusDownId) {
5933        mNextFocusDownId = nextFocusDownId;
5934    }
5935
5936    /**
5937     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5938     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5939     *
5940     * @attr ref android.R.styleable#View_nextFocusForward
5941     */
5942    public int getNextFocusForwardId() {
5943        return mNextFocusForwardId;
5944    }
5945
5946    /**
5947     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5948     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5949     * decide automatically.
5950     *
5951     * @attr ref android.R.styleable#View_nextFocusForward
5952     */
5953    public void setNextFocusForwardId(int nextFocusForwardId) {
5954        mNextFocusForwardId = nextFocusForwardId;
5955    }
5956
5957    /**
5958     * Returns the visibility of this view and all of its ancestors
5959     *
5960     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5961     */
5962    public boolean isShown() {
5963        View current = this;
5964        //noinspection ConstantConditions
5965        do {
5966            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5967                return false;
5968            }
5969            ViewParent parent = current.mParent;
5970            if (parent == null) {
5971                return false; // We are not attached to the view root
5972            }
5973            if (!(parent instanceof View)) {
5974                return true;
5975            }
5976            current = (View) parent;
5977        } while (current != null);
5978
5979        return false;
5980    }
5981
5982    /**
5983     * Called by the view hierarchy when the content insets for a window have
5984     * changed, to allow it to adjust its content to fit within those windows.
5985     * The content insets tell you the space that the status bar, input method,
5986     * and other system windows infringe on the application's window.
5987     *
5988     * <p>You do not normally need to deal with this function, since the default
5989     * window decoration given to applications takes care of applying it to the
5990     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5991     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5992     * and your content can be placed under those system elements.  You can then
5993     * use this method within your view hierarchy if you have parts of your UI
5994     * which you would like to ensure are not being covered.
5995     *
5996     * <p>The default implementation of this method simply applies the content
5997     * insets to the view's padding, consuming that content (modifying the
5998     * insets to be 0), and returning true.  This behavior is off by default, but can
5999     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6000     *
6001     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6002     * insets object is propagated down the hierarchy, so any changes made to it will
6003     * be seen by all following views (including potentially ones above in
6004     * the hierarchy since this is a depth-first traversal).  The first view
6005     * that returns true will abort the entire traversal.
6006     *
6007     * <p>The default implementation works well for a situation where it is
6008     * used with a container that covers the entire window, allowing it to
6009     * apply the appropriate insets to its content on all edges.  If you need
6010     * a more complicated layout (such as two different views fitting system
6011     * windows, one on the top of the window, and one on the bottom),
6012     * you can override the method and handle the insets however you would like.
6013     * Note that the insets provided by the framework are always relative to the
6014     * far edges of the window, not accounting for the location of the called view
6015     * within that window.  (In fact when this method is called you do not yet know
6016     * where the layout will place the view, as it is done before layout happens.)
6017     *
6018     * <p>Note: unlike many View methods, there is no dispatch phase to this
6019     * call.  If you are overriding it in a ViewGroup and want to allow the
6020     * call to continue to your children, you must be sure to call the super
6021     * implementation.
6022     *
6023     * <p>Here is a sample layout that makes use of fitting system windows
6024     * to have controls for a video view placed inside of the window decorations
6025     * that it hides and shows.  This can be used with code like the second
6026     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6027     *
6028     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6029     *
6030     * @param insets Current content insets of the window.  Prior to
6031     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6032     * the insets or else you and Android will be unhappy.
6033     *
6034     * @return {@code true} if this view applied the insets and it should not
6035     * continue propagating further down the hierarchy, {@code false} otherwise.
6036     * @see #getFitsSystemWindows()
6037     * @see #setFitsSystemWindows(boolean)
6038     * @see #setSystemUiVisibility(int)
6039     */
6040    protected boolean fitSystemWindows(Rect insets) {
6041        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6042            mUserPaddingStart = UNDEFINED_PADDING;
6043            mUserPaddingEnd = UNDEFINED_PADDING;
6044            Rect localInsets = sThreadLocal.get();
6045            if (localInsets == null) {
6046                localInsets = new Rect();
6047                sThreadLocal.set(localInsets);
6048            }
6049            boolean res = computeFitSystemWindows(insets, localInsets);
6050            mUserPaddingLeftInitial = localInsets.left;
6051            mUserPaddingRightInitial = localInsets.right;
6052            internalSetPadding(localInsets.left, localInsets.top,
6053                    localInsets.right, localInsets.bottom);
6054            return res;
6055        }
6056        return false;
6057    }
6058
6059    /**
6060     * @hide Compute the insets that should be consumed by this view and the ones
6061     * that should propagate to those under it.
6062     */
6063    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6064        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6065                || mAttachInfo == null
6066                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6067                        && !mAttachInfo.mOverscanRequested)) {
6068            outLocalInsets.set(inoutInsets);
6069            inoutInsets.set(0, 0, 0, 0);
6070            return true;
6071        } else {
6072            // The application wants to take care of fitting system window for
6073            // the content...  however we still need to take care of any overscan here.
6074            final Rect overscan = mAttachInfo.mOverscanInsets;
6075            outLocalInsets.set(overscan);
6076            inoutInsets.left -= overscan.left;
6077            inoutInsets.top -= overscan.top;
6078            inoutInsets.right -= overscan.right;
6079            inoutInsets.bottom -= overscan.bottom;
6080            return false;
6081        }
6082    }
6083
6084    /**
6085     * Sets whether or not this view should account for system screen decorations
6086     * such as the status bar and inset its content; that is, controlling whether
6087     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6088     * executed.  See that method for more details.
6089     *
6090     * <p>Note that if you are providing your own implementation of
6091     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6092     * flag to true -- your implementation will be overriding the default
6093     * implementation that checks this flag.
6094     *
6095     * @param fitSystemWindows If true, then the default implementation of
6096     * {@link #fitSystemWindows(Rect)} will be executed.
6097     *
6098     * @attr ref android.R.styleable#View_fitsSystemWindows
6099     * @see #getFitsSystemWindows()
6100     * @see #fitSystemWindows(Rect)
6101     * @see #setSystemUiVisibility(int)
6102     */
6103    public void setFitsSystemWindows(boolean fitSystemWindows) {
6104        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6105    }
6106
6107    /**
6108     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6109     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6110     * will be executed.
6111     *
6112     * @return {@code true} if the default implementation of
6113     * {@link #fitSystemWindows(Rect)} will be executed.
6114     *
6115     * @attr ref android.R.styleable#View_fitsSystemWindows
6116     * @see #setFitsSystemWindows(boolean)
6117     * @see #fitSystemWindows(Rect)
6118     * @see #setSystemUiVisibility(int)
6119     */
6120    public boolean getFitsSystemWindows() {
6121        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6122    }
6123
6124    /** @hide */
6125    public boolean fitsSystemWindows() {
6126        return getFitsSystemWindows();
6127    }
6128
6129    /**
6130     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6131     */
6132    public void requestFitSystemWindows() {
6133        if (mParent != null) {
6134            mParent.requestFitSystemWindows();
6135        }
6136    }
6137
6138    /**
6139     * For use by PhoneWindow to make its own system window fitting optional.
6140     * @hide
6141     */
6142    public void makeOptionalFitsSystemWindows() {
6143        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6144    }
6145
6146    /**
6147     * Returns the visibility status for this view.
6148     *
6149     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6150     * @attr ref android.R.styleable#View_visibility
6151     */
6152    @ViewDebug.ExportedProperty(mapping = {
6153        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6154        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6155        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6156    })
6157    @Visibility
6158    public int getVisibility() {
6159        return mViewFlags & VISIBILITY_MASK;
6160    }
6161
6162    /**
6163     * Set the enabled state of this view.
6164     *
6165     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6166     * @attr ref android.R.styleable#View_visibility
6167     */
6168    @RemotableViewMethod
6169    public void setVisibility(@Visibility int visibility) {
6170        setFlags(visibility, VISIBILITY_MASK);
6171        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6172    }
6173
6174    /**
6175     * Returns the enabled status for this view. The interpretation of the
6176     * enabled state varies by subclass.
6177     *
6178     * @return True if this view is enabled, false otherwise.
6179     */
6180    @ViewDebug.ExportedProperty
6181    public boolean isEnabled() {
6182        return (mViewFlags & ENABLED_MASK) == ENABLED;
6183    }
6184
6185    /**
6186     * Set the enabled state of this view. The interpretation of the enabled
6187     * state varies by subclass.
6188     *
6189     * @param enabled True if this view is enabled, false otherwise.
6190     */
6191    @RemotableViewMethod
6192    public void setEnabled(boolean enabled) {
6193        if (enabled == isEnabled()) return;
6194
6195        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6196
6197        /*
6198         * The View most likely has to change its appearance, so refresh
6199         * the drawable state.
6200         */
6201        refreshDrawableState();
6202
6203        // Invalidate too, since the default behavior for views is to be
6204        // be drawn at 50% alpha rather than to change the drawable.
6205        invalidate(true);
6206
6207        if (!enabled) {
6208            cancelPendingInputEvents();
6209        }
6210    }
6211
6212    /**
6213     * Set whether this view can receive the focus.
6214     *
6215     * Setting this to false will also ensure that this view is not focusable
6216     * in touch mode.
6217     *
6218     * @param focusable If true, this view can receive the focus.
6219     *
6220     * @see #setFocusableInTouchMode(boolean)
6221     * @attr ref android.R.styleable#View_focusable
6222     */
6223    public void setFocusable(boolean focusable) {
6224        if (!focusable) {
6225            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6226        }
6227        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6228    }
6229
6230    /**
6231     * Set whether this view can receive focus while in touch mode.
6232     *
6233     * Setting this to true will also ensure that this view is focusable.
6234     *
6235     * @param focusableInTouchMode If true, this view can receive the focus while
6236     *   in touch mode.
6237     *
6238     * @see #setFocusable(boolean)
6239     * @attr ref android.R.styleable#View_focusableInTouchMode
6240     */
6241    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6242        // Focusable in touch mode should always be set before the focusable flag
6243        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6244        // which, in touch mode, will not successfully request focus on this view
6245        // because the focusable in touch mode flag is not set
6246        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6247        if (focusableInTouchMode) {
6248            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6249        }
6250    }
6251
6252    /**
6253     * Set whether this view should have sound effects enabled for events such as
6254     * clicking and touching.
6255     *
6256     * <p>You may wish to disable sound effects for a view if you already play sounds,
6257     * for instance, a dial key that plays dtmf tones.
6258     *
6259     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6260     * @see #isSoundEffectsEnabled()
6261     * @see #playSoundEffect(int)
6262     * @attr ref android.R.styleable#View_soundEffectsEnabled
6263     */
6264    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6265        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6266    }
6267
6268    /**
6269     * @return whether this view should have sound effects enabled for events such as
6270     *     clicking and touching.
6271     *
6272     * @see #setSoundEffectsEnabled(boolean)
6273     * @see #playSoundEffect(int)
6274     * @attr ref android.R.styleable#View_soundEffectsEnabled
6275     */
6276    @ViewDebug.ExportedProperty
6277    public boolean isSoundEffectsEnabled() {
6278        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6279    }
6280
6281    /**
6282     * Set whether this view should have haptic feedback for events such as
6283     * long presses.
6284     *
6285     * <p>You may wish to disable haptic feedback if your view already controls
6286     * its own haptic feedback.
6287     *
6288     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6289     * @see #isHapticFeedbackEnabled()
6290     * @see #performHapticFeedback(int)
6291     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6292     */
6293    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6294        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6295    }
6296
6297    /**
6298     * @return whether this view should have haptic feedback enabled for events
6299     * long presses.
6300     *
6301     * @see #setHapticFeedbackEnabled(boolean)
6302     * @see #performHapticFeedback(int)
6303     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6304     */
6305    @ViewDebug.ExportedProperty
6306    public boolean isHapticFeedbackEnabled() {
6307        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6308    }
6309
6310    /**
6311     * Returns the layout direction for this view.
6312     *
6313     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6314     *   {@link #LAYOUT_DIRECTION_RTL},
6315     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6316     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6317     *
6318     * @attr ref android.R.styleable#View_layoutDirection
6319     *
6320     * @hide
6321     */
6322    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6323        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6324        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6325        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6326        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6327    })
6328    @LayoutDir
6329    public int getRawLayoutDirection() {
6330        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6331    }
6332
6333    /**
6334     * Set the layout direction for this view. This will propagate a reset of layout direction
6335     * resolution to the view's children and resolve layout direction for this view.
6336     *
6337     * @param layoutDirection the layout direction to set. Should be one of:
6338     *
6339     * {@link #LAYOUT_DIRECTION_LTR},
6340     * {@link #LAYOUT_DIRECTION_RTL},
6341     * {@link #LAYOUT_DIRECTION_INHERIT},
6342     * {@link #LAYOUT_DIRECTION_LOCALE}.
6343     *
6344     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6345     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6346     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6347     *
6348     * @attr ref android.R.styleable#View_layoutDirection
6349     */
6350    @RemotableViewMethod
6351    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6352        if (getRawLayoutDirection() != layoutDirection) {
6353            // Reset the current layout direction and the resolved one
6354            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6355            resetRtlProperties();
6356            // Set the new layout direction (filtered)
6357            mPrivateFlags2 |=
6358                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6359            // We need to resolve all RTL properties as they all depend on layout direction
6360            resolveRtlPropertiesIfNeeded();
6361            requestLayout();
6362            invalidate(true);
6363        }
6364    }
6365
6366    /**
6367     * Returns the resolved layout direction for this view.
6368     *
6369     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6370     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6371     *
6372     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6373     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6374     *
6375     * @attr ref android.R.styleable#View_layoutDirection
6376     */
6377    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6378        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6379        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6380    })
6381    @ResolvedLayoutDir
6382    public int getLayoutDirection() {
6383        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6384        if (targetSdkVersion < JELLY_BEAN_MR1) {
6385            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6386            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6387        }
6388        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6389                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6390    }
6391
6392    /**
6393     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6394     * layout attribute and/or the inherited value from the parent
6395     *
6396     * @return true if the layout is right-to-left.
6397     *
6398     * @hide
6399     */
6400    @ViewDebug.ExportedProperty(category = "layout")
6401    public boolean isLayoutRtl() {
6402        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6403    }
6404
6405    /**
6406     * Indicates whether the view is currently tracking transient state that the
6407     * app should not need to concern itself with saving and restoring, but that
6408     * the framework should take special note to preserve when possible.
6409     *
6410     * <p>A view with transient state cannot be trivially rebound from an external
6411     * data source, such as an adapter binding item views in a list. This may be
6412     * because the view is performing an animation, tracking user selection
6413     * of content, or similar.</p>
6414     *
6415     * @return true if the view has transient state
6416     */
6417    @ViewDebug.ExportedProperty(category = "layout")
6418    public boolean hasTransientState() {
6419        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6420    }
6421
6422    /**
6423     * Set whether this view is currently tracking transient state that the
6424     * framework should attempt to preserve when possible. This flag is reference counted,
6425     * so every call to setHasTransientState(true) should be paired with a later call
6426     * to setHasTransientState(false).
6427     *
6428     * <p>A view with transient state cannot be trivially rebound from an external
6429     * data source, such as an adapter binding item views in a list. This may be
6430     * because the view is performing an animation, tracking user selection
6431     * of content, or similar.</p>
6432     *
6433     * @param hasTransientState true if this view has transient state
6434     */
6435    public void setHasTransientState(boolean hasTransientState) {
6436        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6437                mTransientStateCount - 1;
6438        if (mTransientStateCount < 0) {
6439            mTransientStateCount = 0;
6440            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6441                    "unmatched pair of setHasTransientState calls");
6442        } else if ((hasTransientState && mTransientStateCount == 1) ||
6443                (!hasTransientState && mTransientStateCount == 0)) {
6444            // update flag if we've just incremented up from 0 or decremented down to 0
6445            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6446                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6447            if (mParent != null) {
6448                try {
6449                    mParent.childHasTransientStateChanged(this, hasTransientState);
6450                } catch (AbstractMethodError e) {
6451                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6452                            " does not fully implement ViewParent", e);
6453                }
6454            }
6455        }
6456    }
6457
6458    /**
6459     * Returns true if this view is currently attached to a window.
6460     */
6461    public boolean isAttachedToWindow() {
6462        return mAttachInfo != null;
6463    }
6464
6465    /**
6466     * Returns true if this view has been through at least one layout since it
6467     * was last attached to or detached from a window.
6468     */
6469    public boolean isLaidOut() {
6470        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6471    }
6472
6473    /**
6474     * If this view doesn't do any drawing on its own, set this flag to
6475     * allow further optimizations. By default, this flag is not set on
6476     * View, but could be set on some View subclasses such as ViewGroup.
6477     *
6478     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6479     * you should clear this flag.
6480     *
6481     * @param willNotDraw whether or not this View draw on its own
6482     */
6483    public void setWillNotDraw(boolean willNotDraw) {
6484        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6485    }
6486
6487    /**
6488     * Returns whether or not this View draws on its own.
6489     *
6490     * @return true if this view has nothing to draw, false otherwise
6491     */
6492    @ViewDebug.ExportedProperty(category = "drawing")
6493    public boolean willNotDraw() {
6494        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6495    }
6496
6497    /**
6498     * When a View's drawing cache is enabled, drawing is redirected to an
6499     * offscreen bitmap. Some views, like an ImageView, must be able to
6500     * bypass this mechanism if they already draw a single bitmap, to avoid
6501     * unnecessary usage of the memory.
6502     *
6503     * @param willNotCacheDrawing true if this view does not cache its
6504     *        drawing, false otherwise
6505     */
6506    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6507        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6508    }
6509
6510    /**
6511     * Returns whether or not this View can cache its drawing or not.
6512     *
6513     * @return true if this view does not cache its drawing, false otherwise
6514     */
6515    @ViewDebug.ExportedProperty(category = "drawing")
6516    public boolean willNotCacheDrawing() {
6517        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6518    }
6519
6520    /**
6521     * Indicates whether this view reacts to click events or not.
6522     *
6523     * @return true if the view is clickable, false otherwise
6524     *
6525     * @see #setClickable(boolean)
6526     * @attr ref android.R.styleable#View_clickable
6527     */
6528    @ViewDebug.ExportedProperty
6529    public boolean isClickable() {
6530        return (mViewFlags & CLICKABLE) == CLICKABLE;
6531    }
6532
6533    /**
6534     * Enables or disables click events for this view. When a view
6535     * is clickable it will change its state to "pressed" on every click.
6536     * Subclasses should set the view clickable to visually react to
6537     * user's clicks.
6538     *
6539     * @param clickable true to make the view clickable, false otherwise
6540     *
6541     * @see #isClickable()
6542     * @attr ref android.R.styleable#View_clickable
6543     */
6544    public void setClickable(boolean clickable) {
6545        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6546    }
6547
6548    /**
6549     * Indicates whether this view reacts to long click events or not.
6550     *
6551     * @return true if the view is long clickable, false otherwise
6552     *
6553     * @see #setLongClickable(boolean)
6554     * @attr ref android.R.styleable#View_longClickable
6555     */
6556    public boolean isLongClickable() {
6557        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6558    }
6559
6560    /**
6561     * Enables or disables long click events for this view. When a view is long
6562     * clickable it reacts to the user holding down the button for a longer
6563     * duration than a tap. This event can either launch the listener or a
6564     * context menu.
6565     *
6566     * @param longClickable true to make the view long clickable, false otherwise
6567     * @see #isLongClickable()
6568     * @attr ref android.R.styleable#View_longClickable
6569     */
6570    public void setLongClickable(boolean longClickable) {
6571        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6572    }
6573
6574    /**
6575     * Sets the pressed state for this view.
6576     *
6577     * @see #isClickable()
6578     * @see #setClickable(boolean)
6579     *
6580     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6581     *        the View's internal state from a previously set "pressed" state.
6582     */
6583    public void setPressed(boolean pressed) {
6584        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6585
6586        if (pressed) {
6587            mPrivateFlags |= PFLAG_PRESSED;
6588        } else {
6589            mPrivateFlags &= ~PFLAG_PRESSED;
6590        }
6591
6592        if (needsRefresh) {
6593            refreshDrawableState();
6594        }
6595        dispatchSetPressed(pressed);
6596    }
6597
6598    /**
6599     * Dispatch setPressed to all of this View's children.
6600     *
6601     * @see #setPressed(boolean)
6602     *
6603     * @param pressed The new pressed state
6604     */
6605    protected void dispatchSetPressed(boolean pressed) {
6606    }
6607
6608    /**
6609     * Indicates whether the view is currently in pressed state. Unless
6610     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6611     * the pressed state.
6612     *
6613     * @see #setPressed(boolean)
6614     * @see #isClickable()
6615     * @see #setClickable(boolean)
6616     *
6617     * @return true if the view is currently pressed, false otherwise
6618     */
6619    public boolean isPressed() {
6620        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6621    }
6622
6623    /**
6624     * Indicates whether this view will save its state (that is,
6625     * whether its {@link #onSaveInstanceState} method will be called).
6626     *
6627     * @return Returns true if the view state saving is enabled, else false.
6628     *
6629     * @see #setSaveEnabled(boolean)
6630     * @attr ref android.R.styleable#View_saveEnabled
6631     */
6632    public boolean isSaveEnabled() {
6633        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6634    }
6635
6636    /**
6637     * Controls whether the saving of this view's state is
6638     * enabled (that is, whether its {@link #onSaveInstanceState} method
6639     * will be called).  Note that even if freezing is enabled, the
6640     * view still must have an id assigned to it (via {@link #setId(int)})
6641     * for its state to be saved.  This flag can only disable the
6642     * saving of this view; any child views may still have their state saved.
6643     *
6644     * @param enabled Set to false to <em>disable</em> state saving, or true
6645     * (the default) to allow it.
6646     *
6647     * @see #isSaveEnabled()
6648     * @see #setId(int)
6649     * @see #onSaveInstanceState()
6650     * @attr ref android.R.styleable#View_saveEnabled
6651     */
6652    public void setSaveEnabled(boolean enabled) {
6653        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6654    }
6655
6656    /**
6657     * Gets whether the framework should discard touches when the view's
6658     * window is obscured by another visible window.
6659     * Refer to the {@link View} security documentation for more details.
6660     *
6661     * @return True if touch filtering is enabled.
6662     *
6663     * @see #setFilterTouchesWhenObscured(boolean)
6664     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6665     */
6666    @ViewDebug.ExportedProperty
6667    public boolean getFilterTouchesWhenObscured() {
6668        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6669    }
6670
6671    /**
6672     * Sets whether the framework should discard touches when the view's
6673     * window is obscured by another visible window.
6674     * Refer to the {@link View} security documentation for more details.
6675     *
6676     * @param enabled True if touch filtering should be enabled.
6677     *
6678     * @see #getFilterTouchesWhenObscured
6679     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6680     */
6681    public void setFilterTouchesWhenObscured(boolean enabled) {
6682        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6683                FILTER_TOUCHES_WHEN_OBSCURED);
6684    }
6685
6686    /**
6687     * Indicates whether the entire hierarchy under this view will save its
6688     * state when a state saving traversal occurs from its parent.  The default
6689     * is true; if false, these views will not be saved unless
6690     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6691     *
6692     * @return Returns true if the view state saving from parent is enabled, else false.
6693     *
6694     * @see #setSaveFromParentEnabled(boolean)
6695     */
6696    public boolean isSaveFromParentEnabled() {
6697        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6698    }
6699
6700    /**
6701     * Controls whether the entire hierarchy under this view will save its
6702     * state when a state saving traversal occurs from its parent.  The default
6703     * is true; if false, these views will not be saved unless
6704     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6705     *
6706     * @param enabled Set to false to <em>disable</em> state saving, or true
6707     * (the default) to allow it.
6708     *
6709     * @see #isSaveFromParentEnabled()
6710     * @see #setId(int)
6711     * @see #onSaveInstanceState()
6712     */
6713    public void setSaveFromParentEnabled(boolean enabled) {
6714        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6715    }
6716
6717
6718    /**
6719     * Returns whether this View is able to take focus.
6720     *
6721     * @return True if this view can take focus, or false otherwise.
6722     * @attr ref android.R.styleable#View_focusable
6723     */
6724    @ViewDebug.ExportedProperty(category = "focus")
6725    public final boolean isFocusable() {
6726        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6727    }
6728
6729    /**
6730     * When a view is focusable, it may not want to take focus when in touch mode.
6731     * For example, a button would like focus when the user is navigating via a D-pad
6732     * so that the user can click on it, but once the user starts touching the screen,
6733     * the button shouldn't take focus
6734     * @return Whether the view is focusable in touch mode.
6735     * @attr ref android.R.styleable#View_focusableInTouchMode
6736     */
6737    @ViewDebug.ExportedProperty
6738    public final boolean isFocusableInTouchMode() {
6739        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6740    }
6741
6742    /**
6743     * Find the nearest view in the specified direction that can take focus.
6744     * This does not actually give focus to that view.
6745     *
6746     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6747     *
6748     * @return The nearest focusable in the specified direction, or null if none
6749     *         can be found.
6750     */
6751    public View focusSearch(@FocusRealDirection int direction) {
6752        if (mParent != null) {
6753            return mParent.focusSearch(this, direction);
6754        } else {
6755            return null;
6756        }
6757    }
6758
6759    /**
6760     * This method is the last chance for the focused view and its ancestors to
6761     * respond to an arrow key. This is called when the focused view did not
6762     * consume the key internally, nor could the view system find a new view in
6763     * the requested direction to give focus to.
6764     *
6765     * @param focused The currently focused view.
6766     * @param direction The direction focus wants to move. One of FOCUS_UP,
6767     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6768     * @return True if the this view consumed this unhandled move.
6769     */
6770    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6771        return false;
6772    }
6773
6774    /**
6775     * If a user manually specified the next view id for a particular direction,
6776     * use the root to look up the view.
6777     * @param root The root view of the hierarchy containing this view.
6778     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6779     * or FOCUS_BACKWARD.
6780     * @return The user specified next view, or null if there is none.
6781     */
6782    View findUserSetNextFocus(View root, @FocusDirection int direction) {
6783        switch (direction) {
6784            case FOCUS_LEFT:
6785                if (mNextFocusLeftId == View.NO_ID) return null;
6786                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6787            case FOCUS_RIGHT:
6788                if (mNextFocusRightId == View.NO_ID) return null;
6789                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6790            case FOCUS_UP:
6791                if (mNextFocusUpId == View.NO_ID) return null;
6792                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6793            case FOCUS_DOWN:
6794                if (mNextFocusDownId == View.NO_ID) return null;
6795                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6796            case FOCUS_FORWARD:
6797                if (mNextFocusForwardId == View.NO_ID) return null;
6798                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6799            case FOCUS_BACKWARD: {
6800                if (mID == View.NO_ID) return null;
6801                final int id = mID;
6802                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6803                    @Override
6804                    public boolean apply(View t) {
6805                        return t.mNextFocusForwardId == id;
6806                    }
6807                });
6808            }
6809        }
6810        return null;
6811    }
6812
6813    private View findViewInsideOutShouldExist(View root, int id) {
6814        if (mMatchIdPredicate == null) {
6815            mMatchIdPredicate = new MatchIdPredicate();
6816        }
6817        mMatchIdPredicate.mId = id;
6818        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6819        if (result == null) {
6820            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6821        }
6822        return result;
6823    }
6824
6825    /**
6826     * Find and return all focusable views that are descendants of this view,
6827     * possibly including this view if it is focusable itself.
6828     *
6829     * @param direction The direction of the focus
6830     * @return A list of focusable views
6831     */
6832    public ArrayList<View> getFocusables(@FocusDirection int direction) {
6833        ArrayList<View> result = new ArrayList<View>(24);
6834        addFocusables(result, direction);
6835        return result;
6836    }
6837
6838    /**
6839     * Add any focusable views that are descendants of this view (possibly
6840     * including this view if it is focusable itself) to views.  If we are in touch mode,
6841     * only add views that are also focusable in touch mode.
6842     *
6843     * @param views Focusable views found so far
6844     * @param direction The direction of the focus
6845     */
6846    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
6847        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6848    }
6849
6850    /**
6851     * Adds any focusable views that are descendants of this view (possibly
6852     * including this view if it is focusable itself) to views. This method
6853     * adds all focusable views regardless if we are in touch mode or
6854     * only views focusable in touch mode if we are in touch mode or
6855     * only views that can take accessibility focus if accessibility is enabeld
6856     * depending on the focusable mode paramater.
6857     *
6858     * @param views Focusable views found so far or null if all we are interested is
6859     *        the number of focusables.
6860     * @param direction The direction of the focus.
6861     * @param focusableMode The type of focusables to be added.
6862     *
6863     * @see #FOCUSABLES_ALL
6864     * @see #FOCUSABLES_TOUCH_MODE
6865     */
6866    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
6867            @FocusableMode int focusableMode) {
6868        if (views == null) {
6869            return;
6870        }
6871        if (!isFocusable()) {
6872            return;
6873        }
6874        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6875                && isInTouchMode() && !isFocusableInTouchMode()) {
6876            return;
6877        }
6878        views.add(this);
6879    }
6880
6881    /**
6882     * Finds the Views that contain given text. The containment is case insensitive.
6883     * The search is performed by either the text that the View renders or the content
6884     * description that describes the view for accessibility purposes and the view does
6885     * not render or both. Clients can specify how the search is to be performed via
6886     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6887     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6888     *
6889     * @param outViews The output list of matching Views.
6890     * @param searched The text to match against.
6891     *
6892     * @see #FIND_VIEWS_WITH_TEXT
6893     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6894     * @see #setContentDescription(CharSequence)
6895     */
6896    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
6897            @FindViewFlags int flags) {
6898        if (getAccessibilityNodeProvider() != null) {
6899            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6900                outViews.add(this);
6901            }
6902        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6903                && (searched != null && searched.length() > 0)
6904                && (mContentDescription != null && mContentDescription.length() > 0)) {
6905            String searchedLowerCase = searched.toString().toLowerCase();
6906            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6907            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6908                outViews.add(this);
6909            }
6910        }
6911    }
6912
6913    /**
6914     * Find and return all touchable views that are descendants of this view,
6915     * possibly including this view if it is touchable itself.
6916     *
6917     * @return A list of touchable views
6918     */
6919    public ArrayList<View> getTouchables() {
6920        ArrayList<View> result = new ArrayList<View>();
6921        addTouchables(result);
6922        return result;
6923    }
6924
6925    /**
6926     * Add any touchable views that are descendants of this view (possibly
6927     * including this view if it is touchable itself) to views.
6928     *
6929     * @param views Touchable views found so far
6930     */
6931    public void addTouchables(ArrayList<View> views) {
6932        final int viewFlags = mViewFlags;
6933
6934        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6935                && (viewFlags & ENABLED_MASK) == ENABLED) {
6936            views.add(this);
6937        }
6938    }
6939
6940    /**
6941     * Returns whether this View is accessibility focused.
6942     *
6943     * @return True if this View is accessibility focused.
6944     * @hide
6945     */
6946    public boolean isAccessibilityFocused() {
6947        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6948    }
6949
6950    /**
6951     * Call this to try to give accessibility focus to this view.
6952     *
6953     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6954     * returns false or the view is no visible or the view already has accessibility
6955     * focus.
6956     *
6957     * See also {@link #focusSearch(int)}, which is what you call to say that you
6958     * have focus, and you want your parent to look for the next one.
6959     *
6960     * @return Whether this view actually took accessibility focus.
6961     *
6962     * @hide
6963     */
6964    public boolean requestAccessibilityFocus() {
6965        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6966        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6967            return false;
6968        }
6969        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6970            return false;
6971        }
6972        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6973            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6974            ViewRootImpl viewRootImpl = getViewRootImpl();
6975            if (viewRootImpl != null) {
6976                viewRootImpl.setAccessibilityFocus(this, null);
6977            }
6978            invalidate();
6979            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6980            return true;
6981        }
6982        return false;
6983    }
6984
6985    /**
6986     * Call this to try to clear accessibility focus of this view.
6987     *
6988     * See also {@link #focusSearch(int)}, which is what you call to say that you
6989     * have focus, and you want your parent to look for the next one.
6990     *
6991     * @hide
6992     */
6993    public void clearAccessibilityFocus() {
6994        clearAccessibilityFocusNoCallbacks();
6995        // Clear the global reference of accessibility focus if this
6996        // view or any of its descendants had accessibility focus.
6997        ViewRootImpl viewRootImpl = getViewRootImpl();
6998        if (viewRootImpl != null) {
6999            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7000            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7001                viewRootImpl.setAccessibilityFocus(null, null);
7002            }
7003        }
7004    }
7005
7006    private void sendAccessibilityHoverEvent(int eventType) {
7007        // Since we are not delivering to a client accessibility events from not
7008        // important views (unless the clinet request that) we need to fire the
7009        // event from the deepest view exposed to the client. As a consequence if
7010        // the user crosses a not exposed view the client will see enter and exit
7011        // of the exposed predecessor followed by and enter and exit of that same
7012        // predecessor when entering and exiting the not exposed descendant. This
7013        // is fine since the client has a clear idea which view is hovered at the
7014        // price of a couple more events being sent. This is a simple and
7015        // working solution.
7016        View source = this;
7017        while (true) {
7018            if (source.includeForAccessibility()) {
7019                source.sendAccessibilityEvent(eventType);
7020                return;
7021            }
7022            ViewParent parent = source.getParent();
7023            if (parent instanceof View) {
7024                source = (View) parent;
7025            } else {
7026                return;
7027            }
7028        }
7029    }
7030
7031    /**
7032     * Clears accessibility focus without calling any callback methods
7033     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7034     * is used for clearing accessibility focus when giving this focus to
7035     * another view.
7036     */
7037    void clearAccessibilityFocusNoCallbacks() {
7038        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7039            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7040            invalidate();
7041            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7042        }
7043    }
7044
7045    /**
7046     * Call this to try to give focus to a specific view or to one of its
7047     * descendants.
7048     *
7049     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7050     * false), or if it is focusable and it is not focusable in touch mode
7051     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7052     *
7053     * See also {@link #focusSearch(int)}, which is what you call to say that you
7054     * have focus, and you want your parent to look for the next one.
7055     *
7056     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7057     * {@link #FOCUS_DOWN} and <code>null</code>.
7058     *
7059     * @return Whether this view or one of its descendants actually took focus.
7060     */
7061    public final boolean requestFocus() {
7062        return requestFocus(View.FOCUS_DOWN);
7063    }
7064
7065    /**
7066     * Call this to try to give focus to a specific view or to one of its
7067     * descendants and give it a hint about what direction focus is heading.
7068     *
7069     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7070     * false), or if it is focusable and it is not focusable in touch mode
7071     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7072     *
7073     * See also {@link #focusSearch(int)}, which is what you call to say that you
7074     * have focus, and you want your parent to look for the next one.
7075     *
7076     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7077     * <code>null</code> set for the previously focused rectangle.
7078     *
7079     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7080     * @return Whether this view or one of its descendants actually took focus.
7081     */
7082    public final boolean requestFocus(int direction) {
7083        return requestFocus(direction, null);
7084    }
7085
7086    /**
7087     * Call this to try to give focus to a specific view or to one of its descendants
7088     * and give it hints about the direction and a specific rectangle that the focus
7089     * is coming from.  The rectangle can help give larger views a finer grained hint
7090     * about where focus is coming from, and therefore, where to show selection, or
7091     * forward focus change internally.
7092     *
7093     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7094     * false), or if it is focusable and it is not focusable in touch mode
7095     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7096     *
7097     * A View will not take focus if it is not visible.
7098     *
7099     * A View will not take focus if one of its parents has
7100     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7101     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7102     *
7103     * See also {@link #focusSearch(int)}, which is what you call to say that you
7104     * have focus, and you want your parent to look for the next one.
7105     *
7106     * You may wish to override this method if your custom {@link View} has an internal
7107     * {@link View} that it wishes to forward the request to.
7108     *
7109     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7110     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7111     *        to give a finer grained hint about where focus is coming from.  May be null
7112     *        if there is no hint.
7113     * @return Whether this view or one of its descendants actually took focus.
7114     */
7115    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7116        return requestFocusNoSearch(direction, previouslyFocusedRect);
7117    }
7118
7119    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7120        // need to be focusable
7121        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7122                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7123            return false;
7124        }
7125
7126        // need to be focusable in touch mode if in touch mode
7127        if (isInTouchMode() &&
7128            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7129               return false;
7130        }
7131
7132        // need to not have any parents blocking us
7133        if (hasAncestorThatBlocksDescendantFocus()) {
7134            return false;
7135        }
7136
7137        handleFocusGainInternal(direction, previouslyFocusedRect);
7138        return true;
7139    }
7140
7141    /**
7142     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7143     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7144     * touch mode to request focus when they are touched.
7145     *
7146     * @return Whether this view or one of its descendants actually took focus.
7147     *
7148     * @see #isInTouchMode()
7149     *
7150     */
7151    public final boolean requestFocusFromTouch() {
7152        // Leave touch mode if we need to
7153        if (isInTouchMode()) {
7154            ViewRootImpl viewRoot = getViewRootImpl();
7155            if (viewRoot != null) {
7156                viewRoot.ensureTouchMode(false);
7157            }
7158        }
7159        return requestFocus(View.FOCUS_DOWN);
7160    }
7161
7162    /**
7163     * @return Whether any ancestor of this view blocks descendant focus.
7164     */
7165    private boolean hasAncestorThatBlocksDescendantFocus() {
7166        ViewParent ancestor = mParent;
7167        while (ancestor instanceof ViewGroup) {
7168            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7169            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7170                return true;
7171            } else {
7172                ancestor = vgAncestor.getParent();
7173            }
7174        }
7175        return false;
7176    }
7177
7178    /**
7179     * Gets the mode for determining whether this View is important for accessibility
7180     * which is if it fires accessibility events and if it is reported to
7181     * accessibility services that query the screen.
7182     *
7183     * @return The mode for determining whether a View is important for accessibility.
7184     *
7185     * @attr ref android.R.styleable#View_importantForAccessibility
7186     *
7187     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7188     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7189     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7190     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7191     */
7192    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7193            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7194            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7195            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7196            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7197                    to = "noHideDescendants")
7198        })
7199    public int getImportantForAccessibility() {
7200        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7201                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7202    }
7203
7204    /**
7205     * Sets the live region mode for this view. This indicates to accessibility
7206     * services whether they should automatically notify the user about changes
7207     * to the view's content description or text, or to the content descriptions
7208     * or text of the view's children (where applicable).
7209     * <p>
7210     * For example, in a login screen with a TextView that displays an "incorrect
7211     * password" notification, that view should be marked as a live region with
7212     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7213     * <p>
7214     * To disable change notifications for this view, use
7215     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7216     * mode for most views.
7217     * <p>
7218     * To indicate that the user should be notified of changes, use
7219     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7220     * <p>
7221     * If the view's changes should interrupt ongoing speech and notify the user
7222     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7223     *
7224     * @param mode The live region mode for this view, one of:
7225     *        <ul>
7226     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7227     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7228     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7229     *        </ul>
7230     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7231     */
7232    public void setAccessibilityLiveRegion(int mode) {
7233        if (mode != getAccessibilityLiveRegion()) {
7234            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7235            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7236                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7237            notifyViewAccessibilityStateChangedIfNeeded(
7238                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7239        }
7240    }
7241
7242    /**
7243     * Gets the live region mode for this View.
7244     *
7245     * @return The live region mode for the view.
7246     *
7247     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7248     *
7249     * @see #setAccessibilityLiveRegion(int)
7250     */
7251    public int getAccessibilityLiveRegion() {
7252        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7253                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7254    }
7255
7256    /**
7257     * Sets how to determine whether this view is important for accessibility
7258     * which is if it fires accessibility events and if it is reported to
7259     * accessibility services that query the screen.
7260     *
7261     * @param mode How to determine whether this view is important for accessibility.
7262     *
7263     * @attr ref android.R.styleable#View_importantForAccessibility
7264     *
7265     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7266     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7267     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7268     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7269     */
7270    public void setImportantForAccessibility(int mode) {
7271        final int oldMode = getImportantForAccessibility();
7272        if (mode != oldMode) {
7273            // If we're moving between AUTO and another state, we might not need
7274            // to send a subtree changed notification. We'll store the computed
7275            // importance, since we'll need to check it later to make sure.
7276            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7277                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7278            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7279            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7280            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7281                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7282            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7283                notifySubtreeAccessibilityStateChangedIfNeeded();
7284            } else {
7285                notifyViewAccessibilityStateChangedIfNeeded(
7286                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7287            }
7288        }
7289    }
7290
7291    /**
7292     * Gets whether this view should be exposed for accessibility.
7293     *
7294     * @return Whether the view is exposed for accessibility.
7295     *
7296     * @hide
7297     */
7298    public boolean isImportantForAccessibility() {
7299        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7300                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7301        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7302                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7303            return false;
7304        }
7305
7306        // Check parent mode to ensure we're not hidden.
7307        ViewParent parent = mParent;
7308        while (parent instanceof View) {
7309            if (((View) parent).getImportantForAccessibility()
7310                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7311                return false;
7312            }
7313            parent = parent.getParent();
7314        }
7315
7316        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7317                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7318                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7319    }
7320
7321    /**
7322     * Gets the parent for accessibility purposes. Note that the parent for
7323     * accessibility is not necessary the immediate parent. It is the first
7324     * predecessor that is important for accessibility.
7325     *
7326     * @return The parent for accessibility purposes.
7327     */
7328    public ViewParent getParentForAccessibility() {
7329        if (mParent instanceof View) {
7330            View parentView = (View) mParent;
7331            if (parentView.includeForAccessibility()) {
7332                return mParent;
7333            } else {
7334                return mParent.getParentForAccessibility();
7335            }
7336        }
7337        return null;
7338    }
7339
7340    /**
7341     * Adds the children of a given View for accessibility. Since some Views are
7342     * not important for accessibility the children for accessibility are not
7343     * necessarily direct children of the view, rather they are the first level of
7344     * descendants important for accessibility.
7345     *
7346     * @param children The list of children for accessibility.
7347     */
7348    public void addChildrenForAccessibility(ArrayList<View> children) {
7349        if (includeForAccessibility()) {
7350            children.add(this);
7351        }
7352    }
7353
7354    /**
7355     * Whether to regard this view for accessibility. A view is regarded for
7356     * accessibility if it is important for accessibility or the querying
7357     * accessibility service has explicitly requested that view not
7358     * important for accessibility are regarded.
7359     *
7360     * @return Whether to regard the view for accessibility.
7361     *
7362     * @hide
7363     */
7364    public boolean includeForAccessibility() {
7365        //noinspection SimplifiableIfStatement
7366        if (mAttachInfo != null) {
7367            return (mAttachInfo.mAccessibilityFetchFlags
7368                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7369                    || isImportantForAccessibility();
7370        }
7371        return false;
7372    }
7373
7374    /**
7375     * Returns whether the View is considered actionable from
7376     * accessibility perspective. Such view are important for
7377     * accessibility.
7378     *
7379     * @return True if the view is actionable for accessibility.
7380     *
7381     * @hide
7382     */
7383    public boolean isActionableForAccessibility() {
7384        return (isClickable() || isLongClickable() || isFocusable());
7385    }
7386
7387    /**
7388     * Returns whether the View has registered callbacks which makes it
7389     * important for accessibility.
7390     *
7391     * @return True if the view is actionable for accessibility.
7392     */
7393    private boolean hasListenersForAccessibility() {
7394        ListenerInfo info = getListenerInfo();
7395        return mTouchDelegate != null || info.mOnKeyListener != null
7396                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7397                || info.mOnHoverListener != null || info.mOnDragListener != null;
7398    }
7399
7400    /**
7401     * Notifies that the accessibility state of this view changed. The change
7402     * is local to this view and does not represent structural changes such
7403     * as children and parent. For example, the view became focusable. The
7404     * notification is at at most once every
7405     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7406     * to avoid unnecessary load to the system. Also once a view has a pending
7407     * notification this method is a NOP until the notification has been sent.
7408     *
7409     * @hide
7410     */
7411    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7412        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7413            return;
7414        }
7415        if (mSendViewStateChangedAccessibilityEvent == null) {
7416            mSendViewStateChangedAccessibilityEvent =
7417                    new SendViewStateChangedAccessibilityEvent();
7418        }
7419        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7420    }
7421
7422    /**
7423     * Notifies that the accessibility state of this view changed. The change
7424     * is *not* local to this view and does represent structural changes such
7425     * as children and parent. For example, the view size changed. The
7426     * notification is at at most once every
7427     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7428     * to avoid unnecessary load to the system. Also once a view has a pending
7429     * notifucation this method is a NOP until the notification has been sent.
7430     *
7431     * @hide
7432     */
7433    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7434        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7435            return;
7436        }
7437        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7438            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7439            if (mParent != null) {
7440                try {
7441                    mParent.notifySubtreeAccessibilityStateChanged(
7442                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7443                } catch (AbstractMethodError e) {
7444                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7445                            " does not fully implement ViewParent", e);
7446                }
7447            }
7448        }
7449    }
7450
7451    /**
7452     * Reset the flag indicating the accessibility state of the subtree rooted
7453     * at this view changed.
7454     */
7455    void resetSubtreeAccessibilityStateChanged() {
7456        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7457    }
7458
7459    /**
7460     * Performs the specified accessibility action on the view. For
7461     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7462     * <p>
7463     * If an {@link AccessibilityDelegate} has been specified via calling
7464     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7465     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7466     * is responsible for handling this call.
7467     * </p>
7468     *
7469     * @param action The action to perform.
7470     * @param arguments Optional action arguments.
7471     * @return Whether the action was performed.
7472     */
7473    public boolean performAccessibilityAction(int action, Bundle arguments) {
7474      if (mAccessibilityDelegate != null) {
7475          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7476      } else {
7477          return performAccessibilityActionInternal(action, arguments);
7478      }
7479    }
7480
7481   /**
7482    * @see #performAccessibilityAction(int, Bundle)
7483    *
7484    * Note: Called from the default {@link AccessibilityDelegate}.
7485    */
7486    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7487        switch (action) {
7488            case AccessibilityNodeInfo.ACTION_CLICK: {
7489                if (isClickable()) {
7490                    performClick();
7491                    return true;
7492                }
7493            } break;
7494            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7495                if (isLongClickable()) {
7496                    performLongClick();
7497                    return true;
7498                }
7499            } break;
7500            case AccessibilityNodeInfo.ACTION_FOCUS: {
7501                if (!hasFocus()) {
7502                    // Get out of touch mode since accessibility
7503                    // wants to move focus around.
7504                    getViewRootImpl().ensureTouchMode(false);
7505                    return requestFocus();
7506                }
7507            } break;
7508            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7509                if (hasFocus()) {
7510                    clearFocus();
7511                    return !isFocused();
7512                }
7513            } break;
7514            case AccessibilityNodeInfo.ACTION_SELECT: {
7515                if (!isSelected()) {
7516                    setSelected(true);
7517                    return isSelected();
7518                }
7519            } break;
7520            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7521                if (isSelected()) {
7522                    setSelected(false);
7523                    return !isSelected();
7524                }
7525            } break;
7526            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7527                if (!isAccessibilityFocused()) {
7528                    return requestAccessibilityFocus();
7529                }
7530            } break;
7531            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7532                if (isAccessibilityFocused()) {
7533                    clearAccessibilityFocus();
7534                    return true;
7535                }
7536            } break;
7537            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7538                if (arguments != null) {
7539                    final int granularity = arguments.getInt(
7540                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7541                    final boolean extendSelection = arguments.getBoolean(
7542                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7543                    return traverseAtGranularity(granularity, true, extendSelection);
7544                }
7545            } break;
7546            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7547                if (arguments != null) {
7548                    final int granularity = arguments.getInt(
7549                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7550                    final boolean extendSelection = arguments.getBoolean(
7551                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7552                    return traverseAtGranularity(granularity, false, extendSelection);
7553                }
7554            } break;
7555            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7556                CharSequence text = getIterableTextForAccessibility();
7557                if (text == null) {
7558                    return false;
7559                }
7560                final int start = (arguments != null) ? arguments.getInt(
7561                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7562                final int end = (arguments != null) ? arguments.getInt(
7563                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7564                // Only cursor position can be specified (selection length == 0)
7565                if ((getAccessibilitySelectionStart() != start
7566                        || getAccessibilitySelectionEnd() != end)
7567                        && (start == end)) {
7568                    setAccessibilitySelection(start, end);
7569                    notifyViewAccessibilityStateChangedIfNeeded(
7570                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7571                    return true;
7572                }
7573            } break;
7574        }
7575        return false;
7576    }
7577
7578    private boolean traverseAtGranularity(int granularity, boolean forward,
7579            boolean extendSelection) {
7580        CharSequence text = getIterableTextForAccessibility();
7581        if (text == null || text.length() == 0) {
7582            return false;
7583        }
7584        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7585        if (iterator == null) {
7586            return false;
7587        }
7588        int current = getAccessibilitySelectionEnd();
7589        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7590            current = forward ? 0 : text.length();
7591        }
7592        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7593        if (range == null) {
7594            return false;
7595        }
7596        final int segmentStart = range[0];
7597        final int segmentEnd = range[1];
7598        int selectionStart;
7599        int selectionEnd;
7600        if (extendSelection && isAccessibilitySelectionExtendable()) {
7601            selectionStart = getAccessibilitySelectionStart();
7602            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7603                selectionStart = forward ? segmentStart : segmentEnd;
7604            }
7605            selectionEnd = forward ? segmentEnd : segmentStart;
7606        } else {
7607            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7608        }
7609        setAccessibilitySelection(selectionStart, selectionEnd);
7610        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7611                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7612        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7613        return true;
7614    }
7615
7616    /**
7617     * Gets the text reported for accessibility purposes.
7618     *
7619     * @return The accessibility text.
7620     *
7621     * @hide
7622     */
7623    public CharSequence getIterableTextForAccessibility() {
7624        return getContentDescription();
7625    }
7626
7627    /**
7628     * Gets whether accessibility selection can be extended.
7629     *
7630     * @return If selection is extensible.
7631     *
7632     * @hide
7633     */
7634    public boolean isAccessibilitySelectionExtendable() {
7635        return false;
7636    }
7637
7638    /**
7639     * @hide
7640     */
7641    public int getAccessibilitySelectionStart() {
7642        return mAccessibilityCursorPosition;
7643    }
7644
7645    /**
7646     * @hide
7647     */
7648    public int getAccessibilitySelectionEnd() {
7649        return getAccessibilitySelectionStart();
7650    }
7651
7652    /**
7653     * @hide
7654     */
7655    public void setAccessibilitySelection(int start, int end) {
7656        if (start ==  end && end == mAccessibilityCursorPosition) {
7657            return;
7658        }
7659        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7660            mAccessibilityCursorPosition = start;
7661        } else {
7662            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7663        }
7664        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7665    }
7666
7667    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7668            int fromIndex, int toIndex) {
7669        if (mParent == null) {
7670            return;
7671        }
7672        AccessibilityEvent event = AccessibilityEvent.obtain(
7673                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7674        onInitializeAccessibilityEvent(event);
7675        onPopulateAccessibilityEvent(event);
7676        event.setFromIndex(fromIndex);
7677        event.setToIndex(toIndex);
7678        event.setAction(action);
7679        event.setMovementGranularity(granularity);
7680        mParent.requestSendAccessibilityEvent(this, event);
7681    }
7682
7683    /**
7684     * @hide
7685     */
7686    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7687        switch (granularity) {
7688            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7689                CharSequence text = getIterableTextForAccessibility();
7690                if (text != null && text.length() > 0) {
7691                    CharacterTextSegmentIterator iterator =
7692                        CharacterTextSegmentIterator.getInstance(
7693                                mContext.getResources().getConfiguration().locale);
7694                    iterator.initialize(text.toString());
7695                    return iterator;
7696                }
7697            } break;
7698            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7699                CharSequence text = getIterableTextForAccessibility();
7700                if (text != null && text.length() > 0) {
7701                    WordTextSegmentIterator iterator =
7702                        WordTextSegmentIterator.getInstance(
7703                                mContext.getResources().getConfiguration().locale);
7704                    iterator.initialize(text.toString());
7705                    return iterator;
7706                }
7707            } break;
7708            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7709                CharSequence text = getIterableTextForAccessibility();
7710                if (text != null && text.length() > 0) {
7711                    ParagraphTextSegmentIterator iterator =
7712                        ParagraphTextSegmentIterator.getInstance();
7713                    iterator.initialize(text.toString());
7714                    return iterator;
7715                }
7716            } break;
7717        }
7718        return null;
7719    }
7720
7721    /**
7722     * @hide
7723     */
7724    public void dispatchStartTemporaryDetach() {
7725        clearDisplayList();
7726
7727        onStartTemporaryDetach();
7728    }
7729
7730    /**
7731     * This is called when a container is going to temporarily detach a child, with
7732     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7733     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7734     * {@link #onDetachedFromWindow()} when the container is done.
7735     */
7736    public void onStartTemporaryDetach() {
7737        removeUnsetPressCallback();
7738        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7739    }
7740
7741    /**
7742     * @hide
7743     */
7744    public void dispatchFinishTemporaryDetach() {
7745        onFinishTemporaryDetach();
7746    }
7747
7748    /**
7749     * Called after {@link #onStartTemporaryDetach} when the container is done
7750     * changing the view.
7751     */
7752    public void onFinishTemporaryDetach() {
7753    }
7754
7755    /**
7756     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7757     * for this view's window.  Returns null if the view is not currently attached
7758     * to the window.  Normally you will not need to use this directly, but
7759     * just use the standard high-level event callbacks like
7760     * {@link #onKeyDown(int, KeyEvent)}.
7761     */
7762    public KeyEvent.DispatcherState getKeyDispatcherState() {
7763        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7764    }
7765
7766    /**
7767     * Dispatch a key event before it is processed by any input method
7768     * associated with the view hierarchy.  This can be used to intercept
7769     * key events in special situations before the IME consumes them; a
7770     * typical example would be handling the BACK key to update the application's
7771     * UI instead of allowing the IME to see it and close itself.
7772     *
7773     * @param event The key event to be dispatched.
7774     * @return True if the event was handled, false otherwise.
7775     */
7776    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7777        return onKeyPreIme(event.getKeyCode(), event);
7778    }
7779
7780    /**
7781     * Dispatch a key event to the next view on the focus path. This path runs
7782     * from the top of the view tree down to the currently focused view. If this
7783     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7784     * the next node down the focus path. This method also fires any key
7785     * listeners.
7786     *
7787     * @param event The key event to be dispatched.
7788     * @return True if the event was handled, false otherwise.
7789     */
7790    public boolean dispatchKeyEvent(KeyEvent event) {
7791        if (mInputEventConsistencyVerifier != null) {
7792            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7793        }
7794
7795        // Give any attached key listener a first crack at the event.
7796        //noinspection SimplifiableIfStatement
7797        ListenerInfo li = mListenerInfo;
7798        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7799                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7800            return true;
7801        }
7802
7803        if (event.dispatch(this, mAttachInfo != null
7804                ? mAttachInfo.mKeyDispatchState : null, this)) {
7805            return true;
7806        }
7807
7808        if (mInputEventConsistencyVerifier != null) {
7809            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7810        }
7811        return false;
7812    }
7813
7814    /**
7815     * Dispatches a key shortcut event.
7816     *
7817     * @param event The key event to be dispatched.
7818     * @return True if the event was handled by the view, false otherwise.
7819     */
7820    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7821        return onKeyShortcut(event.getKeyCode(), event);
7822    }
7823
7824    /**
7825     * Pass the touch screen motion event down to the target view, or this
7826     * view if it is the target.
7827     *
7828     * @param event The motion event to be dispatched.
7829     * @return True if the event was handled by the view, false otherwise.
7830     */
7831    public boolean dispatchTouchEvent(MotionEvent event) {
7832        if (mInputEventConsistencyVerifier != null) {
7833            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7834        }
7835
7836        if (onFilterTouchEventForSecurity(event)) {
7837            //noinspection SimplifiableIfStatement
7838            ListenerInfo li = mListenerInfo;
7839            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7840                    && li.mOnTouchListener.onTouch(this, event)) {
7841                return true;
7842            }
7843
7844            if (onTouchEvent(event)) {
7845                return true;
7846            }
7847        }
7848
7849        if (mInputEventConsistencyVerifier != null) {
7850            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7851        }
7852        return false;
7853    }
7854
7855    /**
7856     * Filter the touch event to apply security policies.
7857     *
7858     * @param event The motion event to be filtered.
7859     * @return True if the event should be dispatched, false if the event should be dropped.
7860     *
7861     * @see #getFilterTouchesWhenObscured
7862     */
7863    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7864        //noinspection RedundantIfStatement
7865        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7866                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7867            // Window is obscured, drop this touch.
7868            return false;
7869        }
7870        return true;
7871    }
7872
7873    /**
7874     * Pass a trackball motion event down to the focused view.
7875     *
7876     * @param event The motion event to be dispatched.
7877     * @return True if the event was handled by the view, false otherwise.
7878     */
7879    public boolean dispatchTrackballEvent(MotionEvent event) {
7880        if (mInputEventConsistencyVerifier != null) {
7881            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7882        }
7883
7884        return onTrackballEvent(event);
7885    }
7886
7887    /**
7888     * Dispatch a generic motion event.
7889     * <p>
7890     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7891     * are delivered to the view under the pointer.  All other generic motion events are
7892     * delivered to the focused view.  Hover events are handled specially and are delivered
7893     * to {@link #onHoverEvent(MotionEvent)}.
7894     * </p>
7895     *
7896     * @param event The motion event to be dispatched.
7897     * @return True if the event was handled by the view, false otherwise.
7898     */
7899    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7900        if (mInputEventConsistencyVerifier != null) {
7901            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7902        }
7903
7904        final int source = event.getSource();
7905        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7906            final int action = event.getAction();
7907            if (action == MotionEvent.ACTION_HOVER_ENTER
7908                    || action == MotionEvent.ACTION_HOVER_MOVE
7909                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7910                if (dispatchHoverEvent(event)) {
7911                    return true;
7912                }
7913            } else if (dispatchGenericPointerEvent(event)) {
7914                return true;
7915            }
7916        } else if (dispatchGenericFocusedEvent(event)) {
7917            return true;
7918        }
7919
7920        if (dispatchGenericMotionEventInternal(event)) {
7921            return true;
7922        }
7923
7924        if (mInputEventConsistencyVerifier != null) {
7925            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7926        }
7927        return false;
7928    }
7929
7930    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7931        //noinspection SimplifiableIfStatement
7932        ListenerInfo li = mListenerInfo;
7933        if (li != null && li.mOnGenericMotionListener != null
7934                && (mViewFlags & ENABLED_MASK) == ENABLED
7935                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7936            return true;
7937        }
7938
7939        if (onGenericMotionEvent(event)) {
7940            return true;
7941        }
7942
7943        if (mInputEventConsistencyVerifier != null) {
7944            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7945        }
7946        return false;
7947    }
7948
7949    /**
7950     * Dispatch a hover event.
7951     * <p>
7952     * Do not call this method directly.
7953     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7954     * </p>
7955     *
7956     * @param event The motion event to be dispatched.
7957     * @return True if the event was handled by the view, false otherwise.
7958     */
7959    protected boolean dispatchHoverEvent(MotionEvent event) {
7960        ListenerInfo li = mListenerInfo;
7961        //noinspection SimplifiableIfStatement
7962        if (li != null && li.mOnHoverListener != null
7963                && (mViewFlags & ENABLED_MASK) == ENABLED
7964                && li.mOnHoverListener.onHover(this, event)) {
7965            return true;
7966        }
7967
7968        return onHoverEvent(event);
7969    }
7970
7971    /**
7972     * Returns true if the view has a child to which it has recently sent
7973     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7974     * it does not have a hovered child, then it must be the innermost hovered view.
7975     * @hide
7976     */
7977    protected boolean hasHoveredChild() {
7978        return false;
7979    }
7980
7981    /**
7982     * Dispatch a generic motion event to the view under the first pointer.
7983     * <p>
7984     * Do not call this method directly.
7985     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7986     * </p>
7987     *
7988     * @param event The motion event to be dispatched.
7989     * @return True if the event was handled by the view, false otherwise.
7990     */
7991    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7992        return false;
7993    }
7994
7995    /**
7996     * Dispatch a generic motion event to the currently focused view.
7997     * <p>
7998     * Do not call this method directly.
7999     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8000     * </p>
8001     *
8002     * @param event The motion event to be dispatched.
8003     * @return True if the event was handled by the view, false otherwise.
8004     */
8005    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8006        return false;
8007    }
8008
8009    /**
8010     * Dispatch a pointer event.
8011     * <p>
8012     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8013     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8014     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8015     * and should not be expected to handle other pointing device features.
8016     * </p>
8017     *
8018     * @param event The motion event to be dispatched.
8019     * @return True if the event was handled by the view, false otherwise.
8020     * @hide
8021     */
8022    public final boolean dispatchPointerEvent(MotionEvent event) {
8023        if (event.isTouchEvent()) {
8024            return dispatchTouchEvent(event);
8025        } else {
8026            return dispatchGenericMotionEvent(event);
8027        }
8028    }
8029
8030    /**
8031     * Called when the window containing this view gains or loses window focus.
8032     * ViewGroups should override to route to their children.
8033     *
8034     * @param hasFocus True if the window containing this view now has focus,
8035     *        false otherwise.
8036     */
8037    public void dispatchWindowFocusChanged(boolean hasFocus) {
8038        onWindowFocusChanged(hasFocus);
8039    }
8040
8041    /**
8042     * Called when the window containing this view gains or loses focus.  Note
8043     * that this is separate from view focus: to receive key events, both
8044     * your view and its window must have focus.  If a window is displayed
8045     * on top of yours that takes input focus, then your own window will lose
8046     * focus but the view focus will remain unchanged.
8047     *
8048     * @param hasWindowFocus True if the window containing this view now has
8049     *        focus, false otherwise.
8050     */
8051    public void onWindowFocusChanged(boolean hasWindowFocus) {
8052        InputMethodManager imm = InputMethodManager.peekInstance();
8053        if (!hasWindowFocus) {
8054            if (isPressed()) {
8055                setPressed(false);
8056            }
8057            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8058                imm.focusOut(this);
8059            }
8060            removeLongPressCallback();
8061            removeTapCallback();
8062            onFocusLost();
8063        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8064            imm.focusIn(this);
8065        }
8066        refreshDrawableState();
8067    }
8068
8069    /**
8070     * Returns true if this view is in a window that currently has window focus.
8071     * Note that this is not the same as the view itself having focus.
8072     *
8073     * @return True if this view is in a window that currently has window focus.
8074     */
8075    public boolean hasWindowFocus() {
8076        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8077    }
8078
8079    /**
8080     * Dispatch a view visibility change down the view hierarchy.
8081     * ViewGroups should override to route to their children.
8082     * @param changedView The view whose visibility changed. Could be 'this' or
8083     * an ancestor view.
8084     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8085     * {@link #INVISIBLE} or {@link #GONE}.
8086     */
8087    protected void dispatchVisibilityChanged(@NonNull View changedView,
8088            @Visibility int visibility) {
8089        onVisibilityChanged(changedView, visibility);
8090    }
8091
8092    /**
8093     * Called when the visibility of the view or an ancestor of the view is changed.
8094     * @param changedView The view whose visibility changed. Could be 'this' or
8095     * an ancestor view.
8096     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8097     * {@link #INVISIBLE} or {@link #GONE}.
8098     */
8099    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8100        if (visibility == VISIBLE) {
8101            if (mAttachInfo != null) {
8102                initialAwakenScrollBars();
8103            } else {
8104                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8105            }
8106        }
8107    }
8108
8109    /**
8110     * Dispatch a hint about whether this view is displayed. For instance, when
8111     * a View moves out of the screen, it might receives a display hint indicating
8112     * the view is not displayed. Applications should not <em>rely</em> on this hint
8113     * as there is no guarantee that they will receive one.
8114     *
8115     * @param hint A hint about whether or not this view is displayed:
8116     * {@link #VISIBLE} or {@link #INVISIBLE}.
8117     */
8118    public void dispatchDisplayHint(@Visibility int hint) {
8119        onDisplayHint(hint);
8120    }
8121
8122    /**
8123     * Gives this view a hint about whether is displayed or not. For instance, when
8124     * a View moves out of the screen, it might receives a display hint indicating
8125     * the view is not displayed. Applications should not <em>rely</em> on this hint
8126     * as there is no guarantee that they will receive one.
8127     *
8128     * @param hint A hint about whether or not this view is displayed:
8129     * {@link #VISIBLE} or {@link #INVISIBLE}.
8130     */
8131    protected void onDisplayHint(@Visibility int hint) {
8132    }
8133
8134    /**
8135     * Dispatch a window visibility change down the view hierarchy.
8136     * ViewGroups should override to route to their children.
8137     *
8138     * @param visibility The new visibility of the window.
8139     *
8140     * @see #onWindowVisibilityChanged(int)
8141     */
8142    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8143        onWindowVisibilityChanged(visibility);
8144    }
8145
8146    /**
8147     * Called when the window containing has change its visibility
8148     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8149     * that this tells you whether or not your window is being made visible
8150     * to the window manager; this does <em>not</em> tell you whether or not
8151     * your window is obscured by other windows on the screen, even if it
8152     * is itself visible.
8153     *
8154     * @param visibility The new visibility of the window.
8155     */
8156    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8157        if (visibility == VISIBLE) {
8158            initialAwakenScrollBars();
8159        }
8160    }
8161
8162    /**
8163     * Returns the current visibility of the window this view is attached to
8164     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8165     *
8166     * @return Returns the current visibility of the view's window.
8167     */
8168    @Visibility
8169    public int getWindowVisibility() {
8170        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8171    }
8172
8173    /**
8174     * Retrieve the overall visible display size in which the window this view is
8175     * attached to has been positioned in.  This takes into account screen
8176     * decorations above the window, for both cases where the window itself
8177     * is being position inside of them or the window is being placed under
8178     * then and covered insets are used for the window to position its content
8179     * inside.  In effect, this tells you the available area where content can
8180     * be placed and remain visible to users.
8181     *
8182     * <p>This function requires an IPC back to the window manager to retrieve
8183     * the requested information, so should not be used in performance critical
8184     * code like drawing.
8185     *
8186     * @param outRect Filled in with the visible display frame.  If the view
8187     * is not attached to a window, this is simply the raw display size.
8188     */
8189    public void getWindowVisibleDisplayFrame(Rect outRect) {
8190        if (mAttachInfo != null) {
8191            try {
8192                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8193            } catch (RemoteException e) {
8194                return;
8195            }
8196            // XXX This is really broken, and probably all needs to be done
8197            // in the window manager, and we need to know more about whether
8198            // we want the area behind or in front of the IME.
8199            final Rect insets = mAttachInfo.mVisibleInsets;
8200            outRect.left += insets.left;
8201            outRect.top += insets.top;
8202            outRect.right -= insets.right;
8203            outRect.bottom -= insets.bottom;
8204            return;
8205        }
8206        // The view is not attached to a display so we don't have a context.
8207        // Make a best guess about the display size.
8208        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8209        d.getRectSize(outRect);
8210    }
8211
8212    /**
8213     * Dispatch a notification about a resource configuration change down
8214     * the view hierarchy.
8215     * ViewGroups should override to route to their children.
8216     *
8217     * @param newConfig The new resource configuration.
8218     *
8219     * @see #onConfigurationChanged(android.content.res.Configuration)
8220     */
8221    public void dispatchConfigurationChanged(Configuration newConfig) {
8222        onConfigurationChanged(newConfig);
8223    }
8224
8225    /**
8226     * Called when the current configuration of the resources being used
8227     * by the application have changed.  You can use this to decide when
8228     * to reload resources that can changed based on orientation and other
8229     * configuration characterstics.  You only need to use this if you are
8230     * not relying on the normal {@link android.app.Activity} mechanism of
8231     * recreating the activity instance upon a configuration change.
8232     *
8233     * @param newConfig The new resource configuration.
8234     */
8235    protected void onConfigurationChanged(Configuration newConfig) {
8236    }
8237
8238    /**
8239     * Private function to aggregate all per-view attributes in to the view
8240     * root.
8241     */
8242    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8243        performCollectViewAttributes(attachInfo, visibility);
8244    }
8245
8246    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8247        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8248            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8249                attachInfo.mKeepScreenOn = true;
8250            }
8251            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8252            ListenerInfo li = mListenerInfo;
8253            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8254                attachInfo.mHasSystemUiListeners = true;
8255            }
8256        }
8257    }
8258
8259    void needGlobalAttributesUpdate(boolean force) {
8260        final AttachInfo ai = mAttachInfo;
8261        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8262            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8263                    || ai.mHasSystemUiListeners) {
8264                ai.mRecomputeGlobalAttributes = true;
8265            }
8266        }
8267    }
8268
8269    /**
8270     * Returns whether the device is currently in touch mode.  Touch mode is entered
8271     * once the user begins interacting with the device by touch, and affects various
8272     * things like whether focus is always visible to the user.
8273     *
8274     * @return Whether the device is in touch mode.
8275     */
8276    @ViewDebug.ExportedProperty
8277    public boolean isInTouchMode() {
8278        if (mAttachInfo != null) {
8279            return mAttachInfo.mInTouchMode;
8280        } else {
8281            return ViewRootImpl.isInTouchMode();
8282        }
8283    }
8284
8285    /**
8286     * Returns the context the view is running in, through which it can
8287     * access the current theme, resources, etc.
8288     *
8289     * @return The view's Context.
8290     */
8291    @ViewDebug.CapturedViewProperty
8292    public final Context getContext() {
8293        return mContext;
8294    }
8295
8296    /**
8297     * Handle a key event before it is processed by any input method
8298     * associated with the view hierarchy.  This can be used to intercept
8299     * key events in special situations before the IME consumes them; a
8300     * typical example would be handling the BACK key to update the application's
8301     * UI instead of allowing the IME to see it and close itself.
8302     *
8303     * @param keyCode The value in event.getKeyCode().
8304     * @param event Description of the key event.
8305     * @return If you handled the event, return true. If you want to allow the
8306     *         event to be handled by the next receiver, return false.
8307     */
8308    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8309        return false;
8310    }
8311
8312    /**
8313     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8314     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8315     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8316     * is released, if the view is enabled and clickable.
8317     *
8318     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8319     * although some may elect to do so in some situations. Do not rely on this to
8320     * catch software key presses.
8321     *
8322     * @param keyCode A key code that represents the button pressed, from
8323     *                {@link android.view.KeyEvent}.
8324     * @param event   The KeyEvent object that defines the button action.
8325     */
8326    public boolean onKeyDown(int keyCode, KeyEvent event) {
8327        boolean result = false;
8328
8329        if (KeyEvent.isConfirmKey(keyCode)) {
8330            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8331                return true;
8332            }
8333            // Long clickable items don't necessarily have to be clickable
8334            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8335                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8336                    (event.getRepeatCount() == 0)) {
8337                setPressed(true);
8338                checkForLongClick(0);
8339                return true;
8340            }
8341        }
8342        return result;
8343    }
8344
8345    /**
8346     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8347     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8348     * the event).
8349     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8350     * although some may elect to do so in some situations. Do not rely on this to
8351     * catch software key presses.
8352     */
8353    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8354        return false;
8355    }
8356
8357    /**
8358     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8359     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8360     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8361     * {@link KeyEvent#KEYCODE_ENTER} is released.
8362     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8363     * although some may elect to do so in some situations. Do not rely on this to
8364     * catch software key presses.
8365     *
8366     * @param keyCode A key code that represents the button pressed, from
8367     *                {@link android.view.KeyEvent}.
8368     * @param event   The KeyEvent object that defines the button action.
8369     */
8370    public boolean onKeyUp(int keyCode, KeyEvent event) {
8371        if (KeyEvent.isConfirmKey(keyCode)) {
8372            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8373                return true;
8374            }
8375            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8376                setPressed(false);
8377
8378                if (!mHasPerformedLongPress) {
8379                    // This is a tap, so remove the longpress check
8380                    removeLongPressCallback();
8381                    return performClick();
8382                }
8383            }
8384        }
8385        return false;
8386    }
8387
8388    /**
8389     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8390     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8391     * the event).
8392     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8393     * although some may elect to do so in some situations. Do not rely on this to
8394     * catch software key presses.
8395     *
8396     * @param keyCode     A key code that represents the button pressed, from
8397     *                    {@link android.view.KeyEvent}.
8398     * @param repeatCount The number of times the action was made.
8399     * @param event       The KeyEvent object that defines the button action.
8400     */
8401    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8402        return false;
8403    }
8404
8405    /**
8406     * Called on the focused view when a key shortcut event is not handled.
8407     * Override this method to implement local key shortcuts for the View.
8408     * Key shortcuts can also be implemented by setting the
8409     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8410     *
8411     * @param keyCode The value in event.getKeyCode().
8412     * @param event Description of the key event.
8413     * @return If you handled the event, return true. If you want to allow the
8414     *         event to be handled by the next receiver, return false.
8415     */
8416    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8417        return false;
8418    }
8419
8420    /**
8421     * Check whether the called view is a text editor, in which case it
8422     * would make sense to automatically display a soft input window for
8423     * it.  Subclasses should override this if they implement
8424     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8425     * a call on that method would return a non-null InputConnection, and
8426     * they are really a first-class editor that the user would normally
8427     * start typing on when the go into a window containing your view.
8428     *
8429     * <p>The default implementation always returns false.  This does
8430     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8431     * will not be called or the user can not otherwise perform edits on your
8432     * view; it is just a hint to the system that this is not the primary
8433     * purpose of this view.
8434     *
8435     * @return Returns true if this view is a text editor, else false.
8436     */
8437    public boolean onCheckIsTextEditor() {
8438        return false;
8439    }
8440
8441    /**
8442     * Create a new InputConnection for an InputMethod to interact
8443     * with the view.  The default implementation returns null, since it doesn't
8444     * support input methods.  You can override this to implement such support.
8445     * This is only needed for views that take focus and text input.
8446     *
8447     * <p>When implementing this, you probably also want to implement
8448     * {@link #onCheckIsTextEditor()} to indicate you will return a
8449     * non-null InputConnection.
8450     *
8451     * @param outAttrs Fill in with attribute information about the connection.
8452     */
8453    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8454        return null;
8455    }
8456
8457    /**
8458     * Called by the {@link android.view.inputmethod.InputMethodManager}
8459     * when a view who is not the current
8460     * input connection target is trying to make a call on the manager.  The
8461     * default implementation returns false; you can override this to return
8462     * true for certain views if you are performing InputConnection proxying
8463     * to them.
8464     * @param view The View that is making the InputMethodManager call.
8465     * @return Return true to allow the call, false to reject.
8466     */
8467    public boolean checkInputConnectionProxy(View view) {
8468        return false;
8469    }
8470
8471    /**
8472     * Show the context menu for this view. It is not safe to hold on to the
8473     * menu after returning from this method.
8474     *
8475     * You should normally not overload this method. Overload
8476     * {@link #onCreateContextMenu(ContextMenu)} or define an
8477     * {@link OnCreateContextMenuListener} to add items to the context menu.
8478     *
8479     * @param menu The context menu to populate
8480     */
8481    public void createContextMenu(ContextMenu menu) {
8482        ContextMenuInfo menuInfo = getContextMenuInfo();
8483
8484        // Sets the current menu info so all items added to menu will have
8485        // my extra info set.
8486        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8487
8488        onCreateContextMenu(menu);
8489        ListenerInfo li = mListenerInfo;
8490        if (li != null && li.mOnCreateContextMenuListener != null) {
8491            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8492        }
8493
8494        // Clear the extra information so subsequent items that aren't mine don't
8495        // have my extra info.
8496        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8497
8498        if (mParent != null) {
8499            mParent.createContextMenu(menu);
8500        }
8501    }
8502
8503    /**
8504     * Views should implement this if they have extra information to associate
8505     * with the context menu. The return result is supplied as a parameter to
8506     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8507     * callback.
8508     *
8509     * @return Extra information about the item for which the context menu
8510     *         should be shown. This information will vary across different
8511     *         subclasses of View.
8512     */
8513    protected ContextMenuInfo getContextMenuInfo() {
8514        return null;
8515    }
8516
8517    /**
8518     * Views should implement this if the view itself is going to add items to
8519     * the context menu.
8520     *
8521     * @param menu the context menu to populate
8522     */
8523    protected void onCreateContextMenu(ContextMenu menu) {
8524    }
8525
8526    /**
8527     * Implement this method to handle trackball motion events.  The
8528     * <em>relative</em> movement of the trackball since the last event
8529     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8530     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8531     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8532     * they will often be fractional values, representing the more fine-grained
8533     * movement information available from a trackball).
8534     *
8535     * @param event The motion event.
8536     * @return True if the event was handled, false otherwise.
8537     */
8538    public boolean onTrackballEvent(MotionEvent event) {
8539        return false;
8540    }
8541
8542    /**
8543     * Implement this method to handle generic motion events.
8544     * <p>
8545     * Generic motion events describe joystick movements, mouse hovers, track pad
8546     * touches, scroll wheel movements and other input events.  The
8547     * {@link MotionEvent#getSource() source} of the motion event specifies
8548     * the class of input that was received.  Implementations of this method
8549     * must examine the bits in the source before processing the event.
8550     * The following code example shows how this is done.
8551     * </p><p>
8552     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8553     * are delivered to the view under the pointer.  All other generic motion events are
8554     * delivered to the focused view.
8555     * </p>
8556     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8557     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8558     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8559     *             // process the joystick movement...
8560     *             return true;
8561     *         }
8562     *     }
8563     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8564     *         switch (event.getAction()) {
8565     *             case MotionEvent.ACTION_HOVER_MOVE:
8566     *                 // process the mouse hover movement...
8567     *                 return true;
8568     *             case MotionEvent.ACTION_SCROLL:
8569     *                 // process the scroll wheel movement...
8570     *                 return true;
8571     *         }
8572     *     }
8573     *     return super.onGenericMotionEvent(event);
8574     * }</pre>
8575     *
8576     * @param event The generic motion event being processed.
8577     * @return True if the event was handled, false otherwise.
8578     */
8579    public boolean onGenericMotionEvent(MotionEvent event) {
8580        return false;
8581    }
8582
8583    /**
8584     * Implement this method to handle hover events.
8585     * <p>
8586     * This method is called whenever a pointer is hovering into, over, or out of the
8587     * bounds of a view and the view is not currently being touched.
8588     * Hover events are represented as pointer events with action
8589     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8590     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8591     * </p>
8592     * <ul>
8593     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8594     * when the pointer enters the bounds of the view.</li>
8595     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8596     * when the pointer has already entered the bounds of the view and has moved.</li>
8597     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8598     * when the pointer has exited the bounds of the view or when the pointer is
8599     * about to go down due to a button click, tap, or similar user action that
8600     * causes the view to be touched.</li>
8601     * </ul>
8602     * <p>
8603     * The view should implement this method to return true to indicate that it is
8604     * handling the hover event, such as by changing its drawable state.
8605     * </p><p>
8606     * The default implementation calls {@link #setHovered} to update the hovered state
8607     * of the view when a hover enter or hover exit event is received, if the view
8608     * is enabled and is clickable.  The default implementation also sends hover
8609     * accessibility events.
8610     * </p>
8611     *
8612     * @param event The motion event that describes the hover.
8613     * @return True if the view handled the hover event.
8614     *
8615     * @see #isHovered
8616     * @see #setHovered
8617     * @see #onHoverChanged
8618     */
8619    public boolean onHoverEvent(MotionEvent event) {
8620        // The root view may receive hover (or touch) events that are outside the bounds of
8621        // the window.  This code ensures that we only send accessibility events for
8622        // hovers that are actually within the bounds of the root view.
8623        final int action = event.getActionMasked();
8624        if (!mSendingHoverAccessibilityEvents) {
8625            if ((action == MotionEvent.ACTION_HOVER_ENTER
8626                    || action == MotionEvent.ACTION_HOVER_MOVE)
8627                    && !hasHoveredChild()
8628                    && pointInView(event.getX(), event.getY())) {
8629                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8630                mSendingHoverAccessibilityEvents = true;
8631            }
8632        } else {
8633            if (action == MotionEvent.ACTION_HOVER_EXIT
8634                    || (action == MotionEvent.ACTION_MOVE
8635                            && !pointInView(event.getX(), event.getY()))) {
8636                mSendingHoverAccessibilityEvents = false;
8637                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8638                // If the window does not have input focus we take away accessibility
8639                // focus as soon as the user stop hovering over the view.
8640                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8641                    getViewRootImpl().setAccessibilityFocus(null, null);
8642                }
8643            }
8644        }
8645
8646        if (isHoverable()) {
8647            switch (action) {
8648                case MotionEvent.ACTION_HOVER_ENTER:
8649                    setHovered(true);
8650                    break;
8651                case MotionEvent.ACTION_HOVER_EXIT:
8652                    setHovered(false);
8653                    break;
8654            }
8655
8656            // Dispatch the event to onGenericMotionEvent before returning true.
8657            // This is to provide compatibility with existing applications that
8658            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8659            // break because of the new default handling for hoverable views
8660            // in onHoverEvent.
8661            // Note that onGenericMotionEvent will be called by default when
8662            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8663            dispatchGenericMotionEventInternal(event);
8664            // The event was already handled by calling setHovered(), so always
8665            // return true.
8666            return true;
8667        }
8668
8669        return false;
8670    }
8671
8672    /**
8673     * Returns true if the view should handle {@link #onHoverEvent}
8674     * by calling {@link #setHovered} to change its hovered state.
8675     *
8676     * @return True if the view is hoverable.
8677     */
8678    private boolean isHoverable() {
8679        final int viewFlags = mViewFlags;
8680        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8681            return false;
8682        }
8683
8684        return (viewFlags & CLICKABLE) == CLICKABLE
8685                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8686    }
8687
8688    /**
8689     * Returns true if the view is currently hovered.
8690     *
8691     * @return True if the view is currently hovered.
8692     *
8693     * @see #setHovered
8694     * @see #onHoverChanged
8695     */
8696    @ViewDebug.ExportedProperty
8697    public boolean isHovered() {
8698        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8699    }
8700
8701    /**
8702     * Sets whether the view is currently hovered.
8703     * <p>
8704     * Calling this method also changes the drawable state of the view.  This
8705     * enables the view to react to hover by using different drawable resources
8706     * to change its appearance.
8707     * </p><p>
8708     * The {@link #onHoverChanged} method is called when the hovered state changes.
8709     * </p>
8710     *
8711     * @param hovered True if the view is hovered.
8712     *
8713     * @see #isHovered
8714     * @see #onHoverChanged
8715     */
8716    public void setHovered(boolean hovered) {
8717        if (hovered) {
8718            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8719                mPrivateFlags |= PFLAG_HOVERED;
8720                refreshDrawableState();
8721                onHoverChanged(true);
8722            }
8723        } else {
8724            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8725                mPrivateFlags &= ~PFLAG_HOVERED;
8726                refreshDrawableState();
8727                onHoverChanged(false);
8728            }
8729        }
8730    }
8731
8732    /**
8733     * Implement this method to handle hover state changes.
8734     * <p>
8735     * This method is called whenever the hover state changes as a result of a
8736     * call to {@link #setHovered}.
8737     * </p>
8738     *
8739     * @param hovered The current hover state, as returned by {@link #isHovered}.
8740     *
8741     * @see #isHovered
8742     * @see #setHovered
8743     */
8744    public void onHoverChanged(boolean hovered) {
8745    }
8746
8747    /**
8748     * Implement this method to handle touch screen motion events.
8749     * <p>
8750     * If this method is used to detect click actions, it is recommended that
8751     * the actions be performed by implementing and calling
8752     * {@link #performClick()}. This will ensure consistent system behavior,
8753     * including:
8754     * <ul>
8755     * <li>obeying click sound preferences
8756     * <li>dispatching OnClickListener calls
8757     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
8758     * accessibility features are enabled
8759     * </ul>
8760     *
8761     * @param event The motion event.
8762     * @return True if the event was handled, false otherwise.
8763     */
8764    public boolean onTouchEvent(MotionEvent event) {
8765        final int viewFlags = mViewFlags;
8766
8767        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8768            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8769                setPressed(false);
8770            }
8771            // A disabled view that is clickable still consumes the touch
8772            // events, it just doesn't respond to them.
8773            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8774                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8775        }
8776
8777        if (mTouchDelegate != null) {
8778            if (mTouchDelegate.onTouchEvent(event)) {
8779                return true;
8780            }
8781        }
8782
8783        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8784                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8785            switch (event.getAction()) {
8786                case MotionEvent.ACTION_UP:
8787                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8788                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8789                        // take focus if we don't have it already and we should in
8790                        // touch mode.
8791                        boolean focusTaken = false;
8792                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8793                            focusTaken = requestFocus();
8794                        }
8795
8796                        if (prepressed) {
8797                            // The button is being released before we actually
8798                            // showed it as pressed.  Make it show the pressed
8799                            // state now (before scheduling the click) to ensure
8800                            // the user sees it.
8801                            setPressed(true);
8802                       }
8803
8804                        if (!mHasPerformedLongPress) {
8805                            // This is a tap, so remove the longpress check
8806                            removeLongPressCallback();
8807
8808                            // Only perform take click actions if we were in the pressed state
8809                            if (!focusTaken) {
8810                                // Use a Runnable and post this rather than calling
8811                                // performClick directly. This lets other visual state
8812                                // of the view update before click actions start.
8813                                if (mPerformClick == null) {
8814                                    mPerformClick = new PerformClick();
8815                                }
8816                                if (!post(mPerformClick)) {
8817                                    performClick();
8818                                }
8819                            }
8820                        }
8821
8822                        if (mUnsetPressedState == null) {
8823                            mUnsetPressedState = new UnsetPressedState();
8824                        }
8825
8826                        if (prepressed) {
8827                            postDelayed(mUnsetPressedState,
8828                                    ViewConfiguration.getPressedStateDuration());
8829                        } else if (!post(mUnsetPressedState)) {
8830                            // If the post failed, unpress right now
8831                            mUnsetPressedState.run();
8832                        }
8833                        removeTapCallback();
8834                    }
8835                    break;
8836
8837                case MotionEvent.ACTION_DOWN:
8838                    mHasPerformedLongPress = false;
8839
8840                    if (performButtonActionOnTouchDown(event)) {
8841                        break;
8842                    }
8843
8844                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8845                    boolean isInScrollingContainer = isInScrollingContainer();
8846
8847                    // For views inside a scrolling container, delay the pressed feedback for
8848                    // a short period in case this is a scroll.
8849                    if (isInScrollingContainer) {
8850                        mPrivateFlags |= PFLAG_PREPRESSED;
8851                        if (mPendingCheckForTap == null) {
8852                            mPendingCheckForTap = new CheckForTap();
8853                        }
8854                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8855                    } else {
8856                        // Not inside a scrolling container, so show the feedback right away
8857                        setPressed(true);
8858                        checkForLongClick(0);
8859                    }
8860                    break;
8861
8862                case MotionEvent.ACTION_CANCEL:
8863                    setPressed(false);
8864                    removeTapCallback();
8865                    removeLongPressCallback();
8866                    break;
8867
8868                case MotionEvent.ACTION_MOVE:
8869                    final int x = (int) event.getX();
8870                    final int y = (int) event.getY();
8871
8872                    // Be lenient about moving outside of buttons
8873                    if (!pointInView(x, y, mTouchSlop)) {
8874                        // Outside button
8875                        removeTapCallback();
8876                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8877                            // Remove any future long press/tap checks
8878                            removeLongPressCallback();
8879
8880                            setPressed(false);
8881                        }
8882                    }
8883                    break;
8884            }
8885            return true;
8886        }
8887
8888        return false;
8889    }
8890
8891    /**
8892     * @hide
8893     */
8894    public boolean isInScrollingContainer() {
8895        ViewParent p = getParent();
8896        while (p != null && p instanceof ViewGroup) {
8897            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8898                return true;
8899            }
8900            p = p.getParent();
8901        }
8902        return false;
8903    }
8904
8905    /**
8906     * Remove the longpress detection timer.
8907     */
8908    private void removeLongPressCallback() {
8909        if (mPendingCheckForLongPress != null) {
8910          removeCallbacks(mPendingCheckForLongPress);
8911        }
8912    }
8913
8914    /**
8915     * Remove the pending click action
8916     */
8917    private void removePerformClickCallback() {
8918        if (mPerformClick != null) {
8919            removeCallbacks(mPerformClick);
8920        }
8921    }
8922
8923    /**
8924     * Remove the prepress detection timer.
8925     */
8926    private void removeUnsetPressCallback() {
8927        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8928            setPressed(false);
8929            removeCallbacks(mUnsetPressedState);
8930        }
8931    }
8932
8933    /**
8934     * Remove the tap detection timer.
8935     */
8936    private void removeTapCallback() {
8937        if (mPendingCheckForTap != null) {
8938            mPrivateFlags &= ~PFLAG_PREPRESSED;
8939            removeCallbacks(mPendingCheckForTap);
8940        }
8941    }
8942
8943    /**
8944     * Cancels a pending long press.  Your subclass can use this if you
8945     * want the context menu to come up if the user presses and holds
8946     * at the same place, but you don't want it to come up if they press
8947     * and then move around enough to cause scrolling.
8948     */
8949    public void cancelLongPress() {
8950        removeLongPressCallback();
8951
8952        /*
8953         * The prepressed state handled by the tap callback is a display
8954         * construct, but the tap callback will post a long press callback
8955         * less its own timeout. Remove it here.
8956         */
8957        removeTapCallback();
8958    }
8959
8960    /**
8961     * Remove the pending callback for sending a
8962     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8963     */
8964    private void removeSendViewScrolledAccessibilityEventCallback() {
8965        if (mSendViewScrolledAccessibilityEvent != null) {
8966            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8967            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8968        }
8969    }
8970
8971    /**
8972     * Sets the TouchDelegate for this View.
8973     */
8974    public void setTouchDelegate(TouchDelegate delegate) {
8975        mTouchDelegate = delegate;
8976    }
8977
8978    /**
8979     * Gets the TouchDelegate for this View.
8980     */
8981    public TouchDelegate getTouchDelegate() {
8982        return mTouchDelegate;
8983    }
8984
8985    /**
8986     * Set flags controlling behavior of this view.
8987     *
8988     * @param flags Constant indicating the value which should be set
8989     * @param mask Constant indicating the bit range that should be changed
8990     */
8991    void setFlags(int flags, int mask) {
8992        final boolean accessibilityEnabled =
8993                AccessibilityManager.getInstance(mContext).isEnabled();
8994        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8995
8996        int old = mViewFlags;
8997        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8998
8999        int changed = mViewFlags ^ old;
9000        if (changed == 0) {
9001            return;
9002        }
9003        int privateFlags = mPrivateFlags;
9004
9005        /* Check if the FOCUSABLE bit has changed */
9006        if (((changed & FOCUSABLE_MASK) != 0) &&
9007                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9008            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9009                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9010                /* Give up focus if we are no longer focusable */
9011                clearFocus();
9012            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9013                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9014                /*
9015                 * Tell the view system that we are now available to take focus
9016                 * if no one else already has it.
9017                 */
9018                if (mParent != null) mParent.focusableViewAvailable(this);
9019            }
9020        }
9021
9022        final int newVisibility = flags & VISIBILITY_MASK;
9023        if (newVisibility == VISIBLE) {
9024            if ((changed & VISIBILITY_MASK) != 0) {
9025                /*
9026                 * If this view is becoming visible, invalidate it in case it changed while
9027                 * it was not visible. Marking it drawn ensures that the invalidation will
9028                 * go through.
9029                 */
9030                mPrivateFlags |= PFLAG_DRAWN;
9031                invalidate(true);
9032
9033                needGlobalAttributesUpdate(true);
9034
9035                // a view becoming visible is worth notifying the parent
9036                // about in case nothing has focus.  even if this specific view
9037                // isn't focusable, it may contain something that is, so let
9038                // the root view try to give this focus if nothing else does.
9039                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9040                    mParent.focusableViewAvailable(this);
9041                }
9042            }
9043        }
9044
9045        /* Check if the GONE bit has changed */
9046        if ((changed & GONE) != 0) {
9047            needGlobalAttributesUpdate(false);
9048            requestLayout();
9049
9050            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9051                if (hasFocus()) clearFocus();
9052                clearAccessibilityFocus();
9053                destroyDrawingCache();
9054                if (mParent instanceof View) {
9055                    // GONE views noop invalidation, so invalidate the parent
9056                    ((View) mParent).invalidate(true);
9057                }
9058                // Mark the view drawn to ensure that it gets invalidated properly the next
9059                // time it is visible and gets invalidated
9060                mPrivateFlags |= PFLAG_DRAWN;
9061            }
9062            if (mAttachInfo != null) {
9063                mAttachInfo.mViewVisibilityChanged = true;
9064            }
9065        }
9066
9067        /* Check if the VISIBLE bit has changed */
9068        if ((changed & INVISIBLE) != 0) {
9069            needGlobalAttributesUpdate(false);
9070            /*
9071             * If this view is becoming invisible, set the DRAWN flag so that
9072             * the next invalidate() will not be skipped.
9073             */
9074            mPrivateFlags |= PFLAG_DRAWN;
9075
9076            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9077                // root view becoming invisible shouldn't clear focus and accessibility focus
9078                if (getRootView() != this) {
9079                    if (hasFocus()) clearFocus();
9080                    clearAccessibilityFocus();
9081                }
9082            }
9083            if (mAttachInfo != null) {
9084                mAttachInfo.mViewVisibilityChanged = true;
9085            }
9086        }
9087
9088        if ((changed & VISIBILITY_MASK) != 0) {
9089            // If the view is invisible, cleanup its display list to free up resources
9090            if (newVisibility != VISIBLE) {
9091                cleanupDraw();
9092            }
9093
9094            if (mParent instanceof ViewGroup) {
9095                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9096                        (changed & VISIBILITY_MASK), newVisibility);
9097                ((View) mParent).invalidate(true);
9098            } else if (mParent != null) {
9099                mParent.invalidateChild(this, null);
9100            }
9101            dispatchVisibilityChanged(this, newVisibility);
9102        }
9103
9104        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9105            destroyDrawingCache();
9106        }
9107
9108        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9109            destroyDrawingCache();
9110            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9111            invalidateParentCaches();
9112        }
9113
9114        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9115            destroyDrawingCache();
9116            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9117        }
9118
9119        if ((changed & DRAW_MASK) != 0) {
9120            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9121                if (mBackground != null) {
9122                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9123                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9124                } else {
9125                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9126                }
9127            } else {
9128                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9129            }
9130            requestLayout();
9131            invalidate(true);
9132        }
9133
9134        if ((changed & KEEP_SCREEN_ON) != 0) {
9135            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9136                mParent.recomputeViewAttributes(this);
9137            }
9138        }
9139
9140        if (accessibilityEnabled) {
9141            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9142                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9143                if (oldIncludeForAccessibility != includeForAccessibility()) {
9144                    notifySubtreeAccessibilityStateChangedIfNeeded();
9145                } else {
9146                    notifyViewAccessibilityStateChangedIfNeeded(
9147                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9148                }
9149            } else if ((changed & ENABLED_MASK) != 0) {
9150                notifyViewAccessibilityStateChangedIfNeeded(
9151                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9152            }
9153        }
9154    }
9155
9156    /**
9157     * Change the view's z order in the tree, so it's on top of other sibling
9158     * views. This ordering change may affect layout, if the parent container
9159     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9160     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9161     * method should be followed by calls to {@link #requestLayout()} and
9162     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9163     * with the new child ordering.
9164     *
9165     * @see ViewGroup#bringChildToFront(View)
9166     */
9167    public void bringToFront() {
9168        if (mParent != null) {
9169            mParent.bringChildToFront(this);
9170        }
9171    }
9172
9173    /**
9174     * This is called in response to an internal scroll in this view (i.e., the
9175     * view scrolled its own contents). This is typically as a result of
9176     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9177     * called.
9178     *
9179     * @param l Current horizontal scroll origin.
9180     * @param t Current vertical scroll origin.
9181     * @param oldl Previous horizontal scroll origin.
9182     * @param oldt Previous vertical scroll origin.
9183     */
9184    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9185        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9186            postSendViewScrolledAccessibilityEventCallback();
9187        }
9188
9189        mBackgroundSizeChanged = true;
9190
9191        final AttachInfo ai = mAttachInfo;
9192        if (ai != null) {
9193            ai.mViewScrollChanged = true;
9194        }
9195    }
9196
9197    /**
9198     * Interface definition for a callback to be invoked when the layout bounds of a view
9199     * changes due to layout processing.
9200     */
9201    public interface OnLayoutChangeListener {
9202        /**
9203         * Called when the layout bounds of a view changes due to layout processing.
9204         *
9205         * @param v The view whose bounds have changed.
9206         * @param left The new value of the view's left property.
9207         * @param top The new value of the view's top property.
9208         * @param right The new value of the view's right property.
9209         * @param bottom The new value of the view's bottom property.
9210         * @param oldLeft The previous value of the view's left property.
9211         * @param oldTop The previous value of the view's top property.
9212         * @param oldRight The previous value of the view's right property.
9213         * @param oldBottom The previous value of the view's bottom property.
9214         */
9215        void onLayoutChange(View v, int left, int top, int right, int bottom,
9216            int oldLeft, int oldTop, int oldRight, int oldBottom);
9217    }
9218
9219    /**
9220     * This is called during layout when the size of this view has changed. If
9221     * you were just added to the view hierarchy, you're called with the old
9222     * values of 0.
9223     *
9224     * @param w Current width of this view.
9225     * @param h Current height of this view.
9226     * @param oldw Old width of this view.
9227     * @param oldh Old height of this view.
9228     */
9229    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9230    }
9231
9232    /**
9233     * Called by draw to draw the child views. This may be overridden
9234     * by derived classes to gain control just before its children are drawn
9235     * (but after its own view has been drawn).
9236     * @param canvas the canvas on which to draw the view
9237     */
9238    protected void dispatchDraw(Canvas canvas) {
9239
9240    }
9241
9242    /**
9243     * Gets the parent of this view. Note that the parent is a
9244     * ViewParent and not necessarily a View.
9245     *
9246     * @return Parent of this view.
9247     */
9248    public final ViewParent getParent() {
9249        return mParent;
9250    }
9251
9252    /**
9253     * Set the horizontal scrolled position of your view. This will cause a call to
9254     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9255     * invalidated.
9256     * @param value the x position to scroll to
9257     */
9258    public void setScrollX(int value) {
9259        scrollTo(value, mScrollY);
9260    }
9261
9262    /**
9263     * Set the vertical scrolled position of your view. This will cause a call to
9264     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9265     * invalidated.
9266     * @param value the y position to scroll to
9267     */
9268    public void setScrollY(int value) {
9269        scrollTo(mScrollX, value);
9270    }
9271
9272    /**
9273     * Return the scrolled left position of this view. This is the left edge of
9274     * the displayed part of your view. You do not need to draw any pixels
9275     * farther left, since those are outside of the frame of your view on
9276     * screen.
9277     *
9278     * @return The left edge of the displayed part of your view, in pixels.
9279     */
9280    public final int getScrollX() {
9281        return mScrollX;
9282    }
9283
9284    /**
9285     * Return the scrolled top position of this view. This is the top edge of
9286     * the displayed part of your view. You do not need to draw any pixels above
9287     * it, since those are outside of the frame of your view on screen.
9288     *
9289     * @return The top edge of the displayed part of your view, in pixels.
9290     */
9291    public final int getScrollY() {
9292        return mScrollY;
9293    }
9294
9295    /**
9296     * Return the width of the your view.
9297     *
9298     * @return The width of your view, in pixels.
9299     */
9300    @ViewDebug.ExportedProperty(category = "layout")
9301    public final int getWidth() {
9302        return mRight - mLeft;
9303    }
9304
9305    /**
9306     * Return the height of your view.
9307     *
9308     * @return The height of your view, in pixels.
9309     */
9310    @ViewDebug.ExportedProperty(category = "layout")
9311    public final int getHeight() {
9312        return mBottom - mTop;
9313    }
9314
9315    /**
9316     * Return the visible drawing bounds of your view. Fills in the output
9317     * rectangle with the values from getScrollX(), getScrollY(),
9318     * getWidth(), and getHeight(). These bounds do not account for any
9319     * transformation properties currently set on the view, such as
9320     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9321     *
9322     * @param outRect The (scrolled) drawing bounds of the view.
9323     */
9324    public void getDrawingRect(Rect outRect) {
9325        outRect.left = mScrollX;
9326        outRect.top = mScrollY;
9327        outRect.right = mScrollX + (mRight - mLeft);
9328        outRect.bottom = mScrollY + (mBottom - mTop);
9329    }
9330
9331    /**
9332     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9333     * raw width component (that is the result is masked by
9334     * {@link #MEASURED_SIZE_MASK}).
9335     *
9336     * @return The raw measured width of this view.
9337     */
9338    public final int getMeasuredWidth() {
9339        return mMeasuredWidth & MEASURED_SIZE_MASK;
9340    }
9341
9342    /**
9343     * Return the full width measurement information for this view as computed
9344     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9345     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9346     * This should be used during measurement and layout calculations only. Use
9347     * {@link #getWidth()} to see how wide a view is after layout.
9348     *
9349     * @return The measured width of this view as a bit mask.
9350     */
9351    public final int getMeasuredWidthAndState() {
9352        return mMeasuredWidth;
9353    }
9354
9355    /**
9356     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9357     * raw width component (that is the result is masked by
9358     * {@link #MEASURED_SIZE_MASK}).
9359     *
9360     * @return The raw measured height of this view.
9361     */
9362    public final int getMeasuredHeight() {
9363        return mMeasuredHeight & MEASURED_SIZE_MASK;
9364    }
9365
9366    /**
9367     * Return the full height measurement information for this view as computed
9368     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9369     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9370     * This should be used during measurement and layout calculations only. Use
9371     * {@link #getHeight()} to see how wide a view is after layout.
9372     *
9373     * @return The measured width of this view as a bit mask.
9374     */
9375    public final int getMeasuredHeightAndState() {
9376        return mMeasuredHeight;
9377    }
9378
9379    /**
9380     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9381     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9382     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9383     * and the height component is at the shifted bits
9384     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9385     */
9386    public final int getMeasuredState() {
9387        return (mMeasuredWidth&MEASURED_STATE_MASK)
9388                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9389                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9390    }
9391
9392    /**
9393     * The transform matrix of this view, which is calculated based on the current
9394     * roation, scale, and pivot properties.
9395     *
9396     * @see #getRotation()
9397     * @see #getScaleX()
9398     * @see #getScaleY()
9399     * @see #getPivotX()
9400     * @see #getPivotY()
9401     * @return The current transform matrix for the view
9402     */
9403    public Matrix getMatrix() {
9404        if (mTransformationInfo != null) {
9405            updateMatrix();
9406            return mTransformationInfo.mMatrix;
9407        }
9408        return Matrix.IDENTITY_MATRIX;
9409    }
9410
9411    /**
9412     * Utility function to determine if the value is far enough away from zero to be
9413     * considered non-zero.
9414     * @param value A floating point value to check for zero-ness
9415     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9416     */
9417    private static boolean nonzero(float value) {
9418        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9419    }
9420
9421    /**
9422     * Returns true if the transform matrix is the identity matrix.
9423     * Recomputes the matrix if necessary.
9424     *
9425     * @return True if the transform matrix is the identity matrix, false otherwise.
9426     */
9427    final boolean hasIdentityMatrix() {
9428        if (mTransformationInfo != null) {
9429            updateMatrix();
9430            return mTransformationInfo.mMatrixIsIdentity;
9431        }
9432        return true;
9433    }
9434
9435    void ensureTransformationInfo() {
9436        if (mTransformationInfo == null) {
9437            mTransformationInfo = new TransformationInfo();
9438        }
9439    }
9440
9441    /**
9442     * Recomputes the transform matrix if necessary.
9443     */
9444    private void updateMatrix() {
9445        final TransformationInfo info = mTransformationInfo;
9446        if (info == null) {
9447            return;
9448        }
9449        if (info.mMatrixDirty) {
9450            // transform-related properties have changed since the last time someone
9451            // asked for the matrix; recalculate it with the current values
9452
9453            // Figure out if we need to update the pivot point
9454            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9455                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9456                    info.mPrevWidth = mRight - mLeft;
9457                    info.mPrevHeight = mBottom - mTop;
9458                    info.mPivotX = info.mPrevWidth / 2f;
9459                    info.mPivotY = info.mPrevHeight / 2f;
9460                }
9461            }
9462            info.mMatrix.reset();
9463            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9464                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9465                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9466                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9467            } else {
9468                if (info.mCamera == null) {
9469                    info.mCamera = new Camera();
9470                    info.matrix3D = new Matrix();
9471                }
9472                info.mCamera.save();
9473                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9474                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9475                info.mCamera.getMatrix(info.matrix3D);
9476                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9477                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9478                        info.mPivotY + info.mTranslationY);
9479                info.mMatrix.postConcat(info.matrix3D);
9480                info.mCamera.restore();
9481            }
9482            info.mMatrixDirty = false;
9483            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9484            info.mInverseMatrixDirty = true;
9485        }
9486    }
9487
9488   /**
9489     * Utility method to retrieve the inverse of the current mMatrix property.
9490     * We cache the matrix to avoid recalculating it when transform properties
9491     * have not changed.
9492     *
9493     * @return The inverse of the current matrix of this view.
9494     */
9495    final Matrix getInverseMatrix() {
9496        final TransformationInfo info = mTransformationInfo;
9497        if (info != null) {
9498            updateMatrix();
9499            if (info.mInverseMatrixDirty) {
9500                if (info.mInverseMatrix == null) {
9501                    info.mInverseMatrix = new Matrix();
9502                }
9503                info.mMatrix.invert(info.mInverseMatrix);
9504                info.mInverseMatrixDirty = false;
9505            }
9506            return info.mInverseMatrix;
9507        }
9508        return Matrix.IDENTITY_MATRIX;
9509    }
9510
9511    /**
9512     * Gets the distance along the Z axis from the camera to this view.
9513     *
9514     * @see #setCameraDistance(float)
9515     *
9516     * @return The distance along the Z axis.
9517     */
9518    public float getCameraDistance() {
9519        ensureTransformationInfo();
9520        final float dpi = mResources.getDisplayMetrics().densityDpi;
9521        final TransformationInfo info = mTransformationInfo;
9522        if (info.mCamera == null) {
9523            info.mCamera = new Camera();
9524            info.matrix3D = new Matrix();
9525        }
9526        return -(info.mCamera.getLocationZ() * dpi);
9527    }
9528
9529    /**
9530     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9531     * views are drawn) from the camera to this view. The camera's distance
9532     * affects 3D transformations, for instance rotations around the X and Y
9533     * axis. If the rotationX or rotationY properties are changed and this view is
9534     * large (more than half the size of the screen), it is recommended to always
9535     * use a camera distance that's greater than the height (X axis rotation) or
9536     * the width (Y axis rotation) of this view.</p>
9537     *
9538     * <p>The distance of the camera from the view plane can have an affect on the
9539     * perspective distortion of the view when it is rotated around the x or y axis.
9540     * For example, a large distance will result in a large viewing angle, and there
9541     * will not be much perspective distortion of the view as it rotates. A short
9542     * distance may cause much more perspective distortion upon rotation, and can
9543     * also result in some drawing artifacts if the rotated view ends up partially
9544     * behind the camera (which is why the recommendation is to use a distance at
9545     * least as far as the size of the view, if the view is to be rotated.)</p>
9546     *
9547     * <p>The distance is expressed in "depth pixels." The default distance depends
9548     * on the screen density. For instance, on a medium density display, the
9549     * default distance is 1280. On a high density display, the default distance
9550     * is 1920.</p>
9551     *
9552     * <p>If you want to specify a distance that leads to visually consistent
9553     * results across various densities, use the following formula:</p>
9554     * <pre>
9555     * float scale = context.getResources().getDisplayMetrics().density;
9556     * view.setCameraDistance(distance * scale);
9557     * </pre>
9558     *
9559     * <p>The density scale factor of a high density display is 1.5,
9560     * and 1920 = 1280 * 1.5.</p>
9561     *
9562     * @param distance The distance in "depth pixels", if negative the opposite
9563     *        value is used
9564     *
9565     * @see #setRotationX(float)
9566     * @see #setRotationY(float)
9567     */
9568    public void setCameraDistance(float distance) {
9569        invalidateViewProperty(true, false);
9570
9571        ensureTransformationInfo();
9572        final float dpi = mResources.getDisplayMetrics().densityDpi;
9573        final TransformationInfo info = mTransformationInfo;
9574        if (info.mCamera == null) {
9575            info.mCamera = new Camera();
9576            info.matrix3D = new Matrix();
9577        }
9578
9579        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9580        info.mMatrixDirty = true;
9581
9582        invalidateViewProperty(false, false);
9583        if (mDisplayList != null) {
9584            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9585        }
9586        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9587            // View was rejected last time it was drawn by its parent; this may have changed
9588            invalidateParentIfNeeded();
9589        }
9590    }
9591
9592    /**
9593     * The degrees that the view is rotated around the pivot point.
9594     *
9595     * @see #setRotation(float)
9596     * @see #getPivotX()
9597     * @see #getPivotY()
9598     *
9599     * @return The degrees of rotation.
9600     */
9601    @ViewDebug.ExportedProperty(category = "drawing")
9602    public float getRotation() {
9603        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9604    }
9605
9606    /**
9607     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9608     * result in clockwise rotation.
9609     *
9610     * @param rotation The degrees of rotation.
9611     *
9612     * @see #getRotation()
9613     * @see #getPivotX()
9614     * @see #getPivotY()
9615     * @see #setRotationX(float)
9616     * @see #setRotationY(float)
9617     *
9618     * @attr ref android.R.styleable#View_rotation
9619     */
9620    public void setRotation(float rotation) {
9621        ensureTransformationInfo();
9622        final TransformationInfo info = mTransformationInfo;
9623        if (info.mRotation != rotation) {
9624            // Double-invalidation is necessary to capture view's old and new areas
9625            invalidateViewProperty(true, false);
9626            info.mRotation = rotation;
9627            info.mMatrixDirty = true;
9628            invalidateViewProperty(false, true);
9629            if (mDisplayList != null) {
9630                mDisplayList.setRotation(rotation);
9631            }
9632            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9633                // View was rejected last time it was drawn by its parent; this may have changed
9634                invalidateParentIfNeeded();
9635            }
9636        }
9637    }
9638
9639    /**
9640     * The degrees that the view is rotated around the vertical axis through the pivot point.
9641     *
9642     * @see #getPivotX()
9643     * @see #getPivotY()
9644     * @see #setRotationY(float)
9645     *
9646     * @return The degrees of Y rotation.
9647     */
9648    @ViewDebug.ExportedProperty(category = "drawing")
9649    public float getRotationY() {
9650        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9651    }
9652
9653    /**
9654     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9655     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9656     * down the y axis.
9657     *
9658     * When rotating large views, it is recommended to adjust the camera distance
9659     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9660     *
9661     * @param rotationY The degrees of Y rotation.
9662     *
9663     * @see #getRotationY()
9664     * @see #getPivotX()
9665     * @see #getPivotY()
9666     * @see #setRotation(float)
9667     * @see #setRotationX(float)
9668     * @see #setCameraDistance(float)
9669     *
9670     * @attr ref android.R.styleable#View_rotationY
9671     */
9672    public void setRotationY(float rotationY) {
9673        ensureTransformationInfo();
9674        final TransformationInfo info = mTransformationInfo;
9675        if (info.mRotationY != rotationY) {
9676            invalidateViewProperty(true, false);
9677            info.mRotationY = rotationY;
9678            info.mMatrixDirty = true;
9679            invalidateViewProperty(false, true);
9680            if (mDisplayList != null) {
9681                mDisplayList.setRotationY(rotationY);
9682            }
9683            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9684                // View was rejected last time it was drawn by its parent; this may have changed
9685                invalidateParentIfNeeded();
9686            }
9687        }
9688    }
9689
9690    /**
9691     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9692     *
9693     * @see #getPivotX()
9694     * @see #getPivotY()
9695     * @see #setRotationX(float)
9696     *
9697     * @return The degrees of X rotation.
9698     */
9699    @ViewDebug.ExportedProperty(category = "drawing")
9700    public float getRotationX() {
9701        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9702    }
9703
9704    /**
9705     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9706     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9707     * x axis.
9708     *
9709     * When rotating large views, it is recommended to adjust the camera distance
9710     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9711     *
9712     * @param rotationX The degrees of X rotation.
9713     *
9714     * @see #getRotationX()
9715     * @see #getPivotX()
9716     * @see #getPivotY()
9717     * @see #setRotation(float)
9718     * @see #setRotationY(float)
9719     * @see #setCameraDistance(float)
9720     *
9721     * @attr ref android.R.styleable#View_rotationX
9722     */
9723    public void setRotationX(float rotationX) {
9724        ensureTransformationInfo();
9725        final TransformationInfo info = mTransformationInfo;
9726        if (info.mRotationX != rotationX) {
9727            invalidateViewProperty(true, false);
9728            info.mRotationX = rotationX;
9729            info.mMatrixDirty = true;
9730            invalidateViewProperty(false, true);
9731            if (mDisplayList != null) {
9732                mDisplayList.setRotationX(rotationX);
9733            }
9734            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9735                // View was rejected last time it was drawn by its parent; this may have changed
9736                invalidateParentIfNeeded();
9737            }
9738        }
9739    }
9740
9741    /**
9742     * The amount that the view is scaled in x around the pivot point, as a proportion of
9743     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9744     *
9745     * <p>By default, this is 1.0f.
9746     *
9747     * @see #getPivotX()
9748     * @see #getPivotY()
9749     * @return The scaling factor.
9750     */
9751    @ViewDebug.ExportedProperty(category = "drawing")
9752    public float getScaleX() {
9753        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9754    }
9755
9756    /**
9757     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9758     * the view's unscaled width. A value of 1 means that no scaling is applied.
9759     *
9760     * @param scaleX The scaling factor.
9761     * @see #getPivotX()
9762     * @see #getPivotY()
9763     *
9764     * @attr ref android.R.styleable#View_scaleX
9765     */
9766    public void setScaleX(float scaleX) {
9767        ensureTransformationInfo();
9768        final TransformationInfo info = mTransformationInfo;
9769        if (info.mScaleX != scaleX) {
9770            invalidateViewProperty(true, false);
9771            info.mScaleX = scaleX;
9772            info.mMatrixDirty = true;
9773            invalidateViewProperty(false, true);
9774            if (mDisplayList != null) {
9775                mDisplayList.setScaleX(scaleX);
9776            }
9777            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9778                // View was rejected last time it was drawn by its parent; this may have changed
9779                invalidateParentIfNeeded();
9780            }
9781        }
9782    }
9783
9784    /**
9785     * The amount that the view is scaled in y around the pivot point, as a proportion of
9786     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9787     *
9788     * <p>By default, this is 1.0f.
9789     *
9790     * @see #getPivotX()
9791     * @see #getPivotY()
9792     * @return The scaling factor.
9793     */
9794    @ViewDebug.ExportedProperty(category = "drawing")
9795    public float getScaleY() {
9796        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9797    }
9798
9799    /**
9800     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9801     * the view's unscaled width. A value of 1 means that no scaling is applied.
9802     *
9803     * @param scaleY The scaling factor.
9804     * @see #getPivotX()
9805     * @see #getPivotY()
9806     *
9807     * @attr ref android.R.styleable#View_scaleY
9808     */
9809    public void setScaleY(float scaleY) {
9810        ensureTransformationInfo();
9811        final TransformationInfo info = mTransformationInfo;
9812        if (info.mScaleY != scaleY) {
9813            invalidateViewProperty(true, false);
9814            info.mScaleY = scaleY;
9815            info.mMatrixDirty = true;
9816            invalidateViewProperty(false, true);
9817            if (mDisplayList != null) {
9818                mDisplayList.setScaleY(scaleY);
9819            }
9820            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9821                // View was rejected last time it was drawn by its parent; this may have changed
9822                invalidateParentIfNeeded();
9823            }
9824        }
9825    }
9826
9827    /**
9828     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9829     * and {@link #setScaleX(float) scaled}.
9830     *
9831     * @see #getRotation()
9832     * @see #getScaleX()
9833     * @see #getScaleY()
9834     * @see #getPivotY()
9835     * @return The x location of the pivot point.
9836     *
9837     * @attr ref android.R.styleable#View_transformPivotX
9838     */
9839    @ViewDebug.ExportedProperty(category = "drawing")
9840    public float getPivotX() {
9841        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9842    }
9843
9844    /**
9845     * Sets the x location of the point around which the view is
9846     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9847     * By default, the pivot point is centered on the object.
9848     * Setting this property disables this behavior and causes the view to use only the
9849     * explicitly set pivotX and pivotY values.
9850     *
9851     * @param pivotX The x location of the pivot point.
9852     * @see #getRotation()
9853     * @see #getScaleX()
9854     * @see #getScaleY()
9855     * @see #getPivotY()
9856     *
9857     * @attr ref android.R.styleable#View_transformPivotX
9858     */
9859    public void setPivotX(float pivotX) {
9860        ensureTransformationInfo();
9861        final TransformationInfo info = mTransformationInfo;
9862        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9863                PFLAG_PIVOT_EXPLICITLY_SET;
9864        if (info.mPivotX != pivotX || !pivotSet) {
9865            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9866            invalidateViewProperty(true, false);
9867            info.mPivotX = pivotX;
9868            info.mMatrixDirty = true;
9869            invalidateViewProperty(false, true);
9870            if (mDisplayList != null) {
9871                mDisplayList.setPivotX(pivotX);
9872            }
9873            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9874                // View was rejected last time it was drawn by its parent; this may have changed
9875                invalidateParentIfNeeded();
9876            }
9877        }
9878    }
9879
9880    /**
9881     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9882     * and {@link #setScaleY(float) scaled}.
9883     *
9884     * @see #getRotation()
9885     * @see #getScaleX()
9886     * @see #getScaleY()
9887     * @see #getPivotY()
9888     * @return The y location of the pivot point.
9889     *
9890     * @attr ref android.R.styleable#View_transformPivotY
9891     */
9892    @ViewDebug.ExportedProperty(category = "drawing")
9893    public float getPivotY() {
9894        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9895    }
9896
9897    /**
9898     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9899     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9900     * Setting this property disables this behavior and causes the view to use only the
9901     * explicitly set pivotX and pivotY values.
9902     *
9903     * @param pivotY The y location of the pivot point.
9904     * @see #getRotation()
9905     * @see #getScaleX()
9906     * @see #getScaleY()
9907     * @see #getPivotY()
9908     *
9909     * @attr ref android.R.styleable#View_transformPivotY
9910     */
9911    public void setPivotY(float pivotY) {
9912        ensureTransformationInfo();
9913        final TransformationInfo info = mTransformationInfo;
9914        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9915                PFLAG_PIVOT_EXPLICITLY_SET;
9916        if (info.mPivotY != pivotY || !pivotSet) {
9917            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9918            invalidateViewProperty(true, false);
9919            info.mPivotY = pivotY;
9920            info.mMatrixDirty = true;
9921            invalidateViewProperty(false, true);
9922            if (mDisplayList != null) {
9923                mDisplayList.setPivotY(pivotY);
9924            }
9925            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9926                // View was rejected last time it was drawn by its parent; this may have changed
9927                invalidateParentIfNeeded();
9928            }
9929        }
9930    }
9931
9932    /**
9933     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9934     * completely transparent and 1 means the view is completely opaque.
9935     *
9936     * <p>By default this is 1.0f.
9937     * @return The opacity of the view.
9938     */
9939    @ViewDebug.ExportedProperty(category = "drawing")
9940    public float getAlpha() {
9941        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9942    }
9943
9944    /**
9945     * Returns whether this View has content which overlaps.
9946     *
9947     * <p>This function, intended to be overridden by specific View types, is an optimization when
9948     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
9949     * an offscreen buffer and then composited into place, which can be expensive. If the view has
9950     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
9951     * directly. An example of overlapping rendering is a TextView with a background image, such as
9952     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
9953     * ImageView with only the foreground image. The default implementation returns true; subclasses
9954     * should override if they have cases which can be optimized.</p>
9955     *
9956     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
9957     * necessitates that a View return true if it uses the methods internally without passing the
9958     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
9959     *
9960     * @return true if the content in this view might overlap, false otherwise.
9961     */
9962    public boolean hasOverlappingRendering() {
9963        return true;
9964    }
9965
9966    /**
9967     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9968     * completely transparent and 1 means the view is completely opaque.</p>
9969     *
9970     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9971     * performance implications, especially for large views. It is best to use the alpha property
9972     * sparingly and transiently, as in the case of fading animations.</p>
9973     *
9974     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9975     * strongly recommended for performance reasons to either override
9976     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9977     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9978     *
9979     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9980     * responsible for applying the opacity itself.</p>
9981     *
9982     * <p>Note that if the view is backed by a
9983     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9984     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9985     * 1.0 will supercede the alpha of the layer paint.</p>
9986     *
9987     * @param alpha The opacity of the view.
9988     *
9989     * @see #hasOverlappingRendering()
9990     * @see #setLayerType(int, android.graphics.Paint)
9991     *
9992     * @attr ref android.R.styleable#View_alpha
9993     */
9994    public void setAlpha(float alpha) {
9995        ensureTransformationInfo();
9996        if (mTransformationInfo.mAlpha != alpha) {
9997            mTransformationInfo.mAlpha = alpha;
9998            if (onSetAlpha((int) (alpha * 255))) {
9999                mPrivateFlags |= PFLAG_ALPHA_SET;
10000                // subclass is handling alpha - don't optimize rendering cache invalidation
10001                invalidateParentCaches();
10002                invalidate(true);
10003            } else {
10004                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10005                invalidateViewProperty(true, false);
10006                if (mDisplayList != null) {
10007                    mDisplayList.setAlpha(getFinalAlpha());
10008                }
10009            }
10010        }
10011    }
10012
10013    /**
10014     * Faster version of setAlpha() which performs the same steps except there are
10015     * no calls to invalidate(). The caller of this function should perform proper invalidation
10016     * on the parent and this object. The return value indicates whether the subclass handles
10017     * alpha (the return value for onSetAlpha()).
10018     *
10019     * @param alpha The new value for the alpha property
10020     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10021     *         the new value for the alpha property is different from the old value
10022     */
10023    boolean setAlphaNoInvalidation(float alpha) {
10024        ensureTransformationInfo();
10025        if (mTransformationInfo.mAlpha != alpha) {
10026            mTransformationInfo.mAlpha = alpha;
10027            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10028            if (subclassHandlesAlpha) {
10029                mPrivateFlags |= PFLAG_ALPHA_SET;
10030                return true;
10031            } else {
10032                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10033                if (mDisplayList != null) {
10034                    mDisplayList.setAlpha(getFinalAlpha());
10035                }
10036            }
10037        }
10038        return false;
10039    }
10040
10041    /**
10042     * This property is hidden and intended only for use by the Fade transition, which
10043     * animates it to produce a visual translucency that does not side-effect (or get
10044     * affected by) the real alpha property. This value is composited with the other
10045     * alpha value (and the AlphaAnimation value, when that is present) to produce
10046     * a final visual translucency result, which is what is passed into the DisplayList.
10047     *
10048     * @hide
10049     */
10050    public void setTransitionAlpha(float alpha) {
10051        ensureTransformationInfo();
10052        if (mTransformationInfo.mTransitionAlpha != alpha) {
10053            mTransformationInfo.mTransitionAlpha = alpha;
10054            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10055            invalidateViewProperty(true, false);
10056            if (mDisplayList != null) {
10057                mDisplayList.setAlpha(getFinalAlpha());
10058            }
10059        }
10060    }
10061
10062    /**
10063     * Calculates the visual alpha of this view, which is a combination of the actual
10064     * alpha value and the transitionAlpha value (if set).
10065     */
10066    private float getFinalAlpha() {
10067        if (mTransformationInfo != null) {
10068            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10069        }
10070        return 1;
10071    }
10072
10073    /**
10074     * This property is hidden and intended only for use by the Fade transition, which
10075     * animates it to produce a visual translucency that does not side-effect (or get
10076     * affected by) the real alpha property. This value is composited with the other
10077     * alpha value (and the AlphaAnimation value, when that is present) to produce
10078     * a final visual translucency result, which is what is passed into the DisplayList.
10079     *
10080     * @hide
10081     */
10082    public float getTransitionAlpha() {
10083        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10084    }
10085
10086    /**
10087     * Top position of this view relative to its parent.
10088     *
10089     * @return The top of this view, in pixels.
10090     */
10091    @ViewDebug.CapturedViewProperty
10092    public final int getTop() {
10093        return mTop;
10094    }
10095
10096    /**
10097     * Sets the top position of this view relative to its parent. This method is meant to be called
10098     * by the layout system and should not generally be called otherwise, because the property
10099     * may be changed at any time by the layout.
10100     *
10101     * @param top The top of this view, in pixels.
10102     */
10103    public final void setTop(int top) {
10104        if (top != mTop) {
10105            updateMatrix();
10106            final boolean matrixIsIdentity = mTransformationInfo == null
10107                    || mTransformationInfo.mMatrixIsIdentity;
10108            if (matrixIsIdentity) {
10109                if (mAttachInfo != null) {
10110                    int minTop;
10111                    int yLoc;
10112                    if (top < mTop) {
10113                        minTop = top;
10114                        yLoc = top - mTop;
10115                    } else {
10116                        minTop = mTop;
10117                        yLoc = 0;
10118                    }
10119                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10120                }
10121            } else {
10122                // Double-invalidation is necessary to capture view's old and new areas
10123                invalidate(true);
10124            }
10125
10126            int width = mRight - mLeft;
10127            int oldHeight = mBottom - mTop;
10128
10129            mTop = top;
10130            if (mDisplayList != null) {
10131                mDisplayList.setTop(mTop);
10132            }
10133
10134            sizeChange(width, mBottom - mTop, width, oldHeight);
10135
10136            if (!matrixIsIdentity) {
10137                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10138                    // A change in dimension means an auto-centered pivot point changes, too
10139                    mTransformationInfo.mMatrixDirty = true;
10140                }
10141                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10142                invalidate(true);
10143            }
10144            mBackgroundSizeChanged = true;
10145            invalidateParentIfNeeded();
10146            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10147                // View was rejected last time it was drawn by its parent; this may have changed
10148                invalidateParentIfNeeded();
10149            }
10150        }
10151    }
10152
10153    /**
10154     * Bottom position of this view relative to its parent.
10155     *
10156     * @return The bottom of this view, in pixels.
10157     */
10158    @ViewDebug.CapturedViewProperty
10159    public final int getBottom() {
10160        return mBottom;
10161    }
10162
10163    /**
10164     * True if this view has changed since the last time being drawn.
10165     *
10166     * @return The dirty state of this view.
10167     */
10168    public boolean isDirty() {
10169        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10170    }
10171
10172    /**
10173     * Sets the bottom position of this view relative to its parent. This method is meant to be
10174     * called by the layout system and should not generally be called otherwise, because the
10175     * property may be changed at any time by the layout.
10176     *
10177     * @param bottom The bottom of this view, in pixels.
10178     */
10179    public final void setBottom(int bottom) {
10180        if (bottom != mBottom) {
10181            updateMatrix();
10182            final boolean matrixIsIdentity = mTransformationInfo == null
10183                    || mTransformationInfo.mMatrixIsIdentity;
10184            if (matrixIsIdentity) {
10185                if (mAttachInfo != null) {
10186                    int maxBottom;
10187                    if (bottom < mBottom) {
10188                        maxBottom = mBottom;
10189                    } else {
10190                        maxBottom = bottom;
10191                    }
10192                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10193                }
10194            } else {
10195                // Double-invalidation is necessary to capture view's old and new areas
10196                invalidate(true);
10197            }
10198
10199            int width = mRight - mLeft;
10200            int oldHeight = mBottom - mTop;
10201
10202            mBottom = bottom;
10203            if (mDisplayList != null) {
10204                mDisplayList.setBottom(mBottom);
10205            }
10206
10207            sizeChange(width, mBottom - mTop, width, oldHeight);
10208
10209            if (!matrixIsIdentity) {
10210                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10211                    // A change in dimension means an auto-centered pivot point changes, too
10212                    mTransformationInfo.mMatrixDirty = true;
10213                }
10214                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10215                invalidate(true);
10216            }
10217            mBackgroundSizeChanged = true;
10218            invalidateParentIfNeeded();
10219            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10220                // View was rejected last time it was drawn by its parent; this may have changed
10221                invalidateParentIfNeeded();
10222            }
10223        }
10224    }
10225
10226    /**
10227     * Left position of this view relative to its parent.
10228     *
10229     * @return The left edge of this view, in pixels.
10230     */
10231    @ViewDebug.CapturedViewProperty
10232    public final int getLeft() {
10233        return mLeft;
10234    }
10235
10236    /**
10237     * Sets the left position of this view relative to its parent. This method is meant to be called
10238     * by the layout system and should not generally be called otherwise, because the property
10239     * may be changed at any time by the layout.
10240     *
10241     * @param left The bottom of this view, in pixels.
10242     */
10243    public final void setLeft(int left) {
10244        if (left != mLeft) {
10245            updateMatrix();
10246            final boolean matrixIsIdentity = mTransformationInfo == null
10247                    || mTransformationInfo.mMatrixIsIdentity;
10248            if (matrixIsIdentity) {
10249                if (mAttachInfo != null) {
10250                    int minLeft;
10251                    int xLoc;
10252                    if (left < mLeft) {
10253                        minLeft = left;
10254                        xLoc = left - mLeft;
10255                    } else {
10256                        minLeft = mLeft;
10257                        xLoc = 0;
10258                    }
10259                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10260                }
10261            } else {
10262                // Double-invalidation is necessary to capture view's old and new areas
10263                invalidate(true);
10264            }
10265
10266            int oldWidth = mRight - mLeft;
10267            int height = mBottom - mTop;
10268
10269            mLeft = left;
10270            if (mDisplayList != null) {
10271                mDisplayList.setLeft(left);
10272            }
10273
10274            sizeChange(mRight - mLeft, height, oldWidth, height);
10275
10276            if (!matrixIsIdentity) {
10277                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10278                    // A change in dimension means an auto-centered pivot point changes, too
10279                    mTransformationInfo.mMatrixDirty = true;
10280                }
10281                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10282                invalidate(true);
10283            }
10284            mBackgroundSizeChanged = true;
10285            invalidateParentIfNeeded();
10286            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10287                // View was rejected last time it was drawn by its parent; this may have changed
10288                invalidateParentIfNeeded();
10289            }
10290        }
10291    }
10292
10293    /**
10294     * Right position of this view relative to its parent.
10295     *
10296     * @return The right edge of this view, in pixels.
10297     */
10298    @ViewDebug.CapturedViewProperty
10299    public final int getRight() {
10300        return mRight;
10301    }
10302
10303    /**
10304     * Sets the right position of this view relative to its parent. This method is meant to be called
10305     * by the layout system and should not generally be called otherwise, because the property
10306     * may be changed at any time by the layout.
10307     *
10308     * @param right The bottom of this view, in pixels.
10309     */
10310    public final void setRight(int right) {
10311        if (right != mRight) {
10312            updateMatrix();
10313            final boolean matrixIsIdentity = mTransformationInfo == null
10314                    || mTransformationInfo.mMatrixIsIdentity;
10315            if (matrixIsIdentity) {
10316                if (mAttachInfo != null) {
10317                    int maxRight;
10318                    if (right < mRight) {
10319                        maxRight = mRight;
10320                    } else {
10321                        maxRight = right;
10322                    }
10323                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10324                }
10325            } else {
10326                // Double-invalidation is necessary to capture view's old and new areas
10327                invalidate(true);
10328            }
10329
10330            int oldWidth = mRight - mLeft;
10331            int height = mBottom - mTop;
10332
10333            mRight = right;
10334            if (mDisplayList != null) {
10335                mDisplayList.setRight(mRight);
10336            }
10337
10338            sizeChange(mRight - mLeft, height, oldWidth, height);
10339
10340            if (!matrixIsIdentity) {
10341                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10342                    // A change in dimension means an auto-centered pivot point changes, too
10343                    mTransformationInfo.mMatrixDirty = true;
10344                }
10345                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10346                invalidate(true);
10347            }
10348            mBackgroundSizeChanged = true;
10349            invalidateParentIfNeeded();
10350            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10351                // View was rejected last time it was drawn by its parent; this may have changed
10352                invalidateParentIfNeeded();
10353            }
10354        }
10355    }
10356
10357    /**
10358     * The visual x position of this view, in pixels. This is equivalent to the
10359     * {@link #setTranslationX(float) translationX} property plus the current
10360     * {@link #getLeft() left} property.
10361     *
10362     * @return The visual x position of this view, in pixels.
10363     */
10364    @ViewDebug.ExportedProperty(category = "drawing")
10365    public float getX() {
10366        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10367    }
10368
10369    /**
10370     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10371     * {@link #setTranslationX(float) translationX} property to be the difference between
10372     * the x value passed in and the current {@link #getLeft() left} property.
10373     *
10374     * @param x The visual x position of this view, in pixels.
10375     */
10376    public void setX(float x) {
10377        setTranslationX(x - mLeft);
10378    }
10379
10380    /**
10381     * The visual y position of this view, in pixels. This is equivalent to the
10382     * {@link #setTranslationY(float) translationY} property plus the current
10383     * {@link #getTop() top} property.
10384     *
10385     * @return The visual y position of this view, in pixels.
10386     */
10387    @ViewDebug.ExportedProperty(category = "drawing")
10388    public float getY() {
10389        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10390    }
10391
10392    /**
10393     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10394     * {@link #setTranslationY(float) translationY} property to be the difference between
10395     * the y value passed in and the current {@link #getTop() top} property.
10396     *
10397     * @param y The visual y position of this view, in pixels.
10398     */
10399    public void setY(float y) {
10400        setTranslationY(y - mTop);
10401    }
10402
10403
10404    /**
10405     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10406     * This position is post-layout, in addition to wherever the object's
10407     * layout placed it.
10408     *
10409     * @return The horizontal position of this view relative to its left position, in pixels.
10410     */
10411    @ViewDebug.ExportedProperty(category = "drawing")
10412    public float getTranslationX() {
10413        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10414    }
10415
10416    /**
10417     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10418     * This effectively positions the object post-layout, in addition to wherever the object's
10419     * layout placed it.
10420     *
10421     * @param translationX The horizontal position of this view relative to its left position,
10422     * in pixels.
10423     *
10424     * @attr ref android.R.styleable#View_translationX
10425     */
10426    public void setTranslationX(float translationX) {
10427        ensureTransformationInfo();
10428        final TransformationInfo info = mTransformationInfo;
10429        if (info.mTranslationX != translationX) {
10430            // Double-invalidation is necessary to capture view's old and new areas
10431            invalidateViewProperty(true, false);
10432            info.mTranslationX = translationX;
10433            info.mMatrixDirty = true;
10434            invalidateViewProperty(false, true);
10435            if (mDisplayList != null) {
10436                mDisplayList.setTranslationX(translationX);
10437            }
10438            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10439                // View was rejected last time it was drawn by its parent; this may have changed
10440                invalidateParentIfNeeded();
10441            }
10442        }
10443    }
10444
10445    /**
10446     * The vertical location of this view relative to its {@link #getTop() top} position.
10447     * This position is post-layout, in addition to wherever the object's
10448     * layout placed it.
10449     *
10450     * @return The vertical position of this view relative to its top position,
10451     * in pixels.
10452     */
10453    @ViewDebug.ExportedProperty(category = "drawing")
10454    public float getTranslationY() {
10455        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10456    }
10457
10458    /**
10459     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10460     * This effectively positions the object post-layout, in addition to wherever the object's
10461     * layout placed it.
10462     *
10463     * @param translationY The vertical position of this view relative to its top position,
10464     * in pixels.
10465     *
10466     * @attr ref android.R.styleable#View_translationY
10467     */
10468    public void setTranslationY(float translationY) {
10469        ensureTransformationInfo();
10470        final TransformationInfo info = mTransformationInfo;
10471        if (info.mTranslationY != translationY) {
10472            invalidateViewProperty(true, false);
10473            info.mTranslationY = translationY;
10474            info.mMatrixDirty = true;
10475            invalidateViewProperty(false, true);
10476            if (mDisplayList != null) {
10477                mDisplayList.setTranslationY(translationY);
10478            }
10479            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10480                // View was rejected last time it was drawn by its parent; this may have changed
10481                invalidateParentIfNeeded();
10482            }
10483        }
10484    }
10485
10486    /**
10487     * Hit rectangle in parent's coordinates
10488     *
10489     * @param outRect The hit rectangle of the view.
10490     */
10491    public void getHitRect(Rect outRect) {
10492        updateMatrix();
10493        final TransformationInfo info = mTransformationInfo;
10494        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10495            outRect.set(mLeft, mTop, mRight, mBottom);
10496        } else {
10497            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10498            tmpRect.set(0, 0, getWidth(), getHeight());
10499            info.mMatrix.mapRect(tmpRect);
10500            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10501                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10502        }
10503    }
10504
10505    /**
10506     * Determines whether the given point, in local coordinates is inside the view.
10507     */
10508    /*package*/ final boolean pointInView(float localX, float localY) {
10509        return localX >= 0 && localX < (mRight - mLeft)
10510                && localY >= 0 && localY < (mBottom - mTop);
10511    }
10512
10513    /**
10514     * Utility method to determine whether the given point, in local coordinates,
10515     * is inside the view, where the area of the view is expanded by the slop factor.
10516     * This method is called while processing touch-move events to determine if the event
10517     * is still within the view.
10518     *
10519     * @hide
10520     */
10521    public boolean pointInView(float localX, float localY, float slop) {
10522        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10523                localY < ((mBottom - mTop) + slop);
10524    }
10525
10526    /**
10527     * When a view has focus and the user navigates away from it, the next view is searched for
10528     * starting from the rectangle filled in by this method.
10529     *
10530     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10531     * of the view.  However, if your view maintains some idea of internal selection,
10532     * such as a cursor, or a selected row or column, you should override this method and
10533     * fill in a more specific rectangle.
10534     *
10535     * @param r The rectangle to fill in, in this view's coordinates.
10536     */
10537    public void getFocusedRect(Rect r) {
10538        getDrawingRect(r);
10539    }
10540
10541    /**
10542     * If some part of this view is not clipped by any of its parents, then
10543     * return that area in r in global (root) coordinates. To convert r to local
10544     * coordinates (without taking possible View rotations into account), offset
10545     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10546     * If the view is completely clipped or translated out, return false.
10547     *
10548     * @param r If true is returned, r holds the global coordinates of the
10549     *        visible portion of this view.
10550     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10551     *        between this view and its root. globalOffet may be null.
10552     * @return true if r is non-empty (i.e. part of the view is visible at the
10553     *         root level.
10554     */
10555    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10556        int width = mRight - mLeft;
10557        int height = mBottom - mTop;
10558        if (width > 0 && height > 0) {
10559            r.set(0, 0, width, height);
10560            if (globalOffset != null) {
10561                globalOffset.set(-mScrollX, -mScrollY);
10562            }
10563            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10564        }
10565        return false;
10566    }
10567
10568    public final boolean getGlobalVisibleRect(Rect r) {
10569        return getGlobalVisibleRect(r, null);
10570    }
10571
10572    public final boolean getLocalVisibleRect(Rect r) {
10573        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10574        if (getGlobalVisibleRect(r, offset)) {
10575            r.offset(-offset.x, -offset.y); // make r local
10576            return true;
10577        }
10578        return false;
10579    }
10580
10581    /**
10582     * Offset this view's vertical location by the specified number of pixels.
10583     *
10584     * @param offset the number of pixels to offset the view by
10585     */
10586    public void offsetTopAndBottom(int offset) {
10587        if (offset != 0) {
10588            updateMatrix();
10589            final boolean matrixIsIdentity = mTransformationInfo == null
10590                    || mTransformationInfo.mMatrixIsIdentity;
10591            if (matrixIsIdentity) {
10592                if (mDisplayList != null) {
10593                    invalidateViewProperty(false, false);
10594                } else {
10595                    final ViewParent p = mParent;
10596                    if (p != null && mAttachInfo != null) {
10597                        final Rect r = mAttachInfo.mTmpInvalRect;
10598                        int minTop;
10599                        int maxBottom;
10600                        int yLoc;
10601                        if (offset < 0) {
10602                            minTop = mTop + offset;
10603                            maxBottom = mBottom;
10604                            yLoc = offset;
10605                        } else {
10606                            minTop = mTop;
10607                            maxBottom = mBottom + offset;
10608                            yLoc = 0;
10609                        }
10610                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10611                        p.invalidateChild(this, r);
10612                    }
10613                }
10614            } else {
10615                invalidateViewProperty(false, false);
10616            }
10617
10618            mTop += offset;
10619            mBottom += offset;
10620            if (mDisplayList != null) {
10621                mDisplayList.offsetTopAndBottom(offset);
10622                invalidateViewProperty(false, false);
10623            } else {
10624                if (!matrixIsIdentity) {
10625                    invalidateViewProperty(false, true);
10626                }
10627                invalidateParentIfNeeded();
10628            }
10629        }
10630    }
10631
10632    /**
10633     * Offset this view's horizontal location by the specified amount of pixels.
10634     *
10635     * @param offset the number of pixels to offset the view by
10636     */
10637    public void offsetLeftAndRight(int offset) {
10638        if (offset != 0) {
10639            updateMatrix();
10640            final boolean matrixIsIdentity = mTransformationInfo == null
10641                    || mTransformationInfo.mMatrixIsIdentity;
10642            if (matrixIsIdentity) {
10643                if (mDisplayList != null) {
10644                    invalidateViewProperty(false, false);
10645                } else {
10646                    final ViewParent p = mParent;
10647                    if (p != null && mAttachInfo != null) {
10648                        final Rect r = mAttachInfo.mTmpInvalRect;
10649                        int minLeft;
10650                        int maxRight;
10651                        if (offset < 0) {
10652                            minLeft = mLeft + offset;
10653                            maxRight = mRight;
10654                        } else {
10655                            minLeft = mLeft;
10656                            maxRight = mRight + offset;
10657                        }
10658                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10659                        p.invalidateChild(this, r);
10660                    }
10661                }
10662            } else {
10663                invalidateViewProperty(false, false);
10664            }
10665
10666            mLeft += offset;
10667            mRight += offset;
10668            if (mDisplayList != null) {
10669                mDisplayList.offsetLeftAndRight(offset);
10670                invalidateViewProperty(false, false);
10671            } else {
10672                if (!matrixIsIdentity) {
10673                    invalidateViewProperty(false, true);
10674                }
10675                invalidateParentIfNeeded();
10676            }
10677        }
10678    }
10679
10680    /**
10681     * Get the LayoutParams associated with this view. All views should have
10682     * layout parameters. These supply parameters to the <i>parent</i> of this
10683     * view specifying how it should be arranged. There are many subclasses of
10684     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10685     * of ViewGroup that are responsible for arranging their children.
10686     *
10687     * This method may return null if this View is not attached to a parent
10688     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10689     * was not invoked successfully. When a View is attached to a parent
10690     * ViewGroup, this method must not return null.
10691     *
10692     * @return The LayoutParams associated with this view, or null if no
10693     *         parameters have been set yet
10694     */
10695    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10696    public ViewGroup.LayoutParams getLayoutParams() {
10697        return mLayoutParams;
10698    }
10699
10700    /**
10701     * Set the layout parameters associated with this view. These supply
10702     * parameters to the <i>parent</i> of this view specifying how it should be
10703     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10704     * correspond to the different subclasses of ViewGroup that are responsible
10705     * for arranging their children.
10706     *
10707     * @param params The layout parameters for this view, cannot be null
10708     */
10709    public void setLayoutParams(ViewGroup.LayoutParams params) {
10710        if (params == null) {
10711            throw new NullPointerException("Layout parameters cannot be null");
10712        }
10713        mLayoutParams = params;
10714        resolveLayoutParams();
10715        if (mParent instanceof ViewGroup) {
10716            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10717        }
10718        requestLayout();
10719    }
10720
10721    /**
10722     * Resolve the layout parameters depending on the resolved layout direction
10723     *
10724     * @hide
10725     */
10726    public void resolveLayoutParams() {
10727        if (mLayoutParams != null) {
10728            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10729        }
10730    }
10731
10732    /**
10733     * Set the scrolled position of your view. This will cause a call to
10734     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10735     * invalidated.
10736     * @param x the x position to scroll to
10737     * @param y the y position to scroll to
10738     */
10739    public void scrollTo(int x, int y) {
10740        if (mScrollX != x || mScrollY != y) {
10741            int oldX = mScrollX;
10742            int oldY = mScrollY;
10743            mScrollX = x;
10744            mScrollY = y;
10745            invalidateParentCaches();
10746            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10747            if (!awakenScrollBars()) {
10748                postInvalidateOnAnimation();
10749            }
10750        }
10751    }
10752
10753    /**
10754     * Move the scrolled position of your view. This will cause a call to
10755     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10756     * invalidated.
10757     * @param x the amount of pixels to scroll by horizontally
10758     * @param y the amount of pixels to scroll by vertically
10759     */
10760    public void scrollBy(int x, int y) {
10761        scrollTo(mScrollX + x, mScrollY + y);
10762    }
10763
10764    /**
10765     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10766     * animation to fade the scrollbars out after a default delay. If a subclass
10767     * provides animated scrolling, the start delay should equal the duration
10768     * of the scrolling animation.</p>
10769     *
10770     * <p>The animation starts only if at least one of the scrollbars is
10771     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10772     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10773     * this method returns true, and false otherwise. If the animation is
10774     * started, this method calls {@link #invalidate()}; in that case the
10775     * caller should not call {@link #invalidate()}.</p>
10776     *
10777     * <p>This method should be invoked every time a subclass directly updates
10778     * the scroll parameters.</p>
10779     *
10780     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10781     * and {@link #scrollTo(int, int)}.</p>
10782     *
10783     * @return true if the animation is played, false otherwise
10784     *
10785     * @see #awakenScrollBars(int)
10786     * @see #scrollBy(int, int)
10787     * @see #scrollTo(int, int)
10788     * @see #isHorizontalScrollBarEnabled()
10789     * @see #isVerticalScrollBarEnabled()
10790     * @see #setHorizontalScrollBarEnabled(boolean)
10791     * @see #setVerticalScrollBarEnabled(boolean)
10792     */
10793    protected boolean awakenScrollBars() {
10794        return mScrollCache != null &&
10795                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10796    }
10797
10798    /**
10799     * Trigger the scrollbars to draw.
10800     * This method differs from awakenScrollBars() only in its default duration.
10801     * initialAwakenScrollBars() will show the scroll bars for longer than
10802     * usual to give the user more of a chance to notice them.
10803     *
10804     * @return true if the animation is played, false otherwise.
10805     */
10806    private boolean initialAwakenScrollBars() {
10807        return mScrollCache != null &&
10808                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10809    }
10810
10811    /**
10812     * <p>
10813     * Trigger the scrollbars to draw. When invoked this method starts an
10814     * animation to fade the scrollbars out after a fixed delay. If a subclass
10815     * provides animated scrolling, the start delay should equal the duration of
10816     * the scrolling animation.
10817     * </p>
10818     *
10819     * <p>
10820     * The animation starts only if at least one of the scrollbars is enabled,
10821     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10822     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10823     * this method returns true, and false otherwise. If the animation is
10824     * started, this method calls {@link #invalidate()}; in that case the caller
10825     * should not call {@link #invalidate()}.
10826     * </p>
10827     *
10828     * <p>
10829     * This method should be invoked everytime a subclass directly updates the
10830     * scroll parameters.
10831     * </p>
10832     *
10833     * @param startDelay the delay, in milliseconds, after which the animation
10834     *        should start; when the delay is 0, the animation starts
10835     *        immediately
10836     * @return true if the animation is played, false otherwise
10837     *
10838     * @see #scrollBy(int, int)
10839     * @see #scrollTo(int, int)
10840     * @see #isHorizontalScrollBarEnabled()
10841     * @see #isVerticalScrollBarEnabled()
10842     * @see #setHorizontalScrollBarEnabled(boolean)
10843     * @see #setVerticalScrollBarEnabled(boolean)
10844     */
10845    protected boolean awakenScrollBars(int startDelay) {
10846        return awakenScrollBars(startDelay, true);
10847    }
10848
10849    /**
10850     * <p>
10851     * Trigger the scrollbars to draw. When invoked this method starts an
10852     * animation to fade the scrollbars out after a fixed delay. If a subclass
10853     * provides animated scrolling, the start delay should equal the duration of
10854     * the scrolling animation.
10855     * </p>
10856     *
10857     * <p>
10858     * The animation starts only if at least one of the scrollbars is enabled,
10859     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10860     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10861     * this method returns true, and false otherwise. If the animation is
10862     * started, this method calls {@link #invalidate()} if the invalidate parameter
10863     * is set to true; in that case the caller
10864     * should not call {@link #invalidate()}.
10865     * </p>
10866     *
10867     * <p>
10868     * This method should be invoked everytime a subclass directly updates the
10869     * scroll parameters.
10870     * </p>
10871     *
10872     * @param startDelay the delay, in milliseconds, after which the animation
10873     *        should start; when the delay is 0, the animation starts
10874     *        immediately
10875     *
10876     * @param invalidate Wheter this method should call invalidate
10877     *
10878     * @return true if the animation is played, false otherwise
10879     *
10880     * @see #scrollBy(int, int)
10881     * @see #scrollTo(int, int)
10882     * @see #isHorizontalScrollBarEnabled()
10883     * @see #isVerticalScrollBarEnabled()
10884     * @see #setHorizontalScrollBarEnabled(boolean)
10885     * @see #setVerticalScrollBarEnabled(boolean)
10886     */
10887    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10888        final ScrollabilityCache scrollCache = mScrollCache;
10889
10890        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10891            return false;
10892        }
10893
10894        if (scrollCache.scrollBar == null) {
10895            scrollCache.scrollBar = new ScrollBarDrawable();
10896        }
10897
10898        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10899
10900            if (invalidate) {
10901                // Invalidate to show the scrollbars
10902                postInvalidateOnAnimation();
10903            }
10904
10905            if (scrollCache.state == ScrollabilityCache.OFF) {
10906                // FIXME: this is copied from WindowManagerService.
10907                // We should get this value from the system when it
10908                // is possible to do so.
10909                final int KEY_REPEAT_FIRST_DELAY = 750;
10910                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10911            }
10912
10913            // Tell mScrollCache when we should start fading. This may
10914            // extend the fade start time if one was already scheduled
10915            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10916            scrollCache.fadeStartTime = fadeStartTime;
10917            scrollCache.state = ScrollabilityCache.ON;
10918
10919            // Schedule our fader to run, unscheduling any old ones first
10920            if (mAttachInfo != null) {
10921                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10922                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10923            }
10924
10925            return true;
10926        }
10927
10928        return false;
10929    }
10930
10931    /**
10932     * Do not invalidate views which are not visible and which are not running an animation. They
10933     * will not get drawn and they should not set dirty flags as if they will be drawn
10934     */
10935    private boolean skipInvalidate() {
10936        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10937                (!(mParent instanceof ViewGroup) ||
10938                        !((ViewGroup) mParent).isViewTransitioning(this));
10939    }
10940    /**
10941     * Mark the area defined by dirty as needing to be drawn. If the view is
10942     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10943     * in the future. This must be called from a UI thread. To call from a non-UI
10944     * thread, call {@link #postInvalidate()}.
10945     *
10946     * WARNING: This method is destructive to dirty.
10947     * @param dirty the rectangle representing the bounds of the dirty region
10948     */
10949    public void invalidate(Rect dirty) {
10950        if (skipInvalidate()) {
10951            return;
10952        }
10953        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10954                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10955                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10956            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10957            mPrivateFlags |= PFLAG_INVALIDATED;
10958            mPrivateFlags |= PFLAG_DIRTY;
10959            final ViewParent p = mParent;
10960            final AttachInfo ai = mAttachInfo;
10961            if (p != null && ai != null) {
10962                final int scrollX = mScrollX;
10963                final int scrollY = mScrollY;
10964                final Rect r = ai.mTmpInvalRect;
10965                r.set(dirty.left - scrollX, dirty.top - scrollY,
10966                        dirty.right - scrollX, dirty.bottom - scrollY);
10967                mParent.invalidateChild(this, r);
10968            }
10969        }
10970    }
10971
10972    /**
10973     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10974     * The coordinates of the dirty rect are relative to the view.
10975     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10976     * will be called at some point in the future. This must be called from
10977     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10978     * @param l the left position of the dirty region
10979     * @param t the top position of the dirty region
10980     * @param r the right position of the dirty region
10981     * @param b the bottom position of the dirty region
10982     */
10983    public void invalidate(int l, int t, int r, int b) {
10984        if (skipInvalidate()) {
10985            return;
10986        }
10987        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10988                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10989                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10990            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10991            mPrivateFlags |= PFLAG_INVALIDATED;
10992            mPrivateFlags |= PFLAG_DIRTY;
10993            final ViewParent p = mParent;
10994            final AttachInfo ai = mAttachInfo;
10995            if (p != null && ai != null && l < r && t < b) {
10996                final int scrollX = mScrollX;
10997                final int scrollY = mScrollY;
10998                final Rect tmpr = ai.mTmpInvalRect;
10999                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
11000                p.invalidateChild(this, tmpr);
11001            }
11002        }
11003    }
11004
11005    /**
11006     * Invalidate the whole view. If the view is visible,
11007     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11008     * the future. This must be called from a UI thread. To call from a non-UI thread,
11009     * call {@link #postInvalidate()}.
11010     */
11011    public void invalidate() {
11012        invalidate(true);
11013    }
11014
11015    /**
11016     * This is where the invalidate() work actually happens. A full invalidate()
11017     * causes the drawing cache to be invalidated, but this function can be called with
11018     * invalidateCache set to false to skip that invalidation step for cases that do not
11019     * need it (for example, a component that remains at the same dimensions with the same
11020     * content).
11021     *
11022     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
11023     * well. This is usually true for a full invalidate, but may be set to false if the
11024     * View's contents or dimensions have not changed.
11025     */
11026    void invalidate(boolean invalidateCache) {
11027        if (skipInvalidate()) {
11028            return;
11029        }
11030        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
11031                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
11032                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
11033            mLastIsOpaque = isOpaque();
11034            mPrivateFlags &= ~PFLAG_DRAWN;
11035            mPrivateFlags |= PFLAG_DIRTY;
11036            if (invalidateCache) {
11037                mPrivateFlags |= PFLAG_INVALIDATED;
11038                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11039            }
11040            final AttachInfo ai = mAttachInfo;
11041            final ViewParent p = mParent;
11042
11043            if (p != null && ai != null) {
11044                final Rect r = ai.mTmpInvalRect;
11045                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11046                // Don't call invalidate -- we don't want to internally scroll
11047                // our own bounds
11048                p.invalidateChild(this, r);
11049            }
11050        }
11051    }
11052
11053    /**
11054     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11055     * set any flags or handle all of the cases handled by the default invalidation methods.
11056     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11057     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11058     * walk up the hierarchy, transforming the dirty rect as necessary.
11059     *
11060     * The method also handles normal invalidation logic if display list properties are not
11061     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11062     * backup approach, to handle these cases used in the various property-setting methods.
11063     *
11064     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11065     * are not being used in this view
11066     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11067     * list properties are not being used in this view
11068     */
11069    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11070        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
11071            if (invalidateParent) {
11072                invalidateParentCaches();
11073            }
11074            if (forceRedraw) {
11075                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11076            }
11077            invalidate(false);
11078        } else {
11079            final AttachInfo ai = mAttachInfo;
11080            final ViewParent p = mParent;
11081            if (p != null && ai != null) {
11082                final Rect r = ai.mTmpInvalRect;
11083                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11084                if (mParent instanceof ViewGroup) {
11085                    ((ViewGroup) mParent).invalidateChildFast(this, r);
11086                } else {
11087                    mParent.invalidateChild(this, r);
11088                }
11089            }
11090        }
11091    }
11092
11093    /**
11094     * Utility method to transform a given Rect by the current matrix of this view.
11095     */
11096    void transformRect(final Rect rect) {
11097        if (!getMatrix().isIdentity()) {
11098            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11099            boundingRect.set(rect);
11100            getMatrix().mapRect(boundingRect);
11101            rect.set((int) Math.floor(boundingRect.left),
11102                    (int) Math.floor(boundingRect.top),
11103                    (int) Math.ceil(boundingRect.right),
11104                    (int) Math.ceil(boundingRect.bottom));
11105        }
11106    }
11107
11108    /**
11109     * Used to indicate that the parent of this view should clear its caches. This functionality
11110     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11111     * which is necessary when various parent-managed properties of the view change, such as
11112     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11113     * clears the parent caches and does not causes an invalidate event.
11114     *
11115     * @hide
11116     */
11117    protected void invalidateParentCaches() {
11118        if (mParent instanceof View) {
11119            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11120        }
11121    }
11122
11123    /**
11124     * Used to indicate that the parent of this view should be invalidated. This functionality
11125     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11126     * which is necessary when various parent-managed properties of the view change, such as
11127     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11128     * an invalidation event to the parent.
11129     *
11130     * @hide
11131     */
11132    protected void invalidateParentIfNeeded() {
11133        if (isHardwareAccelerated() && mParent instanceof View) {
11134            ((View) mParent).invalidate(true);
11135        }
11136    }
11137
11138    /**
11139     * Indicates whether this View is opaque. An opaque View guarantees that it will
11140     * draw all the pixels overlapping its bounds using a fully opaque color.
11141     *
11142     * Subclasses of View should override this method whenever possible to indicate
11143     * whether an instance is opaque. Opaque Views are treated in a special way by
11144     * the View hierarchy, possibly allowing it to perform optimizations during
11145     * invalidate/draw passes.
11146     *
11147     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11148     */
11149    @ViewDebug.ExportedProperty(category = "drawing")
11150    public boolean isOpaque() {
11151        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11152                getFinalAlpha() >= 1.0f;
11153    }
11154
11155    /**
11156     * @hide
11157     */
11158    protected void computeOpaqueFlags() {
11159        // Opaque if:
11160        //   - Has a background
11161        //   - Background is opaque
11162        //   - Doesn't have scrollbars or scrollbars overlay
11163
11164        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11165            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11166        } else {
11167            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11168        }
11169
11170        final int flags = mViewFlags;
11171        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11172                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11173                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11174            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11175        } else {
11176            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11177        }
11178    }
11179
11180    /**
11181     * @hide
11182     */
11183    protected boolean hasOpaqueScrollbars() {
11184        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11185    }
11186
11187    /**
11188     * @return A handler associated with the thread running the View. This
11189     * handler can be used to pump events in the UI events queue.
11190     */
11191    public Handler getHandler() {
11192        final AttachInfo attachInfo = mAttachInfo;
11193        if (attachInfo != null) {
11194            return attachInfo.mHandler;
11195        }
11196        return null;
11197    }
11198
11199    /**
11200     * Gets the view root associated with the View.
11201     * @return The view root, or null if none.
11202     * @hide
11203     */
11204    public ViewRootImpl getViewRootImpl() {
11205        if (mAttachInfo != null) {
11206            return mAttachInfo.mViewRootImpl;
11207        }
11208        return null;
11209    }
11210
11211    /**
11212     * <p>Causes the Runnable to be added to the message queue.
11213     * The runnable will be run on the user interface thread.</p>
11214     *
11215     * @param action The Runnable that will be executed.
11216     *
11217     * @return Returns true if the Runnable was successfully placed in to the
11218     *         message queue.  Returns false on failure, usually because the
11219     *         looper processing the message queue is exiting.
11220     *
11221     * @see #postDelayed
11222     * @see #removeCallbacks
11223     */
11224    public boolean post(Runnable action) {
11225        final AttachInfo attachInfo = mAttachInfo;
11226        if (attachInfo != null) {
11227            return attachInfo.mHandler.post(action);
11228        }
11229        // Assume that post will succeed later
11230        ViewRootImpl.getRunQueue().post(action);
11231        return true;
11232    }
11233
11234    /**
11235     * <p>Causes the Runnable to be added to the message queue, to be run
11236     * after the specified amount of time elapses.
11237     * The runnable will be run on the user interface thread.</p>
11238     *
11239     * @param action The Runnable that will be executed.
11240     * @param delayMillis The delay (in milliseconds) until the Runnable
11241     *        will be executed.
11242     *
11243     * @return true if the Runnable was successfully placed in to the
11244     *         message queue.  Returns false on failure, usually because the
11245     *         looper processing the message queue is exiting.  Note that a
11246     *         result of true does not mean the Runnable will be processed --
11247     *         if the looper is quit before the delivery time of the message
11248     *         occurs then the message will be dropped.
11249     *
11250     * @see #post
11251     * @see #removeCallbacks
11252     */
11253    public boolean postDelayed(Runnable action, long delayMillis) {
11254        final AttachInfo attachInfo = mAttachInfo;
11255        if (attachInfo != null) {
11256            return attachInfo.mHandler.postDelayed(action, delayMillis);
11257        }
11258        // Assume that post will succeed later
11259        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11260        return true;
11261    }
11262
11263    /**
11264     * <p>Causes the Runnable to execute on the next animation time step.
11265     * The runnable will be run on the user interface thread.</p>
11266     *
11267     * @param action The Runnable that will be executed.
11268     *
11269     * @see #postOnAnimationDelayed
11270     * @see #removeCallbacks
11271     */
11272    public void postOnAnimation(Runnable action) {
11273        final AttachInfo attachInfo = mAttachInfo;
11274        if (attachInfo != null) {
11275            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11276                    Choreographer.CALLBACK_ANIMATION, action, null);
11277        } else {
11278            // Assume that post will succeed later
11279            ViewRootImpl.getRunQueue().post(action);
11280        }
11281    }
11282
11283    /**
11284     * <p>Causes the Runnable to execute on the next animation time step,
11285     * after the specified amount of time elapses.
11286     * The runnable will be run on the user interface thread.</p>
11287     *
11288     * @param action The Runnable that will be executed.
11289     * @param delayMillis The delay (in milliseconds) until the Runnable
11290     *        will be executed.
11291     *
11292     * @see #postOnAnimation
11293     * @see #removeCallbacks
11294     */
11295    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11296        final AttachInfo attachInfo = mAttachInfo;
11297        if (attachInfo != null) {
11298            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11299                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11300        } else {
11301            // Assume that post will succeed later
11302            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11303        }
11304    }
11305
11306    /**
11307     * <p>Removes the specified Runnable from the message queue.</p>
11308     *
11309     * @param action The Runnable to remove from the message handling queue
11310     *
11311     * @return true if this view could ask the Handler to remove the Runnable,
11312     *         false otherwise. When the returned value is true, the Runnable
11313     *         may or may not have been actually removed from the message queue
11314     *         (for instance, if the Runnable was not in the queue already.)
11315     *
11316     * @see #post
11317     * @see #postDelayed
11318     * @see #postOnAnimation
11319     * @see #postOnAnimationDelayed
11320     */
11321    public boolean removeCallbacks(Runnable action) {
11322        if (action != null) {
11323            final AttachInfo attachInfo = mAttachInfo;
11324            if (attachInfo != null) {
11325                attachInfo.mHandler.removeCallbacks(action);
11326                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11327                        Choreographer.CALLBACK_ANIMATION, action, null);
11328            }
11329            // Assume that post will succeed later
11330            ViewRootImpl.getRunQueue().removeCallbacks(action);
11331        }
11332        return true;
11333    }
11334
11335    /**
11336     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11337     * Use this to invalidate the View from a non-UI thread.</p>
11338     *
11339     * <p>This method can be invoked from outside of the UI thread
11340     * only when this View is attached to a window.</p>
11341     *
11342     * @see #invalidate()
11343     * @see #postInvalidateDelayed(long)
11344     */
11345    public void postInvalidate() {
11346        postInvalidateDelayed(0);
11347    }
11348
11349    /**
11350     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11351     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11352     *
11353     * <p>This method can be invoked from outside of the UI thread
11354     * only when this View is attached to a window.</p>
11355     *
11356     * @param left The left coordinate of the rectangle to invalidate.
11357     * @param top The top coordinate of the rectangle to invalidate.
11358     * @param right The right coordinate of the rectangle to invalidate.
11359     * @param bottom The bottom coordinate of the rectangle to invalidate.
11360     *
11361     * @see #invalidate(int, int, int, int)
11362     * @see #invalidate(Rect)
11363     * @see #postInvalidateDelayed(long, int, int, int, int)
11364     */
11365    public void postInvalidate(int left, int top, int right, int bottom) {
11366        postInvalidateDelayed(0, left, top, right, bottom);
11367    }
11368
11369    /**
11370     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11371     * loop. Waits for the specified amount of time.</p>
11372     *
11373     * <p>This method can be invoked from outside of the UI thread
11374     * only when this View is attached to a window.</p>
11375     *
11376     * @param delayMilliseconds the duration in milliseconds to delay the
11377     *         invalidation by
11378     *
11379     * @see #invalidate()
11380     * @see #postInvalidate()
11381     */
11382    public void postInvalidateDelayed(long delayMilliseconds) {
11383        // We try only with the AttachInfo because there's no point in invalidating
11384        // if we are not attached to our window
11385        final AttachInfo attachInfo = mAttachInfo;
11386        if (attachInfo != null) {
11387            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11388        }
11389    }
11390
11391    /**
11392     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11393     * through the event loop. Waits for the specified amount of time.</p>
11394     *
11395     * <p>This method can be invoked from outside of the UI thread
11396     * only when this View is attached to a window.</p>
11397     *
11398     * @param delayMilliseconds the duration in milliseconds to delay the
11399     *         invalidation by
11400     * @param left The left coordinate of the rectangle to invalidate.
11401     * @param top The top coordinate of the rectangle to invalidate.
11402     * @param right The right coordinate of the rectangle to invalidate.
11403     * @param bottom The bottom coordinate of the rectangle to invalidate.
11404     *
11405     * @see #invalidate(int, int, int, int)
11406     * @see #invalidate(Rect)
11407     * @see #postInvalidate(int, int, int, int)
11408     */
11409    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11410            int right, int bottom) {
11411
11412        // We try only with the AttachInfo because there's no point in invalidating
11413        // if we are not attached to our window
11414        final AttachInfo attachInfo = mAttachInfo;
11415        if (attachInfo != null) {
11416            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11417            info.target = this;
11418            info.left = left;
11419            info.top = top;
11420            info.right = right;
11421            info.bottom = bottom;
11422
11423            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11424        }
11425    }
11426
11427    /**
11428     * <p>Cause an invalidate to happen on the next animation time step, typically the
11429     * next display frame.</p>
11430     *
11431     * <p>This method can be invoked from outside of the UI thread
11432     * only when this View is attached to a window.</p>
11433     *
11434     * @see #invalidate()
11435     */
11436    public void postInvalidateOnAnimation() {
11437        // We try only with the AttachInfo because there's no point in invalidating
11438        // if we are not attached to our window
11439        final AttachInfo attachInfo = mAttachInfo;
11440        if (attachInfo != null) {
11441            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11442        }
11443    }
11444
11445    /**
11446     * <p>Cause an invalidate of the specified area to happen on the next animation
11447     * time step, typically the next display frame.</p>
11448     *
11449     * <p>This method can be invoked from outside of the UI thread
11450     * only when this View is attached to a window.</p>
11451     *
11452     * @param left The left coordinate of the rectangle to invalidate.
11453     * @param top The top coordinate of the rectangle to invalidate.
11454     * @param right The right coordinate of the rectangle to invalidate.
11455     * @param bottom The bottom coordinate of the rectangle to invalidate.
11456     *
11457     * @see #invalidate(int, int, int, int)
11458     * @see #invalidate(Rect)
11459     */
11460    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11461        // We try only with the AttachInfo because there's no point in invalidating
11462        // if we are not attached to our window
11463        final AttachInfo attachInfo = mAttachInfo;
11464        if (attachInfo != null) {
11465            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11466            info.target = this;
11467            info.left = left;
11468            info.top = top;
11469            info.right = right;
11470            info.bottom = bottom;
11471
11472            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11473        }
11474    }
11475
11476    /**
11477     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11478     * This event is sent at most once every
11479     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11480     */
11481    private void postSendViewScrolledAccessibilityEventCallback() {
11482        if (mSendViewScrolledAccessibilityEvent == null) {
11483            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11484        }
11485        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11486            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11487            postDelayed(mSendViewScrolledAccessibilityEvent,
11488                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11489        }
11490    }
11491
11492    /**
11493     * Called by a parent to request that a child update its values for mScrollX
11494     * and mScrollY if necessary. This will typically be done if the child is
11495     * animating a scroll using a {@link android.widget.Scroller Scroller}
11496     * object.
11497     */
11498    public void computeScroll() {
11499    }
11500
11501    /**
11502     * <p>Indicate whether the horizontal edges are faded when the view is
11503     * scrolled horizontally.</p>
11504     *
11505     * @return true if the horizontal edges should are faded on scroll, false
11506     *         otherwise
11507     *
11508     * @see #setHorizontalFadingEdgeEnabled(boolean)
11509     *
11510     * @attr ref android.R.styleable#View_requiresFadingEdge
11511     */
11512    public boolean isHorizontalFadingEdgeEnabled() {
11513        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11514    }
11515
11516    /**
11517     * <p>Define whether the horizontal edges should be faded when this view
11518     * is scrolled horizontally.</p>
11519     *
11520     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11521     *                                    be faded when the view is scrolled
11522     *                                    horizontally
11523     *
11524     * @see #isHorizontalFadingEdgeEnabled()
11525     *
11526     * @attr ref android.R.styleable#View_requiresFadingEdge
11527     */
11528    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11529        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11530            if (horizontalFadingEdgeEnabled) {
11531                initScrollCache();
11532            }
11533
11534            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11535        }
11536    }
11537
11538    /**
11539     * <p>Indicate whether the vertical edges are faded when the view is
11540     * scrolled horizontally.</p>
11541     *
11542     * @return true if the vertical edges should are faded on scroll, false
11543     *         otherwise
11544     *
11545     * @see #setVerticalFadingEdgeEnabled(boolean)
11546     *
11547     * @attr ref android.R.styleable#View_requiresFadingEdge
11548     */
11549    public boolean isVerticalFadingEdgeEnabled() {
11550        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11551    }
11552
11553    /**
11554     * <p>Define whether the vertical edges should be faded when this view
11555     * is scrolled vertically.</p>
11556     *
11557     * @param verticalFadingEdgeEnabled true if the vertical edges should
11558     *                                  be faded when the view is scrolled
11559     *                                  vertically
11560     *
11561     * @see #isVerticalFadingEdgeEnabled()
11562     *
11563     * @attr ref android.R.styleable#View_requiresFadingEdge
11564     */
11565    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11566        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11567            if (verticalFadingEdgeEnabled) {
11568                initScrollCache();
11569            }
11570
11571            mViewFlags ^= FADING_EDGE_VERTICAL;
11572        }
11573    }
11574
11575    /**
11576     * Returns the strength, or intensity, of the top faded edge. The strength is
11577     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11578     * returns 0.0 or 1.0 but no value in between.
11579     *
11580     * Subclasses should override this method to provide a smoother fade transition
11581     * when scrolling occurs.
11582     *
11583     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11584     */
11585    protected float getTopFadingEdgeStrength() {
11586        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11587    }
11588
11589    /**
11590     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11591     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11592     * returns 0.0 or 1.0 but no value in between.
11593     *
11594     * Subclasses should override this method to provide a smoother fade transition
11595     * when scrolling occurs.
11596     *
11597     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11598     */
11599    protected float getBottomFadingEdgeStrength() {
11600        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11601                computeVerticalScrollRange() ? 1.0f : 0.0f;
11602    }
11603
11604    /**
11605     * Returns the strength, or intensity, of the left faded edge. The strength is
11606     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11607     * returns 0.0 or 1.0 but no value in between.
11608     *
11609     * Subclasses should override this method to provide a smoother fade transition
11610     * when scrolling occurs.
11611     *
11612     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11613     */
11614    protected float getLeftFadingEdgeStrength() {
11615        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11616    }
11617
11618    /**
11619     * Returns the strength, or intensity, of the right faded edge. The strength is
11620     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11621     * returns 0.0 or 1.0 but no value in between.
11622     *
11623     * Subclasses should override this method to provide a smoother fade transition
11624     * when scrolling occurs.
11625     *
11626     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11627     */
11628    protected float getRightFadingEdgeStrength() {
11629        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11630                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11631    }
11632
11633    /**
11634     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11635     * scrollbar is not drawn by default.</p>
11636     *
11637     * @return true if the horizontal scrollbar should be painted, false
11638     *         otherwise
11639     *
11640     * @see #setHorizontalScrollBarEnabled(boolean)
11641     */
11642    public boolean isHorizontalScrollBarEnabled() {
11643        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11644    }
11645
11646    /**
11647     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11648     * scrollbar is not drawn by default.</p>
11649     *
11650     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11651     *                                   be painted
11652     *
11653     * @see #isHorizontalScrollBarEnabled()
11654     */
11655    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11656        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11657            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11658            computeOpaqueFlags();
11659            resolvePadding();
11660        }
11661    }
11662
11663    /**
11664     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11665     * scrollbar is not drawn by default.</p>
11666     *
11667     * @return true if the vertical scrollbar should be painted, false
11668     *         otherwise
11669     *
11670     * @see #setVerticalScrollBarEnabled(boolean)
11671     */
11672    public boolean isVerticalScrollBarEnabled() {
11673        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11674    }
11675
11676    /**
11677     * <p>Define whether the vertical scrollbar should be drawn or not. The
11678     * scrollbar is not drawn by default.</p>
11679     *
11680     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11681     *                                 be painted
11682     *
11683     * @see #isVerticalScrollBarEnabled()
11684     */
11685    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11686        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11687            mViewFlags ^= SCROLLBARS_VERTICAL;
11688            computeOpaqueFlags();
11689            resolvePadding();
11690        }
11691    }
11692
11693    /**
11694     * @hide
11695     */
11696    protected void recomputePadding() {
11697        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11698    }
11699
11700    /**
11701     * Define whether scrollbars will fade when the view is not scrolling.
11702     *
11703     * @param fadeScrollbars wheter to enable fading
11704     *
11705     * @attr ref android.R.styleable#View_fadeScrollbars
11706     */
11707    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11708        initScrollCache();
11709        final ScrollabilityCache scrollabilityCache = mScrollCache;
11710        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11711        if (fadeScrollbars) {
11712            scrollabilityCache.state = ScrollabilityCache.OFF;
11713        } else {
11714            scrollabilityCache.state = ScrollabilityCache.ON;
11715        }
11716    }
11717
11718    /**
11719     *
11720     * Returns true if scrollbars will fade when this view is not scrolling
11721     *
11722     * @return true if scrollbar fading is enabled
11723     *
11724     * @attr ref android.R.styleable#View_fadeScrollbars
11725     */
11726    public boolean isScrollbarFadingEnabled() {
11727        return mScrollCache != null && mScrollCache.fadeScrollBars;
11728    }
11729
11730    /**
11731     *
11732     * Returns the delay before scrollbars fade.
11733     *
11734     * @return the delay before scrollbars fade
11735     *
11736     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11737     */
11738    public int getScrollBarDefaultDelayBeforeFade() {
11739        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11740                mScrollCache.scrollBarDefaultDelayBeforeFade;
11741    }
11742
11743    /**
11744     * Define the delay before scrollbars fade.
11745     *
11746     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11747     *
11748     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11749     */
11750    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11751        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11752    }
11753
11754    /**
11755     *
11756     * Returns the scrollbar fade duration.
11757     *
11758     * @return the scrollbar fade duration
11759     *
11760     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11761     */
11762    public int getScrollBarFadeDuration() {
11763        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11764                mScrollCache.scrollBarFadeDuration;
11765    }
11766
11767    /**
11768     * Define the scrollbar fade duration.
11769     *
11770     * @param scrollBarFadeDuration - the scrollbar fade duration
11771     *
11772     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11773     */
11774    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11775        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11776    }
11777
11778    /**
11779     *
11780     * Returns the scrollbar size.
11781     *
11782     * @return the scrollbar size
11783     *
11784     * @attr ref android.R.styleable#View_scrollbarSize
11785     */
11786    public int getScrollBarSize() {
11787        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11788                mScrollCache.scrollBarSize;
11789    }
11790
11791    /**
11792     * Define the scrollbar size.
11793     *
11794     * @param scrollBarSize - the scrollbar size
11795     *
11796     * @attr ref android.R.styleable#View_scrollbarSize
11797     */
11798    public void setScrollBarSize(int scrollBarSize) {
11799        getScrollCache().scrollBarSize = scrollBarSize;
11800    }
11801
11802    /**
11803     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11804     * inset. When inset, they add to the padding of the view. And the scrollbars
11805     * can be drawn inside the padding area or on the edge of the view. For example,
11806     * if a view has a background drawable and you want to draw the scrollbars
11807     * inside the padding specified by the drawable, you can use
11808     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11809     * appear at the edge of the view, ignoring the padding, then you can use
11810     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11811     * @param style the style of the scrollbars. Should be one of
11812     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11813     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11814     * @see #SCROLLBARS_INSIDE_OVERLAY
11815     * @see #SCROLLBARS_INSIDE_INSET
11816     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11817     * @see #SCROLLBARS_OUTSIDE_INSET
11818     *
11819     * @attr ref android.R.styleable#View_scrollbarStyle
11820     */
11821    public void setScrollBarStyle(@ScrollBarStyle int style) {
11822        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11823            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11824            computeOpaqueFlags();
11825            resolvePadding();
11826        }
11827    }
11828
11829    /**
11830     * <p>Returns the current scrollbar style.</p>
11831     * @return the current scrollbar style
11832     * @see #SCROLLBARS_INSIDE_OVERLAY
11833     * @see #SCROLLBARS_INSIDE_INSET
11834     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11835     * @see #SCROLLBARS_OUTSIDE_INSET
11836     *
11837     * @attr ref android.R.styleable#View_scrollbarStyle
11838     */
11839    @ViewDebug.ExportedProperty(mapping = {
11840            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11841            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11842            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11843            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11844    })
11845    @ScrollBarStyle
11846    public int getScrollBarStyle() {
11847        return mViewFlags & SCROLLBARS_STYLE_MASK;
11848    }
11849
11850    /**
11851     * <p>Compute the horizontal range that the horizontal scrollbar
11852     * represents.</p>
11853     *
11854     * <p>The range is expressed in arbitrary units that must be the same as the
11855     * units used by {@link #computeHorizontalScrollExtent()} and
11856     * {@link #computeHorizontalScrollOffset()}.</p>
11857     *
11858     * <p>The default range is the drawing width of this view.</p>
11859     *
11860     * @return the total horizontal range represented by the horizontal
11861     *         scrollbar
11862     *
11863     * @see #computeHorizontalScrollExtent()
11864     * @see #computeHorizontalScrollOffset()
11865     * @see android.widget.ScrollBarDrawable
11866     */
11867    protected int computeHorizontalScrollRange() {
11868        return getWidth();
11869    }
11870
11871    /**
11872     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11873     * within the horizontal range. This value is used to compute the position
11874     * of the thumb within the scrollbar's track.</p>
11875     *
11876     * <p>The range is expressed in arbitrary units that must be the same as the
11877     * units used by {@link #computeHorizontalScrollRange()} and
11878     * {@link #computeHorizontalScrollExtent()}.</p>
11879     *
11880     * <p>The default offset is the scroll offset of this view.</p>
11881     *
11882     * @return the horizontal offset of the scrollbar's thumb
11883     *
11884     * @see #computeHorizontalScrollRange()
11885     * @see #computeHorizontalScrollExtent()
11886     * @see android.widget.ScrollBarDrawable
11887     */
11888    protected int computeHorizontalScrollOffset() {
11889        return mScrollX;
11890    }
11891
11892    /**
11893     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11894     * within the horizontal range. This value is used to compute the length
11895     * of the thumb within the scrollbar's track.</p>
11896     *
11897     * <p>The range is expressed in arbitrary units that must be the same as the
11898     * units used by {@link #computeHorizontalScrollRange()} and
11899     * {@link #computeHorizontalScrollOffset()}.</p>
11900     *
11901     * <p>The default extent is the drawing width of this view.</p>
11902     *
11903     * @return the horizontal extent of the scrollbar's thumb
11904     *
11905     * @see #computeHorizontalScrollRange()
11906     * @see #computeHorizontalScrollOffset()
11907     * @see android.widget.ScrollBarDrawable
11908     */
11909    protected int computeHorizontalScrollExtent() {
11910        return getWidth();
11911    }
11912
11913    /**
11914     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11915     *
11916     * <p>The range is expressed in arbitrary units that must be the same as the
11917     * units used by {@link #computeVerticalScrollExtent()} and
11918     * {@link #computeVerticalScrollOffset()}.</p>
11919     *
11920     * @return the total vertical range represented by the vertical scrollbar
11921     *
11922     * <p>The default range is the drawing height of this view.</p>
11923     *
11924     * @see #computeVerticalScrollExtent()
11925     * @see #computeVerticalScrollOffset()
11926     * @see android.widget.ScrollBarDrawable
11927     */
11928    protected int computeVerticalScrollRange() {
11929        return getHeight();
11930    }
11931
11932    /**
11933     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11934     * within the horizontal range. This value is used to compute the position
11935     * of the thumb within the scrollbar's track.</p>
11936     *
11937     * <p>The range is expressed in arbitrary units that must be the same as the
11938     * units used by {@link #computeVerticalScrollRange()} and
11939     * {@link #computeVerticalScrollExtent()}.</p>
11940     *
11941     * <p>The default offset is the scroll offset of this view.</p>
11942     *
11943     * @return the vertical offset of the scrollbar's thumb
11944     *
11945     * @see #computeVerticalScrollRange()
11946     * @see #computeVerticalScrollExtent()
11947     * @see android.widget.ScrollBarDrawable
11948     */
11949    protected int computeVerticalScrollOffset() {
11950        return mScrollY;
11951    }
11952
11953    /**
11954     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11955     * within the vertical range. This value is used to compute the length
11956     * of the thumb within the scrollbar's track.</p>
11957     *
11958     * <p>The range is expressed in arbitrary units that must be the same as the
11959     * units used by {@link #computeVerticalScrollRange()} and
11960     * {@link #computeVerticalScrollOffset()}.</p>
11961     *
11962     * <p>The default extent is the drawing height of this view.</p>
11963     *
11964     * @return the vertical extent of the scrollbar's thumb
11965     *
11966     * @see #computeVerticalScrollRange()
11967     * @see #computeVerticalScrollOffset()
11968     * @see android.widget.ScrollBarDrawable
11969     */
11970    protected int computeVerticalScrollExtent() {
11971        return getHeight();
11972    }
11973
11974    /**
11975     * Check if this view can be scrolled horizontally in a certain direction.
11976     *
11977     * @param direction Negative to check scrolling left, positive to check scrolling right.
11978     * @return true if this view can be scrolled in the specified direction, false otherwise.
11979     */
11980    public boolean canScrollHorizontally(int direction) {
11981        final int offset = computeHorizontalScrollOffset();
11982        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11983        if (range == 0) return false;
11984        if (direction < 0) {
11985            return offset > 0;
11986        } else {
11987            return offset < range - 1;
11988        }
11989    }
11990
11991    /**
11992     * Check if this view can be scrolled vertically in a certain direction.
11993     *
11994     * @param direction Negative to check scrolling up, positive to check scrolling down.
11995     * @return true if this view can be scrolled in the specified direction, false otherwise.
11996     */
11997    public boolean canScrollVertically(int direction) {
11998        final int offset = computeVerticalScrollOffset();
11999        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12000        if (range == 0) return false;
12001        if (direction < 0) {
12002            return offset > 0;
12003        } else {
12004            return offset < range - 1;
12005        }
12006    }
12007
12008    /**
12009     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12010     * scrollbars are painted only if they have been awakened first.</p>
12011     *
12012     * @param canvas the canvas on which to draw the scrollbars
12013     *
12014     * @see #awakenScrollBars(int)
12015     */
12016    protected final void onDrawScrollBars(Canvas canvas) {
12017        // scrollbars are drawn only when the animation is running
12018        final ScrollabilityCache cache = mScrollCache;
12019        if (cache != null) {
12020
12021            int state = cache.state;
12022
12023            if (state == ScrollabilityCache.OFF) {
12024                return;
12025            }
12026
12027            boolean invalidate = false;
12028
12029            if (state == ScrollabilityCache.FADING) {
12030                // We're fading -- get our fade interpolation
12031                if (cache.interpolatorValues == null) {
12032                    cache.interpolatorValues = new float[1];
12033                }
12034
12035                float[] values = cache.interpolatorValues;
12036
12037                // Stops the animation if we're done
12038                if (cache.scrollBarInterpolator.timeToValues(values) ==
12039                        Interpolator.Result.FREEZE_END) {
12040                    cache.state = ScrollabilityCache.OFF;
12041                } else {
12042                    cache.scrollBar.setAlpha(Math.round(values[0]));
12043                }
12044
12045                // This will make the scroll bars inval themselves after
12046                // drawing. We only want this when we're fading so that
12047                // we prevent excessive redraws
12048                invalidate = true;
12049            } else {
12050                // We're just on -- but we may have been fading before so
12051                // reset alpha
12052                cache.scrollBar.setAlpha(255);
12053            }
12054
12055
12056            final int viewFlags = mViewFlags;
12057
12058            final boolean drawHorizontalScrollBar =
12059                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12060            final boolean drawVerticalScrollBar =
12061                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12062                && !isVerticalScrollBarHidden();
12063
12064            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12065                final int width = mRight - mLeft;
12066                final int height = mBottom - mTop;
12067
12068                final ScrollBarDrawable scrollBar = cache.scrollBar;
12069
12070                final int scrollX = mScrollX;
12071                final int scrollY = mScrollY;
12072                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12073
12074                int left;
12075                int top;
12076                int right;
12077                int bottom;
12078
12079                if (drawHorizontalScrollBar) {
12080                    int size = scrollBar.getSize(false);
12081                    if (size <= 0) {
12082                        size = cache.scrollBarSize;
12083                    }
12084
12085                    scrollBar.setParameters(computeHorizontalScrollRange(),
12086                                            computeHorizontalScrollOffset(),
12087                                            computeHorizontalScrollExtent(), false);
12088                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12089                            getVerticalScrollbarWidth() : 0;
12090                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12091                    left = scrollX + (mPaddingLeft & inside);
12092                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12093                    bottom = top + size;
12094                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12095                    if (invalidate) {
12096                        invalidate(left, top, right, bottom);
12097                    }
12098                }
12099
12100                if (drawVerticalScrollBar) {
12101                    int size = scrollBar.getSize(true);
12102                    if (size <= 0) {
12103                        size = cache.scrollBarSize;
12104                    }
12105
12106                    scrollBar.setParameters(computeVerticalScrollRange(),
12107                                            computeVerticalScrollOffset(),
12108                                            computeVerticalScrollExtent(), true);
12109                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12110                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12111                        verticalScrollbarPosition = isLayoutRtl() ?
12112                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12113                    }
12114                    switch (verticalScrollbarPosition) {
12115                        default:
12116                        case SCROLLBAR_POSITION_RIGHT:
12117                            left = scrollX + width - size - (mUserPaddingRight & inside);
12118                            break;
12119                        case SCROLLBAR_POSITION_LEFT:
12120                            left = scrollX + (mUserPaddingLeft & inside);
12121                            break;
12122                    }
12123                    top = scrollY + (mPaddingTop & inside);
12124                    right = left + size;
12125                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12126                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12127                    if (invalidate) {
12128                        invalidate(left, top, right, bottom);
12129                    }
12130                }
12131            }
12132        }
12133    }
12134
12135    /**
12136     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12137     * FastScroller is visible.
12138     * @return whether to temporarily hide the vertical scrollbar
12139     * @hide
12140     */
12141    protected boolean isVerticalScrollBarHidden() {
12142        return false;
12143    }
12144
12145    /**
12146     * <p>Draw the horizontal scrollbar if
12147     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12148     *
12149     * @param canvas the canvas on which to draw the scrollbar
12150     * @param scrollBar the scrollbar's drawable
12151     *
12152     * @see #isHorizontalScrollBarEnabled()
12153     * @see #computeHorizontalScrollRange()
12154     * @see #computeHorizontalScrollExtent()
12155     * @see #computeHorizontalScrollOffset()
12156     * @see android.widget.ScrollBarDrawable
12157     * @hide
12158     */
12159    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12160            int l, int t, int r, int b) {
12161        scrollBar.setBounds(l, t, r, b);
12162        scrollBar.draw(canvas);
12163    }
12164
12165    /**
12166     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12167     * returns true.</p>
12168     *
12169     * @param canvas the canvas on which to draw the scrollbar
12170     * @param scrollBar the scrollbar's drawable
12171     *
12172     * @see #isVerticalScrollBarEnabled()
12173     * @see #computeVerticalScrollRange()
12174     * @see #computeVerticalScrollExtent()
12175     * @see #computeVerticalScrollOffset()
12176     * @see android.widget.ScrollBarDrawable
12177     * @hide
12178     */
12179    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12180            int l, int t, int r, int b) {
12181        scrollBar.setBounds(l, t, r, b);
12182        scrollBar.draw(canvas);
12183    }
12184
12185    /**
12186     * Implement this to do your drawing.
12187     *
12188     * @param canvas the canvas on which the background will be drawn
12189     */
12190    protected void onDraw(Canvas canvas) {
12191    }
12192
12193    /*
12194     * Caller is responsible for calling requestLayout if necessary.
12195     * (This allows addViewInLayout to not request a new layout.)
12196     */
12197    void assignParent(ViewParent parent) {
12198        if (mParent == null) {
12199            mParent = parent;
12200        } else if (parent == null) {
12201            mParent = null;
12202        } else {
12203            throw new RuntimeException("view " + this + " being added, but"
12204                    + " it already has a parent");
12205        }
12206    }
12207
12208    /**
12209     * This is called when the view is attached to a window.  At this point it
12210     * has a Surface and will start drawing.  Note that this function is
12211     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12212     * however it may be called any time before the first onDraw -- including
12213     * before or after {@link #onMeasure(int, int)}.
12214     *
12215     * @see #onDetachedFromWindow()
12216     */
12217    protected void onAttachedToWindow() {
12218        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12219            mParent.requestTransparentRegion(this);
12220        }
12221
12222        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12223            initialAwakenScrollBars();
12224            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12225        }
12226
12227        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12228
12229        jumpDrawablesToCurrentState();
12230
12231        resetSubtreeAccessibilityStateChanged();
12232
12233        if (isFocused()) {
12234            InputMethodManager imm = InputMethodManager.peekInstance();
12235            imm.focusIn(this);
12236        }
12237
12238        if (mDisplayList != null) {
12239            mDisplayList.clearDirty();
12240        }
12241    }
12242
12243    /**
12244     * Resolve all RTL related properties.
12245     *
12246     * @return true if resolution of RTL properties has been done
12247     *
12248     * @hide
12249     */
12250    public boolean resolveRtlPropertiesIfNeeded() {
12251        if (!needRtlPropertiesResolution()) return false;
12252
12253        // Order is important here: LayoutDirection MUST be resolved first
12254        if (!isLayoutDirectionResolved()) {
12255            resolveLayoutDirection();
12256            resolveLayoutParams();
12257        }
12258        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12259        if (!isTextDirectionResolved()) {
12260            resolveTextDirection();
12261        }
12262        if (!isTextAlignmentResolved()) {
12263            resolveTextAlignment();
12264        }
12265        // Should resolve Drawables before Padding because we need the layout direction of the
12266        // Drawable to correctly resolve Padding.
12267        if (!isDrawablesResolved()) {
12268            resolveDrawables();
12269        }
12270        if (!isPaddingResolved()) {
12271            resolvePadding();
12272        }
12273        onRtlPropertiesChanged(getLayoutDirection());
12274        return true;
12275    }
12276
12277    /**
12278     * Reset resolution of all RTL related properties.
12279     *
12280     * @hide
12281     */
12282    public void resetRtlProperties() {
12283        resetResolvedLayoutDirection();
12284        resetResolvedTextDirection();
12285        resetResolvedTextAlignment();
12286        resetResolvedPadding();
12287        resetResolvedDrawables();
12288    }
12289
12290    /**
12291     * @see #onScreenStateChanged(int)
12292     */
12293    void dispatchScreenStateChanged(int screenState) {
12294        onScreenStateChanged(screenState);
12295    }
12296
12297    /**
12298     * This method is called whenever the state of the screen this view is
12299     * attached to changes. A state change will usually occurs when the screen
12300     * turns on or off (whether it happens automatically or the user does it
12301     * manually.)
12302     *
12303     * @param screenState The new state of the screen. Can be either
12304     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12305     */
12306    public void onScreenStateChanged(int screenState) {
12307    }
12308
12309    /**
12310     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12311     */
12312    private boolean hasRtlSupport() {
12313        return mContext.getApplicationInfo().hasRtlSupport();
12314    }
12315
12316    /**
12317     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12318     * RTL not supported)
12319     */
12320    private boolean isRtlCompatibilityMode() {
12321        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12322        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12323    }
12324
12325    /**
12326     * @return true if RTL properties need resolution.
12327     *
12328     */
12329    private boolean needRtlPropertiesResolution() {
12330        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12331    }
12332
12333    /**
12334     * Called when any RTL property (layout direction or text direction or text alignment) has
12335     * been changed.
12336     *
12337     * Subclasses need to override this method to take care of cached information that depends on the
12338     * resolved layout direction, or to inform child views that inherit their layout direction.
12339     *
12340     * The default implementation does nothing.
12341     *
12342     * @param layoutDirection the direction of the layout
12343     *
12344     * @see #LAYOUT_DIRECTION_LTR
12345     * @see #LAYOUT_DIRECTION_RTL
12346     */
12347    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12348    }
12349
12350    /**
12351     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12352     * that the parent directionality can and will be resolved before its children.
12353     *
12354     * @return true if resolution has been done, false otherwise.
12355     *
12356     * @hide
12357     */
12358    public boolean resolveLayoutDirection() {
12359        // Clear any previous layout direction resolution
12360        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12361
12362        if (hasRtlSupport()) {
12363            // Set resolved depending on layout direction
12364            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12365                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12366                case LAYOUT_DIRECTION_INHERIT:
12367                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12368                    // later to get the correct resolved value
12369                    if (!canResolveLayoutDirection()) return false;
12370
12371                    // Parent has not yet resolved, LTR is still the default
12372                    try {
12373                        if (!mParent.isLayoutDirectionResolved()) return false;
12374
12375                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12376                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12377                        }
12378                    } catch (AbstractMethodError e) {
12379                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12380                                " does not fully implement ViewParent", e);
12381                    }
12382                    break;
12383                case LAYOUT_DIRECTION_RTL:
12384                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12385                    break;
12386                case LAYOUT_DIRECTION_LOCALE:
12387                    if((LAYOUT_DIRECTION_RTL ==
12388                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12389                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12390                    }
12391                    break;
12392                default:
12393                    // Nothing to do, LTR by default
12394            }
12395        }
12396
12397        // Set to resolved
12398        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12399        return true;
12400    }
12401
12402    /**
12403     * Check if layout direction resolution can be done.
12404     *
12405     * @return true if layout direction resolution can be done otherwise return false.
12406     */
12407    public boolean canResolveLayoutDirection() {
12408        switch (getRawLayoutDirection()) {
12409            case LAYOUT_DIRECTION_INHERIT:
12410                if (mParent != null) {
12411                    try {
12412                        return mParent.canResolveLayoutDirection();
12413                    } catch (AbstractMethodError e) {
12414                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12415                                " does not fully implement ViewParent", e);
12416                    }
12417                }
12418                return false;
12419
12420            default:
12421                return true;
12422        }
12423    }
12424
12425    /**
12426     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12427     * {@link #onMeasure(int, int)}.
12428     *
12429     * @hide
12430     */
12431    public void resetResolvedLayoutDirection() {
12432        // Reset the current resolved bits
12433        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12434    }
12435
12436    /**
12437     * @return true if the layout direction is inherited.
12438     *
12439     * @hide
12440     */
12441    public boolean isLayoutDirectionInherited() {
12442        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12443    }
12444
12445    /**
12446     * @return true if layout direction has been resolved.
12447     */
12448    public boolean isLayoutDirectionResolved() {
12449        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12450    }
12451
12452    /**
12453     * Return if padding has been resolved
12454     *
12455     * @hide
12456     */
12457    boolean isPaddingResolved() {
12458        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12459    }
12460
12461    /**
12462     * Resolves padding depending on layout direction, if applicable, and
12463     * recomputes internal padding values to adjust for scroll bars.
12464     *
12465     * @hide
12466     */
12467    public void resolvePadding() {
12468        final int resolvedLayoutDirection = getLayoutDirection();
12469
12470        if (!isRtlCompatibilityMode()) {
12471            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12472            // If start / end padding are defined, they will be resolved (hence overriding) to
12473            // left / right or right / left depending on the resolved layout direction.
12474            // If start / end padding are not defined, use the left / right ones.
12475            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12476                Rect padding = sThreadLocal.get();
12477                if (padding == null) {
12478                    padding = new Rect();
12479                    sThreadLocal.set(padding);
12480                }
12481                mBackground.getPadding(padding);
12482                if (!mLeftPaddingDefined) {
12483                    mUserPaddingLeftInitial = padding.left;
12484                }
12485                if (!mRightPaddingDefined) {
12486                    mUserPaddingRightInitial = padding.right;
12487                }
12488            }
12489            switch (resolvedLayoutDirection) {
12490                case LAYOUT_DIRECTION_RTL:
12491                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12492                        mUserPaddingRight = mUserPaddingStart;
12493                    } else {
12494                        mUserPaddingRight = mUserPaddingRightInitial;
12495                    }
12496                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12497                        mUserPaddingLeft = mUserPaddingEnd;
12498                    } else {
12499                        mUserPaddingLeft = mUserPaddingLeftInitial;
12500                    }
12501                    break;
12502                case LAYOUT_DIRECTION_LTR:
12503                default:
12504                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12505                        mUserPaddingLeft = mUserPaddingStart;
12506                    } else {
12507                        mUserPaddingLeft = mUserPaddingLeftInitial;
12508                    }
12509                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12510                        mUserPaddingRight = mUserPaddingEnd;
12511                    } else {
12512                        mUserPaddingRight = mUserPaddingRightInitial;
12513                    }
12514            }
12515
12516            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12517        }
12518
12519        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12520        onRtlPropertiesChanged(resolvedLayoutDirection);
12521
12522        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12523    }
12524
12525    /**
12526     * Reset the resolved layout direction.
12527     *
12528     * @hide
12529     */
12530    public void resetResolvedPadding() {
12531        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12532    }
12533
12534    /**
12535     * This is called when the view is detached from a window.  At this point it
12536     * no longer has a surface for drawing.
12537     *
12538     * @see #onAttachedToWindow()
12539     */
12540    protected void onDetachedFromWindow() {
12541        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12542        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12543
12544        removeUnsetPressCallback();
12545        removeLongPressCallback();
12546        removePerformClickCallback();
12547        removeSendViewScrolledAccessibilityEventCallback();
12548
12549        destroyDrawingCache();
12550        destroyLayer(false);
12551
12552        cleanupDraw();
12553
12554        mCurrentAnimation = null;
12555    }
12556
12557    private void cleanupDraw() {
12558        if (mAttachInfo != null) {
12559            if (mDisplayList != null) {
12560                mDisplayList.markDirty();
12561                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12562            }
12563            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12564        } else {
12565            // Should never happen
12566            resetDisplayList();
12567        }
12568    }
12569
12570    /**
12571     * This method ensures the hardware renderer is in a valid state
12572     * before executing the specified action.
12573     *
12574     * This method will attempt to set a valid state even if the window
12575     * the renderer is attached to was destroyed.
12576     *
12577     * This method is not guaranteed to work. If the hardware renderer
12578     * does not exist or cannot be put in a valid state, this method
12579     * will not executed the specified action.
12580     *
12581     * The specified action is executed synchronously.
12582     *
12583     * @param action The action to execute after the renderer is in a valid state
12584     *
12585     * @return True if the specified Runnable was executed, false otherwise
12586     *
12587     * @hide
12588     */
12589    public boolean executeHardwareAction(Runnable action) {
12590        //noinspection SimplifiableIfStatement
12591        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12592            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12593        }
12594        return false;
12595    }
12596
12597    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12598    }
12599
12600    /**
12601     * @return The number of times this view has been attached to a window
12602     */
12603    protected int getWindowAttachCount() {
12604        return mWindowAttachCount;
12605    }
12606
12607    /**
12608     * Retrieve a unique token identifying the window this view is attached to.
12609     * @return Return the window's token for use in
12610     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12611     */
12612    public IBinder getWindowToken() {
12613        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12614    }
12615
12616    /**
12617     * Retrieve the {@link WindowId} for the window this view is
12618     * currently attached to.
12619     */
12620    public WindowId getWindowId() {
12621        if (mAttachInfo == null) {
12622            return null;
12623        }
12624        if (mAttachInfo.mWindowId == null) {
12625            try {
12626                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12627                        mAttachInfo.mWindowToken);
12628                mAttachInfo.mWindowId = new WindowId(
12629                        mAttachInfo.mIWindowId);
12630            } catch (RemoteException e) {
12631            }
12632        }
12633        return mAttachInfo.mWindowId;
12634    }
12635
12636    /**
12637     * Retrieve a unique token identifying the top-level "real" window of
12638     * the window that this view is attached to.  That is, this is like
12639     * {@link #getWindowToken}, except if the window this view in is a panel
12640     * window (attached to another containing window), then the token of
12641     * the containing window is returned instead.
12642     *
12643     * @return Returns the associated window token, either
12644     * {@link #getWindowToken()} or the containing window's token.
12645     */
12646    public IBinder getApplicationWindowToken() {
12647        AttachInfo ai = mAttachInfo;
12648        if (ai != null) {
12649            IBinder appWindowToken = ai.mPanelParentWindowToken;
12650            if (appWindowToken == null) {
12651                appWindowToken = ai.mWindowToken;
12652            }
12653            return appWindowToken;
12654        }
12655        return null;
12656    }
12657
12658    /**
12659     * Gets the logical display to which the view's window has been attached.
12660     *
12661     * @return The logical display, or null if the view is not currently attached to a window.
12662     */
12663    public Display getDisplay() {
12664        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12665    }
12666
12667    /**
12668     * Retrieve private session object this view hierarchy is using to
12669     * communicate with the window manager.
12670     * @return the session object to communicate with the window manager
12671     */
12672    /*package*/ IWindowSession getWindowSession() {
12673        return mAttachInfo != null ? mAttachInfo.mSession : null;
12674    }
12675
12676    /**
12677     * @param info the {@link android.view.View.AttachInfo} to associated with
12678     *        this view
12679     */
12680    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12681        //System.out.println("Attached! " + this);
12682        mAttachInfo = info;
12683        if (mOverlay != null) {
12684            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12685        }
12686        mWindowAttachCount++;
12687        // We will need to evaluate the drawable state at least once.
12688        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12689        if (mFloatingTreeObserver != null) {
12690            info.mTreeObserver.merge(mFloatingTreeObserver);
12691            mFloatingTreeObserver = null;
12692        }
12693        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12694            mAttachInfo.mScrollContainers.add(this);
12695            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12696        }
12697        performCollectViewAttributes(mAttachInfo, visibility);
12698        onAttachedToWindow();
12699
12700        ListenerInfo li = mListenerInfo;
12701        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12702                li != null ? li.mOnAttachStateChangeListeners : null;
12703        if (listeners != null && listeners.size() > 0) {
12704            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12705            // perform the dispatching. The iterator is a safe guard against listeners that
12706            // could mutate the list by calling the various add/remove methods. This prevents
12707            // the array from being modified while we iterate it.
12708            for (OnAttachStateChangeListener listener : listeners) {
12709                listener.onViewAttachedToWindow(this);
12710            }
12711        }
12712
12713        int vis = info.mWindowVisibility;
12714        if (vis != GONE) {
12715            onWindowVisibilityChanged(vis);
12716        }
12717        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12718            // If nobody has evaluated the drawable state yet, then do it now.
12719            refreshDrawableState();
12720        }
12721        needGlobalAttributesUpdate(false);
12722    }
12723
12724    void dispatchDetachedFromWindow() {
12725        AttachInfo info = mAttachInfo;
12726        if (info != null) {
12727            int vis = info.mWindowVisibility;
12728            if (vis != GONE) {
12729                onWindowVisibilityChanged(GONE);
12730            }
12731        }
12732
12733        onDetachedFromWindow();
12734
12735        ListenerInfo li = mListenerInfo;
12736        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12737                li != null ? li.mOnAttachStateChangeListeners : null;
12738        if (listeners != null && listeners.size() > 0) {
12739            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12740            // perform the dispatching. The iterator is a safe guard against listeners that
12741            // could mutate the list by calling the various add/remove methods. This prevents
12742            // the array from being modified while we iterate it.
12743            for (OnAttachStateChangeListener listener : listeners) {
12744                listener.onViewDetachedFromWindow(this);
12745            }
12746        }
12747
12748        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12749            mAttachInfo.mScrollContainers.remove(this);
12750            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12751        }
12752
12753        mAttachInfo = null;
12754        if (mOverlay != null) {
12755            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12756        }
12757    }
12758
12759    /**
12760     * Cancel any deferred high-level input events that were previously posted to the event queue.
12761     *
12762     * <p>Many views post high-level events such as click handlers to the event queue
12763     * to run deferred in order to preserve a desired user experience - clearing visible
12764     * pressed states before executing, etc. This method will abort any events of this nature
12765     * that are currently in flight.</p>
12766     *
12767     * <p>Custom views that generate their own high-level deferred input events should override
12768     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
12769     *
12770     * <p>This will also cancel pending input events for any child views.</p>
12771     *
12772     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
12773     * This will not impact newer events posted after this call that may occur as a result of
12774     * lower-level input events still waiting in the queue. If you are trying to prevent
12775     * double-submitted  events for the duration of some sort of asynchronous transaction
12776     * you should also take other steps to protect against unexpected double inputs e.g. calling
12777     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
12778     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
12779     */
12780    public final void cancelPendingInputEvents() {
12781        dispatchCancelPendingInputEvents();
12782    }
12783
12784    /**
12785     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
12786     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
12787     */
12788    void dispatchCancelPendingInputEvents() {
12789        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
12790        onCancelPendingInputEvents();
12791        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
12792            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
12793                    " did not call through to super.onCancelPendingInputEvents()");
12794        }
12795    }
12796
12797    /**
12798     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
12799     * a parent view.
12800     *
12801     * <p>This method is responsible for removing any pending high-level input events that were
12802     * posted to the event queue to run later. Custom view classes that post their own deferred
12803     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
12804     * {@link android.os.Handler} should override this method, call
12805     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
12806     * </p>
12807     */
12808    public void onCancelPendingInputEvents() {
12809        removePerformClickCallback();
12810        cancelLongPress();
12811        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
12812    }
12813
12814    /**
12815     * Store this view hierarchy's frozen state into the given container.
12816     *
12817     * @param container The SparseArray in which to save the view's state.
12818     *
12819     * @see #restoreHierarchyState(android.util.SparseArray)
12820     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12821     * @see #onSaveInstanceState()
12822     */
12823    public void saveHierarchyState(SparseArray<Parcelable> container) {
12824        dispatchSaveInstanceState(container);
12825    }
12826
12827    /**
12828     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12829     * this view and its children. May be overridden to modify how freezing happens to a
12830     * view's children; for example, some views may want to not store state for their children.
12831     *
12832     * @param container The SparseArray in which to save the view's state.
12833     *
12834     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12835     * @see #saveHierarchyState(android.util.SparseArray)
12836     * @see #onSaveInstanceState()
12837     */
12838    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12839        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12840            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12841            Parcelable state = onSaveInstanceState();
12842            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12843                throw new IllegalStateException(
12844                        "Derived class did not call super.onSaveInstanceState()");
12845            }
12846            if (state != null) {
12847                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12848                // + ": " + state);
12849                container.put(mID, state);
12850            }
12851        }
12852    }
12853
12854    /**
12855     * Hook allowing a view to generate a representation of its internal state
12856     * that can later be used to create a new instance with that same state.
12857     * This state should only contain information that is not persistent or can
12858     * not be reconstructed later. For example, you will never store your
12859     * current position on screen because that will be computed again when a
12860     * new instance of the view is placed in its view hierarchy.
12861     * <p>
12862     * Some examples of things you may store here: the current cursor position
12863     * in a text view (but usually not the text itself since that is stored in a
12864     * content provider or other persistent storage), the currently selected
12865     * item in a list view.
12866     *
12867     * @return Returns a Parcelable object containing the view's current dynamic
12868     *         state, or null if there is nothing interesting to save. The
12869     *         default implementation returns null.
12870     * @see #onRestoreInstanceState(android.os.Parcelable)
12871     * @see #saveHierarchyState(android.util.SparseArray)
12872     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12873     * @see #setSaveEnabled(boolean)
12874     */
12875    protected Parcelable onSaveInstanceState() {
12876        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12877        return BaseSavedState.EMPTY_STATE;
12878    }
12879
12880    /**
12881     * Restore this view hierarchy's frozen state from the given container.
12882     *
12883     * @param container The SparseArray which holds previously frozen states.
12884     *
12885     * @see #saveHierarchyState(android.util.SparseArray)
12886     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12887     * @see #onRestoreInstanceState(android.os.Parcelable)
12888     */
12889    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12890        dispatchRestoreInstanceState(container);
12891    }
12892
12893    /**
12894     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12895     * state for this view and its children. May be overridden to modify how restoring
12896     * happens to a view's children; for example, some views may want to not store state
12897     * for their children.
12898     *
12899     * @param container The SparseArray which holds previously saved state.
12900     *
12901     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12902     * @see #restoreHierarchyState(android.util.SparseArray)
12903     * @see #onRestoreInstanceState(android.os.Parcelable)
12904     */
12905    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12906        if (mID != NO_ID) {
12907            Parcelable state = container.get(mID);
12908            if (state != null) {
12909                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12910                // + ": " + state);
12911                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12912                onRestoreInstanceState(state);
12913                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12914                    throw new IllegalStateException(
12915                            "Derived class did not call super.onRestoreInstanceState()");
12916                }
12917            }
12918        }
12919    }
12920
12921    /**
12922     * Hook allowing a view to re-apply a representation of its internal state that had previously
12923     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12924     * null state.
12925     *
12926     * @param state The frozen state that had previously been returned by
12927     *        {@link #onSaveInstanceState}.
12928     *
12929     * @see #onSaveInstanceState()
12930     * @see #restoreHierarchyState(android.util.SparseArray)
12931     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12932     */
12933    protected void onRestoreInstanceState(Parcelable state) {
12934        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12935        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12936            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12937                    + "received " + state.getClass().toString() + " instead. This usually happens "
12938                    + "when two views of different type have the same id in the same hierarchy. "
12939                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12940                    + "other views do not use the same id.");
12941        }
12942    }
12943
12944    /**
12945     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12946     *
12947     * @return the drawing start time in milliseconds
12948     */
12949    public long getDrawingTime() {
12950        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12951    }
12952
12953    /**
12954     * <p>Enables or disables the duplication of the parent's state into this view. When
12955     * duplication is enabled, this view gets its drawable state from its parent rather
12956     * than from its own internal properties.</p>
12957     *
12958     * <p>Note: in the current implementation, setting this property to true after the
12959     * view was added to a ViewGroup might have no effect at all. This property should
12960     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12961     *
12962     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12963     * property is enabled, an exception will be thrown.</p>
12964     *
12965     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12966     * parent, these states should not be affected by this method.</p>
12967     *
12968     * @param enabled True to enable duplication of the parent's drawable state, false
12969     *                to disable it.
12970     *
12971     * @see #getDrawableState()
12972     * @see #isDuplicateParentStateEnabled()
12973     */
12974    public void setDuplicateParentStateEnabled(boolean enabled) {
12975        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12976    }
12977
12978    /**
12979     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12980     *
12981     * @return True if this view's drawable state is duplicated from the parent,
12982     *         false otherwise
12983     *
12984     * @see #getDrawableState()
12985     * @see #setDuplicateParentStateEnabled(boolean)
12986     */
12987    public boolean isDuplicateParentStateEnabled() {
12988        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12989    }
12990
12991    /**
12992     * <p>Specifies the type of layer backing this view. The layer can be
12993     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12994     * {@link #LAYER_TYPE_HARDWARE}.</p>
12995     *
12996     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12997     * instance that controls how the layer is composed on screen. The following
12998     * properties of the paint are taken into account when composing the layer:</p>
12999     * <ul>
13000     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13001     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13002     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13003     * </ul>
13004     *
13005     * <p>If this view has an alpha value set to < 1.0 by calling
13006     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13007     * by this view's alpha value.</p>
13008     *
13009     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13010     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13011     * for more information on when and how to use layers.</p>
13012     *
13013     * @param layerType The type of layer to use with this view, must be one of
13014     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13015     *        {@link #LAYER_TYPE_HARDWARE}
13016     * @param paint The paint used to compose the layer. This argument is optional
13017     *        and can be null. It is ignored when the layer type is
13018     *        {@link #LAYER_TYPE_NONE}
13019     *
13020     * @see #getLayerType()
13021     * @see #LAYER_TYPE_NONE
13022     * @see #LAYER_TYPE_SOFTWARE
13023     * @see #LAYER_TYPE_HARDWARE
13024     * @see #setAlpha(float)
13025     *
13026     * @attr ref android.R.styleable#View_layerType
13027     */
13028    public void setLayerType(int layerType, Paint paint) {
13029        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13030            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13031                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13032        }
13033
13034        if (layerType == mLayerType) {
13035            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
13036                mLayerPaint = paint == null ? new Paint() : paint;
13037                invalidateParentCaches();
13038                invalidate(true);
13039            }
13040            return;
13041        }
13042
13043        // Destroy any previous software drawing cache if needed
13044        switch (mLayerType) {
13045            case LAYER_TYPE_HARDWARE:
13046                destroyLayer(false);
13047                // fall through - non-accelerated views may use software layer mechanism instead
13048            case LAYER_TYPE_SOFTWARE:
13049                destroyDrawingCache();
13050                break;
13051            default:
13052                break;
13053        }
13054
13055        mLayerType = layerType;
13056        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
13057        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13058        mLocalDirtyRect = layerDisabled ? null : new Rect();
13059
13060        invalidateParentCaches();
13061        invalidate(true);
13062    }
13063
13064    /**
13065     * Updates the {@link Paint} object used with the current layer (used only if the current
13066     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13067     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13068     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13069     * ensure that the view gets redrawn immediately.
13070     *
13071     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13072     * instance that controls how the layer is composed on screen. The following
13073     * properties of the paint are taken into account when composing the layer:</p>
13074     * <ul>
13075     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13076     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13077     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13078     * </ul>
13079     *
13080     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13081     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13082     *
13083     * @param paint The paint used to compose the layer. This argument is optional
13084     *        and can be null. It is ignored when the layer type is
13085     *        {@link #LAYER_TYPE_NONE}
13086     *
13087     * @see #setLayerType(int, android.graphics.Paint)
13088     */
13089    public void setLayerPaint(Paint paint) {
13090        int layerType = getLayerType();
13091        if (layerType != LAYER_TYPE_NONE) {
13092            mLayerPaint = paint == null ? new Paint() : paint;
13093            if (layerType == LAYER_TYPE_HARDWARE) {
13094                HardwareLayer layer = getHardwareLayer();
13095                if (layer != null) {
13096                    layer.setLayerPaint(paint);
13097                }
13098                invalidateViewProperty(false, false);
13099            } else {
13100                invalidate();
13101            }
13102        }
13103    }
13104
13105    /**
13106     * Indicates whether this view has a static layer. A view with layer type
13107     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13108     * dynamic.
13109     */
13110    boolean hasStaticLayer() {
13111        return true;
13112    }
13113
13114    /**
13115     * Indicates what type of layer is currently associated with this view. By default
13116     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13117     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13118     * for more information on the different types of layers.
13119     *
13120     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13121     *         {@link #LAYER_TYPE_HARDWARE}
13122     *
13123     * @see #setLayerType(int, android.graphics.Paint)
13124     * @see #buildLayer()
13125     * @see #LAYER_TYPE_NONE
13126     * @see #LAYER_TYPE_SOFTWARE
13127     * @see #LAYER_TYPE_HARDWARE
13128     */
13129    public int getLayerType() {
13130        return mLayerType;
13131    }
13132
13133    /**
13134     * Forces this view's layer to be created and this view to be rendered
13135     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13136     * invoking this method will have no effect.
13137     *
13138     * This method can for instance be used to render a view into its layer before
13139     * starting an animation. If this view is complex, rendering into the layer
13140     * before starting the animation will avoid skipping frames.
13141     *
13142     * @throws IllegalStateException If this view is not attached to a window
13143     *
13144     * @see #setLayerType(int, android.graphics.Paint)
13145     */
13146    public void buildLayer() {
13147        if (mLayerType == LAYER_TYPE_NONE) return;
13148
13149        final AttachInfo attachInfo = mAttachInfo;
13150        if (attachInfo == null) {
13151            throw new IllegalStateException("This view must be attached to a window first");
13152        }
13153
13154        switch (mLayerType) {
13155            case LAYER_TYPE_HARDWARE:
13156                if (attachInfo.mHardwareRenderer != null &&
13157                        attachInfo.mHardwareRenderer.isEnabled() &&
13158                        attachInfo.mHardwareRenderer.validate()) {
13159                    getHardwareLayer();
13160                    // TODO: We need a better way to handle this case
13161                    // If views have registered pre-draw listeners they need
13162                    // to be notified before we build the layer. Those listeners
13163                    // may however rely on other events to happen first so we
13164                    // cannot just invoke them here until they don't cancel the
13165                    // current frame
13166                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13167                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13168                    }
13169                }
13170                break;
13171            case LAYER_TYPE_SOFTWARE:
13172                buildDrawingCache(true);
13173                break;
13174        }
13175    }
13176
13177    /**
13178     * <p>Returns a hardware layer that can be used to draw this view again
13179     * without executing its draw method.</p>
13180     *
13181     * @return A HardwareLayer ready to render, or null if an error occurred.
13182     */
13183    HardwareLayer getHardwareLayer() {
13184        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13185                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13186            return null;
13187        }
13188
13189        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
13190
13191        final int width = mRight - mLeft;
13192        final int height = mBottom - mTop;
13193
13194        if (width == 0 || height == 0) {
13195            return null;
13196        }
13197
13198        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13199            if (mHardwareLayer == null) {
13200                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
13201                        width, height, isOpaque());
13202                mLocalDirtyRect.set(0, 0, width, height);
13203            } else {
13204                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
13205                    if (mHardwareLayer.resize(width, height)) {
13206                        mLocalDirtyRect.set(0, 0, width, height);
13207                    }
13208                }
13209
13210                // This should not be necessary but applications that change
13211                // the parameters of their background drawable without calling
13212                // this.setBackground(Drawable) can leave the view in a bad state
13213                // (for instance isOpaque() returns true, but the background is
13214                // not opaque.)
13215                computeOpaqueFlags();
13216
13217                final boolean opaque = isOpaque();
13218                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
13219                    mHardwareLayer.setOpaque(opaque);
13220                    mLocalDirtyRect.set(0, 0, width, height);
13221                }
13222            }
13223
13224            // The layer is not valid if the underlying GPU resources cannot be allocated
13225            if (!mHardwareLayer.isValid()) {
13226                return null;
13227            }
13228
13229            mHardwareLayer.setLayerPaint(mLayerPaint);
13230            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
13231            ViewRootImpl viewRoot = getViewRootImpl();
13232            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
13233
13234            mLocalDirtyRect.setEmpty();
13235        }
13236
13237        return mHardwareLayer;
13238    }
13239
13240    /**
13241     * Destroys this View's hardware layer if possible.
13242     *
13243     * @return True if the layer was destroyed, false otherwise.
13244     *
13245     * @see #setLayerType(int, android.graphics.Paint)
13246     * @see #LAYER_TYPE_HARDWARE
13247     */
13248    boolean destroyLayer(boolean valid) {
13249        if (mHardwareLayer != null) {
13250            AttachInfo info = mAttachInfo;
13251            if (info != null && info.mHardwareRenderer != null &&
13252                    info.mHardwareRenderer.isEnabled() &&
13253                    (valid || info.mHardwareRenderer.validate())) {
13254
13255                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
13256                mHardwareLayer.destroy();
13257                mHardwareLayer = null;
13258
13259                invalidate(true);
13260                invalidateParentCaches();
13261            }
13262            return true;
13263        }
13264        return false;
13265    }
13266
13267    /**
13268     * Destroys all hardware rendering resources. This method is invoked
13269     * when the system needs to reclaim resources. Upon execution of this
13270     * method, you should free any OpenGL resources created by the view.
13271     *
13272     * Note: you <strong>must</strong> call
13273     * <code>super.destroyHardwareResources()</code> when overriding
13274     * this method.
13275     *
13276     * @hide
13277     */
13278    protected void destroyHardwareResources() {
13279        resetDisplayList();
13280        destroyLayer(true);
13281    }
13282
13283    /**
13284     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13285     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13286     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13287     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13288     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13289     * null.</p>
13290     *
13291     * <p>Enabling the drawing cache is similar to
13292     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13293     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13294     * drawing cache has no effect on rendering because the system uses a different mechanism
13295     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13296     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13297     * for information on how to enable software and hardware layers.</p>
13298     *
13299     * <p>This API can be used to manually generate
13300     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13301     * {@link #getDrawingCache()}.</p>
13302     *
13303     * @param enabled true to enable the drawing cache, false otherwise
13304     *
13305     * @see #isDrawingCacheEnabled()
13306     * @see #getDrawingCache()
13307     * @see #buildDrawingCache()
13308     * @see #setLayerType(int, android.graphics.Paint)
13309     */
13310    public void setDrawingCacheEnabled(boolean enabled) {
13311        mCachingFailed = false;
13312        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13313    }
13314
13315    /**
13316     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13317     *
13318     * @return true if the drawing cache is enabled
13319     *
13320     * @see #setDrawingCacheEnabled(boolean)
13321     * @see #getDrawingCache()
13322     */
13323    @ViewDebug.ExportedProperty(category = "drawing")
13324    public boolean isDrawingCacheEnabled() {
13325        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13326    }
13327
13328    /**
13329     * Debugging utility which recursively outputs the dirty state of a view and its
13330     * descendants.
13331     *
13332     * @hide
13333     */
13334    @SuppressWarnings({"UnusedDeclaration"})
13335    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13336        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13337                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13338                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13339                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13340        if (clear) {
13341            mPrivateFlags &= clearMask;
13342        }
13343        if (this instanceof ViewGroup) {
13344            ViewGroup parent = (ViewGroup) this;
13345            final int count = parent.getChildCount();
13346            for (int i = 0; i < count; i++) {
13347                final View child = parent.getChildAt(i);
13348                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13349            }
13350        }
13351    }
13352
13353    /**
13354     * This method is used by ViewGroup to cause its children to restore or recreate their
13355     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13356     * to recreate its own display list, which would happen if it went through the normal
13357     * draw/dispatchDraw mechanisms.
13358     *
13359     * @hide
13360     */
13361    protected void dispatchGetDisplayList() {}
13362
13363    /**
13364     * A view that is not attached or hardware accelerated cannot create a display list.
13365     * This method checks these conditions and returns the appropriate result.
13366     *
13367     * @return true if view has the ability to create a display list, false otherwise.
13368     *
13369     * @hide
13370     */
13371    public boolean canHaveDisplayList() {
13372        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13373    }
13374
13375    /**
13376     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13377     * Otherwise, the same display list will be returned (after having been rendered into
13378     * along the way, depending on the invalidation state of the view).
13379     *
13380     * @param displayList The previous version of this displayList, could be null.
13381     * @param isLayer Whether the requester of the display list is a layer. If so,
13382     * the view will avoid creating a layer inside the resulting display list.
13383     * @return A new or reused DisplayList object.
13384     */
13385    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13386        if (!canHaveDisplayList()) {
13387            return null;
13388        }
13389
13390        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13391                displayList == null || !displayList.isValid() ||
13392                (!isLayer && mRecreateDisplayList))) {
13393            // Don't need to recreate the display list, just need to tell our
13394            // children to restore/recreate theirs
13395            if (displayList != null && displayList.isValid() &&
13396                    !isLayer && !mRecreateDisplayList) {
13397                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13398                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13399                dispatchGetDisplayList();
13400
13401                return displayList;
13402            }
13403
13404            if (!isLayer) {
13405                // If we got here, we're recreating it. Mark it as such to ensure that
13406                // we copy in child display lists into ours in drawChild()
13407                mRecreateDisplayList = true;
13408            }
13409            if (displayList == null) {
13410                displayList = DisplayList.create(getClass().getName());
13411                // If we're creating a new display list, make sure our parent gets invalidated
13412                // since they will need to recreate their display list to account for this
13413                // new child display list.
13414                invalidateParentCaches();
13415            }
13416
13417            boolean caching = false;
13418            int width = mRight - mLeft;
13419            int height = mBottom - mTop;
13420            int layerType = getLayerType();
13421
13422            final HardwareCanvas canvas = displayList.start(width, height);
13423
13424            try {
13425                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13426                    if (layerType == LAYER_TYPE_HARDWARE) {
13427                        final HardwareLayer layer = getHardwareLayer();
13428                        if (layer != null && layer.isValid()) {
13429                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13430                        } else {
13431                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13432                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13433                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13434                        }
13435                        caching = true;
13436                    } else {
13437                        buildDrawingCache(true);
13438                        Bitmap cache = getDrawingCache(true);
13439                        if (cache != null) {
13440                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13441                            caching = true;
13442                        }
13443                    }
13444                } else {
13445
13446                    computeScroll();
13447
13448                    canvas.translate(-mScrollX, -mScrollY);
13449                    if (!isLayer) {
13450                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13451                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13452                    }
13453
13454                    // Fast path for layouts with no backgrounds
13455                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13456                        dispatchDraw(canvas);
13457                        if (mOverlay != null && !mOverlay.isEmpty()) {
13458                            mOverlay.getOverlayView().draw(canvas);
13459                        }
13460                    } else {
13461                        draw(canvas);
13462                    }
13463                }
13464            } finally {
13465                displayList.end();
13466                displayList.setCaching(caching);
13467                if (isLayer) {
13468                    displayList.setLeftTopRightBottom(0, 0, width, height);
13469                } else {
13470                    setDisplayListProperties(displayList);
13471                }
13472            }
13473        } else if (!isLayer) {
13474            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13475            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13476        }
13477
13478        return displayList;
13479    }
13480
13481    /**
13482     * Get the DisplayList for the HardwareLayer
13483     *
13484     * @param layer The HardwareLayer whose DisplayList we want
13485     * @return A DisplayList fopr the specified HardwareLayer
13486     */
13487    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13488        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13489        layer.setDisplayList(displayList);
13490        return displayList;
13491    }
13492
13493
13494    /**
13495     * <p>Returns a display list that can be used to draw this view again
13496     * without executing its draw method.</p>
13497     *
13498     * @return A DisplayList ready to replay, or null if caching is not enabled.
13499     *
13500     * @hide
13501     */
13502    public DisplayList getDisplayList() {
13503        mDisplayList = getDisplayList(mDisplayList, false);
13504        return mDisplayList;
13505    }
13506
13507    private void clearDisplayList() {
13508        if (mDisplayList != null) {
13509            mDisplayList.clear();
13510        }
13511    }
13512
13513    private void resetDisplayList() {
13514        if (mDisplayList != null) {
13515            mDisplayList.reset();
13516        }
13517    }
13518
13519    /**
13520     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13521     *
13522     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13523     *
13524     * @see #getDrawingCache(boolean)
13525     */
13526    public Bitmap getDrawingCache() {
13527        return getDrawingCache(false);
13528    }
13529
13530    /**
13531     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13532     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13533     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13534     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13535     * request the drawing cache by calling this method and draw it on screen if the
13536     * returned bitmap is not null.</p>
13537     *
13538     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13539     * this method will create a bitmap of the same size as this view. Because this bitmap
13540     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13541     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13542     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13543     * size than the view. This implies that your application must be able to handle this
13544     * size.</p>
13545     *
13546     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13547     *        the current density of the screen when the application is in compatibility
13548     *        mode.
13549     *
13550     * @return A bitmap representing this view or null if cache is disabled.
13551     *
13552     * @see #setDrawingCacheEnabled(boolean)
13553     * @see #isDrawingCacheEnabled()
13554     * @see #buildDrawingCache(boolean)
13555     * @see #destroyDrawingCache()
13556     */
13557    public Bitmap getDrawingCache(boolean autoScale) {
13558        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13559            return null;
13560        }
13561        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13562            buildDrawingCache(autoScale);
13563        }
13564        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13565    }
13566
13567    /**
13568     * <p>Frees the resources used by the drawing cache. If you call
13569     * {@link #buildDrawingCache()} manually without calling
13570     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13571     * should cleanup the cache with this method afterwards.</p>
13572     *
13573     * @see #setDrawingCacheEnabled(boolean)
13574     * @see #buildDrawingCache()
13575     * @see #getDrawingCache()
13576     */
13577    public void destroyDrawingCache() {
13578        if (mDrawingCache != null) {
13579            mDrawingCache.recycle();
13580            mDrawingCache = null;
13581        }
13582        if (mUnscaledDrawingCache != null) {
13583            mUnscaledDrawingCache.recycle();
13584            mUnscaledDrawingCache = null;
13585        }
13586    }
13587
13588    /**
13589     * Setting a solid background color for the drawing cache's bitmaps will improve
13590     * performance and memory usage. Note, though that this should only be used if this
13591     * view will always be drawn on top of a solid color.
13592     *
13593     * @param color The background color to use for the drawing cache's bitmap
13594     *
13595     * @see #setDrawingCacheEnabled(boolean)
13596     * @see #buildDrawingCache()
13597     * @see #getDrawingCache()
13598     */
13599    public void setDrawingCacheBackgroundColor(int color) {
13600        if (color != mDrawingCacheBackgroundColor) {
13601            mDrawingCacheBackgroundColor = color;
13602            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13603        }
13604    }
13605
13606    /**
13607     * @see #setDrawingCacheBackgroundColor(int)
13608     *
13609     * @return The background color to used for the drawing cache's bitmap
13610     */
13611    public int getDrawingCacheBackgroundColor() {
13612        return mDrawingCacheBackgroundColor;
13613    }
13614
13615    /**
13616     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13617     *
13618     * @see #buildDrawingCache(boolean)
13619     */
13620    public void buildDrawingCache() {
13621        buildDrawingCache(false);
13622    }
13623
13624    /**
13625     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13626     *
13627     * <p>If you call {@link #buildDrawingCache()} manually without calling
13628     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13629     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13630     *
13631     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13632     * this method will create a bitmap of the same size as this view. Because this bitmap
13633     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13634     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13635     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13636     * size than the view. This implies that your application must be able to handle this
13637     * size.</p>
13638     *
13639     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13640     * you do not need the drawing cache bitmap, calling this method will increase memory
13641     * usage and cause the view to be rendered in software once, thus negatively impacting
13642     * performance.</p>
13643     *
13644     * @see #getDrawingCache()
13645     * @see #destroyDrawingCache()
13646     */
13647    public void buildDrawingCache(boolean autoScale) {
13648        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13649                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13650            mCachingFailed = false;
13651
13652            int width = mRight - mLeft;
13653            int height = mBottom - mTop;
13654
13655            final AttachInfo attachInfo = mAttachInfo;
13656            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13657
13658            if (autoScale && scalingRequired) {
13659                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13660                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13661            }
13662
13663            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13664            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13665            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13666
13667            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13668            final long drawingCacheSize =
13669                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13670            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13671                if (width > 0 && height > 0) {
13672                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13673                            + projectedBitmapSize + " bytes, only "
13674                            + drawingCacheSize + " available");
13675                }
13676                destroyDrawingCache();
13677                mCachingFailed = true;
13678                return;
13679            }
13680
13681            boolean clear = true;
13682            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13683
13684            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13685                Bitmap.Config quality;
13686                if (!opaque) {
13687                    // Never pick ARGB_4444 because it looks awful
13688                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13689                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13690                        case DRAWING_CACHE_QUALITY_AUTO:
13691                        case DRAWING_CACHE_QUALITY_LOW:
13692                        case DRAWING_CACHE_QUALITY_HIGH:
13693                        default:
13694                            quality = Bitmap.Config.ARGB_8888;
13695                            break;
13696                    }
13697                } else {
13698                    // Optimization for translucent windows
13699                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13700                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13701                }
13702
13703                // Try to cleanup memory
13704                if (bitmap != null) bitmap.recycle();
13705
13706                try {
13707                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13708                            width, height, quality);
13709                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13710                    if (autoScale) {
13711                        mDrawingCache = bitmap;
13712                    } else {
13713                        mUnscaledDrawingCache = bitmap;
13714                    }
13715                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13716                } catch (OutOfMemoryError e) {
13717                    // If there is not enough memory to create the bitmap cache, just
13718                    // ignore the issue as bitmap caches are not required to draw the
13719                    // view hierarchy
13720                    if (autoScale) {
13721                        mDrawingCache = null;
13722                    } else {
13723                        mUnscaledDrawingCache = null;
13724                    }
13725                    mCachingFailed = true;
13726                    return;
13727                }
13728
13729                clear = drawingCacheBackgroundColor != 0;
13730            }
13731
13732            Canvas canvas;
13733            if (attachInfo != null) {
13734                canvas = attachInfo.mCanvas;
13735                if (canvas == null) {
13736                    canvas = new Canvas();
13737                }
13738                canvas.setBitmap(bitmap);
13739                // Temporarily clobber the cached Canvas in case one of our children
13740                // is also using a drawing cache. Without this, the children would
13741                // steal the canvas by attaching their own bitmap to it and bad, bad
13742                // thing would happen (invisible views, corrupted drawings, etc.)
13743                attachInfo.mCanvas = null;
13744            } else {
13745                // This case should hopefully never or seldom happen
13746                canvas = new Canvas(bitmap);
13747            }
13748
13749            if (clear) {
13750                bitmap.eraseColor(drawingCacheBackgroundColor);
13751            }
13752
13753            computeScroll();
13754            final int restoreCount = canvas.save();
13755
13756            if (autoScale && scalingRequired) {
13757                final float scale = attachInfo.mApplicationScale;
13758                canvas.scale(scale, scale);
13759            }
13760
13761            canvas.translate(-mScrollX, -mScrollY);
13762
13763            mPrivateFlags |= PFLAG_DRAWN;
13764            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13765                    mLayerType != LAYER_TYPE_NONE) {
13766                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13767            }
13768
13769            // Fast path for layouts with no backgrounds
13770            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13771                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13772                dispatchDraw(canvas);
13773                if (mOverlay != null && !mOverlay.isEmpty()) {
13774                    mOverlay.getOverlayView().draw(canvas);
13775                }
13776            } else {
13777                draw(canvas);
13778            }
13779
13780            canvas.restoreToCount(restoreCount);
13781            canvas.setBitmap(null);
13782
13783            if (attachInfo != null) {
13784                // Restore the cached Canvas for our siblings
13785                attachInfo.mCanvas = canvas;
13786            }
13787        }
13788    }
13789
13790    /**
13791     * Create a snapshot of the view into a bitmap.  We should probably make
13792     * some form of this public, but should think about the API.
13793     */
13794    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13795        int width = mRight - mLeft;
13796        int height = mBottom - mTop;
13797
13798        final AttachInfo attachInfo = mAttachInfo;
13799        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13800        width = (int) ((width * scale) + 0.5f);
13801        height = (int) ((height * scale) + 0.5f);
13802
13803        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13804                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13805        if (bitmap == null) {
13806            throw new OutOfMemoryError();
13807        }
13808
13809        Resources resources = getResources();
13810        if (resources != null) {
13811            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13812        }
13813
13814        Canvas canvas;
13815        if (attachInfo != null) {
13816            canvas = attachInfo.mCanvas;
13817            if (canvas == null) {
13818                canvas = new Canvas();
13819            }
13820            canvas.setBitmap(bitmap);
13821            // Temporarily clobber the cached Canvas in case one of our children
13822            // is also using a drawing cache. Without this, the children would
13823            // steal the canvas by attaching their own bitmap to it and bad, bad
13824            // things would happen (invisible views, corrupted drawings, etc.)
13825            attachInfo.mCanvas = null;
13826        } else {
13827            // This case should hopefully never or seldom happen
13828            canvas = new Canvas(bitmap);
13829        }
13830
13831        if ((backgroundColor & 0xff000000) != 0) {
13832            bitmap.eraseColor(backgroundColor);
13833        }
13834
13835        computeScroll();
13836        final int restoreCount = canvas.save();
13837        canvas.scale(scale, scale);
13838        canvas.translate(-mScrollX, -mScrollY);
13839
13840        // Temporarily remove the dirty mask
13841        int flags = mPrivateFlags;
13842        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13843
13844        // Fast path for layouts with no backgrounds
13845        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13846            dispatchDraw(canvas);
13847            if (mOverlay != null && !mOverlay.isEmpty()) {
13848                mOverlay.getOverlayView().draw(canvas);
13849            }
13850        } else {
13851            draw(canvas);
13852        }
13853
13854        mPrivateFlags = flags;
13855
13856        canvas.restoreToCount(restoreCount);
13857        canvas.setBitmap(null);
13858
13859        if (attachInfo != null) {
13860            // Restore the cached Canvas for our siblings
13861            attachInfo.mCanvas = canvas;
13862        }
13863
13864        return bitmap;
13865    }
13866
13867    /**
13868     * Indicates whether this View is currently in edit mode. A View is usually
13869     * in edit mode when displayed within a developer tool. For instance, if
13870     * this View is being drawn by a visual user interface builder, this method
13871     * should return true.
13872     *
13873     * Subclasses should check the return value of this method to provide
13874     * different behaviors if their normal behavior might interfere with the
13875     * host environment. For instance: the class spawns a thread in its
13876     * constructor, the drawing code relies on device-specific features, etc.
13877     *
13878     * This method is usually checked in the drawing code of custom widgets.
13879     *
13880     * @return True if this View is in edit mode, false otherwise.
13881     */
13882    public boolean isInEditMode() {
13883        return false;
13884    }
13885
13886    /**
13887     * If the View draws content inside its padding and enables fading edges,
13888     * it needs to support padding offsets. Padding offsets are added to the
13889     * fading edges to extend the length of the fade so that it covers pixels
13890     * drawn inside the padding.
13891     *
13892     * Subclasses of this class should override this method if they need
13893     * to draw content inside the padding.
13894     *
13895     * @return True if padding offset must be applied, false otherwise.
13896     *
13897     * @see #getLeftPaddingOffset()
13898     * @see #getRightPaddingOffset()
13899     * @see #getTopPaddingOffset()
13900     * @see #getBottomPaddingOffset()
13901     *
13902     * @since CURRENT
13903     */
13904    protected boolean isPaddingOffsetRequired() {
13905        return false;
13906    }
13907
13908    /**
13909     * Amount by which to extend the left fading region. Called only when
13910     * {@link #isPaddingOffsetRequired()} returns true.
13911     *
13912     * @return The left padding offset in pixels.
13913     *
13914     * @see #isPaddingOffsetRequired()
13915     *
13916     * @since CURRENT
13917     */
13918    protected int getLeftPaddingOffset() {
13919        return 0;
13920    }
13921
13922    /**
13923     * Amount by which to extend the right fading region. Called only when
13924     * {@link #isPaddingOffsetRequired()} returns true.
13925     *
13926     * @return The right padding offset in pixels.
13927     *
13928     * @see #isPaddingOffsetRequired()
13929     *
13930     * @since CURRENT
13931     */
13932    protected int getRightPaddingOffset() {
13933        return 0;
13934    }
13935
13936    /**
13937     * Amount by which to extend the top fading region. Called only when
13938     * {@link #isPaddingOffsetRequired()} returns true.
13939     *
13940     * @return The top padding offset in pixels.
13941     *
13942     * @see #isPaddingOffsetRequired()
13943     *
13944     * @since CURRENT
13945     */
13946    protected int getTopPaddingOffset() {
13947        return 0;
13948    }
13949
13950    /**
13951     * Amount by which to extend the bottom fading region. Called only when
13952     * {@link #isPaddingOffsetRequired()} returns true.
13953     *
13954     * @return The bottom padding offset in pixels.
13955     *
13956     * @see #isPaddingOffsetRequired()
13957     *
13958     * @since CURRENT
13959     */
13960    protected int getBottomPaddingOffset() {
13961        return 0;
13962    }
13963
13964    /**
13965     * @hide
13966     * @param offsetRequired
13967     */
13968    protected int getFadeTop(boolean offsetRequired) {
13969        int top = mPaddingTop;
13970        if (offsetRequired) top += getTopPaddingOffset();
13971        return top;
13972    }
13973
13974    /**
13975     * @hide
13976     * @param offsetRequired
13977     */
13978    protected int getFadeHeight(boolean offsetRequired) {
13979        int padding = mPaddingTop;
13980        if (offsetRequired) padding += getTopPaddingOffset();
13981        return mBottom - mTop - mPaddingBottom - padding;
13982    }
13983
13984    /**
13985     * <p>Indicates whether this view is attached to a hardware accelerated
13986     * window or not.</p>
13987     *
13988     * <p>Even if this method returns true, it does not mean that every call
13989     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13990     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13991     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13992     * window is hardware accelerated,
13993     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13994     * return false, and this method will return true.</p>
13995     *
13996     * @return True if the view is attached to a window and the window is
13997     *         hardware accelerated; false in any other case.
13998     */
13999    public boolean isHardwareAccelerated() {
14000        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14001    }
14002
14003    /**
14004     * Sets a rectangular area on this view to which the view will be clipped
14005     * when it is drawn. Setting the value to null will remove the clip bounds
14006     * and the view will draw normally, using its full bounds.
14007     *
14008     * @param clipBounds The rectangular area, in the local coordinates of
14009     * this view, to which future drawing operations will be clipped.
14010     */
14011    public void setClipBounds(Rect clipBounds) {
14012        if (clipBounds != null) {
14013            if (clipBounds.equals(mClipBounds)) {
14014                return;
14015            }
14016            if (mClipBounds == null) {
14017                invalidate();
14018                mClipBounds = new Rect(clipBounds);
14019            } else {
14020                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14021                        Math.min(mClipBounds.top, clipBounds.top),
14022                        Math.max(mClipBounds.right, clipBounds.right),
14023                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14024                mClipBounds.set(clipBounds);
14025            }
14026        } else {
14027            if (mClipBounds != null) {
14028                invalidate();
14029                mClipBounds = null;
14030            }
14031        }
14032    }
14033
14034    /**
14035     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14036     *
14037     * @return A copy of the current clip bounds if clip bounds are set,
14038     * otherwise null.
14039     */
14040    public Rect getClipBounds() {
14041        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14042    }
14043
14044    /**
14045     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14046     * case of an active Animation being run on the view.
14047     */
14048    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14049            Animation a, boolean scalingRequired) {
14050        Transformation invalidationTransform;
14051        final int flags = parent.mGroupFlags;
14052        final boolean initialized = a.isInitialized();
14053        if (!initialized) {
14054            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14055            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14056            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14057            onAnimationStart();
14058        }
14059
14060        final Transformation t = parent.getChildTransformation();
14061        boolean more = a.getTransformation(drawingTime, t, 1f);
14062        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14063            if (parent.mInvalidationTransformation == null) {
14064                parent.mInvalidationTransformation = new Transformation();
14065            }
14066            invalidationTransform = parent.mInvalidationTransformation;
14067            a.getTransformation(drawingTime, invalidationTransform, 1f);
14068        } else {
14069            invalidationTransform = t;
14070        }
14071
14072        if (more) {
14073            if (!a.willChangeBounds()) {
14074                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14075                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14076                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14077                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14078                    // The child need to draw an animation, potentially offscreen, so
14079                    // make sure we do not cancel invalidate requests
14080                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14081                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14082                }
14083            } else {
14084                if (parent.mInvalidateRegion == null) {
14085                    parent.mInvalidateRegion = new RectF();
14086                }
14087                final RectF region = parent.mInvalidateRegion;
14088                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14089                        invalidationTransform);
14090
14091                // The child need to draw an animation, potentially offscreen, so
14092                // make sure we do not cancel invalidate requests
14093                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14094
14095                final int left = mLeft + (int) region.left;
14096                final int top = mTop + (int) region.top;
14097                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14098                        top + (int) (region.height() + .5f));
14099            }
14100        }
14101        return more;
14102    }
14103
14104    /**
14105     * This method is called by getDisplayList() when a display list is created or re-rendered.
14106     * It sets or resets the current value of all properties on that display list (resetting is
14107     * necessary when a display list is being re-created, because we need to make sure that
14108     * previously-set transform values
14109     */
14110    void setDisplayListProperties(DisplayList displayList) {
14111        if (displayList != null) {
14112            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14113            displayList.setHasOverlappingRendering(hasOverlappingRendering());
14114            if (mParent instanceof ViewGroup) {
14115                displayList.setClipToBounds(
14116                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14117            }
14118            float alpha = 1;
14119            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14120                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14121                ViewGroup parentVG = (ViewGroup) mParent;
14122                final Transformation t = parentVG.getChildTransformation();
14123                if (parentVG.getChildStaticTransformation(this, t)) {
14124                    final int transformType = t.getTransformationType();
14125                    if (transformType != Transformation.TYPE_IDENTITY) {
14126                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14127                            alpha = t.getAlpha();
14128                        }
14129                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14130                            displayList.setMatrix(t.getMatrix());
14131                        }
14132                    }
14133                }
14134            }
14135            if (mTransformationInfo != null) {
14136                alpha *= getFinalAlpha();
14137                if (alpha < 1) {
14138                    final int multipliedAlpha = (int) (255 * alpha);
14139                    if (onSetAlpha(multipliedAlpha)) {
14140                        alpha = 1;
14141                    }
14142                }
14143                displayList.setTransformationInfo(alpha,
14144                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14145                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14146                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14147                        mTransformationInfo.mScaleY);
14148                if (mTransformationInfo.mCamera == null) {
14149                    mTransformationInfo.mCamera = new Camera();
14150                    mTransformationInfo.matrix3D = new Matrix();
14151                }
14152                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14153                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14154                    displayList.setPivotX(getPivotX());
14155                    displayList.setPivotY(getPivotY());
14156                }
14157            } else if (alpha < 1) {
14158                displayList.setAlpha(alpha);
14159            }
14160        }
14161    }
14162
14163    /**
14164     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14165     * This draw() method is an implementation detail and is not intended to be overridden or
14166     * to be called from anywhere else other than ViewGroup.drawChild().
14167     */
14168    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14169        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14170        boolean more = false;
14171        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14172        final int flags = parent.mGroupFlags;
14173
14174        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14175            parent.getChildTransformation().clear();
14176            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14177        }
14178
14179        Transformation transformToApply = null;
14180        boolean concatMatrix = false;
14181
14182        boolean scalingRequired = false;
14183        boolean caching;
14184        int layerType = getLayerType();
14185
14186        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14187        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14188                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14189            caching = true;
14190            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14191            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14192        } else {
14193            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14194        }
14195
14196        final Animation a = getAnimation();
14197        if (a != null) {
14198            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14199            concatMatrix = a.willChangeTransformationMatrix();
14200            if (concatMatrix) {
14201                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14202            }
14203            transformToApply = parent.getChildTransformation();
14204        } else {
14205            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14206                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14207                // No longer animating: clear out old animation matrix
14208                mDisplayList.setAnimationMatrix(null);
14209                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14210            }
14211            if (!useDisplayListProperties &&
14212                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14213                final Transformation t = parent.getChildTransformation();
14214                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14215                if (hasTransform) {
14216                    final int transformType = t.getTransformationType();
14217                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14218                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14219                }
14220            }
14221        }
14222
14223        concatMatrix |= !childHasIdentityMatrix;
14224
14225        // Sets the flag as early as possible to allow draw() implementations
14226        // to call invalidate() successfully when doing animations
14227        mPrivateFlags |= PFLAG_DRAWN;
14228
14229        if (!concatMatrix &&
14230                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14231                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14232                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14233                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14234            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14235            return more;
14236        }
14237        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14238
14239        if (hardwareAccelerated) {
14240            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14241            // retain the flag's value temporarily in the mRecreateDisplayList flag
14242            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14243            mPrivateFlags &= ~PFLAG_INVALIDATED;
14244        }
14245
14246        DisplayList displayList = null;
14247        Bitmap cache = null;
14248        boolean hasDisplayList = false;
14249        if (caching) {
14250            if (!hardwareAccelerated) {
14251                if (layerType != LAYER_TYPE_NONE) {
14252                    layerType = LAYER_TYPE_SOFTWARE;
14253                    buildDrawingCache(true);
14254                }
14255                cache = getDrawingCache(true);
14256            } else {
14257                switch (layerType) {
14258                    case LAYER_TYPE_SOFTWARE:
14259                        if (useDisplayListProperties) {
14260                            hasDisplayList = canHaveDisplayList();
14261                        } else {
14262                            buildDrawingCache(true);
14263                            cache = getDrawingCache(true);
14264                        }
14265                        break;
14266                    case LAYER_TYPE_HARDWARE:
14267                        if (useDisplayListProperties) {
14268                            hasDisplayList = canHaveDisplayList();
14269                        }
14270                        break;
14271                    case LAYER_TYPE_NONE:
14272                        // Delay getting the display list until animation-driven alpha values are
14273                        // set up and possibly passed on to the view
14274                        hasDisplayList = canHaveDisplayList();
14275                        break;
14276                }
14277            }
14278        }
14279        useDisplayListProperties &= hasDisplayList;
14280        if (useDisplayListProperties) {
14281            displayList = getDisplayList();
14282            if (!displayList.isValid()) {
14283                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14284                // to getDisplayList(), the display list will be marked invalid and we should not
14285                // try to use it again.
14286                displayList = null;
14287                hasDisplayList = false;
14288                useDisplayListProperties = false;
14289            }
14290        }
14291
14292        int sx = 0;
14293        int sy = 0;
14294        if (!hasDisplayList) {
14295            computeScroll();
14296            sx = mScrollX;
14297            sy = mScrollY;
14298        }
14299
14300        final boolean hasNoCache = cache == null || hasDisplayList;
14301        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14302                layerType != LAYER_TYPE_HARDWARE;
14303
14304        int restoreTo = -1;
14305        if (!useDisplayListProperties || transformToApply != null) {
14306            restoreTo = canvas.save();
14307        }
14308        if (offsetForScroll) {
14309            canvas.translate(mLeft - sx, mTop - sy);
14310        } else {
14311            if (!useDisplayListProperties) {
14312                canvas.translate(mLeft, mTop);
14313            }
14314            if (scalingRequired) {
14315                if (useDisplayListProperties) {
14316                    // TODO: Might not need this if we put everything inside the DL
14317                    restoreTo = canvas.save();
14318                }
14319                // mAttachInfo cannot be null, otherwise scalingRequired == false
14320                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14321                canvas.scale(scale, scale);
14322            }
14323        }
14324
14325        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14326        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14327                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14328            if (transformToApply != null || !childHasIdentityMatrix) {
14329                int transX = 0;
14330                int transY = 0;
14331
14332                if (offsetForScroll) {
14333                    transX = -sx;
14334                    transY = -sy;
14335                }
14336
14337                if (transformToApply != null) {
14338                    if (concatMatrix) {
14339                        if (useDisplayListProperties) {
14340                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14341                        } else {
14342                            // Undo the scroll translation, apply the transformation matrix,
14343                            // then redo the scroll translate to get the correct result.
14344                            canvas.translate(-transX, -transY);
14345                            canvas.concat(transformToApply.getMatrix());
14346                            canvas.translate(transX, transY);
14347                        }
14348                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14349                    }
14350
14351                    float transformAlpha = transformToApply.getAlpha();
14352                    if (transformAlpha < 1) {
14353                        alpha *= transformAlpha;
14354                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14355                    }
14356                }
14357
14358                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14359                    canvas.translate(-transX, -transY);
14360                    canvas.concat(getMatrix());
14361                    canvas.translate(transX, transY);
14362                }
14363            }
14364
14365            // Deal with alpha if it is or used to be <1
14366            if (alpha < 1 ||
14367                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14368                if (alpha < 1) {
14369                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14370                } else {
14371                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14372                }
14373                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14374                if (hasNoCache) {
14375                    final int multipliedAlpha = (int) (255 * alpha);
14376                    if (!onSetAlpha(multipliedAlpha)) {
14377                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14378                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14379                                layerType != LAYER_TYPE_NONE) {
14380                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14381                        }
14382                        if (useDisplayListProperties) {
14383                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14384                        } else  if (layerType == LAYER_TYPE_NONE) {
14385                            final int scrollX = hasDisplayList ? 0 : sx;
14386                            final int scrollY = hasDisplayList ? 0 : sy;
14387                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14388                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14389                        }
14390                    } else {
14391                        // Alpha is handled by the child directly, clobber the layer's alpha
14392                        mPrivateFlags |= PFLAG_ALPHA_SET;
14393                    }
14394                }
14395            }
14396        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14397            onSetAlpha(255);
14398            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14399        }
14400
14401        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14402                !useDisplayListProperties && cache == null) {
14403            if (offsetForScroll) {
14404                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14405            } else {
14406                if (!scalingRequired || cache == null) {
14407                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14408                } else {
14409                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14410                }
14411            }
14412        }
14413
14414        if (!useDisplayListProperties && hasDisplayList) {
14415            displayList = getDisplayList();
14416            if (!displayList.isValid()) {
14417                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14418                // to getDisplayList(), the display list will be marked invalid and we should not
14419                // try to use it again.
14420                displayList = null;
14421                hasDisplayList = false;
14422            }
14423        }
14424
14425        if (hasNoCache) {
14426            boolean layerRendered = false;
14427            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14428                final HardwareLayer layer = getHardwareLayer();
14429                if (layer != null && layer.isValid()) {
14430                    mLayerPaint.setAlpha((int) (alpha * 255));
14431                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14432                    layerRendered = true;
14433                } else {
14434                    final int scrollX = hasDisplayList ? 0 : sx;
14435                    final int scrollY = hasDisplayList ? 0 : sy;
14436                    canvas.saveLayer(scrollX, scrollY,
14437                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14438                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14439                }
14440            }
14441
14442            if (!layerRendered) {
14443                if (!hasDisplayList) {
14444                    // Fast path for layouts with no backgrounds
14445                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14446                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14447                        dispatchDraw(canvas);
14448                    } else {
14449                        draw(canvas);
14450                    }
14451                } else {
14452                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14453                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14454                }
14455            }
14456        } else if (cache != null) {
14457            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14458            Paint cachePaint;
14459
14460            if (layerType == LAYER_TYPE_NONE) {
14461                cachePaint = parent.mCachePaint;
14462                if (cachePaint == null) {
14463                    cachePaint = new Paint();
14464                    cachePaint.setDither(false);
14465                    parent.mCachePaint = cachePaint;
14466                }
14467                if (alpha < 1) {
14468                    cachePaint.setAlpha((int) (alpha * 255));
14469                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14470                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14471                    cachePaint.setAlpha(255);
14472                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14473                }
14474            } else {
14475                cachePaint = mLayerPaint;
14476                cachePaint.setAlpha((int) (alpha * 255));
14477            }
14478            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14479        }
14480
14481        if (restoreTo >= 0) {
14482            canvas.restoreToCount(restoreTo);
14483        }
14484
14485        if (a != null && !more) {
14486            if (!hardwareAccelerated && !a.getFillAfter()) {
14487                onSetAlpha(255);
14488            }
14489            parent.finishAnimatingView(this, a);
14490        }
14491
14492        if (more && hardwareAccelerated) {
14493            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14494                // alpha animations should cause the child to recreate its display list
14495                invalidate(true);
14496            }
14497        }
14498
14499        mRecreateDisplayList = false;
14500
14501        return more;
14502    }
14503
14504    /**
14505     * Manually render this view (and all of its children) to the given Canvas.
14506     * The view must have already done a full layout before this function is
14507     * called.  When implementing a view, implement
14508     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14509     * If you do need to override this method, call the superclass version.
14510     *
14511     * @param canvas The Canvas to which the View is rendered.
14512     */
14513    public void draw(Canvas canvas) {
14514        if (mClipBounds != null) {
14515            canvas.clipRect(mClipBounds);
14516        }
14517        final int privateFlags = mPrivateFlags;
14518        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14519                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14520        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14521
14522        /*
14523         * Draw traversal performs several drawing steps which must be executed
14524         * in the appropriate order:
14525         *
14526         *      1. Draw the background
14527         *      2. If necessary, save the canvas' layers to prepare for fading
14528         *      3. Draw view's content
14529         *      4. Draw children
14530         *      5. If necessary, draw the fading edges and restore layers
14531         *      6. Draw decorations (scrollbars for instance)
14532         */
14533
14534        // Step 1, draw the background, if needed
14535        int saveCount;
14536
14537        if (!dirtyOpaque) {
14538            final Drawable background = mBackground;
14539            if (background != null) {
14540                final int scrollX = mScrollX;
14541                final int scrollY = mScrollY;
14542
14543                if (mBackgroundSizeChanged) {
14544                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14545                    mBackgroundSizeChanged = false;
14546                }
14547
14548                if ((scrollX | scrollY) == 0) {
14549                    background.draw(canvas);
14550                } else {
14551                    canvas.translate(scrollX, scrollY);
14552                    background.draw(canvas);
14553                    canvas.translate(-scrollX, -scrollY);
14554                }
14555            }
14556        }
14557
14558        // skip step 2 & 5 if possible (common case)
14559        final int viewFlags = mViewFlags;
14560        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14561        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14562        if (!verticalEdges && !horizontalEdges) {
14563            // Step 3, draw the content
14564            if (!dirtyOpaque) onDraw(canvas);
14565
14566            // Step 4, draw the children
14567            dispatchDraw(canvas);
14568
14569            // Step 6, draw decorations (scrollbars)
14570            onDrawScrollBars(canvas);
14571
14572            if (mOverlay != null && !mOverlay.isEmpty()) {
14573                mOverlay.getOverlayView().dispatchDraw(canvas);
14574            }
14575
14576            // we're done...
14577            return;
14578        }
14579
14580        /*
14581         * Here we do the full fledged routine...
14582         * (this is an uncommon case where speed matters less,
14583         * this is why we repeat some of the tests that have been
14584         * done above)
14585         */
14586
14587        boolean drawTop = false;
14588        boolean drawBottom = false;
14589        boolean drawLeft = false;
14590        boolean drawRight = false;
14591
14592        float topFadeStrength = 0.0f;
14593        float bottomFadeStrength = 0.0f;
14594        float leftFadeStrength = 0.0f;
14595        float rightFadeStrength = 0.0f;
14596
14597        // Step 2, save the canvas' layers
14598        int paddingLeft = mPaddingLeft;
14599
14600        final boolean offsetRequired = isPaddingOffsetRequired();
14601        if (offsetRequired) {
14602            paddingLeft += getLeftPaddingOffset();
14603        }
14604
14605        int left = mScrollX + paddingLeft;
14606        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14607        int top = mScrollY + getFadeTop(offsetRequired);
14608        int bottom = top + getFadeHeight(offsetRequired);
14609
14610        if (offsetRequired) {
14611            right += getRightPaddingOffset();
14612            bottom += getBottomPaddingOffset();
14613        }
14614
14615        final ScrollabilityCache scrollabilityCache = mScrollCache;
14616        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14617        int length = (int) fadeHeight;
14618
14619        // clip the fade length if top and bottom fades overlap
14620        // overlapping fades produce odd-looking artifacts
14621        if (verticalEdges && (top + length > bottom - length)) {
14622            length = (bottom - top) / 2;
14623        }
14624
14625        // also clip horizontal fades if necessary
14626        if (horizontalEdges && (left + length > right - length)) {
14627            length = (right - left) / 2;
14628        }
14629
14630        if (verticalEdges) {
14631            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14632            drawTop = topFadeStrength * fadeHeight > 1.0f;
14633            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14634            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14635        }
14636
14637        if (horizontalEdges) {
14638            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14639            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14640            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14641            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14642        }
14643
14644        saveCount = canvas.getSaveCount();
14645
14646        int solidColor = getSolidColor();
14647        if (solidColor == 0) {
14648            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14649
14650            if (drawTop) {
14651                canvas.saveLayer(left, top, right, top + length, null, flags);
14652            }
14653
14654            if (drawBottom) {
14655                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14656            }
14657
14658            if (drawLeft) {
14659                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14660            }
14661
14662            if (drawRight) {
14663                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14664            }
14665        } else {
14666            scrollabilityCache.setFadeColor(solidColor);
14667        }
14668
14669        // Step 3, draw the content
14670        if (!dirtyOpaque) onDraw(canvas);
14671
14672        // Step 4, draw the children
14673        dispatchDraw(canvas);
14674
14675        // Step 5, draw the fade effect and restore layers
14676        final Paint p = scrollabilityCache.paint;
14677        final Matrix matrix = scrollabilityCache.matrix;
14678        final Shader fade = scrollabilityCache.shader;
14679
14680        if (drawTop) {
14681            matrix.setScale(1, fadeHeight * topFadeStrength);
14682            matrix.postTranslate(left, top);
14683            fade.setLocalMatrix(matrix);
14684            canvas.drawRect(left, top, right, top + length, p);
14685        }
14686
14687        if (drawBottom) {
14688            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14689            matrix.postRotate(180);
14690            matrix.postTranslate(left, bottom);
14691            fade.setLocalMatrix(matrix);
14692            canvas.drawRect(left, bottom - length, right, bottom, p);
14693        }
14694
14695        if (drawLeft) {
14696            matrix.setScale(1, fadeHeight * leftFadeStrength);
14697            matrix.postRotate(-90);
14698            matrix.postTranslate(left, top);
14699            fade.setLocalMatrix(matrix);
14700            canvas.drawRect(left, top, left + length, bottom, p);
14701        }
14702
14703        if (drawRight) {
14704            matrix.setScale(1, fadeHeight * rightFadeStrength);
14705            matrix.postRotate(90);
14706            matrix.postTranslate(right, top);
14707            fade.setLocalMatrix(matrix);
14708            canvas.drawRect(right - length, top, right, bottom, p);
14709        }
14710
14711        canvas.restoreToCount(saveCount);
14712
14713        // Step 6, draw decorations (scrollbars)
14714        onDrawScrollBars(canvas);
14715
14716        if (mOverlay != null && !mOverlay.isEmpty()) {
14717            mOverlay.getOverlayView().dispatchDraw(canvas);
14718        }
14719    }
14720
14721    /**
14722     * Returns the overlay for this view, creating it if it does not yet exist.
14723     * Adding drawables to the overlay will cause them to be displayed whenever
14724     * the view itself is redrawn. Objects in the overlay should be actively
14725     * managed: remove them when they should not be displayed anymore. The
14726     * overlay will always have the same size as its host view.
14727     *
14728     * <p>Note: Overlays do not currently work correctly with {@link
14729     * SurfaceView} or {@link TextureView}; contents in overlays for these
14730     * types of views may not display correctly.</p>
14731     *
14732     * @return The ViewOverlay object for this view.
14733     * @see ViewOverlay
14734     */
14735    public ViewOverlay getOverlay() {
14736        if (mOverlay == null) {
14737            mOverlay = new ViewOverlay(mContext, this);
14738        }
14739        return mOverlay;
14740    }
14741
14742    /**
14743     * Override this if your view is known to always be drawn on top of a solid color background,
14744     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14745     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14746     * should be set to 0xFF.
14747     *
14748     * @see #setVerticalFadingEdgeEnabled(boolean)
14749     * @see #setHorizontalFadingEdgeEnabled(boolean)
14750     *
14751     * @return The known solid color background for this view, or 0 if the color may vary
14752     */
14753    @ViewDebug.ExportedProperty(category = "drawing")
14754    public int getSolidColor() {
14755        return 0;
14756    }
14757
14758    /**
14759     * Build a human readable string representation of the specified view flags.
14760     *
14761     * @param flags the view flags to convert to a string
14762     * @return a String representing the supplied flags
14763     */
14764    private static String printFlags(int flags) {
14765        String output = "";
14766        int numFlags = 0;
14767        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14768            output += "TAKES_FOCUS";
14769            numFlags++;
14770        }
14771
14772        switch (flags & VISIBILITY_MASK) {
14773        case INVISIBLE:
14774            if (numFlags > 0) {
14775                output += " ";
14776            }
14777            output += "INVISIBLE";
14778            // USELESS HERE numFlags++;
14779            break;
14780        case GONE:
14781            if (numFlags > 0) {
14782                output += " ";
14783            }
14784            output += "GONE";
14785            // USELESS HERE numFlags++;
14786            break;
14787        default:
14788            break;
14789        }
14790        return output;
14791    }
14792
14793    /**
14794     * Build a human readable string representation of the specified private
14795     * view flags.
14796     *
14797     * @param privateFlags the private view flags to convert to a string
14798     * @return a String representing the supplied flags
14799     */
14800    private static String printPrivateFlags(int privateFlags) {
14801        String output = "";
14802        int numFlags = 0;
14803
14804        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14805            output += "WANTS_FOCUS";
14806            numFlags++;
14807        }
14808
14809        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14810            if (numFlags > 0) {
14811                output += " ";
14812            }
14813            output += "FOCUSED";
14814            numFlags++;
14815        }
14816
14817        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14818            if (numFlags > 0) {
14819                output += " ";
14820            }
14821            output += "SELECTED";
14822            numFlags++;
14823        }
14824
14825        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14826            if (numFlags > 0) {
14827                output += " ";
14828            }
14829            output += "IS_ROOT_NAMESPACE";
14830            numFlags++;
14831        }
14832
14833        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14834            if (numFlags > 0) {
14835                output += " ";
14836            }
14837            output += "HAS_BOUNDS";
14838            numFlags++;
14839        }
14840
14841        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14842            if (numFlags > 0) {
14843                output += " ";
14844            }
14845            output += "DRAWN";
14846            // USELESS HERE numFlags++;
14847        }
14848        return output;
14849    }
14850
14851    /**
14852     * <p>Indicates whether or not this view's layout will be requested during
14853     * the next hierarchy layout pass.</p>
14854     *
14855     * @return true if the layout will be forced during next layout pass
14856     */
14857    public boolean isLayoutRequested() {
14858        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14859    }
14860
14861    /**
14862     * Return true if o is a ViewGroup that is laying out using optical bounds.
14863     * @hide
14864     */
14865    public static boolean isLayoutModeOptical(Object o) {
14866        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14867    }
14868
14869    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14870        Insets parentInsets = mParent instanceof View ?
14871                ((View) mParent).getOpticalInsets() : Insets.NONE;
14872        Insets childInsets = getOpticalInsets();
14873        return setFrame(
14874                left   + parentInsets.left - childInsets.left,
14875                top    + parentInsets.top  - childInsets.top,
14876                right  + parentInsets.left + childInsets.right,
14877                bottom + parentInsets.top  + childInsets.bottom);
14878    }
14879
14880    /**
14881     * Assign a size and position to a view and all of its
14882     * descendants
14883     *
14884     * <p>This is the second phase of the layout mechanism.
14885     * (The first is measuring). In this phase, each parent calls
14886     * layout on all of its children to position them.
14887     * This is typically done using the child measurements
14888     * that were stored in the measure pass().</p>
14889     *
14890     * <p>Derived classes should not override this method.
14891     * Derived classes with children should override
14892     * onLayout. In that method, they should
14893     * call layout on each of their children.</p>
14894     *
14895     * @param l Left position, relative to parent
14896     * @param t Top position, relative to parent
14897     * @param r Right position, relative to parent
14898     * @param b Bottom position, relative to parent
14899     */
14900    @SuppressWarnings({"unchecked"})
14901    public void layout(int l, int t, int r, int b) {
14902        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14903            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14904            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14905        }
14906
14907        int oldL = mLeft;
14908        int oldT = mTop;
14909        int oldB = mBottom;
14910        int oldR = mRight;
14911
14912        boolean changed = isLayoutModeOptical(mParent) ?
14913                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14914
14915        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14916            onLayout(changed, l, t, r, b);
14917            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14918
14919            ListenerInfo li = mListenerInfo;
14920            if (li != null && li.mOnLayoutChangeListeners != null) {
14921                ArrayList<OnLayoutChangeListener> listenersCopy =
14922                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14923                int numListeners = listenersCopy.size();
14924                for (int i = 0; i < numListeners; ++i) {
14925                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14926                }
14927            }
14928        }
14929
14930        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14931        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14932    }
14933
14934    /**
14935     * Called from layout when this view should
14936     * assign a size and position to each of its children.
14937     *
14938     * Derived classes with children should override
14939     * this method and call layout on each of
14940     * their children.
14941     * @param changed This is a new size or position for this view
14942     * @param left Left position, relative to parent
14943     * @param top Top position, relative to parent
14944     * @param right Right position, relative to parent
14945     * @param bottom Bottom position, relative to parent
14946     */
14947    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14948    }
14949
14950    /**
14951     * Assign a size and position to this view.
14952     *
14953     * This is called from layout.
14954     *
14955     * @param left Left position, relative to parent
14956     * @param top Top position, relative to parent
14957     * @param right Right position, relative to parent
14958     * @param bottom Bottom position, relative to parent
14959     * @return true if the new size and position are different than the
14960     *         previous ones
14961     * {@hide}
14962     */
14963    protected boolean setFrame(int left, int top, int right, int bottom) {
14964        boolean changed = false;
14965
14966        if (DBG) {
14967            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14968                    + right + "," + bottom + ")");
14969        }
14970
14971        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14972            changed = true;
14973
14974            // Remember our drawn bit
14975            int drawn = mPrivateFlags & PFLAG_DRAWN;
14976
14977            int oldWidth = mRight - mLeft;
14978            int oldHeight = mBottom - mTop;
14979            int newWidth = right - left;
14980            int newHeight = bottom - top;
14981            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14982
14983            // Invalidate our old position
14984            invalidate(sizeChanged);
14985
14986            mLeft = left;
14987            mTop = top;
14988            mRight = right;
14989            mBottom = bottom;
14990            if (mDisplayList != null) {
14991                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14992            }
14993
14994            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14995
14996
14997            if (sizeChanged) {
14998                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14999                    // A change in dimension means an auto-centered pivot point changes, too
15000                    if (mTransformationInfo != null) {
15001                        mTransformationInfo.mMatrixDirty = true;
15002                    }
15003                }
15004                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15005            }
15006
15007            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15008                // If we are visible, force the DRAWN bit to on so that
15009                // this invalidate will go through (at least to our parent).
15010                // This is because someone may have invalidated this view
15011                // before this call to setFrame came in, thereby clearing
15012                // the DRAWN bit.
15013                mPrivateFlags |= PFLAG_DRAWN;
15014                invalidate(sizeChanged);
15015                // parent display list may need to be recreated based on a change in the bounds
15016                // of any child
15017                invalidateParentCaches();
15018            }
15019
15020            // Reset drawn bit to original value (invalidate turns it off)
15021            mPrivateFlags |= drawn;
15022
15023            mBackgroundSizeChanged = true;
15024
15025            notifySubtreeAccessibilityStateChangedIfNeeded();
15026        }
15027        return changed;
15028    }
15029
15030    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15031        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15032        if (mOverlay != null) {
15033            mOverlay.getOverlayView().setRight(newWidth);
15034            mOverlay.getOverlayView().setBottom(newHeight);
15035        }
15036    }
15037
15038    /**
15039     * Finalize inflating a view from XML.  This is called as the last phase
15040     * of inflation, after all child views have been added.
15041     *
15042     * <p>Even if the subclass overrides onFinishInflate, they should always be
15043     * sure to call the super method, so that we get called.
15044     */
15045    protected void onFinishInflate() {
15046    }
15047
15048    /**
15049     * Returns the resources associated with this view.
15050     *
15051     * @return Resources object.
15052     */
15053    public Resources getResources() {
15054        return mResources;
15055    }
15056
15057    /**
15058     * Invalidates the specified Drawable.
15059     *
15060     * @param drawable the drawable to invalidate
15061     */
15062    public void invalidateDrawable(Drawable drawable) {
15063        if (verifyDrawable(drawable)) {
15064            final Rect dirty = drawable.getBounds();
15065            final int scrollX = mScrollX;
15066            final int scrollY = mScrollY;
15067
15068            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15069                    dirty.right + scrollX, dirty.bottom + scrollY);
15070        }
15071    }
15072
15073    /**
15074     * Schedules an action on a drawable to occur at a specified time.
15075     *
15076     * @param who the recipient of the action
15077     * @param what the action to run on the drawable
15078     * @param when the time at which the action must occur. Uses the
15079     *        {@link SystemClock#uptimeMillis} timebase.
15080     */
15081    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15082        if (verifyDrawable(who) && what != null) {
15083            final long delay = when - SystemClock.uptimeMillis();
15084            if (mAttachInfo != null) {
15085                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15086                        Choreographer.CALLBACK_ANIMATION, what, who,
15087                        Choreographer.subtractFrameDelay(delay));
15088            } else {
15089                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15090            }
15091        }
15092    }
15093
15094    /**
15095     * Cancels a scheduled action on a drawable.
15096     *
15097     * @param who the recipient of the action
15098     * @param what the action to cancel
15099     */
15100    public void unscheduleDrawable(Drawable who, Runnable what) {
15101        if (verifyDrawable(who) && what != null) {
15102            if (mAttachInfo != null) {
15103                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15104                        Choreographer.CALLBACK_ANIMATION, what, who);
15105            }
15106            ViewRootImpl.getRunQueue().removeCallbacks(what);
15107        }
15108    }
15109
15110    /**
15111     * Unschedule any events associated with the given Drawable.  This can be
15112     * used when selecting a new Drawable into a view, so that the previous
15113     * one is completely unscheduled.
15114     *
15115     * @param who The Drawable to unschedule.
15116     *
15117     * @see #drawableStateChanged
15118     */
15119    public void unscheduleDrawable(Drawable who) {
15120        if (mAttachInfo != null && who != null) {
15121            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15122                    Choreographer.CALLBACK_ANIMATION, null, who);
15123        }
15124    }
15125
15126    /**
15127     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15128     * that the View directionality can and will be resolved before its Drawables.
15129     *
15130     * Will call {@link View#onResolveDrawables} when resolution is done.
15131     *
15132     * @hide
15133     */
15134    protected void resolveDrawables() {
15135        // Drawables resolution may need to happen before resolving the layout direction (which is
15136        // done only during the measure() call).
15137        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15138        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15139        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15140        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15141        // direction to be resolved as its resolved value will be the same as its raw value.
15142        if (!isLayoutDirectionResolved() &&
15143                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15144            return;
15145        }
15146
15147        final int layoutDirection = isLayoutDirectionResolved() ?
15148                getLayoutDirection() : getRawLayoutDirection();
15149
15150        if (mBackground != null) {
15151            mBackground.setLayoutDirection(layoutDirection);
15152        }
15153        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15154        onResolveDrawables(layoutDirection);
15155    }
15156
15157    /**
15158     * Called when layout direction has been resolved.
15159     *
15160     * The default implementation does nothing.
15161     *
15162     * @param layoutDirection The resolved layout direction.
15163     *
15164     * @see #LAYOUT_DIRECTION_LTR
15165     * @see #LAYOUT_DIRECTION_RTL
15166     *
15167     * @hide
15168     */
15169    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15170    }
15171
15172    /**
15173     * @hide
15174     */
15175    protected void resetResolvedDrawables() {
15176        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15177    }
15178
15179    private boolean isDrawablesResolved() {
15180        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15181    }
15182
15183    /**
15184     * If your view subclass is displaying its own Drawable objects, it should
15185     * override this function and return true for any Drawable it is
15186     * displaying.  This allows animations for those drawables to be
15187     * scheduled.
15188     *
15189     * <p>Be sure to call through to the super class when overriding this
15190     * function.
15191     *
15192     * @param who The Drawable to verify.  Return true if it is one you are
15193     *            displaying, else return the result of calling through to the
15194     *            super class.
15195     *
15196     * @return boolean If true than the Drawable is being displayed in the
15197     *         view; else false and it is not allowed to animate.
15198     *
15199     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15200     * @see #drawableStateChanged()
15201     */
15202    protected boolean verifyDrawable(Drawable who) {
15203        return who == mBackground;
15204    }
15205
15206    /**
15207     * This function is called whenever the state of the view changes in such
15208     * a way that it impacts the state of drawables being shown.
15209     *
15210     * <p>Be sure to call through to the superclass when overriding this
15211     * function.
15212     *
15213     * @see Drawable#setState(int[])
15214     */
15215    protected void drawableStateChanged() {
15216        Drawable d = mBackground;
15217        if (d != null && d.isStateful()) {
15218            d.setState(getDrawableState());
15219        }
15220    }
15221
15222    /**
15223     * Call this to force a view to update its drawable state. This will cause
15224     * drawableStateChanged to be called on this view. Views that are interested
15225     * in the new state should call getDrawableState.
15226     *
15227     * @see #drawableStateChanged
15228     * @see #getDrawableState
15229     */
15230    public void refreshDrawableState() {
15231        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15232        drawableStateChanged();
15233
15234        ViewParent parent = mParent;
15235        if (parent != null) {
15236            parent.childDrawableStateChanged(this);
15237        }
15238    }
15239
15240    /**
15241     * Return an array of resource IDs of the drawable states representing the
15242     * current state of the view.
15243     *
15244     * @return The current drawable state
15245     *
15246     * @see Drawable#setState(int[])
15247     * @see #drawableStateChanged()
15248     * @see #onCreateDrawableState(int)
15249     */
15250    public final int[] getDrawableState() {
15251        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15252            return mDrawableState;
15253        } else {
15254            mDrawableState = onCreateDrawableState(0);
15255            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15256            return mDrawableState;
15257        }
15258    }
15259
15260    /**
15261     * Generate the new {@link android.graphics.drawable.Drawable} state for
15262     * this view. This is called by the view
15263     * system when the cached Drawable state is determined to be invalid.  To
15264     * retrieve the current state, you should use {@link #getDrawableState}.
15265     *
15266     * @param extraSpace if non-zero, this is the number of extra entries you
15267     * would like in the returned array in which you can place your own
15268     * states.
15269     *
15270     * @return Returns an array holding the current {@link Drawable} state of
15271     * the view.
15272     *
15273     * @see #mergeDrawableStates(int[], int[])
15274     */
15275    protected int[] onCreateDrawableState(int extraSpace) {
15276        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15277                mParent instanceof View) {
15278            return ((View) mParent).onCreateDrawableState(extraSpace);
15279        }
15280
15281        int[] drawableState;
15282
15283        int privateFlags = mPrivateFlags;
15284
15285        int viewStateIndex = 0;
15286        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15287        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15288        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15289        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15290        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15291        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15292        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15293                HardwareRenderer.isAvailable()) {
15294            // This is set if HW acceleration is requested, even if the current
15295            // process doesn't allow it.  This is just to allow app preview
15296            // windows to better match their app.
15297            viewStateIndex |= VIEW_STATE_ACCELERATED;
15298        }
15299        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15300
15301        final int privateFlags2 = mPrivateFlags2;
15302        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15303        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15304
15305        drawableState = VIEW_STATE_SETS[viewStateIndex];
15306
15307        //noinspection ConstantIfStatement
15308        if (false) {
15309            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15310            Log.i("View", toString()
15311                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15312                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15313                    + " fo=" + hasFocus()
15314                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15315                    + " wf=" + hasWindowFocus()
15316                    + ": " + Arrays.toString(drawableState));
15317        }
15318
15319        if (extraSpace == 0) {
15320            return drawableState;
15321        }
15322
15323        final int[] fullState;
15324        if (drawableState != null) {
15325            fullState = new int[drawableState.length + extraSpace];
15326            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15327        } else {
15328            fullState = new int[extraSpace];
15329        }
15330
15331        return fullState;
15332    }
15333
15334    /**
15335     * Merge your own state values in <var>additionalState</var> into the base
15336     * state values <var>baseState</var> that were returned by
15337     * {@link #onCreateDrawableState(int)}.
15338     *
15339     * @param baseState The base state values returned by
15340     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15341     * own additional state values.
15342     *
15343     * @param additionalState The additional state values you would like
15344     * added to <var>baseState</var>; this array is not modified.
15345     *
15346     * @return As a convenience, the <var>baseState</var> array you originally
15347     * passed into the function is returned.
15348     *
15349     * @see #onCreateDrawableState(int)
15350     */
15351    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15352        final int N = baseState.length;
15353        int i = N - 1;
15354        while (i >= 0 && baseState[i] == 0) {
15355            i--;
15356        }
15357        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15358        return baseState;
15359    }
15360
15361    /**
15362     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15363     * on all Drawable objects associated with this view.
15364     */
15365    public void jumpDrawablesToCurrentState() {
15366        if (mBackground != null) {
15367            mBackground.jumpToCurrentState();
15368        }
15369    }
15370
15371    /**
15372     * Sets the background color for this view.
15373     * @param color the color of the background
15374     */
15375    @RemotableViewMethod
15376    public void setBackgroundColor(int color) {
15377        if (mBackground instanceof ColorDrawable) {
15378            ((ColorDrawable) mBackground.mutate()).setColor(color);
15379            computeOpaqueFlags();
15380            mBackgroundResource = 0;
15381        } else {
15382            setBackground(new ColorDrawable(color));
15383        }
15384    }
15385
15386    /**
15387     * Set the background to a given resource. The resource should refer to
15388     * a Drawable object or 0 to remove the background.
15389     * @param resid The identifier of the resource.
15390     *
15391     * @attr ref android.R.styleable#View_background
15392     */
15393    @RemotableViewMethod
15394    public void setBackgroundResource(int resid) {
15395        if (resid != 0 && resid == mBackgroundResource) {
15396            return;
15397        }
15398
15399        Drawable d= null;
15400        if (resid != 0) {
15401            d = mResources.getDrawable(resid);
15402        }
15403        setBackground(d);
15404
15405        mBackgroundResource = resid;
15406    }
15407
15408    /**
15409     * Set the background to a given Drawable, or remove the background. If the
15410     * background has padding, this View's padding is set to the background's
15411     * padding. However, when a background is removed, this View's padding isn't
15412     * touched. If setting the padding is desired, please use
15413     * {@link #setPadding(int, int, int, int)}.
15414     *
15415     * @param background The Drawable to use as the background, or null to remove the
15416     *        background
15417     */
15418    public void setBackground(Drawable background) {
15419        //noinspection deprecation
15420        setBackgroundDrawable(background);
15421    }
15422
15423    /**
15424     * @deprecated use {@link #setBackground(Drawable)} instead
15425     */
15426    @Deprecated
15427    public void setBackgroundDrawable(Drawable background) {
15428        computeOpaqueFlags();
15429
15430        if (background == mBackground) {
15431            return;
15432        }
15433
15434        boolean requestLayout = false;
15435
15436        mBackgroundResource = 0;
15437
15438        /*
15439         * Regardless of whether we're setting a new background or not, we want
15440         * to clear the previous drawable.
15441         */
15442        if (mBackground != null) {
15443            mBackground.setCallback(null);
15444            unscheduleDrawable(mBackground);
15445        }
15446
15447        if (background != null) {
15448            Rect padding = sThreadLocal.get();
15449            if (padding == null) {
15450                padding = new Rect();
15451                sThreadLocal.set(padding);
15452            }
15453            resetResolvedDrawables();
15454            background.setLayoutDirection(getLayoutDirection());
15455            if (background.getPadding(padding)) {
15456                resetResolvedPadding();
15457                switch (background.getLayoutDirection()) {
15458                    case LAYOUT_DIRECTION_RTL:
15459                        mUserPaddingLeftInitial = padding.right;
15460                        mUserPaddingRightInitial = padding.left;
15461                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15462                        break;
15463                    case LAYOUT_DIRECTION_LTR:
15464                    default:
15465                        mUserPaddingLeftInitial = padding.left;
15466                        mUserPaddingRightInitial = padding.right;
15467                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15468                }
15469                mLeftPaddingDefined = false;
15470                mRightPaddingDefined = false;
15471            }
15472
15473            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15474            // if it has a different minimum size, we should layout again
15475            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15476                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15477                requestLayout = true;
15478            }
15479
15480            background.setCallback(this);
15481            if (background.isStateful()) {
15482                background.setState(getDrawableState());
15483            }
15484            background.setVisible(getVisibility() == VISIBLE, false);
15485            mBackground = background;
15486
15487            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15488                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15489                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15490                requestLayout = true;
15491            }
15492        } else {
15493            /* Remove the background */
15494            mBackground = null;
15495
15496            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15497                /*
15498                 * This view ONLY drew the background before and we're removing
15499                 * the background, so now it won't draw anything
15500                 * (hence we SKIP_DRAW)
15501                 */
15502                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15503                mPrivateFlags |= PFLAG_SKIP_DRAW;
15504            }
15505
15506            /*
15507             * When the background is set, we try to apply its padding to this
15508             * View. When the background is removed, we don't touch this View's
15509             * padding. This is noted in the Javadocs. Hence, we don't need to
15510             * requestLayout(), the invalidate() below is sufficient.
15511             */
15512
15513            // The old background's minimum size could have affected this
15514            // View's layout, so let's requestLayout
15515            requestLayout = true;
15516        }
15517
15518        computeOpaqueFlags();
15519
15520        if (requestLayout) {
15521            requestLayout();
15522        }
15523
15524        mBackgroundSizeChanged = true;
15525        invalidate(true);
15526    }
15527
15528    /**
15529     * Gets the background drawable
15530     *
15531     * @return The drawable used as the background for this view, if any.
15532     *
15533     * @see #setBackground(Drawable)
15534     *
15535     * @attr ref android.R.styleable#View_background
15536     */
15537    public Drawable getBackground() {
15538        return mBackground;
15539    }
15540
15541    /**
15542     * Sets the padding. The view may add on the space required to display
15543     * the scrollbars, depending on the style and visibility of the scrollbars.
15544     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15545     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15546     * from the values set in this call.
15547     *
15548     * @attr ref android.R.styleable#View_padding
15549     * @attr ref android.R.styleable#View_paddingBottom
15550     * @attr ref android.R.styleable#View_paddingLeft
15551     * @attr ref android.R.styleable#View_paddingRight
15552     * @attr ref android.R.styleable#View_paddingTop
15553     * @param left the left padding in pixels
15554     * @param top the top padding in pixels
15555     * @param right the right padding in pixels
15556     * @param bottom the bottom padding in pixels
15557     */
15558    public void setPadding(int left, int top, int right, int bottom) {
15559        resetResolvedPadding();
15560
15561        mUserPaddingStart = UNDEFINED_PADDING;
15562        mUserPaddingEnd = UNDEFINED_PADDING;
15563
15564        mUserPaddingLeftInitial = left;
15565        mUserPaddingRightInitial = right;
15566
15567        mLeftPaddingDefined = true;
15568        mRightPaddingDefined = true;
15569
15570        internalSetPadding(left, top, right, bottom);
15571    }
15572
15573    /**
15574     * @hide
15575     */
15576    protected void internalSetPadding(int left, int top, int right, int bottom) {
15577        mUserPaddingLeft = left;
15578        mUserPaddingRight = right;
15579        mUserPaddingBottom = bottom;
15580
15581        final int viewFlags = mViewFlags;
15582        boolean changed = false;
15583
15584        // Common case is there are no scroll bars.
15585        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15586            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15587                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15588                        ? 0 : getVerticalScrollbarWidth();
15589                switch (mVerticalScrollbarPosition) {
15590                    case SCROLLBAR_POSITION_DEFAULT:
15591                        if (isLayoutRtl()) {
15592                            left += offset;
15593                        } else {
15594                            right += offset;
15595                        }
15596                        break;
15597                    case SCROLLBAR_POSITION_RIGHT:
15598                        right += offset;
15599                        break;
15600                    case SCROLLBAR_POSITION_LEFT:
15601                        left += offset;
15602                        break;
15603                }
15604            }
15605            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15606                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15607                        ? 0 : getHorizontalScrollbarHeight();
15608            }
15609        }
15610
15611        if (mPaddingLeft != left) {
15612            changed = true;
15613            mPaddingLeft = left;
15614        }
15615        if (mPaddingTop != top) {
15616            changed = true;
15617            mPaddingTop = top;
15618        }
15619        if (mPaddingRight != right) {
15620            changed = true;
15621            mPaddingRight = right;
15622        }
15623        if (mPaddingBottom != bottom) {
15624            changed = true;
15625            mPaddingBottom = bottom;
15626        }
15627
15628        if (changed) {
15629            requestLayout();
15630        }
15631    }
15632
15633    /**
15634     * Sets the relative padding. The view may add on the space required to display
15635     * the scrollbars, depending on the style and visibility of the scrollbars.
15636     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15637     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15638     * from the values set in this call.
15639     *
15640     * @attr ref android.R.styleable#View_padding
15641     * @attr ref android.R.styleable#View_paddingBottom
15642     * @attr ref android.R.styleable#View_paddingStart
15643     * @attr ref android.R.styleable#View_paddingEnd
15644     * @attr ref android.R.styleable#View_paddingTop
15645     * @param start the start padding in pixels
15646     * @param top the top padding in pixels
15647     * @param end the end padding in pixels
15648     * @param bottom the bottom padding in pixels
15649     */
15650    public void setPaddingRelative(int start, int top, int end, int bottom) {
15651        resetResolvedPadding();
15652
15653        mUserPaddingStart = start;
15654        mUserPaddingEnd = end;
15655        mLeftPaddingDefined = true;
15656        mRightPaddingDefined = true;
15657
15658        switch(getLayoutDirection()) {
15659            case LAYOUT_DIRECTION_RTL:
15660                mUserPaddingLeftInitial = end;
15661                mUserPaddingRightInitial = start;
15662                internalSetPadding(end, top, start, bottom);
15663                break;
15664            case LAYOUT_DIRECTION_LTR:
15665            default:
15666                mUserPaddingLeftInitial = start;
15667                mUserPaddingRightInitial = end;
15668                internalSetPadding(start, top, end, bottom);
15669        }
15670    }
15671
15672    /**
15673     * Returns the top padding of this view.
15674     *
15675     * @return the top padding in pixels
15676     */
15677    public int getPaddingTop() {
15678        return mPaddingTop;
15679    }
15680
15681    /**
15682     * Returns the bottom padding of this view. If there are inset and enabled
15683     * scrollbars, this value may include the space required to display the
15684     * scrollbars as well.
15685     *
15686     * @return the bottom padding in pixels
15687     */
15688    public int getPaddingBottom() {
15689        return mPaddingBottom;
15690    }
15691
15692    /**
15693     * Returns the left padding of this view. If there are inset and enabled
15694     * scrollbars, this value may include the space required to display the
15695     * scrollbars as well.
15696     *
15697     * @return the left padding in pixels
15698     */
15699    public int getPaddingLeft() {
15700        if (!isPaddingResolved()) {
15701            resolvePadding();
15702        }
15703        return mPaddingLeft;
15704    }
15705
15706    /**
15707     * Returns the start padding of this view depending on its resolved layout direction.
15708     * If there are inset and enabled scrollbars, this value may include the space
15709     * required to display the scrollbars as well.
15710     *
15711     * @return the start padding in pixels
15712     */
15713    public int getPaddingStart() {
15714        if (!isPaddingResolved()) {
15715            resolvePadding();
15716        }
15717        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15718                mPaddingRight : mPaddingLeft;
15719    }
15720
15721    /**
15722     * Returns the right padding of this view. If there are inset and enabled
15723     * scrollbars, this value may include the space required to display the
15724     * scrollbars as well.
15725     *
15726     * @return the right padding in pixels
15727     */
15728    public int getPaddingRight() {
15729        if (!isPaddingResolved()) {
15730            resolvePadding();
15731        }
15732        return mPaddingRight;
15733    }
15734
15735    /**
15736     * Returns the end padding of this view depending on its resolved layout direction.
15737     * If there are inset and enabled scrollbars, this value may include the space
15738     * required to display the scrollbars as well.
15739     *
15740     * @return the end padding in pixels
15741     */
15742    public int getPaddingEnd() {
15743        if (!isPaddingResolved()) {
15744            resolvePadding();
15745        }
15746        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15747                mPaddingLeft : mPaddingRight;
15748    }
15749
15750    /**
15751     * Return if the padding as been set thru relative values
15752     * {@link #setPaddingRelative(int, int, int, int)} or thru
15753     * @attr ref android.R.styleable#View_paddingStart or
15754     * @attr ref android.R.styleable#View_paddingEnd
15755     *
15756     * @return true if the padding is relative or false if it is not.
15757     */
15758    public boolean isPaddingRelative() {
15759        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15760    }
15761
15762    Insets computeOpticalInsets() {
15763        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15764    }
15765
15766    /**
15767     * @hide
15768     */
15769    public void resetPaddingToInitialValues() {
15770        if (isRtlCompatibilityMode()) {
15771            mPaddingLeft = mUserPaddingLeftInitial;
15772            mPaddingRight = mUserPaddingRightInitial;
15773            return;
15774        }
15775        if (isLayoutRtl()) {
15776            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15777            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15778        } else {
15779            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15780            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15781        }
15782    }
15783
15784    /**
15785     * @hide
15786     */
15787    public Insets getOpticalInsets() {
15788        if (mLayoutInsets == null) {
15789            mLayoutInsets = computeOpticalInsets();
15790        }
15791        return mLayoutInsets;
15792    }
15793
15794    /**
15795     * Changes the selection state of this view. A view can be selected or not.
15796     * Note that selection is not the same as focus. Views are typically
15797     * selected in the context of an AdapterView like ListView or GridView;
15798     * the selected view is the view that is highlighted.
15799     *
15800     * @param selected true if the view must be selected, false otherwise
15801     */
15802    public void setSelected(boolean selected) {
15803        //noinspection DoubleNegation
15804        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15805            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15806            if (!selected) resetPressedState();
15807            invalidate(true);
15808            refreshDrawableState();
15809            dispatchSetSelected(selected);
15810            notifyViewAccessibilityStateChangedIfNeeded(
15811                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
15812        }
15813    }
15814
15815    /**
15816     * Dispatch setSelected to all of this View's children.
15817     *
15818     * @see #setSelected(boolean)
15819     *
15820     * @param selected The new selected state
15821     */
15822    protected void dispatchSetSelected(boolean selected) {
15823    }
15824
15825    /**
15826     * Indicates the selection state of this view.
15827     *
15828     * @return true if the view is selected, false otherwise
15829     */
15830    @ViewDebug.ExportedProperty
15831    public boolean isSelected() {
15832        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15833    }
15834
15835    /**
15836     * Changes the activated state of this view. A view can be activated or not.
15837     * Note that activation is not the same as selection.  Selection is
15838     * a transient property, representing the view (hierarchy) the user is
15839     * currently interacting with.  Activation is a longer-term state that the
15840     * user can move views in and out of.  For example, in a list view with
15841     * single or multiple selection enabled, the views in the current selection
15842     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15843     * here.)  The activated state is propagated down to children of the view it
15844     * is set on.
15845     *
15846     * @param activated true if the view must be activated, false otherwise
15847     */
15848    public void setActivated(boolean activated) {
15849        //noinspection DoubleNegation
15850        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15851            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15852            invalidate(true);
15853            refreshDrawableState();
15854            dispatchSetActivated(activated);
15855        }
15856    }
15857
15858    /**
15859     * Dispatch setActivated to all of this View's children.
15860     *
15861     * @see #setActivated(boolean)
15862     *
15863     * @param activated The new activated state
15864     */
15865    protected void dispatchSetActivated(boolean activated) {
15866    }
15867
15868    /**
15869     * Indicates the activation state of this view.
15870     *
15871     * @return true if the view is activated, false otherwise
15872     */
15873    @ViewDebug.ExportedProperty
15874    public boolean isActivated() {
15875        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15876    }
15877
15878    /**
15879     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15880     * observer can be used to get notifications when global events, like
15881     * layout, happen.
15882     *
15883     * The returned ViewTreeObserver observer is not guaranteed to remain
15884     * valid for the lifetime of this View. If the caller of this method keeps
15885     * a long-lived reference to ViewTreeObserver, it should always check for
15886     * the return value of {@link ViewTreeObserver#isAlive()}.
15887     *
15888     * @return The ViewTreeObserver for this view's hierarchy.
15889     */
15890    public ViewTreeObserver getViewTreeObserver() {
15891        if (mAttachInfo != null) {
15892            return mAttachInfo.mTreeObserver;
15893        }
15894        if (mFloatingTreeObserver == null) {
15895            mFloatingTreeObserver = new ViewTreeObserver();
15896        }
15897        return mFloatingTreeObserver;
15898    }
15899
15900    /**
15901     * <p>Finds the topmost view in the current view hierarchy.</p>
15902     *
15903     * @return the topmost view containing this view
15904     */
15905    public View getRootView() {
15906        if (mAttachInfo != null) {
15907            final View v = mAttachInfo.mRootView;
15908            if (v != null) {
15909                return v;
15910            }
15911        }
15912
15913        View parent = this;
15914
15915        while (parent.mParent != null && parent.mParent instanceof View) {
15916            parent = (View) parent.mParent;
15917        }
15918
15919        return parent;
15920    }
15921
15922    /**
15923     * Transforms a motion event from view-local coordinates to on-screen
15924     * coordinates.
15925     *
15926     * @param ev the view-local motion event
15927     * @return false if the transformation could not be applied
15928     * @hide
15929     */
15930    public boolean toGlobalMotionEvent(MotionEvent ev) {
15931        final AttachInfo info = mAttachInfo;
15932        if (info == null) {
15933            return false;
15934        }
15935
15936        final Matrix m = info.mTmpMatrix;
15937        m.set(Matrix.IDENTITY_MATRIX);
15938        transformMatrixToGlobal(m);
15939        ev.transform(m);
15940        return true;
15941    }
15942
15943    /**
15944     * Transforms a motion event from on-screen coordinates to view-local
15945     * coordinates.
15946     *
15947     * @param ev the on-screen motion event
15948     * @return false if the transformation could not be applied
15949     * @hide
15950     */
15951    public boolean toLocalMotionEvent(MotionEvent ev) {
15952        final AttachInfo info = mAttachInfo;
15953        if (info == null) {
15954            return false;
15955        }
15956
15957        final Matrix m = info.mTmpMatrix;
15958        m.set(Matrix.IDENTITY_MATRIX);
15959        transformMatrixToLocal(m);
15960        ev.transform(m);
15961        return true;
15962    }
15963
15964    /**
15965     * Modifies the input matrix such that it maps view-local coordinates to
15966     * on-screen coordinates.
15967     *
15968     * @param m input matrix to modify
15969     */
15970    void transformMatrixToGlobal(Matrix m) {
15971        final ViewParent parent = mParent;
15972        if (parent instanceof View) {
15973            final View vp = (View) parent;
15974            vp.transformMatrixToGlobal(m);
15975            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
15976        } else if (parent instanceof ViewRootImpl) {
15977            final ViewRootImpl vr = (ViewRootImpl) parent;
15978            vr.transformMatrixToGlobal(m);
15979            m.postTranslate(0, -vr.mCurScrollY);
15980        }
15981
15982        m.postTranslate(mLeft, mTop);
15983
15984        if (!hasIdentityMatrix()) {
15985            m.postConcat(getMatrix());
15986        }
15987    }
15988
15989    /**
15990     * Modifies the input matrix such that it maps on-screen coordinates to
15991     * view-local coordinates.
15992     *
15993     * @param m input matrix to modify
15994     */
15995    void transformMatrixToLocal(Matrix m) {
15996        final ViewParent parent = mParent;
15997        if (parent instanceof View) {
15998            final View vp = (View) parent;
15999            vp.transformMatrixToLocal(m);
16000            m.preTranslate(vp.mScrollX, vp.mScrollY);
16001        } else if (parent instanceof ViewRootImpl) {
16002            final ViewRootImpl vr = (ViewRootImpl) parent;
16003            vr.transformMatrixToLocal(m);
16004            m.preTranslate(0, vr.mCurScrollY);
16005        }
16006
16007        m.preTranslate(-mLeft, -mTop);
16008
16009        if (!hasIdentityMatrix()) {
16010            m.preConcat(getInverseMatrix());
16011        }
16012    }
16013
16014    /**
16015     * <p>Computes the coordinates of this view on the screen. The argument
16016     * must be an array of two integers. After the method returns, the array
16017     * contains the x and y location in that order.</p>
16018     *
16019     * @param location an array of two integers in which to hold the coordinates
16020     */
16021    public void getLocationOnScreen(int[] location) {
16022        getLocationInWindow(location);
16023
16024        final AttachInfo info = mAttachInfo;
16025        if (info != null) {
16026            location[0] += info.mWindowLeft;
16027            location[1] += info.mWindowTop;
16028        }
16029    }
16030
16031    /**
16032     * <p>Computes the coordinates of this view in its window. The argument
16033     * must be an array of two integers. After the method returns, the array
16034     * contains the x and y location in that order.</p>
16035     *
16036     * @param location an array of two integers in which to hold the coordinates
16037     */
16038    public void getLocationInWindow(int[] location) {
16039        if (location == null || location.length < 2) {
16040            throw new IllegalArgumentException("location must be an array of two integers");
16041        }
16042
16043        if (mAttachInfo == null) {
16044            // When the view is not attached to a window, this method does not make sense
16045            location[0] = location[1] = 0;
16046            return;
16047        }
16048
16049        float[] position = mAttachInfo.mTmpTransformLocation;
16050        position[0] = position[1] = 0.0f;
16051
16052        if (!hasIdentityMatrix()) {
16053            getMatrix().mapPoints(position);
16054        }
16055
16056        position[0] += mLeft;
16057        position[1] += mTop;
16058
16059        ViewParent viewParent = mParent;
16060        while (viewParent instanceof View) {
16061            final View view = (View) viewParent;
16062
16063            position[0] -= view.mScrollX;
16064            position[1] -= view.mScrollY;
16065
16066            if (!view.hasIdentityMatrix()) {
16067                view.getMatrix().mapPoints(position);
16068            }
16069
16070            position[0] += view.mLeft;
16071            position[1] += view.mTop;
16072
16073            viewParent = view.mParent;
16074         }
16075
16076        if (viewParent instanceof ViewRootImpl) {
16077            // *cough*
16078            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16079            position[1] -= vr.mCurScrollY;
16080        }
16081
16082        location[0] = (int) (position[0] + 0.5f);
16083        location[1] = (int) (position[1] + 0.5f);
16084    }
16085
16086    /**
16087     * {@hide}
16088     * @param id the id of the view to be found
16089     * @return the view of the specified id, null if cannot be found
16090     */
16091    protected View findViewTraversal(int id) {
16092        if (id == mID) {
16093            return this;
16094        }
16095        return null;
16096    }
16097
16098    /**
16099     * {@hide}
16100     * @param tag the tag of the view to be found
16101     * @return the view of specified tag, null if cannot be found
16102     */
16103    protected View findViewWithTagTraversal(Object tag) {
16104        if (tag != null && tag.equals(mTag)) {
16105            return this;
16106        }
16107        return null;
16108    }
16109
16110    /**
16111     * {@hide}
16112     * @param predicate The predicate to evaluate.
16113     * @param childToSkip If not null, ignores this child during the recursive traversal.
16114     * @return The first view that matches the predicate or null.
16115     */
16116    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16117        if (predicate.apply(this)) {
16118            return this;
16119        }
16120        return null;
16121    }
16122
16123    /**
16124     * Look for a child view with the given id.  If this view has the given
16125     * id, return this view.
16126     *
16127     * @param id The id to search for.
16128     * @return The view that has the given id in the hierarchy or null
16129     */
16130    public final View findViewById(int id) {
16131        if (id < 0) {
16132            return null;
16133        }
16134        return findViewTraversal(id);
16135    }
16136
16137    /**
16138     * Finds a view by its unuque and stable accessibility id.
16139     *
16140     * @param accessibilityId The searched accessibility id.
16141     * @return The found view.
16142     */
16143    final View findViewByAccessibilityId(int accessibilityId) {
16144        if (accessibilityId < 0) {
16145            return null;
16146        }
16147        return findViewByAccessibilityIdTraversal(accessibilityId);
16148    }
16149
16150    /**
16151     * Performs the traversal to find a view by its unuque and stable accessibility id.
16152     *
16153     * <strong>Note:</strong>This method does not stop at the root namespace
16154     * boundary since the user can touch the screen at an arbitrary location
16155     * potentially crossing the root namespace bounday which will send an
16156     * accessibility event to accessibility services and they should be able
16157     * to obtain the event source. Also accessibility ids are guaranteed to be
16158     * unique in the window.
16159     *
16160     * @param accessibilityId The accessibility id.
16161     * @return The found view.
16162     *
16163     * @hide
16164     */
16165    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16166        if (getAccessibilityViewId() == accessibilityId) {
16167            return this;
16168        }
16169        return null;
16170    }
16171
16172    /**
16173     * Look for a child view with the given tag.  If this view has the given
16174     * tag, return this view.
16175     *
16176     * @param tag The tag to search for, using "tag.equals(getTag())".
16177     * @return The View that has the given tag in the hierarchy or null
16178     */
16179    public final View findViewWithTag(Object tag) {
16180        if (tag == null) {
16181            return null;
16182        }
16183        return findViewWithTagTraversal(tag);
16184    }
16185
16186    /**
16187     * {@hide}
16188     * Look for a child view that matches the specified predicate.
16189     * If this view matches the predicate, return this view.
16190     *
16191     * @param predicate The predicate to evaluate.
16192     * @return The first view that matches the predicate or null.
16193     */
16194    public final View findViewByPredicate(Predicate<View> predicate) {
16195        return findViewByPredicateTraversal(predicate, null);
16196    }
16197
16198    /**
16199     * {@hide}
16200     * Look for a child view that matches the specified predicate,
16201     * starting with the specified view and its descendents and then
16202     * recusively searching the ancestors and siblings of that view
16203     * until this view is reached.
16204     *
16205     * This method is useful in cases where the predicate does not match
16206     * a single unique view (perhaps multiple views use the same id)
16207     * and we are trying to find the view that is "closest" in scope to the
16208     * starting view.
16209     *
16210     * @param start The view to start from.
16211     * @param predicate The predicate to evaluate.
16212     * @return The first view that matches the predicate or null.
16213     */
16214    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16215        View childToSkip = null;
16216        for (;;) {
16217            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16218            if (view != null || start == this) {
16219                return view;
16220            }
16221
16222            ViewParent parent = start.getParent();
16223            if (parent == null || !(parent instanceof View)) {
16224                return null;
16225            }
16226
16227            childToSkip = start;
16228            start = (View) parent;
16229        }
16230    }
16231
16232    /**
16233     * Sets the identifier for this view. The identifier does not have to be
16234     * unique in this view's hierarchy. The identifier should be a positive
16235     * number.
16236     *
16237     * @see #NO_ID
16238     * @see #getId()
16239     * @see #findViewById(int)
16240     *
16241     * @param id a number used to identify the view
16242     *
16243     * @attr ref android.R.styleable#View_id
16244     */
16245    public void setId(int id) {
16246        mID = id;
16247        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16248            mID = generateViewId();
16249        }
16250    }
16251
16252    /**
16253     * {@hide}
16254     *
16255     * @param isRoot true if the view belongs to the root namespace, false
16256     *        otherwise
16257     */
16258    public void setIsRootNamespace(boolean isRoot) {
16259        if (isRoot) {
16260            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16261        } else {
16262            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16263        }
16264    }
16265
16266    /**
16267     * {@hide}
16268     *
16269     * @return true if the view belongs to the root namespace, false otherwise
16270     */
16271    public boolean isRootNamespace() {
16272        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16273    }
16274
16275    /**
16276     * Returns this view's identifier.
16277     *
16278     * @return a positive integer used to identify the view or {@link #NO_ID}
16279     *         if the view has no ID
16280     *
16281     * @see #setId(int)
16282     * @see #findViewById(int)
16283     * @attr ref android.R.styleable#View_id
16284     */
16285    @ViewDebug.CapturedViewProperty
16286    public int getId() {
16287        return mID;
16288    }
16289
16290    /**
16291     * Returns this view's tag.
16292     *
16293     * @return the Object stored in this view as a tag
16294     *
16295     * @see #setTag(Object)
16296     * @see #getTag(int)
16297     */
16298    @ViewDebug.ExportedProperty
16299    public Object getTag() {
16300        return mTag;
16301    }
16302
16303    /**
16304     * Sets the tag associated with this view. A tag can be used to mark
16305     * a view in its hierarchy and does not have to be unique within the
16306     * hierarchy. Tags can also be used to store data within a view without
16307     * resorting to another data structure.
16308     *
16309     * @param tag an Object to tag the view with
16310     *
16311     * @see #getTag()
16312     * @see #setTag(int, Object)
16313     */
16314    public void setTag(final Object tag) {
16315        mTag = tag;
16316    }
16317
16318    /**
16319     * Returns the tag associated with this view and the specified key.
16320     *
16321     * @param key The key identifying the tag
16322     *
16323     * @return the Object stored in this view as a tag
16324     *
16325     * @see #setTag(int, Object)
16326     * @see #getTag()
16327     */
16328    public Object getTag(int key) {
16329        if (mKeyedTags != null) return mKeyedTags.get(key);
16330        return null;
16331    }
16332
16333    /**
16334     * Sets a tag associated with this view and a key. A tag can be used
16335     * to mark a view in its hierarchy and does not have to be unique within
16336     * the hierarchy. Tags can also be used to store data within a view
16337     * without resorting to another data structure.
16338     *
16339     * The specified key should be an id declared in the resources of the
16340     * application to ensure it is unique (see the <a
16341     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16342     * Keys identified as belonging to
16343     * the Android framework or not associated with any package will cause
16344     * an {@link IllegalArgumentException} to be thrown.
16345     *
16346     * @param key The key identifying the tag
16347     * @param tag An Object to tag the view with
16348     *
16349     * @throws IllegalArgumentException If they specified key is not valid
16350     *
16351     * @see #setTag(Object)
16352     * @see #getTag(int)
16353     */
16354    public void setTag(int key, final Object tag) {
16355        // If the package id is 0x00 or 0x01, it's either an undefined package
16356        // or a framework id
16357        if ((key >>> 24) < 2) {
16358            throw new IllegalArgumentException("The key must be an application-specific "
16359                    + "resource id.");
16360        }
16361
16362        setKeyedTag(key, tag);
16363    }
16364
16365    /**
16366     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16367     * framework id.
16368     *
16369     * @hide
16370     */
16371    public void setTagInternal(int key, Object tag) {
16372        if ((key >>> 24) != 0x1) {
16373            throw new IllegalArgumentException("The key must be a framework-specific "
16374                    + "resource id.");
16375        }
16376
16377        setKeyedTag(key, tag);
16378    }
16379
16380    private void setKeyedTag(int key, Object tag) {
16381        if (mKeyedTags == null) {
16382            mKeyedTags = new SparseArray<Object>(2);
16383        }
16384
16385        mKeyedTags.put(key, tag);
16386    }
16387
16388    /**
16389     * Prints information about this view in the log output, with the tag
16390     * {@link #VIEW_LOG_TAG}.
16391     *
16392     * @hide
16393     */
16394    public void debug() {
16395        debug(0);
16396    }
16397
16398    /**
16399     * Prints information about this view in the log output, with the tag
16400     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16401     * indentation defined by the <code>depth</code>.
16402     *
16403     * @param depth the indentation level
16404     *
16405     * @hide
16406     */
16407    protected void debug(int depth) {
16408        String output = debugIndent(depth - 1);
16409
16410        output += "+ " + this;
16411        int id = getId();
16412        if (id != -1) {
16413            output += " (id=" + id + ")";
16414        }
16415        Object tag = getTag();
16416        if (tag != null) {
16417            output += " (tag=" + tag + ")";
16418        }
16419        Log.d(VIEW_LOG_TAG, output);
16420
16421        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16422            output = debugIndent(depth) + " FOCUSED";
16423            Log.d(VIEW_LOG_TAG, output);
16424        }
16425
16426        output = debugIndent(depth);
16427        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16428                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16429                + "} ";
16430        Log.d(VIEW_LOG_TAG, output);
16431
16432        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16433                || mPaddingBottom != 0) {
16434            output = debugIndent(depth);
16435            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16436                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16437            Log.d(VIEW_LOG_TAG, output);
16438        }
16439
16440        output = debugIndent(depth);
16441        output += "mMeasureWidth=" + mMeasuredWidth +
16442                " mMeasureHeight=" + mMeasuredHeight;
16443        Log.d(VIEW_LOG_TAG, output);
16444
16445        output = debugIndent(depth);
16446        if (mLayoutParams == null) {
16447            output += "BAD! no layout params";
16448        } else {
16449            output = mLayoutParams.debug(output);
16450        }
16451        Log.d(VIEW_LOG_TAG, output);
16452
16453        output = debugIndent(depth);
16454        output += "flags={";
16455        output += View.printFlags(mViewFlags);
16456        output += "}";
16457        Log.d(VIEW_LOG_TAG, output);
16458
16459        output = debugIndent(depth);
16460        output += "privateFlags={";
16461        output += View.printPrivateFlags(mPrivateFlags);
16462        output += "}";
16463        Log.d(VIEW_LOG_TAG, output);
16464    }
16465
16466    /**
16467     * Creates a string of whitespaces used for indentation.
16468     *
16469     * @param depth the indentation level
16470     * @return a String containing (depth * 2 + 3) * 2 white spaces
16471     *
16472     * @hide
16473     */
16474    protected static String debugIndent(int depth) {
16475        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16476        for (int i = 0; i < (depth * 2) + 3; i++) {
16477            spaces.append(' ').append(' ');
16478        }
16479        return spaces.toString();
16480    }
16481
16482    /**
16483     * <p>Return the offset of the widget's text baseline from the widget's top
16484     * boundary. If this widget does not support baseline alignment, this
16485     * method returns -1. </p>
16486     *
16487     * @return the offset of the baseline within the widget's bounds or -1
16488     *         if baseline alignment is not supported
16489     */
16490    @ViewDebug.ExportedProperty(category = "layout")
16491    public int getBaseline() {
16492        return -1;
16493    }
16494
16495    /**
16496     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16497     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16498     * a layout pass.
16499     *
16500     * @return whether the view hierarchy is currently undergoing a layout pass
16501     */
16502    public boolean isInLayout() {
16503        ViewRootImpl viewRoot = getViewRootImpl();
16504        return (viewRoot != null && viewRoot.isInLayout());
16505    }
16506
16507    /**
16508     * Call this when something has changed which has invalidated the
16509     * layout of this view. This will schedule a layout pass of the view
16510     * tree. This should not be called while the view hierarchy is currently in a layout
16511     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16512     * end of the current layout pass (and then layout will run again) or after the current
16513     * frame is drawn and the next layout occurs.
16514     *
16515     * <p>Subclasses which override this method should call the superclass method to
16516     * handle possible request-during-layout errors correctly.</p>
16517     */
16518    public void requestLayout() {
16519        if (mMeasureCache != null) mMeasureCache.clear();
16520
16521        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16522            // Only trigger request-during-layout logic if this is the view requesting it,
16523            // not the views in its parent hierarchy
16524            ViewRootImpl viewRoot = getViewRootImpl();
16525            if (viewRoot != null && viewRoot.isInLayout()) {
16526                if (!viewRoot.requestLayoutDuringLayout(this)) {
16527                    return;
16528                }
16529            }
16530            mAttachInfo.mViewRequestingLayout = this;
16531        }
16532
16533        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16534        mPrivateFlags |= PFLAG_INVALIDATED;
16535
16536        if (mParent != null && !mParent.isLayoutRequested()) {
16537            mParent.requestLayout();
16538        }
16539        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16540            mAttachInfo.mViewRequestingLayout = null;
16541        }
16542    }
16543
16544    /**
16545     * Forces this view to be laid out during the next layout pass.
16546     * This method does not call requestLayout() or forceLayout()
16547     * on the parent.
16548     */
16549    public void forceLayout() {
16550        if (mMeasureCache != null) mMeasureCache.clear();
16551
16552        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16553        mPrivateFlags |= PFLAG_INVALIDATED;
16554    }
16555
16556    /**
16557     * <p>
16558     * This is called to find out how big a view should be. The parent
16559     * supplies constraint information in the width and height parameters.
16560     * </p>
16561     *
16562     * <p>
16563     * The actual measurement work of a view is performed in
16564     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16565     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16566     * </p>
16567     *
16568     *
16569     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16570     *        parent
16571     * @param heightMeasureSpec Vertical space requirements as imposed by the
16572     *        parent
16573     *
16574     * @see #onMeasure(int, int)
16575     */
16576    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16577        boolean optical = isLayoutModeOptical(this);
16578        if (optical != isLayoutModeOptical(mParent)) {
16579            Insets insets = getOpticalInsets();
16580            int oWidth  = insets.left + insets.right;
16581            int oHeight = insets.top  + insets.bottom;
16582            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16583            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16584        }
16585
16586        // Suppress sign extension for the low bytes
16587        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16588        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16589
16590        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16591                widthMeasureSpec != mOldWidthMeasureSpec ||
16592                heightMeasureSpec != mOldHeightMeasureSpec) {
16593
16594            // first clears the measured dimension flag
16595            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16596
16597            resolveRtlPropertiesIfNeeded();
16598
16599            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16600                    mMeasureCache.indexOfKey(key);
16601            if (cacheIndex < 0 || sIgnoreMeasureCache) {
16602                // measure ourselves, this should set the measured dimension flag back
16603                onMeasure(widthMeasureSpec, heightMeasureSpec);
16604                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16605            } else {
16606                long value = mMeasureCache.valueAt(cacheIndex);
16607                // Casting a long to int drops the high 32 bits, no mask needed
16608                setMeasuredDimension((int) (value >> 32), (int) value);
16609                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16610            }
16611
16612            // flag not set, setMeasuredDimension() was not invoked, we raise
16613            // an exception to warn the developer
16614            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16615                throw new IllegalStateException("onMeasure() did not set the"
16616                        + " measured dimension by calling"
16617                        + " setMeasuredDimension()");
16618            }
16619
16620            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16621        }
16622
16623        mOldWidthMeasureSpec = widthMeasureSpec;
16624        mOldHeightMeasureSpec = heightMeasureSpec;
16625
16626        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16627                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16628    }
16629
16630    /**
16631     * <p>
16632     * Measure the view and its content to determine the measured width and the
16633     * measured height. This method is invoked by {@link #measure(int, int)} and
16634     * should be overriden by subclasses to provide accurate and efficient
16635     * measurement of their contents.
16636     * </p>
16637     *
16638     * <p>
16639     * <strong>CONTRACT:</strong> When overriding this method, you
16640     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16641     * measured width and height of this view. Failure to do so will trigger an
16642     * <code>IllegalStateException</code>, thrown by
16643     * {@link #measure(int, int)}. Calling the superclass'
16644     * {@link #onMeasure(int, int)} is a valid use.
16645     * </p>
16646     *
16647     * <p>
16648     * The base class implementation of measure defaults to the background size,
16649     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16650     * override {@link #onMeasure(int, int)} to provide better measurements of
16651     * their content.
16652     * </p>
16653     *
16654     * <p>
16655     * If this method is overridden, it is the subclass's responsibility to make
16656     * sure the measured height and width are at least the view's minimum height
16657     * and width ({@link #getSuggestedMinimumHeight()} and
16658     * {@link #getSuggestedMinimumWidth()}).
16659     * </p>
16660     *
16661     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16662     *                         The requirements are encoded with
16663     *                         {@link android.view.View.MeasureSpec}.
16664     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16665     *                         The requirements are encoded with
16666     *                         {@link android.view.View.MeasureSpec}.
16667     *
16668     * @see #getMeasuredWidth()
16669     * @see #getMeasuredHeight()
16670     * @see #setMeasuredDimension(int, int)
16671     * @see #getSuggestedMinimumHeight()
16672     * @see #getSuggestedMinimumWidth()
16673     * @see android.view.View.MeasureSpec#getMode(int)
16674     * @see android.view.View.MeasureSpec#getSize(int)
16675     */
16676    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16677        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16678                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16679    }
16680
16681    /**
16682     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16683     * measured width and measured height. Failing to do so will trigger an
16684     * exception at measurement time.</p>
16685     *
16686     * @param measuredWidth The measured width of this view.  May be a complex
16687     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16688     * {@link #MEASURED_STATE_TOO_SMALL}.
16689     * @param measuredHeight The measured height of this view.  May be a complex
16690     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16691     * {@link #MEASURED_STATE_TOO_SMALL}.
16692     */
16693    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16694        boolean optical = isLayoutModeOptical(this);
16695        if (optical != isLayoutModeOptical(mParent)) {
16696            Insets insets = getOpticalInsets();
16697            int opticalWidth  = insets.left + insets.right;
16698            int opticalHeight = insets.top  + insets.bottom;
16699
16700            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16701            measuredHeight += optical ? opticalHeight : -opticalHeight;
16702        }
16703        mMeasuredWidth = measuredWidth;
16704        mMeasuredHeight = measuredHeight;
16705
16706        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16707    }
16708
16709    /**
16710     * Merge two states as returned by {@link #getMeasuredState()}.
16711     * @param curState The current state as returned from a view or the result
16712     * of combining multiple views.
16713     * @param newState The new view state to combine.
16714     * @return Returns a new integer reflecting the combination of the two
16715     * states.
16716     */
16717    public static int combineMeasuredStates(int curState, int newState) {
16718        return curState | newState;
16719    }
16720
16721    /**
16722     * Version of {@link #resolveSizeAndState(int, int, int)}
16723     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16724     */
16725    public static int resolveSize(int size, int measureSpec) {
16726        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16727    }
16728
16729    /**
16730     * Utility to reconcile a desired size and state, with constraints imposed
16731     * by a MeasureSpec.  Will take the desired size, unless a different size
16732     * is imposed by the constraints.  The returned value is a compound integer,
16733     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16734     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16735     * size is smaller than the size the view wants to be.
16736     *
16737     * @param size How big the view wants to be
16738     * @param measureSpec Constraints imposed by the parent
16739     * @return Size information bit mask as defined by
16740     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16741     */
16742    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16743        int result = size;
16744        int specMode = MeasureSpec.getMode(measureSpec);
16745        int specSize =  MeasureSpec.getSize(measureSpec);
16746        switch (specMode) {
16747        case MeasureSpec.UNSPECIFIED:
16748            result = size;
16749            break;
16750        case MeasureSpec.AT_MOST:
16751            if (specSize < size) {
16752                result = specSize | MEASURED_STATE_TOO_SMALL;
16753            } else {
16754                result = size;
16755            }
16756            break;
16757        case MeasureSpec.EXACTLY:
16758            result = specSize;
16759            break;
16760        }
16761        return result | (childMeasuredState&MEASURED_STATE_MASK);
16762    }
16763
16764    /**
16765     * Utility to return a default size. Uses the supplied size if the
16766     * MeasureSpec imposed no constraints. Will get larger if allowed
16767     * by the MeasureSpec.
16768     *
16769     * @param size Default size for this view
16770     * @param measureSpec Constraints imposed by the parent
16771     * @return The size this view should be.
16772     */
16773    public static int getDefaultSize(int size, int measureSpec) {
16774        int result = size;
16775        int specMode = MeasureSpec.getMode(measureSpec);
16776        int specSize = MeasureSpec.getSize(measureSpec);
16777
16778        switch (specMode) {
16779        case MeasureSpec.UNSPECIFIED:
16780            result = size;
16781            break;
16782        case MeasureSpec.AT_MOST:
16783        case MeasureSpec.EXACTLY:
16784            result = specSize;
16785            break;
16786        }
16787        return result;
16788    }
16789
16790    /**
16791     * Returns the suggested minimum height that the view should use. This
16792     * returns the maximum of the view's minimum height
16793     * and the background's minimum height
16794     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16795     * <p>
16796     * When being used in {@link #onMeasure(int, int)}, the caller should still
16797     * ensure the returned height is within the requirements of the parent.
16798     *
16799     * @return The suggested minimum height of the view.
16800     */
16801    protected int getSuggestedMinimumHeight() {
16802        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16803
16804    }
16805
16806    /**
16807     * Returns the suggested minimum width that the view should use. This
16808     * returns the maximum of the view's minimum width)
16809     * and the background's minimum width
16810     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16811     * <p>
16812     * When being used in {@link #onMeasure(int, int)}, the caller should still
16813     * ensure the returned width is within the requirements of the parent.
16814     *
16815     * @return The suggested minimum width of the view.
16816     */
16817    protected int getSuggestedMinimumWidth() {
16818        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16819    }
16820
16821    /**
16822     * Returns the minimum height of the view.
16823     *
16824     * @return the minimum height the view will try to be.
16825     *
16826     * @see #setMinimumHeight(int)
16827     *
16828     * @attr ref android.R.styleable#View_minHeight
16829     */
16830    public int getMinimumHeight() {
16831        return mMinHeight;
16832    }
16833
16834    /**
16835     * Sets the minimum height of the view. It is not guaranteed the view will
16836     * be able to achieve this minimum height (for example, if its parent layout
16837     * constrains it with less available height).
16838     *
16839     * @param minHeight The minimum height the view will try to be.
16840     *
16841     * @see #getMinimumHeight()
16842     *
16843     * @attr ref android.R.styleable#View_minHeight
16844     */
16845    public void setMinimumHeight(int minHeight) {
16846        mMinHeight = minHeight;
16847        requestLayout();
16848    }
16849
16850    /**
16851     * Returns the minimum width of the view.
16852     *
16853     * @return the minimum width the view will try to be.
16854     *
16855     * @see #setMinimumWidth(int)
16856     *
16857     * @attr ref android.R.styleable#View_minWidth
16858     */
16859    public int getMinimumWidth() {
16860        return mMinWidth;
16861    }
16862
16863    /**
16864     * Sets the minimum width of the view. It is not guaranteed the view will
16865     * be able to achieve this minimum width (for example, if its parent layout
16866     * constrains it with less available width).
16867     *
16868     * @param minWidth The minimum width the view will try to be.
16869     *
16870     * @see #getMinimumWidth()
16871     *
16872     * @attr ref android.R.styleable#View_minWidth
16873     */
16874    public void setMinimumWidth(int minWidth) {
16875        mMinWidth = minWidth;
16876        requestLayout();
16877
16878    }
16879
16880    /**
16881     * Get the animation currently associated with this view.
16882     *
16883     * @return The animation that is currently playing or
16884     *         scheduled to play for this view.
16885     */
16886    public Animation getAnimation() {
16887        return mCurrentAnimation;
16888    }
16889
16890    /**
16891     * Start the specified animation now.
16892     *
16893     * @param animation the animation to start now
16894     */
16895    public void startAnimation(Animation animation) {
16896        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16897        setAnimation(animation);
16898        invalidateParentCaches();
16899        invalidate(true);
16900    }
16901
16902    /**
16903     * Cancels any animations for this view.
16904     */
16905    public void clearAnimation() {
16906        if (mCurrentAnimation != null) {
16907            mCurrentAnimation.detach();
16908        }
16909        mCurrentAnimation = null;
16910        invalidateParentIfNeeded();
16911    }
16912
16913    /**
16914     * Sets the next animation to play for this view.
16915     * If you want the animation to play immediately, use
16916     * {@link #startAnimation(android.view.animation.Animation)} instead.
16917     * This method provides allows fine-grained
16918     * control over the start time and invalidation, but you
16919     * must make sure that 1) the animation has a start time set, and
16920     * 2) the view's parent (which controls animations on its children)
16921     * will be invalidated when the animation is supposed to
16922     * start.
16923     *
16924     * @param animation The next animation, or null.
16925     */
16926    public void setAnimation(Animation animation) {
16927        mCurrentAnimation = animation;
16928
16929        if (animation != null) {
16930            // If the screen is off assume the animation start time is now instead of
16931            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16932            // would cause the animation to start when the screen turns back on
16933            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16934                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16935                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16936            }
16937            animation.reset();
16938        }
16939    }
16940
16941    /**
16942     * Invoked by a parent ViewGroup to notify the start of the animation
16943     * currently associated with this view. If you override this method,
16944     * always call super.onAnimationStart();
16945     *
16946     * @see #setAnimation(android.view.animation.Animation)
16947     * @see #getAnimation()
16948     */
16949    protected void onAnimationStart() {
16950        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16951    }
16952
16953    /**
16954     * Invoked by a parent ViewGroup to notify the end of the animation
16955     * currently associated with this view. If you override this method,
16956     * always call super.onAnimationEnd();
16957     *
16958     * @see #setAnimation(android.view.animation.Animation)
16959     * @see #getAnimation()
16960     */
16961    protected void onAnimationEnd() {
16962        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16963    }
16964
16965    /**
16966     * Invoked if there is a Transform that involves alpha. Subclass that can
16967     * draw themselves with the specified alpha should return true, and then
16968     * respect that alpha when their onDraw() is called. If this returns false
16969     * then the view may be redirected to draw into an offscreen buffer to
16970     * fulfill the request, which will look fine, but may be slower than if the
16971     * subclass handles it internally. The default implementation returns false.
16972     *
16973     * @param alpha The alpha (0..255) to apply to the view's drawing
16974     * @return true if the view can draw with the specified alpha.
16975     */
16976    protected boolean onSetAlpha(int alpha) {
16977        return false;
16978    }
16979
16980    /**
16981     * This is used by the RootView to perform an optimization when
16982     * the view hierarchy contains one or several SurfaceView.
16983     * SurfaceView is always considered transparent, but its children are not,
16984     * therefore all View objects remove themselves from the global transparent
16985     * region (passed as a parameter to this function).
16986     *
16987     * @param region The transparent region for this ViewAncestor (window).
16988     *
16989     * @return Returns true if the effective visibility of the view at this
16990     * point is opaque, regardless of the transparent region; returns false
16991     * if it is possible for underlying windows to be seen behind the view.
16992     *
16993     * {@hide}
16994     */
16995    public boolean gatherTransparentRegion(Region region) {
16996        final AttachInfo attachInfo = mAttachInfo;
16997        if (region != null && attachInfo != null) {
16998            final int pflags = mPrivateFlags;
16999            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17000                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17001                // remove it from the transparent region.
17002                final int[] location = attachInfo.mTransparentLocation;
17003                getLocationInWindow(location);
17004                region.op(location[0], location[1], location[0] + mRight - mLeft,
17005                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17006            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17007                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17008                // exists, so we remove the background drawable's non-transparent
17009                // parts from this transparent region.
17010                applyDrawableToTransparentRegion(mBackground, region);
17011            }
17012        }
17013        return true;
17014    }
17015
17016    /**
17017     * Play a sound effect for this view.
17018     *
17019     * <p>The framework will play sound effects for some built in actions, such as
17020     * clicking, but you may wish to play these effects in your widget,
17021     * for instance, for internal navigation.
17022     *
17023     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17024     * {@link #isSoundEffectsEnabled()} is true.
17025     *
17026     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17027     */
17028    public void playSoundEffect(int soundConstant) {
17029        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17030            return;
17031        }
17032        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17033    }
17034
17035    /**
17036     * BZZZTT!!1!
17037     *
17038     * <p>Provide haptic feedback to the user for this view.
17039     *
17040     * <p>The framework will provide haptic feedback for some built in actions,
17041     * such as long presses, but you may wish to provide feedback for your
17042     * own widget.
17043     *
17044     * <p>The feedback will only be performed if
17045     * {@link #isHapticFeedbackEnabled()} is true.
17046     *
17047     * @param feedbackConstant One of the constants defined in
17048     * {@link HapticFeedbackConstants}
17049     */
17050    public boolean performHapticFeedback(int feedbackConstant) {
17051        return performHapticFeedback(feedbackConstant, 0);
17052    }
17053
17054    /**
17055     * BZZZTT!!1!
17056     *
17057     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17058     *
17059     * @param feedbackConstant One of the constants defined in
17060     * {@link HapticFeedbackConstants}
17061     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17062     */
17063    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17064        if (mAttachInfo == null) {
17065            return false;
17066        }
17067        //noinspection SimplifiableIfStatement
17068        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17069                && !isHapticFeedbackEnabled()) {
17070            return false;
17071        }
17072        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17073                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17074    }
17075
17076    /**
17077     * Request that the visibility of the status bar or other screen/window
17078     * decorations be changed.
17079     *
17080     * <p>This method is used to put the over device UI into temporary modes
17081     * where the user's attention is focused more on the application content,
17082     * by dimming or hiding surrounding system affordances.  This is typically
17083     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17084     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17085     * to be placed behind the action bar (and with these flags other system
17086     * affordances) so that smooth transitions between hiding and showing them
17087     * can be done.
17088     *
17089     * <p>Two representative examples of the use of system UI visibility is
17090     * implementing a content browsing application (like a magazine reader)
17091     * and a video playing application.
17092     *
17093     * <p>The first code shows a typical implementation of a View in a content
17094     * browsing application.  In this implementation, the application goes
17095     * into a content-oriented mode by hiding the status bar and action bar,
17096     * and putting the navigation elements into lights out mode.  The user can
17097     * then interact with content while in this mode.  Such an application should
17098     * provide an easy way for the user to toggle out of the mode (such as to
17099     * check information in the status bar or access notifications).  In the
17100     * implementation here, this is done simply by tapping on the content.
17101     *
17102     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17103     *      content}
17104     *
17105     * <p>This second code sample shows a typical implementation of a View
17106     * in a video playing application.  In this situation, while the video is
17107     * playing the application would like to go into a complete full-screen mode,
17108     * to use as much of the display as possible for the video.  When in this state
17109     * the user can not interact with the application; the system intercepts
17110     * touching on the screen to pop the UI out of full screen mode.  See
17111     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17112     *
17113     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17114     *      content}
17115     *
17116     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17117     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17118     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17119     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17120     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17121     */
17122    public void setSystemUiVisibility(int visibility) {
17123        if (visibility != mSystemUiVisibility) {
17124            mSystemUiVisibility = visibility;
17125            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17126                mParent.recomputeViewAttributes(this);
17127            }
17128        }
17129    }
17130
17131    /**
17132     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17133     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17134     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17135     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17136     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17137     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17138     */
17139    public int getSystemUiVisibility() {
17140        return mSystemUiVisibility;
17141    }
17142
17143    /**
17144     * Returns the current system UI visibility that is currently set for
17145     * the entire window.  This is the combination of the
17146     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17147     * views in the window.
17148     */
17149    public int getWindowSystemUiVisibility() {
17150        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17151    }
17152
17153    /**
17154     * Override to find out when the window's requested system UI visibility
17155     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17156     * This is different from the callbacks received through
17157     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17158     * in that this is only telling you about the local request of the window,
17159     * not the actual values applied by the system.
17160     */
17161    public void onWindowSystemUiVisibilityChanged(int visible) {
17162    }
17163
17164    /**
17165     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17166     * the view hierarchy.
17167     */
17168    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17169        onWindowSystemUiVisibilityChanged(visible);
17170    }
17171
17172    /**
17173     * Set a listener to receive callbacks when the visibility of the system bar changes.
17174     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17175     */
17176    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17177        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17178        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17179            mParent.recomputeViewAttributes(this);
17180        }
17181    }
17182
17183    /**
17184     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17185     * the view hierarchy.
17186     */
17187    public void dispatchSystemUiVisibilityChanged(int visibility) {
17188        ListenerInfo li = mListenerInfo;
17189        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17190            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17191                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17192        }
17193    }
17194
17195    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17196        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17197        if (val != mSystemUiVisibility) {
17198            setSystemUiVisibility(val);
17199            return true;
17200        }
17201        return false;
17202    }
17203
17204    /** @hide */
17205    public void setDisabledSystemUiVisibility(int flags) {
17206        if (mAttachInfo != null) {
17207            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17208                mAttachInfo.mDisabledSystemUiVisibility = flags;
17209                if (mParent != null) {
17210                    mParent.recomputeViewAttributes(this);
17211                }
17212            }
17213        }
17214    }
17215
17216    /**
17217     * Creates an image that the system displays during the drag and drop
17218     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17219     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17220     * appearance as the given View. The default also positions the center of the drag shadow
17221     * directly under the touch point. If no View is provided (the constructor with no parameters
17222     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17223     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17224     * default is an invisible drag shadow.
17225     * <p>
17226     * You are not required to use the View you provide to the constructor as the basis of the
17227     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17228     * anything you want as the drag shadow.
17229     * </p>
17230     * <p>
17231     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17232     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17233     *  size and position of the drag shadow. It uses this data to construct a
17234     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17235     *  so that your application can draw the shadow image in the Canvas.
17236     * </p>
17237     *
17238     * <div class="special reference">
17239     * <h3>Developer Guides</h3>
17240     * <p>For a guide to implementing drag and drop features, read the
17241     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17242     * </div>
17243     */
17244    public static class DragShadowBuilder {
17245        private final WeakReference<View> mView;
17246
17247        /**
17248         * Constructs a shadow image builder based on a View. By default, the resulting drag
17249         * shadow will have the same appearance and dimensions as the View, with the touch point
17250         * over the center of the View.
17251         * @param view A View. Any View in scope can be used.
17252         */
17253        public DragShadowBuilder(View view) {
17254            mView = new WeakReference<View>(view);
17255        }
17256
17257        /**
17258         * Construct a shadow builder object with no associated View.  This
17259         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17260         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17261         * to supply the drag shadow's dimensions and appearance without
17262         * reference to any View object. If they are not overridden, then the result is an
17263         * invisible drag shadow.
17264         */
17265        public DragShadowBuilder() {
17266            mView = new WeakReference<View>(null);
17267        }
17268
17269        /**
17270         * Returns the View object that had been passed to the
17271         * {@link #View.DragShadowBuilder(View)}
17272         * constructor.  If that View parameter was {@code null} or if the
17273         * {@link #View.DragShadowBuilder()}
17274         * constructor was used to instantiate the builder object, this method will return
17275         * null.
17276         *
17277         * @return The View object associate with this builder object.
17278         */
17279        @SuppressWarnings({"JavadocReference"})
17280        final public View getView() {
17281            return mView.get();
17282        }
17283
17284        /**
17285         * Provides the metrics for the shadow image. These include the dimensions of
17286         * the shadow image, and the point within that shadow that should
17287         * be centered under the touch location while dragging.
17288         * <p>
17289         * The default implementation sets the dimensions of the shadow to be the
17290         * same as the dimensions of the View itself and centers the shadow under
17291         * the touch point.
17292         * </p>
17293         *
17294         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17295         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17296         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17297         * image.
17298         *
17299         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17300         * shadow image that should be underneath the touch point during the drag and drop
17301         * operation. Your application must set {@link android.graphics.Point#x} to the
17302         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17303         */
17304        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17305            final View view = mView.get();
17306            if (view != null) {
17307                shadowSize.set(view.getWidth(), view.getHeight());
17308                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17309            } else {
17310                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17311            }
17312        }
17313
17314        /**
17315         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17316         * based on the dimensions it received from the
17317         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17318         *
17319         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17320         */
17321        public void onDrawShadow(Canvas canvas) {
17322            final View view = mView.get();
17323            if (view != null) {
17324                view.draw(canvas);
17325            } else {
17326                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17327            }
17328        }
17329    }
17330
17331    /**
17332     * Starts a drag and drop operation. When your application calls this method, it passes a
17333     * {@link android.view.View.DragShadowBuilder} object to the system. The
17334     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17335     * to get metrics for the drag shadow, and then calls the object's
17336     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17337     * <p>
17338     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17339     *  drag events to all the View objects in your application that are currently visible. It does
17340     *  this either by calling the View object's drag listener (an implementation of
17341     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17342     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17343     *  Both are passed a {@link android.view.DragEvent} object that has a
17344     *  {@link android.view.DragEvent#getAction()} value of
17345     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17346     * </p>
17347     * <p>
17348     * Your application can invoke startDrag() on any attached View object. The View object does not
17349     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17350     * be related to the View the user selected for dragging.
17351     * </p>
17352     * @param data A {@link android.content.ClipData} object pointing to the data to be
17353     * transferred by the drag and drop operation.
17354     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17355     * drag shadow.
17356     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17357     * drop operation. This Object is put into every DragEvent object sent by the system during the
17358     * current drag.
17359     * <p>
17360     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17361     * to the target Views. For example, it can contain flags that differentiate between a
17362     * a copy operation and a move operation.
17363     * </p>
17364     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17365     * so the parameter should be set to 0.
17366     * @return {@code true} if the method completes successfully, or
17367     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17368     * do a drag, and so no drag operation is in progress.
17369     */
17370    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17371            Object myLocalState, int flags) {
17372        if (ViewDebug.DEBUG_DRAG) {
17373            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17374        }
17375        boolean okay = false;
17376
17377        Point shadowSize = new Point();
17378        Point shadowTouchPoint = new Point();
17379        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17380
17381        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17382                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17383            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17384        }
17385
17386        if (ViewDebug.DEBUG_DRAG) {
17387            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17388                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17389        }
17390        Surface surface = new Surface();
17391        try {
17392            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17393                    flags, shadowSize.x, shadowSize.y, surface);
17394            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17395                    + " surface=" + surface);
17396            if (token != null) {
17397                Canvas canvas = surface.lockCanvas(null);
17398                try {
17399                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17400                    shadowBuilder.onDrawShadow(canvas);
17401                } finally {
17402                    surface.unlockCanvasAndPost(canvas);
17403                }
17404
17405                final ViewRootImpl root = getViewRootImpl();
17406
17407                // Cache the local state object for delivery with DragEvents
17408                root.setLocalDragState(myLocalState);
17409
17410                // repurpose 'shadowSize' for the last touch point
17411                root.getLastTouchPoint(shadowSize);
17412
17413                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17414                        shadowSize.x, shadowSize.y,
17415                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17416                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17417
17418                // Off and running!  Release our local surface instance; the drag
17419                // shadow surface is now managed by the system process.
17420                surface.release();
17421            }
17422        } catch (Exception e) {
17423            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17424            surface.destroy();
17425        }
17426
17427        return okay;
17428    }
17429
17430    /**
17431     * Handles drag events sent by the system following a call to
17432     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17433     *<p>
17434     * When the system calls this method, it passes a
17435     * {@link android.view.DragEvent} object. A call to
17436     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17437     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17438     * operation.
17439     * @param event The {@link android.view.DragEvent} sent by the system.
17440     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17441     * in DragEvent, indicating the type of drag event represented by this object.
17442     * @return {@code true} if the method was successful, otherwise {@code false}.
17443     * <p>
17444     *  The method should return {@code true} in response to an action type of
17445     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17446     *  operation.
17447     * </p>
17448     * <p>
17449     *  The method should also return {@code true} in response to an action type of
17450     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17451     *  {@code false} if it didn't.
17452     * </p>
17453     */
17454    public boolean onDragEvent(DragEvent event) {
17455        return false;
17456    }
17457
17458    /**
17459     * Detects if this View is enabled and has a drag event listener.
17460     * If both are true, then it calls the drag event listener with the
17461     * {@link android.view.DragEvent} it received. If the drag event listener returns
17462     * {@code true}, then dispatchDragEvent() returns {@code true}.
17463     * <p>
17464     * For all other cases, the method calls the
17465     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17466     * method and returns its result.
17467     * </p>
17468     * <p>
17469     * This ensures that a drag event is always consumed, even if the View does not have a drag
17470     * event listener. However, if the View has a listener and the listener returns true, then
17471     * onDragEvent() is not called.
17472     * </p>
17473     */
17474    public boolean dispatchDragEvent(DragEvent event) {
17475        ListenerInfo li = mListenerInfo;
17476        //noinspection SimplifiableIfStatement
17477        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17478                && li.mOnDragListener.onDrag(this, event)) {
17479            return true;
17480        }
17481        return onDragEvent(event);
17482    }
17483
17484    boolean canAcceptDrag() {
17485        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17486    }
17487
17488    /**
17489     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17490     * it is ever exposed at all.
17491     * @hide
17492     */
17493    public void onCloseSystemDialogs(String reason) {
17494    }
17495
17496    /**
17497     * Given a Drawable whose bounds have been set to draw into this view,
17498     * update a Region being computed for
17499     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17500     * that any non-transparent parts of the Drawable are removed from the
17501     * given transparent region.
17502     *
17503     * @param dr The Drawable whose transparency is to be applied to the region.
17504     * @param region A Region holding the current transparency information,
17505     * where any parts of the region that are set are considered to be
17506     * transparent.  On return, this region will be modified to have the
17507     * transparency information reduced by the corresponding parts of the
17508     * Drawable that are not transparent.
17509     * {@hide}
17510     */
17511    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17512        if (DBG) {
17513            Log.i("View", "Getting transparent region for: " + this);
17514        }
17515        final Region r = dr.getTransparentRegion();
17516        final Rect db = dr.getBounds();
17517        final AttachInfo attachInfo = mAttachInfo;
17518        if (r != null && attachInfo != null) {
17519            final int w = getRight()-getLeft();
17520            final int h = getBottom()-getTop();
17521            if (db.left > 0) {
17522                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17523                r.op(0, 0, db.left, h, Region.Op.UNION);
17524            }
17525            if (db.right < w) {
17526                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17527                r.op(db.right, 0, w, h, Region.Op.UNION);
17528            }
17529            if (db.top > 0) {
17530                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17531                r.op(0, 0, w, db.top, Region.Op.UNION);
17532            }
17533            if (db.bottom < h) {
17534                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17535                r.op(0, db.bottom, w, h, Region.Op.UNION);
17536            }
17537            final int[] location = attachInfo.mTransparentLocation;
17538            getLocationInWindow(location);
17539            r.translate(location[0], location[1]);
17540            region.op(r, Region.Op.INTERSECT);
17541        } else {
17542            region.op(db, Region.Op.DIFFERENCE);
17543        }
17544    }
17545
17546    private void checkForLongClick(int delayOffset) {
17547        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17548            mHasPerformedLongPress = false;
17549
17550            if (mPendingCheckForLongPress == null) {
17551                mPendingCheckForLongPress = new CheckForLongPress();
17552            }
17553            mPendingCheckForLongPress.rememberWindowAttachCount();
17554            postDelayed(mPendingCheckForLongPress,
17555                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17556        }
17557    }
17558
17559    /**
17560     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17561     * LayoutInflater} class, which provides a full range of options for view inflation.
17562     *
17563     * @param context The Context object for your activity or application.
17564     * @param resource The resource ID to inflate
17565     * @param root A view group that will be the parent.  Used to properly inflate the
17566     * layout_* parameters.
17567     * @see LayoutInflater
17568     */
17569    public static View inflate(Context context, int resource, ViewGroup root) {
17570        LayoutInflater factory = LayoutInflater.from(context);
17571        return factory.inflate(resource, root);
17572    }
17573
17574    /**
17575     * Scroll the view with standard behavior for scrolling beyond the normal
17576     * content boundaries. Views that call this method should override
17577     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17578     * results of an over-scroll operation.
17579     *
17580     * Views can use this method to handle any touch or fling-based scrolling.
17581     *
17582     * @param deltaX Change in X in pixels
17583     * @param deltaY Change in Y in pixels
17584     * @param scrollX Current X scroll value in pixels before applying deltaX
17585     * @param scrollY Current Y scroll value in pixels before applying deltaY
17586     * @param scrollRangeX Maximum content scroll range along the X axis
17587     * @param scrollRangeY Maximum content scroll range along the Y axis
17588     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17589     *          along the X axis.
17590     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17591     *          along the Y axis.
17592     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17593     * @return true if scrolling was clamped to an over-scroll boundary along either
17594     *          axis, false otherwise.
17595     */
17596    @SuppressWarnings({"UnusedParameters"})
17597    protected boolean overScrollBy(int deltaX, int deltaY,
17598            int scrollX, int scrollY,
17599            int scrollRangeX, int scrollRangeY,
17600            int maxOverScrollX, int maxOverScrollY,
17601            boolean isTouchEvent) {
17602        final int overScrollMode = mOverScrollMode;
17603        final boolean canScrollHorizontal =
17604                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17605        final boolean canScrollVertical =
17606                computeVerticalScrollRange() > computeVerticalScrollExtent();
17607        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17608                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17609        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17610                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17611
17612        int newScrollX = scrollX + deltaX;
17613        if (!overScrollHorizontal) {
17614            maxOverScrollX = 0;
17615        }
17616
17617        int newScrollY = scrollY + deltaY;
17618        if (!overScrollVertical) {
17619            maxOverScrollY = 0;
17620        }
17621
17622        // Clamp values if at the limits and record
17623        final int left = -maxOverScrollX;
17624        final int right = maxOverScrollX + scrollRangeX;
17625        final int top = -maxOverScrollY;
17626        final int bottom = maxOverScrollY + scrollRangeY;
17627
17628        boolean clampedX = false;
17629        if (newScrollX > right) {
17630            newScrollX = right;
17631            clampedX = true;
17632        } else if (newScrollX < left) {
17633            newScrollX = left;
17634            clampedX = true;
17635        }
17636
17637        boolean clampedY = false;
17638        if (newScrollY > bottom) {
17639            newScrollY = bottom;
17640            clampedY = true;
17641        } else if (newScrollY < top) {
17642            newScrollY = top;
17643            clampedY = true;
17644        }
17645
17646        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17647
17648        return clampedX || clampedY;
17649    }
17650
17651    /**
17652     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17653     * respond to the results of an over-scroll operation.
17654     *
17655     * @param scrollX New X scroll value in pixels
17656     * @param scrollY New Y scroll value in pixels
17657     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17658     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17659     */
17660    protected void onOverScrolled(int scrollX, int scrollY,
17661            boolean clampedX, boolean clampedY) {
17662        // Intentionally empty.
17663    }
17664
17665    /**
17666     * Returns the over-scroll mode for this view. The result will be
17667     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17668     * (allow over-scrolling only if the view content is larger than the container),
17669     * or {@link #OVER_SCROLL_NEVER}.
17670     *
17671     * @return This view's over-scroll mode.
17672     */
17673    public int getOverScrollMode() {
17674        return mOverScrollMode;
17675    }
17676
17677    /**
17678     * Set the over-scroll mode for this view. Valid over-scroll modes are
17679     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17680     * (allow over-scrolling only if the view content is larger than the container),
17681     * or {@link #OVER_SCROLL_NEVER}.
17682     *
17683     * Setting the over-scroll mode of a view will have an effect only if the
17684     * view is capable of scrolling.
17685     *
17686     * @param overScrollMode The new over-scroll mode for this view.
17687     */
17688    public void setOverScrollMode(int overScrollMode) {
17689        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17690                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17691                overScrollMode != OVER_SCROLL_NEVER) {
17692            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17693        }
17694        mOverScrollMode = overScrollMode;
17695    }
17696
17697    /**
17698     * Gets a scale factor that determines the distance the view should scroll
17699     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17700     * @return The vertical scroll scale factor.
17701     * @hide
17702     */
17703    protected float getVerticalScrollFactor() {
17704        if (mVerticalScrollFactor == 0) {
17705            TypedValue outValue = new TypedValue();
17706            if (!mContext.getTheme().resolveAttribute(
17707                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17708                throw new IllegalStateException(
17709                        "Expected theme to define listPreferredItemHeight.");
17710            }
17711            mVerticalScrollFactor = outValue.getDimension(
17712                    mContext.getResources().getDisplayMetrics());
17713        }
17714        return mVerticalScrollFactor;
17715    }
17716
17717    /**
17718     * Gets a scale factor that determines the distance the view should scroll
17719     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17720     * @return The horizontal scroll scale factor.
17721     * @hide
17722     */
17723    protected float getHorizontalScrollFactor() {
17724        // TODO: Should use something else.
17725        return getVerticalScrollFactor();
17726    }
17727
17728    /**
17729     * Return the value specifying the text direction or policy that was set with
17730     * {@link #setTextDirection(int)}.
17731     *
17732     * @return the defined text direction. It can be one of:
17733     *
17734     * {@link #TEXT_DIRECTION_INHERIT},
17735     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17736     * {@link #TEXT_DIRECTION_ANY_RTL},
17737     * {@link #TEXT_DIRECTION_LTR},
17738     * {@link #TEXT_DIRECTION_RTL},
17739     * {@link #TEXT_DIRECTION_LOCALE}
17740     *
17741     * @attr ref android.R.styleable#View_textDirection
17742     *
17743     * @hide
17744     */
17745    @ViewDebug.ExportedProperty(category = "text", mapping = {
17746            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17747            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17748            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17749            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17750            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17751            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17752    })
17753    public int getRawTextDirection() {
17754        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17755    }
17756
17757    /**
17758     * Set the text direction.
17759     *
17760     * @param textDirection the direction to set. Should be one of:
17761     *
17762     * {@link #TEXT_DIRECTION_INHERIT},
17763     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17764     * {@link #TEXT_DIRECTION_ANY_RTL},
17765     * {@link #TEXT_DIRECTION_LTR},
17766     * {@link #TEXT_DIRECTION_RTL},
17767     * {@link #TEXT_DIRECTION_LOCALE}
17768     *
17769     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17770     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17771     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17772     *
17773     * @attr ref android.R.styleable#View_textDirection
17774     */
17775    public void setTextDirection(int textDirection) {
17776        if (getRawTextDirection() != textDirection) {
17777            // Reset the current text direction and the resolved one
17778            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17779            resetResolvedTextDirection();
17780            // Set the new text direction
17781            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17782            // Do resolution
17783            resolveTextDirection();
17784            // Notify change
17785            onRtlPropertiesChanged(getLayoutDirection());
17786            // Refresh
17787            requestLayout();
17788            invalidate(true);
17789        }
17790    }
17791
17792    /**
17793     * Return the resolved text direction.
17794     *
17795     * @return the resolved text direction. Returns one of:
17796     *
17797     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17798     * {@link #TEXT_DIRECTION_ANY_RTL},
17799     * {@link #TEXT_DIRECTION_LTR},
17800     * {@link #TEXT_DIRECTION_RTL},
17801     * {@link #TEXT_DIRECTION_LOCALE}
17802     *
17803     * @attr ref android.R.styleable#View_textDirection
17804     */
17805    @ViewDebug.ExportedProperty(category = "text", mapping = {
17806            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17807            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17808            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17809            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17810            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17811            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17812    })
17813    public int getTextDirection() {
17814        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17815    }
17816
17817    /**
17818     * Resolve the text direction.
17819     *
17820     * @return true if resolution has been done, false otherwise.
17821     *
17822     * @hide
17823     */
17824    public boolean resolveTextDirection() {
17825        // Reset any previous text direction resolution
17826        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17827
17828        if (hasRtlSupport()) {
17829            // Set resolved text direction flag depending on text direction flag
17830            final int textDirection = getRawTextDirection();
17831            switch(textDirection) {
17832                case TEXT_DIRECTION_INHERIT:
17833                    if (!canResolveTextDirection()) {
17834                        // We cannot do the resolution if there is no parent, so use the default one
17835                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17836                        // Resolution will need to happen again later
17837                        return false;
17838                    }
17839
17840                    // Parent has not yet resolved, so we still return the default
17841                    try {
17842                        if (!mParent.isTextDirectionResolved()) {
17843                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17844                            // Resolution will need to happen again later
17845                            return false;
17846                        }
17847                    } catch (AbstractMethodError e) {
17848                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17849                                " does not fully implement ViewParent", e);
17850                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17851                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17852                        return true;
17853                    }
17854
17855                    // Set current resolved direction to the same value as the parent's one
17856                    int parentResolvedDirection;
17857                    try {
17858                        parentResolvedDirection = mParent.getTextDirection();
17859                    } catch (AbstractMethodError e) {
17860                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17861                                " does not fully implement ViewParent", e);
17862                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17863                    }
17864                    switch (parentResolvedDirection) {
17865                        case TEXT_DIRECTION_FIRST_STRONG:
17866                        case TEXT_DIRECTION_ANY_RTL:
17867                        case TEXT_DIRECTION_LTR:
17868                        case TEXT_DIRECTION_RTL:
17869                        case TEXT_DIRECTION_LOCALE:
17870                            mPrivateFlags2 |=
17871                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17872                            break;
17873                        default:
17874                            // Default resolved direction is "first strong" heuristic
17875                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17876                    }
17877                    break;
17878                case TEXT_DIRECTION_FIRST_STRONG:
17879                case TEXT_DIRECTION_ANY_RTL:
17880                case TEXT_DIRECTION_LTR:
17881                case TEXT_DIRECTION_RTL:
17882                case TEXT_DIRECTION_LOCALE:
17883                    // Resolved direction is the same as text direction
17884                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17885                    break;
17886                default:
17887                    // Default resolved direction is "first strong" heuristic
17888                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17889            }
17890        } else {
17891            // Default resolved direction is "first strong" heuristic
17892            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17893        }
17894
17895        // Set to resolved
17896        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17897        return true;
17898    }
17899
17900    /**
17901     * Check if text direction resolution can be done.
17902     *
17903     * @return true if text direction resolution can be done otherwise return false.
17904     */
17905    public boolean canResolveTextDirection() {
17906        switch (getRawTextDirection()) {
17907            case TEXT_DIRECTION_INHERIT:
17908                if (mParent != null) {
17909                    try {
17910                        return mParent.canResolveTextDirection();
17911                    } catch (AbstractMethodError e) {
17912                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17913                                " does not fully implement ViewParent", e);
17914                    }
17915                }
17916                return false;
17917
17918            default:
17919                return true;
17920        }
17921    }
17922
17923    /**
17924     * Reset resolved text direction. Text direction will be resolved during a call to
17925     * {@link #onMeasure(int, int)}.
17926     *
17927     * @hide
17928     */
17929    public void resetResolvedTextDirection() {
17930        // Reset any previous text direction resolution
17931        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17932        // Set to default value
17933        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17934    }
17935
17936    /**
17937     * @return true if text direction is inherited.
17938     *
17939     * @hide
17940     */
17941    public boolean isTextDirectionInherited() {
17942        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17943    }
17944
17945    /**
17946     * @return true if text direction is resolved.
17947     */
17948    public boolean isTextDirectionResolved() {
17949        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17950    }
17951
17952    /**
17953     * Return the value specifying the text alignment or policy that was set with
17954     * {@link #setTextAlignment(int)}.
17955     *
17956     * @return the defined text alignment. It can be one of:
17957     *
17958     * {@link #TEXT_ALIGNMENT_INHERIT},
17959     * {@link #TEXT_ALIGNMENT_GRAVITY},
17960     * {@link #TEXT_ALIGNMENT_CENTER},
17961     * {@link #TEXT_ALIGNMENT_TEXT_START},
17962     * {@link #TEXT_ALIGNMENT_TEXT_END},
17963     * {@link #TEXT_ALIGNMENT_VIEW_START},
17964     * {@link #TEXT_ALIGNMENT_VIEW_END}
17965     *
17966     * @attr ref android.R.styleable#View_textAlignment
17967     *
17968     * @hide
17969     */
17970    @ViewDebug.ExportedProperty(category = "text", mapping = {
17971            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17972            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17973            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17974            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17975            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17976            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17977            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17978    })
17979    @TextAlignment
17980    public int getRawTextAlignment() {
17981        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17982    }
17983
17984    /**
17985     * Set the text alignment.
17986     *
17987     * @param textAlignment The text alignment to set. Should be one of
17988     *
17989     * {@link #TEXT_ALIGNMENT_INHERIT},
17990     * {@link #TEXT_ALIGNMENT_GRAVITY},
17991     * {@link #TEXT_ALIGNMENT_CENTER},
17992     * {@link #TEXT_ALIGNMENT_TEXT_START},
17993     * {@link #TEXT_ALIGNMENT_TEXT_END},
17994     * {@link #TEXT_ALIGNMENT_VIEW_START},
17995     * {@link #TEXT_ALIGNMENT_VIEW_END}
17996     *
17997     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17998     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17999     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18000     *
18001     * @attr ref android.R.styleable#View_textAlignment
18002     */
18003    public void setTextAlignment(@TextAlignment int textAlignment) {
18004        if (textAlignment != getRawTextAlignment()) {
18005            // Reset the current and resolved text alignment
18006            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18007            resetResolvedTextAlignment();
18008            // Set the new text alignment
18009            mPrivateFlags2 |=
18010                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18011            // Do resolution
18012            resolveTextAlignment();
18013            // Notify change
18014            onRtlPropertiesChanged(getLayoutDirection());
18015            // Refresh
18016            requestLayout();
18017            invalidate(true);
18018        }
18019    }
18020
18021    /**
18022     * Return the resolved text alignment.
18023     *
18024     * @return the resolved text alignment. Returns one of:
18025     *
18026     * {@link #TEXT_ALIGNMENT_GRAVITY},
18027     * {@link #TEXT_ALIGNMENT_CENTER},
18028     * {@link #TEXT_ALIGNMENT_TEXT_START},
18029     * {@link #TEXT_ALIGNMENT_TEXT_END},
18030     * {@link #TEXT_ALIGNMENT_VIEW_START},
18031     * {@link #TEXT_ALIGNMENT_VIEW_END}
18032     *
18033     * @attr ref android.R.styleable#View_textAlignment
18034     */
18035    @ViewDebug.ExportedProperty(category = "text", mapping = {
18036            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18037            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18038            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18039            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18040            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18041            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18042            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18043    })
18044    @TextAlignment
18045    public int getTextAlignment() {
18046        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18047                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18048    }
18049
18050    /**
18051     * Resolve the text alignment.
18052     *
18053     * @return true if resolution has been done, false otherwise.
18054     *
18055     * @hide
18056     */
18057    public boolean resolveTextAlignment() {
18058        // Reset any previous text alignment resolution
18059        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18060
18061        if (hasRtlSupport()) {
18062            // Set resolved text alignment flag depending on text alignment flag
18063            final int textAlignment = getRawTextAlignment();
18064            switch (textAlignment) {
18065                case TEXT_ALIGNMENT_INHERIT:
18066                    // Check if we can resolve the text alignment
18067                    if (!canResolveTextAlignment()) {
18068                        // We cannot do the resolution if there is no parent so use the default
18069                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18070                        // Resolution will need to happen again later
18071                        return false;
18072                    }
18073
18074                    // Parent has not yet resolved, so we still return the default
18075                    try {
18076                        if (!mParent.isTextAlignmentResolved()) {
18077                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18078                            // Resolution will need to happen again later
18079                            return false;
18080                        }
18081                    } catch (AbstractMethodError e) {
18082                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18083                                " does not fully implement ViewParent", e);
18084                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18085                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18086                        return true;
18087                    }
18088
18089                    int parentResolvedTextAlignment;
18090                    try {
18091                        parentResolvedTextAlignment = mParent.getTextAlignment();
18092                    } catch (AbstractMethodError e) {
18093                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18094                                " does not fully implement ViewParent", e);
18095                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18096                    }
18097                    switch (parentResolvedTextAlignment) {
18098                        case TEXT_ALIGNMENT_GRAVITY:
18099                        case TEXT_ALIGNMENT_TEXT_START:
18100                        case TEXT_ALIGNMENT_TEXT_END:
18101                        case TEXT_ALIGNMENT_CENTER:
18102                        case TEXT_ALIGNMENT_VIEW_START:
18103                        case TEXT_ALIGNMENT_VIEW_END:
18104                            // Resolved text alignment is the same as the parent resolved
18105                            // text alignment
18106                            mPrivateFlags2 |=
18107                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18108                            break;
18109                        default:
18110                            // Use default resolved text alignment
18111                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18112                    }
18113                    break;
18114                case TEXT_ALIGNMENT_GRAVITY:
18115                case TEXT_ALIGNMENT_TEXT_START:
18116                case TEXT_ALIGNMENT_TEXT_END:
18117                case TEXT_ALIGNMENT_CENTER:
18118                case TEXT_ALIGNMENT_VIEW_START:
18119                case TEXT_ALIGNMENT_VIEW_END:
18120                    // Resolved text alignment is the same as text alignment
18121                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18122                    break;
18123                default:
18124                    // Use default resolved text alignment
18125                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18126            }
18127        } else {
18128            // Use default resolved text alignment
18129            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18130        }
18131
18132        // Set the resolved
18133        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18134        return true;
18135    }
18136
18137    /**
18138     * Check if text alignment resolution can be done.
18139     *
18140     * @return true if text alignment resolution can be done otherwise return false.
18141     */
18142    public boolean canResolveTextAlignment() {
18143        switch (getRawTextAlignment()) {
18144            case TEXT_DIRECTION_INHERIT:
18145                if (mParent != null) {
18146                    try {
18147                        return mParent.canResolveTextAlignment();
18148                    } catch (AbstractMethodError e) {
18149                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18150                                " does not fully implement ViewParent", e);
18151                    }
18152                }
18153                return false;
18154
18155            default:
18156                return true;
18157        }
18158    }
18159
18160    /**
18161     * Reset resolved text alignment. Text alignment will be resolved during a call to
18162     * {@link #onMeasure(int, int)}.
18163     *
18164     * @hide
18165     */
18166    public void resetResolvedTextAlignment() {
18167        // Reset any previous text alignment resolution
18168        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18169        // Set to default
18170        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18171    }
18172
18173    /**
18174     * @return true if text alignment is inherited.
18175     *
18176     * @hide
18177     */
18178    public boolean isTextAlignmentInherited() {
18179        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18180    }
18181
18182    /**
18183     * @return true if text alignment is resolved.
18184     */
18185    public boolean isTextAlignmentResolved() {
18186        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18187    }
18188
18189    /**
18190     * Generate a value suitable for use in {@link #setId(int)}.
18191     * This value will not collide with ID values generated at build time by aapt for R.id.
18192     *
18193     * @return a generated ID value
18194     */
18195    public static int generateViewId() {
18196        for (;;) {
18197            final int result = sNextGeneratedId.get();
18198            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18199            int newValue = result + 1;
18200            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18201            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18202                return result;
18203            }
18204        }
18205    }
18206
18207    //
18208    // Properties
18209    //
18210    /**
18211     * A Property wrapper around the <code>alpha</code> functionality handled by the
18212     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18213     */
18214    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18215        @Override
18216        public void setValue(View object, float value) {
18217            object.setAlpha(value);
18218        }
18219
18220        @Override
18221        public Float get(View object) {
18222            return object.getAlpha();
18223        }
18224    };
18225
18226    /**
18227     * A Property wrapper around the <code>translationX</code> functionality handled by the
18228     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18229     */
18230    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18231        @Override
18232        public void setValue(View object, float value) {
18233            object.setTranslationX(value);
18234        }
18235
18236                @Override
18237        public Float get(View object) {
18238            return object.getTranslationX();
18239        }
18240    };
18241
18242    /**
18243     * A Property wrapper around the <code>translationY</code> functionality handled by the
18244     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18245     */
18246    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18247        @Override
18248        public void setValue(View object, float value) {
18249            object.setTranslationY(value);
18250        }
18251
18252        @Override
18253        public Float get(View object) {
18254            return object.getTranslationY();
18255        }
18256    };
18257
18258    /**
18259     * A Property wrapper around the <code>x</code> functionality handled by the
18260     * {@link View#setX(float)} and {@link View#getX()} methods.
18261     */
18262    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18263        @Override
18264        public void setValue(View object, float value) {
18265            object.setX(value);
18266        }
18267
18268        @Override
18269        public Float get(View object) {
18270            return object.getX();
18271        }
18272    };
18273
18274    /**
18275     * A Property wrapper around the <code>y</code> functionality handled by the
18276     * {@link View#setY(float)} and {@link View#getY()} methods.
18277     */
18278    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18279        @Override
18280        public void setValue(View object, float value) {
18281            object.setY(value);
18282        }
18283
18284        @Override
18285        public Float get(View object) {
18286            return object.getY();
18287        }
18288    };
18289
18290    /**
18291     * A Property wrapper around the <code>rotation</code> functionality handled by the
18292     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18293     */
18294    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18295        @Override
18296        public void setValue(View object, float value) {
18297            object.setRotation(value);
18298        }
18299
18300        @Override
18301        public Float get(View object) {
18302            return object.getRotation();
18303        }
18304    };
18305
18306    /**
18307     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18308     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18309     */
18310    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18311        @Override
18312        public void setValue(View object, float value) {
18313            object.setRotationX(value);
18314        }
18315
18316        @Override
18317        public Float get(View object) {
18318            return object.getRotationX();
18319        }
18320    };
18321
18322    /**
18323     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18324     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18325     */
18326    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18327        @Override
18328        public void setValue(View object, float value) {
18329            object.setRotationY(value);
18330        }
18331
18332        @Override
18333        public Float get(View object) {
18334            return object.getRotationY();
18335        }
18336    };
18337
18338    /**
18339     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18340     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18341     */
18342    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18343        @Override
18344        public void setValue(View object, float value) {
18345            object.setScaleX(value);
18346        }
18347
18348        @Override
18349        public Float get(View object) {
18350            return object.getScaleX();
18351        }
18352    };
18353
18354    /**
18355     * A Property wrapper around the <code>scaleY</code> functionality handled by the
18356     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
18357     */
18358    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
18359        @Override
18360        public void setValue(View object, float value) {
18361            object.setScaleY(value);
18362        }
18363
18364        @Override
18365        public Float get(View object) {
18366            return object.getScaleY();
18367        }
18368    };
18369
18370    /**
18371     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
18372     * Each MeasureSpec represents a requirement for either the width or the height.
18373     * A MeasureSpec is comprised of a size and a mode. There are three possible
18374     * modes:
18375     * <dl>
18376     * <dt>UNSPECIFIED</dt>
18377     * <dd>
18378     * The parent has not imposed any constraint on the child. It can be whatever size
18379     * it wants.
18380     * </dd>
18381     *
18382     * <dt>EXACTLY</dt>
18383     * <dd>
18384     * The parent has determined an exact size for the child. The child is going to be
18385     * given those bounds regardless of how big it wants to be.
18386     * </dd>
18387     *
18388     * <dt>AT_MOST</dt>
18389     * <dd>
18390     * The child can be as large as it wants up to the specified size.
18391     * </dd>
18392     * </dl>
18393     *
18394     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18395     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18396     */
18397    public static class MeasureSpec {
18398        private static final int MODE_SHIFT = 30;
18399        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18400
18401        /**
18402         * Measure specification mode: The parent has not imposed any constraint
18403         * on the child. It can be whatever size it wants.
18404         */
18405        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
18406
18407        /**
18408         * Measure specification mode: The parent has determined an exact size
18409         * for the child. The child is going to be given those bounds regardless
18410         * of how big it wants to be.
18411         */
18412        public static final int EXACTLY     = 1 << MODE_SHIFT;
18413
18414        /**
18415         * Measure specification mode: The child can be as large as it wants up
18416         * to the specified size.
18417         */
18418        public static final int AT_MOST     = 2 << MODE_SHIFT;
18419
18420        /**
18421         * Creates a measure specification based on the supplied size and mode.
18422         *
18423         * The mode must always be one of the following:
18424         * <ul>
18425         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
18426         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
18427         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
18428         * </ul>
18429         *
18430         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
18431         * implementation was such that the order of arguments did not matter
18432         * and overflow in either value could impact the resulting MeasureSpec.
18433         * {@link android.widget.RelativeLayout} was affected by this bug.
18434         * Apps targeting API levels greater than 17 will get the fixed, more strict
18435         * behavior.</p>
18436         *
18437         * @param size the size of the measure specification
18438         * @param mode the mode of the measure specification
18439         * @return the measure specification based on size and mode
18440         */
18441        public static int makeMeasureSpec(int size, int mode) {
18442            if (sUseBrokenMakeMeasureSpec) {
18443                return size + mode;
18444            } else {
18445                return (size & ~MODE_MASK) | (mode & MODE_MASK);
18446            }
18447        }
18448
18449        /**
18450         * Extracts the mode from the supplied measure specification.
18451         *
18452         * @param measureSpec the measure specification to extract the mode from
18453         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
18454         *         {@link android.view.View.MeasureSpec#AT_MOST} or
18455         *         {@link android.view.View.MeasureSpec#EXACTLY}
18456         */
18457        public static int getMode(int measureSpec) {
18458            return (measureSpec & MODE_MASK);
18459        }
18460
18461        /**
18462         * Extracts the size from the supplied measure specification.
18463         *
18464         * @param measureSpec the measure specification to extract the size from
18465         * @return the size in pixels defined in the supplied measure specification
18466         */
18467        public static int getSize(int measureSpec) {
18468            return (measureSpec & ~MODE_MASK);
18469        }
18470
18471        static int adjust(int measureSpec, int delta) {
18472            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
18473        }
18474
18475        /**
18476         * Returns a String representation of the specified measure
18477         * specification.
18478         *
18479         * @param measureSpec the measure specification to convert to a String
18480         * @return a String with the following format: "MeasureSpec: MODE SIZE"
18481         */
18482        public static String toString(int measureSpec) {
18483            int mode = getMode(measureSpec);
18484            int size = getSize(measureSpec);
18485
18486            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18487
18488            if (mode == UNSPECIFIED)
18489                sb.append("UNSPECIFIED ");
18490            else if (mode == EXACTLY)
18491                sb.append("EXACTLY ");
18492            else if (mode == AT_MOST)
18493                sb.append("AT_MOST ");
18494            else
18495                sb.append(mode).append(" ");
18496
18497            sb.append(size);
18498            return sb.toString();
18499        }
18500    }
18501
18502    class CheckForLongPress implements Runnable {
18503
18504        private int mOriginalWindowAttachCount;
18505
18506        public void run() {
18507            if (isPressed() && (mParent != null)
18508                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18509                if (performLongClick()) {
18510                    mHasPerformedLongPress = true;
18511                }
18512            }
18513        }
18514
18515        public void rememberWindowAttachCount() {
18516            mOriginalWindowAttachCount = mWindowAttachCount;
18517        }
18518    }
18519
18520    private final class CheckForTap implements Runnable {
18521        public void run() {
18522            mPrivateFlags &= ~PFLAG_PREPRESSED;
18523            setPressed(true);
18524            checkForLongClick(ViewConfiguration.getTapTimeout());
18525        }
18526    }
18527
18528    private final class PerformClick implements Runnable {
18529        public void run() {
18530            performClick();
18531        }
18532    }
18533
18534    /** @hide */
18535    public void hackTurnOffWindowResizeAnim(boolean off) {
18536        mAttachInfo.mTurnOffWindowResizeAnim = off;
18537    }
18538
18539    /**
18540     * This method returns a ViewPropertyAnimator object, which can be used to animate
18541     * specific properties on this View.
18542     *
18543     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
18544     */
18545    public ViewPropertyAnimator animate() {
18546        if (mAnimator == null) {
18547            mAnimator = new ViewPropertyAnimator(this);
18548        }
18549        return mAnimator;
18550    }
18551
18552    /**
18553     * Interface definition for a callback to be invoked when a hardware key event is
18554     * dispatched to this view. The callback will be invoked before the key event is
18555     * given to the view. This is only useful for hardware keyboards; a software input
18556     * method has no obligation to trigger this listener.
18557     */
18558    public interface OnKeyListener {
18559        /**
18560         * Called when a hardware key is dispatched to a view. This allows listeners to
18561         * get a chance to respond before the target view.
18562         * <p>Key presses in software keyboards will generally NOT trigger this method,
18563         * although some may elect to do so in some situations. Do not assume a
18564         * software input method has to be key-based; even if it is, it may use key presses
18565         * in a different way than you expect, so there is no way to reliably catch soft
18566         * input key presses.
18567         *
18568         * @param v The view the key has been dispatched to.
18569         * @param keyCode The code for the physical key that was pressed
18570         * @param event The KeyEvent object containing full information about
18571         *        the event.
18572         * @return True if the listener has consumed the event, false otherwise.
18573         */
18574        boolean onKey(View v, int keyCode, KeyEvent event);
18575    }
18576
18577    /**
18578     * Interface definition for a callback to be invoked when a touch event is
18579     * dispatched to this view. The callback will be invoked before the touch
18580     * event is given to the view.
18581     */
18582    public interface OnTouchListener {
18583        /**
18584         * Called when a touch event is dispatched to a view. This allows listeners to
18585         * get a chance to respond before the target view.
18586         *
18587         * @param v The view the touch event has been dispatched to.
18588         * @param event The MotionEvent object containing full information about
18589         *        the event.
18590         * @return True if the listener has consumed the event, false otherwise.
18591         */
18592        boolean onTouch(View v, MotionEvent event);
18593    }
18594
18595    /**
18596     * Interface definition for a callback to be invoked when a hover event is
18597     * dispatched to this view. The callback will be invoked before the hover
18598     * event is given to the view.
18599     */
18600    public interface OnHoverListener {
18601        /**
18602         * Called when a hover event is dispatched to a view. This allows listeners to
18603         * get a chance to respond before the target view.
18604         *
18605         * @param v The view the hover event has been dispatched to.
18606         * @param event The MotionEvent object containing full information about
18607         *        the event.
18608         * @return True if the listener has consumed the event, false otherwise.
18609         */
18610        boolean onHover(View v, MotionEvent event);
18611    }
18612
18613    /**
18614     * Interface definition for a callback to be invoked when a generic motion event is
18615     * dispatched to this view. The callback will be invoked before the generic motion
18616     * event is given to the view.
18617     */
18618    public interface OnGenericMotionListener {
18619        /**
18620         * Called when a generic motion event is dispatched to a view. This allows listeners to
18621         * get a chance to respond before the target view.
18622         *
18623         * @param v The view the generic motion event has been dispatched to.
18624         * @param event The MotionEvent object containing full information about
18625         *        the event.
18626         * @return True if the listener has consumed the event, false otherwise.
18627         */
18628        boolean onGenericMotion(View v, MotionEvent event);
18629    }
18630
18631    /**
18632     * Interface definition for a callback to be invoked when a view has been clicked and held.
18633     */
18634    public interface OnLongClickListener {
18635        /**
18636         * Called when a view has been clicked and held.
18637         *
18638         * @param v The view that was clicked and held.
18639         *
18640         * @return true if the callback consumed the long click, false otherwise.
18641         */
18642        boolean onLongClick(View v);
18643    }
18644
18645    /**
18646     * Interface definition for a callback to be invoked when a drag is being dispatched
18647     * to this view.  The callback will be invoked before the hosting view's own
18648     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18649     * onDrag(event) behavior, it should return 'false' from this callback.
18650     *
18651     * <div class="special reference">
18652     * <h3>Developer Guides</h3>
18653     * <p>For a guide to implementing drag and drop features, read the
18654     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18655     * </div>
18656     */
18657    public interface OnDragListener {
18658        /**
18659         * Called when a drag event is dispatched to a view. This allows listeners
18660         * to get a chance to override base View behavior.
18661         *
18662         * @param v The View that received the drag event.
18663         * @param event The {@link android.view.DragEvent} object for the drag event.
18664         * @return {@code true} if the drag event was handled successfully, or {@code false}
18665         * if the drag event was not handled. Note that {@code false} will trigger the View
18666         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18667         */
18668        boolean onDrag(View v, DragEvent event);
18669    }
18670
18671    /**
18672     * Interface definition for a callback to be invoked when the focus state of
18673     * a view changed.
18674     */
18675    public interface OnFocusChangeListener {
18676        /**
18677         * Called when the focus state of a view has changed.
18678         *
18679         * @param v The view whose state has changed.
18680         * @param hasFocus The new focus state of v.
18681         */
18682        void onFocusChange(View v, boolean hasFocus);
18683    }
18684
18685    /**
18686     * Interface definition for a callback to be invoked when a view is clicked.
18687     */
18688    public interface OnClickListener {
18689        /**
18690         * Called when a view has been clicked.
18691         *
18692         * @param v The view that was clicked.
18693         */
18694        void onClick(View v);
18695    }
18696
18697    /**
18698     * Interface definition for a callback to be invoked when the context menu
18699     * for this view is being built.
18700     */
18701    public interface OnCreateContextMenuListener {
18702        /**
18703         * Called when the context menu for this view is being built. It is not
18704         * safe to hold onto the menu after this method returns.
18705         *
18706         * @param menu The context menu that is being built
18707         * @param v The view for which the context menu is being built
18708         * @param menuInfo Extra information about the item for which the
18709         *            context menu should be shown. This information will vary
18710         *            depending on the class of v.
18711         */
18712        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18713    }
18714
18715    /**
18716     * Interface definition for a callback to be invoked when the status bar changes
18717     * visibility.  This reports <strong>global</strong> changes to the system UI
18718     * state, not what the application is requesting.
18719     *
18720     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18721     */
18722    public interface OnSystemUiVisibilityChangeListener {
18723        /**
18724         * Called when the status bar changes visibility because of a call to
18725         * {@link View#setSystemUiVisibility(int)}.
18726         *
18727         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18728         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18729         * This tells you the <strong>global</strong> state of these UI visibility
18730         * flags, not what your app is currently applying.
18731         */
18732        public void onSystemUiVisibilityChange(int visibility);
18733    }
18734
18735    /**
18736     * Interface definition for a callback to be invoked when this view is attached
18737     * or detached from its window.
18738     */
18739    public interface OnAttachStateChangeListener {
18740        /**
18741         * Called when the view is attached to a window.
18742         * @param v The view that was attached
18743         */
18744        public void onViewAttachedToWindow(View v);
18745        /**
18746         * Called when the view is detached from a window.
18747         * @param v The view that was detached
18748         */
18749        public void onViewDetachedFromWindow(View v);
18750    }
18751
18752    private final class UnsetPressedState implements Runnable {
18753        public void run() {
18754            setPressed(false);
18755        }
18756    }
18757
18758    /**
18759     * Base class for derived classes that want to save and restore their own
18760     * state in {@link android.view.View#onSaveInstanceState()}.
18761     */
18762    public static class BaseSavedState extends AbsSavedState {
18763        /**
18764         * Constructor used when reading from a parcel. Reads the state of the superclass.
18765         *
18766         * @param source
18767         */
18768        public BaseSavedState(Parcel source) {
18769            super(source);
18770        }
18771
18772        /**
18773         * Constructor called by derived classes when creating their SavedState objects
18774         *
18775         * @param superState The state of the superclass of this view
18776         */
18777        public BaseSavedState(Parcelable superState) {
18778            super(superState);
18779        }
18780
18781        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18782                new Parcelable.Creator<BaseSavedState>() {
18783            public BaseSavedState createFromParcel(Parcel in) {
18784                return new BaseSavedState(in);
18785            }
18786
18787            public BaseSavedState[] newArray(int size) {
18788                return new BaseSavedState[size];
18789            }
18790        };
18791    }
18792
18793    /**
18794     * A set of information given to a view when it is attached to its parent
18795     * window.
18796     */
18797    static class AttachInfo {
18798        interface Callbacks {
18799            void playSoundEffect(int effectId);
18800            boolean performHapticFeedback(int effectId, boolean always);
18801        }
18802
18803        /**
18804         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18805         * to a Handler. This class contains the target (View) to invalidate and
18806         * the coordinates of the dirty rectangle.
18807         *
18808         * For performance purposes, this class also implements a pool of up to
18809         * POOL_LIMIT objects that get reused. This reduces memory allocations
18810         * whenever possible.
18811         */
18812        static class InvalidateInfo {
18813            private static final int POOL_LIMIT = 10;
18814
18815            private static final SynchronizedPool<InvalidateInfo> sPool =
18816                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18817
18818            View target;
18819
18820            int left;
18821            int top;
18822            int right;
18823            int bottom;
18824
18825            public static InvalidateInfo obtain() {
18826                InvalidateInfo instance = sPool.acquire();
18827                return (instance != null) ? instance : new InvalidateInfo();
18828            }
18829
18830            public void recycle() {
18831                target = null;
18832                sPool.release(this);
18833            }
18834        }
18835
18836        final IWindowSession mSession;
18837
18838        final IWindow mWindow;
18839
18840        final IBinder mWindowToken;
18841
18842        final Display mDisplay;
18843
18844        final Callbacks mRootCallbacks;
18845
18846        HardwareCanvas mHardwareCanvas;
18847
18848        IWindowId mIWindowId;
18849        WindowId mWindowId;
18850
18851        /**
18852         * The top view of the hierarchy.
18853         */
18854        View mRootView;
18855
18856        IBinder mPanelParentWindowToken;
18857
18858        boolean mHardwareAccelerated;
18859        boolean mHardwareAccelerationRequested;
18860        HardwareRenderer mHardwareRenderer;
18861
18862        boolean mScreenOn;
18863
18864        /**
18865         * Scale factor used by the compatibility mode
18866         */
18867        float mApplicationScale;
18868
18869        /**
18870         * Indicates whether the application is in compatibility mode
18871         */
18872        boolean mScalingRequired;
18873
18874        /**
18875         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18876         */
18877        boolean mTurnOffWindowResizeAnim;
18878
18879        /**
18880         * Left position of this view's window
18881         */
18882        int mWindowLeft;
18883
18884        /**
18885         * Top position of this view's window
18886         */
18887        int mWindowTop;
18888
18889        /**
18890         * Indicates whether views need to use 32-bit drawing caches
18891         */
18892        boolean mUse32BitDrawingCache;
18893
18894        /**
18895         * For windows that are full-screen but using insets to layout inside
18896         * of the screen areas, these are the current insets to appear inside
18897         * the overscan area of the display.
18898         */
18899        final Rect mOverscanInsets = new Rect();
18900
18901        /**
18902         * For windows that are full-screen but using insets to layout inside
18903         * of the screen decorations, these are the current insets for the
18904         * content of the window.
18905         */
18906        final Rect mContentInsets = new Rect();
18907
18908        /**
18909         * For windows that are full-screen but using insets to layout inside
18910         * of the screen decorations, these are the current insets for the
18911         * actual visible parts of the window.
18912         */
18913        final Rect mVisibleInsets = new Rect();
18914
18915        /**
18916         * The internal insets given by this window.  This value is
18917         * supplied by the client (through
18918         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18919         * be given to the window manager when changed to be used in laying
18920         * out windows behind it.
18921         */
18922        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18923                = new ViewTreeObserver.InternalInsetsInfo();
18924
18925        /**
18926         * Set to true when mGivenInternalInsets is non-empty.
18927         */
18928        boolean mHasNonEmptyGivenInternalInsets;
18929
18930        /**
18931         * All views in the window's hierarchy that serve as scroll containers,
18932         * used to determine if the window can be resized or must be panned
18933         * to adjust for a soft input area.
18934         */
18935        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18936
18937        final KeyEvent.DispatcherState mKeyDispatchState
18938                = new KeyEvent.DispatcherState();
18939
18940        /**
18941         * Indicates whether the view's window currently has the focus.
18942         */
18943        boolean mHasWindowFocus;
18944
18945        /**
18946         * The current visibility of the window.
18947         */
18948        int mWindowVisibility;
18949
18950        /**
18951         * Indicates the time at which drawing started to occur.
18952         */
18953        long mDrawingTime;
18954
18955        /**
18956         * Indicates whether or not ignoring the DIRTY_MASK flags.
18957         */
18958        boolean mIgnoreDirtyState;
18959
18960        /**
18961         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18962         * to avoid clearing that flag prematurely.
18963         */
18964        boolean mSetIgnoreDirtyState = false;
18965
18966        /**
18967         * Indicates whether the view's window is currently in touch mode.
18968         */
18969        boolean mInTouchMode;
18970
18971        /**
18972         * Indicates that ViewAncestor should trigger a global layout change
18973         * the next time it performs a traversal
18974         */
18975        boolean mRecomputeGlobalAttributes;
18976
18977        /**
18978         * Always report new attributes at next traversal.
18979         */
18980        boolean mForceReportNewAttributes;
18981
18982        /**
18983         * Set during a traveral if any views want to keep the screen on.
18984         */
18985        boolean mKeepScreenOn;
18986
18987        /**
18988         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18989         */
18990        int mSystemUiVisibility;
18991
18992        /**
18993         * Hack to force certain system UI visibility flags to be cleared.
18994         */
18995        int mDisabledSystemUiVisibility;
18996
18997        /**
18998         * Last global system UI visibility reported by the window manager.
18999         */
19000        int mGlobalSystemUiVisibility;
19001
19002        /**
19003         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19004         * attached.
19005         */
19006        boolean mHasSystemUiListeners;
19007
19008        /**
19009         * Set if the window has requested to extend into the overscan region
19010         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19011         */
19012        boolean mOverscanRequested;
19013
19014        /**
19015         * Set if the visibility of any views has changed.
19016         */
19017        boolean mViewVisibilityChanged;
19018
19019        /**
19020         * Set to true if a view has been scrolled.
19021         */
19022        boolean mViewScrollChanged;
19023
19024        /**
19025         * Global to the view hierarchy used as a temporary for dealing with
19026         * x/y points in the transparent region computations.
19027         */
19028        final int[] mTransparentLocation = new int[2];
19029
19030        /**
19031         * Global to the view hierarchy used as a temporary for dealing with
19032         * x/y points in the ViewGroup.invalidateChild implementation.
19033         */
19034        final int[] mInvalidateChildLocation = new int[2];
19035
19036
19037        /**
19038         * Global to the view hierarchy used as a temporary for dealing with
19039         * x/y location when view is transformed.
19040         */
19041        final float[] mTmpTransformLocation = new float[2];
19042
19043        /**
19044         * The view tree observer used to dispatch global events like
19045         * layout, pre-draw, touch mode change, etc.
19046         */
19047        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19048
19049        /**
19050         * A Canvas used by the view hierarchy to perform bitmap caching.
19051         */
19052        Canvas mCanvas;
19053
19054        /**
19055         * The view root impl.
19056         */
19057        final ViewRootImpl mViewRootImpl;
19058
19059        /**
19060         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19061         * handler can be used to pump events in the UI events queue.
19062         */
19063        final Handler mHandler;
19064
19065        /**
19066         * Temporary for use in computing invalidate rectangles while
19067         * calling up the hierarchy.
19068         */
19069        final Rect mTmpInvalRect = new Rect();
19070
19071        /**
19072         * Temporary for use in computing hit areas with transformed views
19073         */
19074        final RectF mTmpTransformRect = new RectF();
19075
19076        /**
19077         * Temporary for use in transforming invalidation rect
19078         */
19079        final Matrix mTmpMatrix = new Matrix();
19080
19081        /**
19082         * Temporary for use in transforming invalidation rect
19083         */
19084        final Transformation mTmpTransformation = new Transformation();
19085
19086        /**
19087         * Temporary list for use in collecting focusable descendents of a view.
19088         */
19089        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19090
19091        /**
19092         * The id of the window for accessibility purposes.
19093         */
19094        int mAccessibilityWindowId = View.NO_ID;
19095
19096        /**
19097         * Flags related to accessibility processing.
19098         *
19099         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19100         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19101         */
19102        int mAccessibilityFetchFlags;
19103
19104        /**
19105         * The drawable for highlighting accessibility focus.
19106         */
19107        Drawable mAccessibilityFocusDrawable;
19108
19109        /**
19110         * Show where the margins, bounds and layout bounds are for each view.
19111         */
19112        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19113
19114        /**
19115         * Point used to compute visible regions.
19116         */
19117        final Point mPoint = new Point();
19118
19119        /**
19120         * Used to track which View originated a requestLayout() call, used when
19121         * requestLayout() is called during layout.
19122         */
19123        View mViewRequestingLayout;
19124
19125        /**
19126         * Creates a new set of attachment information with the specified
19127         * events handler and thread.
19128         *
19129         * @param handler the events handler the view must use
19130         */
19131        AttachInfo(IWindowSession session, IWindow window, Display display,
19132                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19133            mSession = session;
19134            mWindow = window;
19135            mWindowToken = window.asBinder();
19136            mDisplay = display;
19137            mViewRootImpl = viewRootImpl;
19138            mHandler = handler;
19139            mRootCallbacks = effectPlayer;
19140        }
19141    }
19142
19143    /**
19144     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19145     * is supported. This avoids keeping too many unused fields in most
19146     * instances of View.</p>
19147     */
19148    private static class ScrollabilityCache implements Runnable {
19149
19150        /**
19151         * Scrollbars are not visible
19152         */
19153        public static final int OFF = 0;
19154
19155        /**
19156         * Scrollbars are visible
19157         */
19158        public static final int ON = 1;
19159
19160        /**
19161         * Scrollbars are fading away
19162         */
19163        public static final int FADING = 2;
19164
19165        public boolean fadeScrollBars;
19166
19167        public int fadingEdgeLength;
19168        public int scrollBarDefaultDelayBeforeFade;
19169        public int scrollBarFadeDuration;
19170
19171        public int scrollBarSize;
19172        public ScrollBarDrawable scrollBar;
19173        public float[] interpolatorValues;
19174        public View host;
19175
19176        public final Paint paint;
19177        public final Matrix matrix;
19178        public Shader shader;
19179
19180        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19181
19182        private static final float[] OPAQUE = { 255 };
19183        private static final float[] TRANSPARENT = { 0.0f };
19184
19185        /**
19186         * When fading should start. This time moves into the future every time
19187         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19188         */
19189        public long fadeStartTime;
19190
19191
19192        /**
19193         * The current state of the scrollbars: ON, OFF, or FADING
19194         */
19195        public int state = OFF;
19196
19197        private int mLastColor;
19198
19199        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19200            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19201            scrollBarSize = configuration.getScaledScrollBarSize();
19202            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19203            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19204
19205            paint = new Paint();
19206            matrix = new Matrix();
19207            // use use a height of 1, and then wack the matrix each time we
19208            // actually use it.
19209            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19210            paint.setShader(shader);
19211            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19212
19213            this.host = host;
19214        }
19215
19216        public void setFadeColor(int color) {
19217            if (color != mLastColor) {
19218                mLastColor = color;
19219
19220                if (color != 0) {
19221                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19222                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19223                    paint.setShader(shader);
19224                    // Restore the default transfer mode (src_over)
19225                    paint.setXfermode(null);
19226                } else {
19227                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19228                    paint.setShader(shader);
19229                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19230                }
19231            }
19232        }
19233
19234        public void run() {
19235            long now = AnimationUtils.currentAnimationTimeMillis();
19236            if (now >= fadeStartTime) {
19237
19238                // the animation fades the scrollbars out by changing
19239                // the opacity (alpha) from fully opaque to fully
19240                // transparent
19241                int nextFrame = (int) now;
19242                int framesCount = 0;
19243
19244                Interpolator interpolator = scrollBarInterpolator;
19245
19246                // Start opaque
19247                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19248
19249                // End transparent
19250                nextFrame += scrollBarFadeDuration;
19251                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19252
19253                state = FADING;
19254
19255                // Kick off the fade animation
19256                host.invalidate(true);
19257            }
19258        }
19259    }
19260
19261    /**
19262     * Resuable callback for sending
19263     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19264     */
19265    private class SendViewScrolledAccessibilityEvent implements Runnable {
19266        public volatile boolean mIsPending;
19267
19268        public void run() {
19269            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19270            mIsPending = false;
19271        }
19272    }
19273
19274    /**
19275     * <p>
19276     * This class represents a delegate that can be registered in a {@link View}
19277     * to enhance accessibility support via composition rather via inheritance.
19278     * It is specifically targeted to widget developers that extend basic View
19279     * classes i.e. classes in package android.view, that would like their
19280     * applications to be backwards compatible.
19281     * </p>
19282     * <div class="special reference">
19283     * <h3>Developer Guides</h3>
19284     * <p>For more information about making applications accessible, read the
19285     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19286     * developer guide.</p>
19287     * </div>
19288     * <p>
19289     * A scenario in which a developer would like to use an accessibility delegate
19290     * is overriding a method introduced in a later API version then the minimal API
19291     * version supported by the application. For example, the method
19292     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19293     * in API version 4 when the accessibility APIs were first introduced. If a
19294     * developer would like his application to run on API version 4 devices (assuming
19295     * all other APIs used by the application are version 4 or lower) and take advantage
19296     * of this method, instead of overriding the method which would break the application's
19297     * backwards compatibility, he can override the corresponding method in this
19298     * delegate and register the delegate in the target View if the API version of
19299     * the system is high enough i.e. the API version is same or higher to the API
19300     * version that introduced
19301     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
19302     * </p>
19303     * <p>
19304     * Here is an example implementation:
19305     * </p>
19306     * <code><pre><p>
19307     * if (Build.VERSION.SDK_INT >= 14) {
19308     *     // If the API version is equal of higher than the version in
19309     *     // which onInitializeAccessibilityNodeInfo was introduced we
19310     *     // register a delegate with a customized implementation.
19311     *     View view = findViewById(R.id.view_id);
19312     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
19313     *         public void onInitializeAccessibilityNodeInfo(View host,
19314     *                 AccessibilityNodeInfo info) {
19315     *             // Let the default implementation populate the info.
19316     *             super.onInitializeAccessibilityNodeInfo(host, info);
19317     *             // Set some other information.
19318     *             info.setEnabled(host.isEnabled());
19319     *         }
19320     *     });
19321     * }
19322     * </code></pre></p>
19323     * <p>
19324     * This delegate contains methods that correspond to the accessibility methods
19325     * in View. If a delegate has been specified the implementation in View hands
19326     * off handling to the corresponding method in this delegate. The default
19327     * implementation the delegate methods behaves exactly as the corresponding
19328     * method in View for the case of no accessibility delegate been set. Hence,
19329     * to customize the behavior of a View method, clients can override only the
19330     * corresponding delegate method without altering the behavior of the rest
19331     * accessibility related methods of the host view.
19332     * </p>
19333     */
19334    public static class AccessibilityDelegate {
19335
19336        /**
19337         * Sends an accessibility event of the given type. If accessibility is not
19338         * enabled this method has no effect.
19339         * <p>
19340         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
19341         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
19342         * been set.
19343         * </p>
19344         *
19345         * @param host The View hosting the delegate.
19346         * @param eventType The type of the event to send.
19347         *
19348         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
19349         */
19350        public void sendAccessibilityEvent(View host, int eventType) {
19351            host.sendAccessibilityEventInternal(eventType);
19352        }
19353
19354        /**
19355         * Performs the specified accessibility action on the view. For
19356         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
19357         * <p>
19358         * The default implementation behaves as
19359         * {@link View#performAccessibilityAction(int, Bundle)
19360         *  View#performAccessibilityAction(int, Bundle)} for the case of
19361         *  no accessibility delegate been set.
19362         * </p>
19363         *
19364         * @param action The action to perform.
19365         * @return Whether the action was performed.
19366         *
19367         * @see View#performAccessibilityAction(int, Bundle)
19368         *      View#performAccessibilityAction(int, Bundle)
19369         */
19370        public boolean performAccessibilityAction(View host, int action, Bundle args) {
19371            return host.performAccessibilityActionInternal(action, args);
19372        }
19373
19374        /**
19375         * Sends an accessibility event. This method behaves exactly as
19376         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
19377         * empty {@link AccessibilityEvent} and does not perform a check whether
19378         * accessibility is enabled.
19379         * <p>
19380         * The default implementation behaves as
19381         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19382         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
19383         * the case of no accessibility delegate been set.
19384         * </p>
19385         *
19386         * @param host The View hosting the delegate.
19387         * @param event The event to send.
19388         *
19389         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19390         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19391         */
19392        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
19393            host.sendAccessibilityEventUncheckedInternal(event);
19394        }
19395
19396        /**
19397         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
19398         * to its children for adding their text content to the event.
19399         * <p>
19400         * The default implementation behaves as
19401         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19402         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
19403         * the case of no accessibility delegate been set.
19404         * </p>
19405         *
19406         * @param host The View hosting the delegate.
19407         * @param event The event.
19408         * @return True if the event population was completed.
19409         *
19410         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19411         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19412         */
19413        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19414            return host.dispatchPopulateAccessibilityEventInternal(event);
19415        }
19416
19417        /**
19418         * Gives a chance to the host View to populate the accessibility event with its
19419         * text content.
19420         * <p>
19421         * The default implementation behaves as
19422         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
19423         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
19424         * the case of no accessibility delegate been set.
19425         * </p>
19426         *
19427         * @param host The View hosting the delegate.
19428         * @param event The accessibility event which to populate.
19429         *
19430         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
19431         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
19432         */
19433        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19434            host.onPopulateAccessibilityEventInternal(event);
19435        }
19436
19437        /**
19438         * Initializes an {@link AccessibilityEvent} with information about the
19439         * the host View which is the event source.
19440         * <p>
19441         * The default implementation behaves as
19442         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
19443         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
19444         * the case of no accessibility delegate been set.
19445         * </p>
19446         *
19447         * @param host The View hosting the delegate.
19448         * @param event The event to initialize.
19449         *
19450         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
19451         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
19452         */
19453        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
19454            host.onInitializeAccessibilityEventInternal(event);
19455        }
19456
19457        /**
19458         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
19459         * <p>
19460         * The default implementation behaves as
19461         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19462         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19463         * the case of no accessibility delegate been set.
19464         * </p>
19465         *
19466         * @param host The View hosting the delegate.
19467         * @param info The instance to initialize.
19468         *
19469         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19470         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19471         */
19472        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19473            host.onInitializeAccessibilityNodeInfoInternal(info);
19474        }
19475
19476        /**
19477         * Called when a child of the host View has requested sending an
19478         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19479         * to augment the event.
19480         * <p>
19481         * The default implementation behaves as
19482         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19483         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19484         * the case of no accessibility delegate been set.
19485         * </p>
19486         *
19487         * @param host The View hosting the delegate.
19488         * @param child The child which requests sending the event.
19489         * @param event The event to be sent.
19490         * @return True if the event should be sent
19491         *
19492         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19493         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19494         */
19495        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
19496                AccessibilityEvent event) {
19497            return host.onRequestSendAccessibilityEventInternal(child, event);
19498        }
19499
19500        /**
19501         * Gets the provider for managing a virtual view hierarchy rooted at this View
19502         * and reported to {@link android.accessibilityservice.AccessibilityService}s
19503         * that explore the window content.
19504         * <p>
19505         * The default implementation behaves as
19506         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
19507         * the case of no accessibility delegate been set.
19508         * </p>
19509         *
19510         * @return The provider.
19511         *
19512         * @see AccessibilityNodeProvider
19513         */
19514        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
19515            return null;
19516        }
19517
19518        /**
19519         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
19520         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
19521         * This method is responsible for obtaining an accessibility node info from a
19522         * pool of reusable instances and calling
19523         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
19524         * view to initialize the former.
19525         * <p>
19526         * <strong>Note:</strong> The client is responsible for recycling the obtained
19527         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
19528         * creation.
19529         * </p>
19530         * <p>
19531         * The default implementation behaves as
19532         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
19533         * the case of no accessibility delegate been set.
19534         * </p>
19535         * @return A populated {@link AccessibilityNodeInfo}.
19536         *
19537         * @see AccessibilityNodeInfo
19538         *
19539         * @hide
19540         */
19541        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
19542            return host.createAccessibilityNodeInfoInternal();
19543        }
19544    }
19545
19546    private class MatchIdPredicate implements Predicate<View> {
19547        public int mId;
19548
19549        @Override
19550        public boolean apply(View view) {
19551            return (view.mID == mId);
19552        }
19553    }
19554
19555    private class MatchLabelForPredicate implements Predicate<View> {
19556        private int mLabeledId;
19557
19558        @Override
19559        public boolean apply(View view) {
19560            return (view.mLabelForId == mLabeledId);
19561        }
19562    }
19563
19564    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19565        private int mChangeTypes = 0;
19566        private boolean mPosted;
19567        private boolean mPostedWithDelay;
19568        private long mLastEventTimeMillis;
19569
19570        @Override
19571        public void run() {
19572            mPosted = false;
19573            mPostedWithDelay = false;
19574            mLastEventTimeMillis = SystemClock.uptimeMillis();
19575            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19576                final AccessibilityEvent event = AccessibilityEvent.obtain();
19577                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19578                event.setContentChangeTypes(mChangeTypes);
19579                sendAccessibilityEventUnchecked(event);
19580            }
19581            mChangeTypes = 0;
19582        }
19583
19584        public void runOrPost(int changeType) {
19585            mChangeTypes |= changeType;
19586
19587            // If this is a live region or the child of a live region, collect
19588            // all events from this frame and send them on the next frame.
19589            if (inLiveRegion()) {
19590                // If we're already posted with a delay, remove that.
19591                if (mPostedWithDelay) {
19592                    removeCallbacks(this);
19593                    mPostedWithDelay = false;
19594                }
19595                // Only post if we're not already posted.
19596                if (!mPosted) {
19597                    post(this);
19598                    mPosted = true;
19599                }
19600                return;
19601            }
19602
19603            if (mPosted) {
19604                return;
19605            }
19606            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19607            final long minEventIntevalMillis =
19608                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19609            if (timeSinceLastMillis >= minEventIntevalMillis) {
19610                removeCallbacks(this);
19611                run();
19612            } else {
19613                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19614                mPosted = true;
19615                mPostedWithDelay = true;
19616            }
19617        }
19618    }
19619
19620    private boolean inLiveRegion() {
19621        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19622            return true;
19623        }
19624
19625        ViewParent parent = getParent();
19626        while (parent instanceof View) {
19627            if (((View) parent).getAccessibilityLiveRegion()
19628                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19629                return true;
19630            }
19631            parent = parent.getParent();
19632        }
19633
19634        return false;
19635    }
19636
19637    /**
19638     * Dump all private flags in readable format, useful for documentation and
19639     * sanity checking.
19640     */
19641    private static void dumpFlags() {
19642        final HashMap<String, String> found = Maps.newHashMap();
19643        try {
19644            for (Field field : View.class.getDeclaredFields()) {
19645                final int modifiers = field.getModifiers();
19646                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19647                    if (field.getType().equals(int.class)) {
19648                        final int value = field.getInt(null);
19649                        dumpFlag(found, field.getName(), value);
19650                    } else if (field.getType().equals(int[].class)) {
19651                        final int[] values = (int[]) field.get(null);
19652                        for (int i = 0; i < values.length; i++) {
19653                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19654                        }
19655                    }
19656                }
19657            }
19658        } catch (IllegalAccessException e) {
19659            throw new RuntimeException(e);
19660        }
19661
19662        final ArrayList<String> keys = Lists.newArrayList();
19663        keys.addAll(found.keySet());
19664        Collections.sort(keys);
19665        for (String key : keys) {
19666            Log.d(VIEW_LOG_TAG, found.get(key));
19667        }
19668    }
19669
19670    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19671        // Sort flags by prefix, then by bits, always keeping unique keys
19672        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19673        final int prefix = name.indexOf('_');
19674        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19675        final String output = bits + " " + name;
19676        found.put(key, output);
19677    }
19678}
19679