View.java revision 7adbecf0004a7aa0ad9d221220dd5db4cb1f1079
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    private static boolean sUseBrokenMakeMeasureSpec = false;
700
701    /**
702     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
703     * calling setFlags.
704     */
705    private static final int NOT_FOCUSABLE = 0x00000000;
706
707    /**
708     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
709     * setFlags.
710     */
711    private static final int FOCUSABLE = 0x00000001;
712
713    /**
714     * Mask for use with setFlags indicating bits used for focus.
715     */
716    private static final int FOCUSABLE_MASK = 0x00000001;
717
718    /**
719     * This view will adjust its padding to fit sytem windows (e.g. status bar)
720     */
721    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
722
723    /** @hide */
724    @IntDef({VISIBLE, INVISIBLE, GONE})
725    @Retention(RetentionPolicy.SOURCE)
726    public @interface Visibility {}
727
728    /**
729     * This view is visible.
730     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
731     * android:visibility}.
732     */
733    public static final int VISIBLE = 0x00000000;
734
735    /**
736     * This view is invisible, but it still takes up space for layout purposes.
737     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
738     * android:visibility}.
739     */
740    public static final int INVISIBLE = 0x00000004;
741
742    /**
743     * This view is invisible, and it doesn't take any space for layout
744     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
745     * android:visibility}.
746     */
747    public static final int GONE = 0x00000008;
748
749    /**
750     * Mask for use with setFlags indicating bits used for visibility.
751     * {@hide}
752     */
753    static final int VISIBILITY_MASK = 0x0000000C;
754
755    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
756
757    /**
758     * This view is enabled. Interpretation varies by subclass.
759     * Use with ENABLED_MASK when calling setFlags.
760     * {@hide}
761     */
762    static final int ENABLED = 0x00000000;
763
764    /**
765     * This view is disabled. Interpretation varies by subclass.
766     * Use with ENABLED_MASK when calling setFlags.
767     * {@hide}
768     */
769    static final int DISABLED = 0x00000020;
770
771   /**
772    * Mask for use with setFlags indicating bits used for indicating whether
773    * this view is enabled
774    * {@hide}
775    */
776    static final int ENABLED_MASK = 0x00000020;
777
778    /**
779     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
780     * called and further optimizations will be performed. It is okay to have
781     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
782     * {@hide}
783     */
784    static final int WILL_NOT_DRAW = 0x00000080;
785
786    /**
787     * Mask for use with setFlags indicating bits used for indicating whether
788     * this view is will draw
789     * {@hide}
790     */
791    static final int DRAW_MASK = 0x00000080;
792
793    /**
794     * <p>This view doesn't show scrollbars.</p>
795     * {@hide}
796     */
797    static final int SCROLLBARS_NONE = 0x00000000;
798
799    /**
800     * <p>This view shows horizontal scrollbars.</p>
801     * {@hide}
802     */
803    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
804
805    /**
806     * <p>This view shows vertical scrollbars.</p>
807     * {@hide}
808     */
809    static final int SCROLLBARS_VERTICAL = 0x00000200;
810
811    /**
812     * <p>Mask for use with setFlags indicating bits used for indicating which
813     * scrollbars are enabled.</p>
814     * {@hide}
815     */
816    static final int SCROLLBARS_MASK = 0x00000300;
817
818    /**
819     * Indicates that the view should filter touches when its window is obscured.
820     * Refer to the class comments for more information about this security feature.
821     * {@hide}
822     */
823    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
824
825    /**
826     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
827     * that they are optional and should be skipped if the window has
828     * requested system UI flags that ignore those insets for layout.
829     */
830    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
831
832    /**
833     * <p>This view doesn't show fading edges.</p>
834     * {@hide}
835     */
836    static final int FADING_EDGE_NONE = 0x00000000;
837
838    /**
839     * <p>This view shows horizontal fading edges.</p>
840     * {@hide}
841     */
842    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
843
844    /**
845     * <p>This view shows vertical fading edges.</p>
846     * {@hide}
847     */
848    static final int FADING_EDGE_VERTICAL = 0x00002000;
849
850    /**
851     * <p>Mask for use with setFlags indicating bits used for indicating which
852     * fading edges are enabled.</p>
853     * {@hide}
854     */
855    static final int FADING_EDGE_MASK = 0x00003000;
856
857    /**
858     * <p>Indicates this view can be clicked. When clickable, a View reacts
859     * to clicks by notifying the OnClickListener.<p>
860     * {@hide}
861     */
862    static final int CLICKABLE = 0x00004000;
863
864    /**
865     * <p>Indicates this view is caching its drawing into a bitmap.</p>
866     * {@hide}
867     */
868    static final int DRAWING_CACHE_ENABLED = 0x00008000;
869
870    /**
871     * <p>Indicates that no icicle should be saved for this view.<p>
872     * {@hide}
873     */
874    static final int SAVE_DISABLED = 0x000010000;
875
876    /**
877     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
878     * property.</p>
879     * {@hide}
880     */
881    static final int SAVE_DISABLED_MASK = 0x000010000;
882
883    /**
884     * <p>Indicates that no drawing cache should ever be created for this view.<p>
885     * {@hide}
886     */
887    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
888
889    /**
890     * <p>Indicates this view can take / keep focus when int touch mode.</p>
891     * {@hide}
892     */
893    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
894
895    /** @hide */
896    @Retention(RetentionPolicy.SOURCE)
897    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
898    public @interface DrawingCacheQuality {}
899
900    /**
901     * <p>Enables low quality mode for the drawing cache.</p>
902     */
903    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
904
905    /**
906     * <p>Enables high quality mode for the drawing cache.</p>
907     */
908    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
909
910    /**
911     * <p>Enables automatic quality mode for the drawing cache.</p>
912     */
913    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
914
915    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
916            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
917    };
918
919    /**
920     * <p>Mask for use with setFlags indicating bits used for the cache
921     * quality property.</p>
922     * {@hide}
923     */
924    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
925
926    /**
927     * <p>
928     * Indicates this view can be long clicked. When long clickable, a View
929     * reacts to long clicks by notifying the OnLongClickListener or showing a
930     * context menu.
931     * </p>
932     * {@hide}
933     */
934    static final int LONG_CLICKABLE = 0x00200000;
935
936    /**
937     * <p>Indicates that this view gets its drawable states from its direct parent
938     * and ignores its original internal states.</p>
939     *
940     * @hide
941     */
942    static final int DUPLICATE_PARENT_STATE = 0x00400000;
943
944    /** @hide */
945    @IntDef({
946        SCROLLBARS_INSIDE_OVERLAY,
947        SCROLLBARS_INSIDE_INSET,
948        SCROLLBARS_OUTSIDE_OVERLAY,
949        SCROLLBARS_OUTSIDE_INSET
950    })
951    @Retention(RetentionPolicy.SOURCE)
952    public @interface ScrollBarStyle {}
953
954    /**
955     * The scrollbar style to display the scrollbars inside the content area,
956     * without increasing the padding. The scrollbars will be overlaid with
957     * translucency on the view's content.
958     */
959    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
960
961    /**
962     * The scrollbar style to display the scrollbars inside the padded area,
963     * increasing the padding of the view. The scrollbars will not overlap the
964     * content area of the view.
965     */
966    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
967
968    /**
969     * The scrollbar style to display the scrollbars at the edge of the view,
970     * without increasing the padding. The scrollbars will be overlaid with
971     * translucency.
972     */
973    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
974
975    /**
976     * The scrollbar style to display the scrollbars at the edge of the view,
977     * increasing the padding of the view. The scrollbars will only overlap the
978     * background, if any.
979     */
980    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
981
982    /**
983     * Mask to check if the scrollbar style is overlay or inset.
984     * {@hide}
985     */
986    static final int SCROLLBARS_INSET_MASK = 0x01000000;
987
988    /**
989     * Mask to check if the scrollbar style is inside or outside.
990     * {@hide}
991     */
992    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
993
994    /**
995     * Mask for scrollbar style.
996     * {@hide}
997     */
998    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
999
1000    /**
1001     * View flag indicating that the screen should remain on while the
1002     * window containing this view is visible to the user.  This effectively
1003     * takes care of automatically setting the WindowManager's
1004     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1005     */
1006    public static final int KEEP_SCREEN_ON = 0x04000000;
1007
1008    /**
1009     * View flag indicating whether this view should have sound effects enabled
1010     * for events such as clicking and touching.
1011     */
1012    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1013
1014    /**
1015     * View flag indicating whether this view should have haptic feedback
1016     * enabled for events such as long presses.
1017     */
1018    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1019
1020    /**
1021     * <p>Indicates that the view hierarchy should stop saving state when
1022     * it reaches this view.  If state saving is initiated immediately at
1023     * the view, it will be allowed.
1024     * {@hide}
1025     */
1026    static final int PARENT_SAVE_DISABLED = 0x20000000;
1027
1028    /**
1029     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1030     * {@hide}
1031     */
1032    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1033
1034    /** @hide */
1035    @IntDef(flag = true,
1036            value = {
1037                FOCUSABLES_ALL,
1038                FOCUSABLES_TOUCH_MODE
1039            })
1040    @Retention(RetentionPolicy.SOURCE)
1041    public @interface FocusableMode {}
1042
1043    /**
1044     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1045     * should add all focusable Views regardless if they are focusable in touch mode.
1046     */
1047    public static final int FOCUSABLES_ALL = 0x00000000;
1048
1049    /**
1050     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1051     * should add only Views focusable in touch mode.
1052     */
1053    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1054
1055    /** @hide */
1056    @IntDef({
1057            FOCUS_BACKWARD,
1058            FOCUS_FORWARD,
1059            FOCUS_LEFT,
1060            FOCUS_UP,
1061            FOCUS_RIGHT,
1062            FOCUS_DOWN
1063    })
1064    @Retention(RetentionPolicy.SOURCE)
1065    public @interface FocusDirection {}
1066
1067    /** @hide */
1068    @IntDef({
1069            FOCUS_LEFT,
1070            FOCUS_UP,
1071            FOCUS_RIGHT,
1072            FOCUS_DOWN
1073    })
1074    @Retention(RetentionPolicy.SOURCE)
1075    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1076
1077    /**
1078     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1079     * item.
1080     */
1081    public static final int FOCUS_BACKWARD = 0x00000001;
1082
1083    /**
1084     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1085     * item.
1086     */
1087    public static final int FOCUS_FORWARD = 0x00000002;
1088
1089    /**
1090     * Use with {@link #focusSearch(int)}. Move focus to the left.
1091     */
1092    public static final int FOCUS_LEFT = 0x00000011;
1093
1094    /**
1095     * Use with {@link #focusSearch(int)}. Move focus up.
1096     */
1097    public static final int FOCUS_UP = 0x00000021;
1098
1099    /**
1100     * Use with {@link #focusSearch(int)}. Move focus to the right.
1101     */
1102    public static final int FOCUS_RIGHT = 0x00000042;
1103
1104    /**
1105     * Use with {@link #focusSearch(int)}. Move focus down.
1106     */
1107    public static final int FOCUS_DOWN = 0x00000082;
1108
1109    /**
1110     * Bits of {@link #getMeasuredWidthAndState()} and
1111     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1112     */
1113    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1114
1115    /**
1116     * Bits of {@link #getMeasuredWidthAndState()} and
1117     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1118     */
1119    public static final int MEASURED_STATE_MASK = 0xff000000;
1120
1121    /**
1122     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1123     * for functions that combine both width and height into a single int,
1124     * such as {@link #getMeasuredState()} and the childState argument of
1125     * {@link #resolveSizeAndState(int, int, int)}.
1126     */
1127    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1128
1129    /**
1130     * Bit of {@link #getMeasuredWidthAndState()} and
1131     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1132     * is smaller that the space the view would like to have.
1133     */
1134    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1135
1136    /**
1137     * Base View state sets
1138     */
1139    // Singles
1140    /**
1141     * Indicates the view has no states set. States are used with
1142     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1143     * view depending on its state.
1144     *
1145     * @see android.graphics.drawable.Drawable
1146     * @see #getDrawableState()
1147     */
1148    protected static final int[] EMPTY_STATE_SET;
1149    /**
1150     * Indicates the view is enabled. States are used with
1151     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1152     * view depending on its state.
1153     *
1154     * @see android.graphics.drawable.Drawable
1155     * @see #getDrawableState()
1156     */
1157    protected static final int[] ENABLED_STATE_SET;
1158    /**
1159     * Indicates the view is focused. States are used with
1160     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1161     * view depending on its state.
1162     *
1163     * @see android.graphics.drawable.Drawable
1164     * @see #getDrawableState()
1165     */
1166    protected static final int[] FOCUSED_STATE_SET;
1167    /**
1168     * Indicates the view is selected. States are used with
1169     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1170     * view depending on its state.
1171     *
1172     * @see android.graphics.drawable.Drawable
1173     * @see #getDrawableState()
1174     */
1175    protected static final int[] SELECTED_STATE_SET;
1176    /**
1177     * Indicates the view is pressed. States are used with
1178     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1179     * view depending on its state.
1180     *
1181     * @see android.graphics.drawable.Drawable
1182     * @see #getDrawableState()
1183     */
1184    protected static final int[] PRESSED_STATE_SET;
1185    /**
1186     * Indicates the view's window has focus. States are used with
1187     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1188     * view depending on its state.
1189     *
1190     * @see android.graphics.drawable.Drawable
1191     * @see #getDrawableState()
1192     */
1193    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1194    // Doubles
1195    /**
1196     * Indicates the view is enabled and has the focus.
1197     *
1198     * @see #ENABLED_STATE_SET
1199     * @see #FOCUSED_STATE_SET
1200     */
1201    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1202    /**
1203     * Indicates the view is enabled and selected.
1204     *
1205     * @see #ENABLED_STATE_SET
1206     * @see #SELECTED_STATE_SET
1207     */
1208    protected static final int[] ENABLED_SELECTED_STATE_SET;
1209    /**
1210     * Indicates the view is enabled and that its window has focus.
1211     *
1212     * @see #ENABLED_STATE_SET
1213     * @see #WINDOW_FOCUSED_STATE_SET
1214     */
1215    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1216    /**
1217     * Indicates the view is focused and selected.
1218     *
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     */
1222    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1223    /**
1224     * Indicates the view has the focus and that its window has the focus.
1225     *
1226     * @see #FOCUSED_STATE_SET
1227     * @see #WINDOW_FOCUSED_STATE_SET
1228     */
1229    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is selected and that its window has the focus.
1232     *
1233     * @see #SELECTED_STATE_SET
1234     * @see #WINDOW_FOCUSED_STATE_SET
1235     */
1236    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1237    // Triples
1238    /**
1239     * Indicates the view is enabled, focused and selected.
1240     *
1241     * @see #ENABLED_STATE_SET
1242     * @see #FOCUSED_STATE_SET
1243     * @see #SELECTED_STATE_SET
1244     */
1245    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1246    /**
1247     * Indicates the view is enabled, focused and its window has the focus.
1248     *
1249     * @see #ENABLED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     * @see #WINDOW_FOCUSED_STATE_SET
1252     */
1253    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1254    /**
1255     * Indicates the view is enabled, selected and its window has the focus.
1256     *
1257     * @see #ENABLED_STATE_SET
1258     * @see #SELECTED_STATE_SET
1259     * @see #WINDOW_FOCUSED_STATE_SET
1260     */
1261    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1262    /**
1263     * Indicates the view is focused, selected and its window has the focus.
1264     *
1265     * @see #FOCUSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     * @see #WINDOW_FOCUSED_STATE_SET
1268     */
1269    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1270    /**
1271     * Indicates the view is enabled, focused, selected and its window
1272     * has the focus.
1273     *
1274     * @see #ENABLED_STATE_SET
1275     * @see #FOCUSED_STATE_SET
1276     * @see #SELECTED_STATE_SET
1277     * @see #WINDOW_FOCUSED_STATE_SET
1278     */
1279    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1280    /**
1281     * Indicates the view is pressed and its window has the focus.
1282     *
1283     * @see #PRESSED_STATE_SET
1284     * @see #WINDOW_FOCUSED_STATE_SET
1285     */
1286    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1287    /**
1288     * Indicates the view is pressed and selected.
1289     *
1290     * @see #PRESSED_STATE_SET
1291     * @see #SELECTED_STATE_SET
1292     */
1293    protected static final int[] PRESSED_SELECTED_STATE_SET;
1294    /**
1295     * Indicates the view is pressed, selected and its window has the focus.
1296     *
1297     * @see #PRESSED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     * @see #WINDOW_FOCUSED_STATE_SET
1300     */
1301    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1302    /**
1303     * Indicates the view is pressed and focused.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #FOCUSED_STATE_SET
1307     */
1308    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1309    /**
1310     * Indicates the view is pressed, focused and its window has the focus.
1311     *
1312     * @see #PRESSED_STATE_SET
1313     * @see #FOCUSED_STATE_SET
1314     * @see #WINDOW_FOCUSED_STATE_SET
1315     */
1316    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1317    /**
1318     * Indicates the view is pressed, focused and selected.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     * @see #FOCUSED_STATE_SET
1323     */
1324    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1325    /**
1326     * Indicates the view is pressed, focused, selected and its window has the focus.
1327     *
1328     * @see #PRESSED_STATE_SET
1329     * @see #FOCUSED_STATE_SET
1330     * @see #SELECTED_STATE_SET
1331     * @see #WINDOW_FOCUSED_STATE_SET
1332     */
1333    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1334    /**
1335     * Indicates the view is pressed and enabled.
1336     *
1337     * @see #PRESSED_STATE_SET
1338     * @see #ENABLED_STATE_SET
1339     */
1340    protected static final int[] PRESSED_ENABLED_STATE_SET;
1341    /**
1342     * Indicates the view is pressed, enabled and its window has the focus.
1343     *
1344     * @see #PRESSED_STATE_SET
1345     * @see #ENABLED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1349    /**
1350     * Indicates the view is pressed, enabled and selected.
1351     *
1352     * @see #PRESSED_STATE_SET
1353     * @see #ENABLED_STATE_SET
1354     * @see #SELECTED_STATE_SET
1355     */
1356    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1357    /**
1358     * Indicates the view is pressed, enabled, selected and its window has the
1359     * focus.
1360     *
1361     * @see #PRESSED_STATE_SET
1362     * @see #ENABLED_STATE_SET
1363     * @see #SELECTED_STATE_SET
1364     * @see #WINDOW_FOCUSED_STATE_SET
1365     */
1366    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1367    /**
1368     * Indicates the view is pressed, enabled and focused.
1369     *
1370     * @see #PRESSED_STATE_SET
1371     * @see #ENABLED_STATE_SET
1372     * @see #FOCUSED_STATE_SET
1373     */
1374    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1375    /**
1376     * Indicates the view is pressed, enabled, focused and its window has the
1377     * focus.
1378     *
1379     * @see #PRESSED_STATE_SET
1380     * @see #ENABLED_STATE_SET
1381     * @see #FOCUSED_STATE_SET
1382     * @see #WINDOW_FOCUSED_STATE_SET
1383     */
1384    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1385    /**
1386     * Indicates the view is pressed, enabled, focused and selected.
1387     *
1388     * @see #PRESSED_STATE_SET
1389     * @see #ENABLED_STATE_SET
1390     * @see #SELECTED_STATE_SET
1391     * @see #FOCUSED_STATE_SET
1392     */
1393    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1394    /**
1395     * Indicates the view is pressed, enabled, focused, selected and its window
1396     * has the focus.
1397     *
1398     * @see #PRESSED_STATE_SET
1399     * @see #ENABLED_STATE_SET
1400     * @see #SELECTED_STATE_SET
1401     * @see #FOCUSED_STATE_SET
1402     * @see #WINDOW_FOCUSED_STATE_SET
1403     */
1404    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1405
1406    /**
1407     * The order here is very important to {@link #getDrawableState()}
1408     */
1409    private static final int[][] VIEW_STATE_SETS;
1410
1411    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1412    static final int VIEW_STATE_SELECTED = 1 << 1;
1413    static final int VIEW_STATE_FOCUSED = 1 << 2;
1414    static final int VIEW_STATE_ENABLED = 1 << 3;
1415    static final int VIEW_STATE_PRESSED = 1 << 4;
1416    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1417    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1418    static final int VIEW_STATE_HOVERED = 1 << 7;
1419    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1420    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1421
1422    static final int[] VIEW_STATE_IDS = new int[] {
1423        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1424        R.attr.state_selected,          VIEW_STATE_SELECTED,
1425        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1426        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1427        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1428        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1429        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1430        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1431        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1432        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1433    };
1434
1435    static {
1436        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1437            throw new IllegalStateException(
1438                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1439        }
1440        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1441        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1442            int viewState = R.styleable.ViewDrawableStates[i];
1443            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1444                if (VIEW_STATE_IDS[j] == viewState) {
1445                    orderedIds[i * 2] = viewState;
1446                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1447                }
1448            }
1449        }
1450        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1451        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1452        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1453            int numBits = Integer.bitCount(i);
1454            int[] set = new int[numBits];
1455            int pos = 0;
1456            for (int j = 0; j < orderedIds.length; j += 2) {
1457                if ((i & orderedIds[j+1]) != 0) {
1458                    set[pos++] = orderedIds[j];
1459                }
1460            }
1461            VIEW_STATE_SETS[i] = set;
1462        }
1463
1464        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1465        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1466        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1467        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1469        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1470        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1472        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1474        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1476                | VIEW_STATE_FOCUSED];
1477        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1478        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1479                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1480        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1482        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1483                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1484                | VIEW_STATE_ENABLED];
1485        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1486                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1487        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1488                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1489                | VIEW_STATE_ENABLED];
1490        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1492                | VIEW_STATE_ENABLED];
1493        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1495                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1496
1497        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1498        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1499                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1500        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1502        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1504                | VIEW_STATE_PRESSED];
1505        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1507        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1508                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1509                | VIEW_STATE_PRESSED];
1510        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1512                | VIEW_STATE_PRESSED];
1513        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1515                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1516        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1518        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1519                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1520                | VIEW_STATE_PRESSED];
1521        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1523                | VIEW_STATE_PRESSED];
1524        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1525                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1526                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1527        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1528                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1529                | VIEW_STATE_PRESSED];
1530        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1532                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1533        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1535                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1536        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1538                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1539                | VIEW_STATE_PRESSED];
1540    }
1541
1542    /**
1543     * Accessibility event types that are dispatched for text population.
1544     */
1545    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1546            AccessibilityEvent.TYPE_VIEW_CLICKED
1547            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1548            | AccessibilityEvent.TYPE_VIEW_SELECTED
1549            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1550            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1551            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1552            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1553            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1554            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1555            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1556            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1557
1558    /**
1559     * Temporary Rect currently for use in setBackground().  This will probably
1560     * be extended in the future to hold our own class with more than just
1561     * a Rect. :)
1562     */
1563    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1564
1565    /**
1566     * Map used to store views' tags.
1567     */
1568    private SparseArray<Object> mKeyedTags;
1569
1570    /**
1571     * The next available accessibility id.
1572     */
1573    private static int sNextAccessibilityViewId;
1574
1575    /**
1576     * The animation currently associated with this view.
1577     * @hide
1578     */
1579    protected Animation mCurrentAnimation = null;
1580
1581    /**
1582     * Width as measured during measure pass.
1583     * {@hide}
1584     */
1585    @ViewDebug.ExportedProperty(category = "measurement")
1586    int mMeasuredWidth;
1587
1588    /**
1589     * Height as measured during measure pass.
1590     * {@hide}
1591     */
1592    @ViewDebug.ExportedProperty(category = "measurement")
1593    int mMeasuredHeight;
1594
1595    /**
1596     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1597     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1598     * its display list. This flag, used only when hw accelerated, allows us to clear the
1599     * flag while retaining this information until it's needed (at getDisplayList() time and
1600     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1601     *
1602     * {@hide}
1603     */
1604    boolean mRecreateDisplayList = false;
1605
1606    /**
1607     * The view's identifier.
1608     * {@hide}
1609     *
1610     * @see #setId(int)
1611     * @see #getId()
1612     */
1613    @ViewDebug.ExportedProperty(resolveId = true)
1614    int mID = NO_ID;
1615
1616    /**
1617     * The stable ID of this view for accessibility purposes.
1618     */
1619    int mAccessibilityViewId = NO_ID;
1620
1621    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1622
1623    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1624
1625    /**
1626     * The view's tag.
1627     * {@hide}
1628     *
1629     * @see #setTag(Object)
1630     * @see #getTag()
1631     */
1632    protected Object mTag;
1633
1634    // for mPrivateFlags:
1635    /** {@hide} */
1636    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1637    /** {@hide} */
1638    static final int PFLAG_FOCUSED                     = 0x00000002;
1639    /** {@hide} */
1640    static final int PFLAG_SELECTED                    = 0x00000004;
1641    /** {@hide} */
1642    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1643    /** {@hide} */
1644    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1645    /** {@hide} */
1646    static final int PFLAG_DRAWN                       = 0x00000020;
1647    /**
1648     * When this flag is set, this view is running an animation on behalf of its
1649     * children and should therefore not cancel invalidate requests, even if they
1650     * lie outside of this view's bounds.
1651     *
1652     * {@hide}
1653     */
1654    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1655    /** {@hide} */
1656    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1657    /** {@hide} */
1658    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1659    /** {@hide} */
1660    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1661    /** {@hide} */
1662    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1663    /** {@hide} */
1664    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1665    /** {@hide} */
1666    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1667    /** {@hide} */
1668    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1669
1670    private static final int PFLAG_PRESSED             = 0x00004000;
1671
1672    /** {@hide} */
1673    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1674    /**
1675     * Flag used to indicate that this view should be drawn once more (and only once
1676     * more) after its animation has completed.
1677     * {@hide}
1678     */
1679    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1680
1681    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1682
1683    /**
1684     * Indicates that the View returned true when onSetAlpha() was called and that
1685     * the alpha must be restored.
1686     * {@hide}
1687     */
1688    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1689
1690    /**
1691     * Set by {@link #setScrollContainer(boolean)}.
1692     */
1693    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1694
1695    /**
1696     * Set by {@link #setScrollContainer(boolean)}.
1697     */
1698    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1699
1700    /**
1701     * View flag indicating whether this view was invalidated (fully or partially.)
1702     *
1703     * @hide
1704     */
1705    static final int PFLAG_DIRTY                       = 0x00200000;
1706
1707    /**
1708     * View flag indicating whether this view was invalidated by an opaque
1709     * invalidate request.
1710     *
1711     * @hide
1712     */
1713    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1714
1715    /**
1716     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1717     *
1718     * @hide
1719     */
1720    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1721
1722    /**
1723     * Indicates whether the background is opaque.
1724     *
1725     * @hide
1726     */
1727    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1728
1729    /**
1730     * Indicates whether the scrollbars are opaque.
1731     *
1732     * @hide
1733     */
1734    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1735
1736    /**
1737     * Indicates whether the view is opaque.
1738     *
1739     * @hide
1740     */
1741    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1742
1743    /**
1744     * Indicates a prepressed state;
1745     * the short time between ACTION_DOWN and recognizing
1746     * a 'real' press. Prepressed is used to recognize quick taps
1747     * even when they are shorter than ViewConfiguration.getTapTimeout().
1748     *
1749     * @hide
1750     */
1751    private static final int PFLAG_PREPRESSED          = 0x02000000;
1752
1753    /**
1754     * Indicates whether the view is temporarily detached.
1755     *
1756     * @hide
1757     */
1758    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1759
1760    /**
1761     * Indicates that we should awaken scroll bars once attached
1762     *
1763     * @hide
1764     */
1765    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1766
1767    /**
1768     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1769     * @hide
1770     */
1771    private static final int PFLAG_HOVERED             = 0x10000000;
1772
1773    /**
1774     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1775     * for transform operations
1776     *
1777     * @hide
1778     */
1779    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1780
1781    /** {@hide} */
1782    static final int PFLAG_ACTIVATED                   = 0x40000000;
1783
1784    /**
1785     * Indicates that this view was specifically invalidated, not just dirtied because some
1786     * child view was invalidated. The flag is used to determine when we need to recreate
1787     * a view's display list (as opposed to just returning a reference to its existing
1788     * display list).
1789     *
1790     * @hide
1791     */
1792    static final int PFLAG_INVALIDATED                 = 0x80000000;
1793
1794    /**
1795     * Masks for mPrivateFlags2, as generated by dumpFlags():
1796     *
1797     * -------|-------|-------|-------|
1798     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1799     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1800     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1801     *                               1  PFLAG2_DRAG_HOVERED
1802     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1803     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1804     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1805     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1806     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1807     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1808     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1809     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1810     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1811     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1812     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1813     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1814     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1815     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1816     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1817     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1818     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1819     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1820     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1821     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1822     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1823     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1824     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1825     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1826     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1827     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1828     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1829     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1830     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1831     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1832     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1833     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1834     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1835     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1836     *   1                              PFLAG2_PADDING_RESOLVED
1837     * -------|-------|-------|-------|
1838     */
1839
1840    /**
1841     * Indicates that this view has reported that it can accept the current drag's content.
1842     * Cleared when the drag operation concludes.
1843     * @hide
1844     */
1845    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1846
1847    /**
1848     * Indicates that this view is currently directly under the drag location in a
1849     * drag-and-drop operation involving content that it can accept.  Cleared when
1850     * the drag exits the view, or when the drag operation concludes.
1851     * @hide
1852     */
1853    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1854
1855    /** @hide */
1856    @IntDef({
1857        LAYOUT_DIRECTION_LTR,
1858        LAYOUT_DIRECTION_RTL,
1859        LAYOUT_DIRECTION_INHERIT,
1860        LAYOUT_DIRECTION_LOCALE
1861    })
1862    @Retention(RetentionPolicy.SOURCE)
1863    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1864    public @interface LayoutDir {}
1865
1866    /** @hide */
1867    @IntDef({
1868        LAYOUT_DIRECTION_LTR,
1869        LAYOUT_DIRECTION_RTL
1870    })
1871    @Retention(RetentionPolicy.SOURCE)
1872    public @interface ResolvedLayoutDir {}
1873
1874    /**
1875     * Horizontal layout direction of this view is from Left to Right.
1876     * Use with {@link #setLayoutDirection}.
1877     */
1878    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1879
1880    /**
1881     * Horizontal layout direction of this view is from Right to Left.
1882     * Use with {@link #setLayoutDirection}.
1883     */
1884    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1885
1886    /**
1887     * Horizontal layout direction of this view is inherited from its parent.
1888     * Use with {@link #setLayoutDirection}.
1889     */
1890    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1891
1892    /**
1893     * Horizontal layout direction of this view is from deduced from the default language
1894     * script for the locale. Use with {@link #setLayoutDirection}.
1895     */
1896    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1897
1898    /**
1899     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1900     * @hide
1901     */
1902    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1903
1904    /**
1905     * Mask for use with private flags indicating bits used for horizontal layout direction.
1906     * @hide
1907     */
1908    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1909
1910    /**
1911     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1912     * right-to-left direction.
1913     * @hide
1914     */
1915    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1916
1917    /**
1918     * Indicates whether the view horizontal layout direction has been resolved.
1919     * @hide
1920     */
1921    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1922
1923    /**
1924     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1925     * @hide
1926     */
1927    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1928            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1929
1930    /*
1931     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1932     * flag value.
1933     * @hide
1934     */
1935    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1936            LAYOUT_DIRECTION_LTR,
1937            LAYOUT_DIRECTION_RTL,
1938            LAYOUT_DIRECTION_INHERIT,
1939            LAYOUT_DIRECTION_LOCALE
1940    };
1941
1942    /**
1943     * Default horizontal layout direction.
1944     */
1945    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1946
1947    /**
1948     * Default horizontal layout direction.
1949     * @hide
1950     */
1951    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1952
1953    /**
1954     * Indicates that the view is tracking some sort of transient state
1955     * that the app should not need to be aware of, but that the framework
1956     * should take special care to preserve.
1957     *
1958     * @hide
1959     */
1960    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1961
1962    /**
1963     * Text direction is inherited thru {@link ViewGroup}
1964     */
1965    public static final int TEXT_DIRECTION_INHERIT = 0;
1966
1967    /**
1968     * Text direction is using "first strong algorithm". The first strong directional character
1969     * determines the paragraph direction. If there is no strong directional character, the
1970     * paragraph direction is the view's resolved layout direction.
1971     */
1972    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1973
1974    /**
1975     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1976     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1977     * If there are neither, the paragraph direction is the view's resolved layout direction.
1978     */
1979    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1980
1981    /**
1982     * Text direction is forced to LTR.
1983     */
1984    public static final int TEXT_DIRECTION_LTR = 3;
1985
1986    /**
1987     * Text direction is forced to RTL.
1988     */
1989    public static final int TEXT_DIRECTION_RTL = 4;
1990
1991    /**
1992     * Text direction is coming from the system Locale.
1993     */
1994    public static final int TEXT_DIRECTION_LOCALE = 5;
1995
1996    /**
1997     * Default text direction is inherited
1998     */
1999    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2000
2001    /**
2002     * Default resolved text direction
2003     * @hide
2004     */
2005    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2006
2007    /**
2008     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2009     * @hide
2010     */
2011    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2012
2013    /**
2014     * Mask for use with private flags indicating bits used for text direction.
2015     * @hide
2016     */
2017    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2018            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2019
2020    /**
2021     * Array of text direction flags for mapping attribute "textDirection" to correct
2022     * flag value.
2023     * @hide
2024     */
2025    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2026            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2027            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2028            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2029            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2030            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2031            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2032    };
2033
2034    /**
2035     * Indicates whether the view text direction has been resolved.
2036     * @hide
2037     */
2038    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2039            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2040
2041    /**
2042     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2043     * @hide
2044     */
2045    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2046
2047    /**
2048     * Mask for use with private flags indicating bits used for resolved text direction.
2049     * @hide
2050     */
2051    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2052            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2053
2054    /**
2055     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2056     * @hide
2057     */
2058    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2059            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2060
2061    /** @hide */
2062    @IntDef({
2063        TEXT_ALIGNMENT_INHERIT,
2064        TEXT_ALIGNMENT_GRAVITY,
2065        TEXT_ALIGNMENT_CENTER,
2066        TEXT_ALIGNMENT_TEXT_START,
2067        TEXT_ALIGNMENT_TEXT_END,
2068        TEXT_ALIGNMENT_VIEW_START,
2069        TEXT_ALIGNMENT_VIEW_END
2070    })
2071    @Retention(RetentionPolicy.SOURCE)
2072    public @interface TextAlignment {}
2073
2074    /**
2075     * Default text alignment. The text alignment of this View is inherited from its parent.
2076     * Use with {@link #setTextAlignment(int)}
2077     */
2078    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2079
2080    /**
2081     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2082     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2083     *
2084     * Use with {@link #setTextAlignment(int)}
2085     */
2086    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2087
2088    /**
2089     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2090     *
2091     * Use with {@link #setTextAlignment(int)}
2092     */
2093    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2094
2095    /**
2096     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2097     *
2098     * Use with {@link #setTextAlignment(int)}
2099     */
2100    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2101
2102    /**
2103     * Center the paragraph, e.g. ALIGN_CENTER.
2104     *
2105     * Use with {@link #setTextAlignment(int)}
2106     */
2107    public static final int TEXT_ALIGNMENT_CENTER = 4;
2108
2109    /**
2110     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2111     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2112     *
2113     * Use with {@link #setTextAlignment(int)}
2114     */
2115    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2116
2117    /**
2118     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2119     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2120     *
2121     * Use with {@link #setTextAlignment(int)}
2122     */
2123    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2124
2125    /**
2126     * Default text alignment is inherited
2127     */
2128    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2129
2130    /**
2131     * Default resolved text alignment
2132     * @hide
2133     */
2134    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2135
2136    /**
2137      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2138      * @hide
2139      */
2140    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2141
2142    /**
2143      * Mask for use with private flags indicating bits used for text alignment.
2144      * @hide
2145      */
2146    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2147
2148    /**
2149     * Array of text direction flags for mapping attribute "textAlignment" to correct
2150     * flag value.
2151     * @hide
2152     */
2153    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2154            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2155            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2156            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2157            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2158            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2159            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2161    };
2162
2163    /**
2164     * Indicates whether the view text alignment has been resolved.
2165     * @hide
2166     */
2167    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2168
2169    /**
2170     * Bit shift to get the resolved text alignment.
2171     * @hide
2172     */
2173    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2174
2175    /**
2176     * Mask for use with private flags indicating bits used for text alignment.
2177     * @hide
2178     */
2179    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2180            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2181
2182    /**
2183     * Indicates whether if the view text alignment has been resolved to gravity
2184     */
2185    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2186            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2187
2188    // Accessiblity constants for mPrivateFlags2
2189
2190    /**
2191     * Shift for the bits in {@link #mPrivateFlags2} related to the
2192     * "importantForAccessibility" attribute.
2193     */
2194    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2195
2196    /**
2197     * Automatically determine whether a view is important for accessibility.
2198     */
2199    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2200
2201    /**
2202     * The view is important for accessibility.
2203     */
2204    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2205
2206    /**
2207     * The view is not important for accessibility.
2208     */
2209    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2210
2211    /**
2212     * The default whether the view is important for accessibility.
2213     */
2214    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2215
2216    /**
2217     * Mask for obtainig the bits which specify how to determine
2218     * whether a view is important for accessibility.
2219     */
2220    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2221        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2222        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2223
2224    /**
2225     * Shift for the bits in {@link #mPrivateFlags2} related to the
2226     * "accessibilityLiveRegion" attribute.
2227     */
2228    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 22;
2229
2230    /**
2231     * Live region mode specifying that accessibility services should not
2232     * automatically announce changes to this view. This is the default live
2233     * region mode for most views.
2234     * <p>
2235     * Use with {@link #setAccessibilityLiveRegion(int)}.
2236     */
2237    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2238
2239    /**
2240     * Live region mode specifying that accessibility services should announce
2241     * changes to this view.
2242     * <p>
2243     * Use with {@link #setAccessibilityLiveRegion(int)}.
2244     */
2245    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2246
2247    /**
2248     * Live region mode specifying that accessibility services should interrupt
2249     * ongoing speech to immediately announce changes to this view.
2250     * <p>
2251     * Use with {@link #setAccessibilityLiveRegion(int)}.
2252     */
2253    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2254
2255    /**
2256     * The default whether the view is important for accessibility.
2257     */
2258    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2259
2260    /**
2261     * Mask for obtaining the bits which specify a view's accessibility live
2262     * region mode.
2263     */
2264    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2265            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2266            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2267
2268    /**
2269     * Flag indicating whether a view has accessibility focus.
2270     */
2271    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2272
2273    /**
2274     * Flag whether the accessibility state of the subtree rooted at this view changed.
2275     */
2276    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2277
2278    /**
2279     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2280     * is used to check whether later changes to the view's transform should invalidate the
2281     * view to force the quickReject test to run again.
2282     */
2283    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2284
2285    /**
2286     * Flag indicating that start/end padding has been resolved into left/right padding
2287     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2288     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2289     * during measurement. In some special cases this is required such as when an adapter-based
2290     * view measures prospective children without attaching them to a window.
2291     */
2292    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2293
2294    /**
2295     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2296     */
2297    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2298
2299    /**
2300     * Group of bits indicating that RTL properties resolution is done.
2301     */
2302    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2303            PFLAG2_TEXT_DIRECTION_RESOLVED |
2304            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2305            PFLAG2_PADDING_RESOLVED |
2306            PFLAG2_DRAWABLE_RESOLVED;
2307
2308    // There are a couple of flags left in mPrivateFlags2
2309
2310    /* End of masks for mPrivateFlags2 */
2311
2312    /* Masks for mPrivateFlags3 */
2313
2314    /**
2315     * Flag indicating that view has a transform animation set on it. This is used to track whether
2316     * an animation is cleared between successive frames, in order to tell the associated
2317     * DisplayList to clear its animation matrix.
2318     */
2319    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2320
2321    /**
2322     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2323     * animation is cleared between successive frames, in order to tell the associated
2324     * DisplayList to restore its alpha value.
2325     */
2326    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2327
2328    /**
2329     * Flag indicating that the view has been through at least one layout since it
2330     * was last attached to a window.
2331     */
2332    static final int PFLAG3_IS_LAID_OUT = 0x4;
2333
2334    /**
2335     * Flag indicating that a call to measure() was skipped and should be done
2336     * instead when layout() is invoked.
2337     */
2338    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2339
2340    /**
2341     * Flag indicating that an overridden method correctly  called down to
2342     * the superclass implementation as required by the API spec.
2343     */
2344    static final int PFLAG3_CALLED_SUPER = 0x10;
2345
2346
2347    /* End of masks for mPrivateFlags3 */
2348
2349    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2350
2351    /**
2352     * Always allow a user to over-scroll this view, provided it is a
2353     * view that can scroll.
2354     *
2355     * @see #getOverScrollMode()
2356     * @see #setOverScrollMode(int)
2357     */
2358    public static final int OVER_SCROLL_ALWAYS = 0;
2359
2360    /**
2361     * Allow a user to over-scroll this view only if the content is large
2362     * enough to meaningfully scroll, provided it is a view that can scroll.
2363     *
2364     * @see #getOverScrollMode()
2365     * @see #setOverScrollMode(int)
2366     */
2367    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2368
2369    /**
2370     * Never allow a user to over-scroll this view.
2371     *
2372     * @see #getOverScrollMode()
2373     * @see #setOverScrollMode(int)
2374     */
2375    public static final int OVER_SCROLL_NEVER = 2;
2376
2377    /**
2378     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2379     * requested the system UI (status bar) to be visible (the default).
2380     *
2381     * @see #setSystemUiVisibility(int)
2382     */
2383    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2384
2385    /**
2386     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2387     * system UI to enter an unobtrusive "low profile" mode.
2388     *
2389     * <p>This is for use in games, book readers, video players, or any other
2390     * "immersive" application where the usual system chrome is deemed too distracting.
2391     *
2392     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2393     *
2394     * @see #setSystemUiVisibility(int)
2395     */
2396    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2397
2398    /**
2399     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2400     * system navigation be temporarily hidden.
2401     *
2402     * <p>This is an even less obtrusive state than that called for by
2403     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2404     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2405     * those to disappear. This is useful (in conjunction with the
2406     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2407     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2408     * window flags) for displaying content using every last pixel on the display.
2409     *
2410     * <p>There is a limitation: because navigation controls are so important, the least user
2411     * interaction will cause them to reappear immediately.  When this happens, both
2412     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2413     * so that both elements reappear at the same time.
2414     *
2415     * @see #setSystemUiVisibility(int)
2416     */
2417    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2418
2419    /**
2420     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2421     * into the normal fullscreen mode so that its content can take over the screen
2422     * while still allowing the user to interact with the application.
2423     *
2424     * <p>This has the same visual effect as
2425     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2426     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2427     * meaning that non-critical screen decorations (such as the status bar) will be
2428     * hidden while the user is in the View's window, focusing the experience on
2429     * that content.  Unlike the window flag, if you are using ActionBar in
2430     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2431     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2432     * hide the action bar.
2433     *
2434     * <p>This approach to going fullscreen is best used over the window flag when
2435     * it is a transient state -- that is, the application does this at certain
2436     * points in its user interaction where it wants to allow the user to focus
2437     * on content, but not as a continuous state.  For situations where the application
2438     * would like to simply stay full screen the entire time (such as a game that
2439     * wants to take over the screen), the
2440     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2441     * is usually a better approach.  The state set here will be removed by the system
2442     * in various situations (such as the user moving to another application) like
2443     * the other system UI states.
2444     *
2445     * <p>When using this flag, the application should provide some easy facility
2446     * for the user to go out of it.  A common example would be in an e-book
2447     * reader, where tapping on the screen brings back whatever screen and UI
2448     * decorations that had been hidden while the user was immersed in reading
2449     * the book.
2450     *
2451     * @see #setSystemUiVisibility(int)
2452     */
2453    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2454
2455    /**
2456     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2457     * flags, we would like a stable view of the content insets given to
2458     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2459     * will always represent the worst case that the application can expect
2460     * as a continuous state.  In the stock Android UI this is the space for
2461     * the system bar, nav bar, and status bar, but not more transient elements
2462     * such as an input method.
2463     *
2464     * The stable layout your UI sees is based on the system UI modes you can
2465     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2466     * then you will get a stable layout for changes of the
2467     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2468     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2469     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2470     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2471     * with a stable layout.  (Note that you should avoid using
2472     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2473     *
2474     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2475     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2476     * then a hidden status bar will be considered a "stable" state for purposes
2477     * here.  This allows your UI to continually hide the status bar, while still
2478     * using the system UI flags to hide the action bar while still retaining
2479     * a stable layout.  Note that changing the window fullscreen flag will never
2480     * provide a stable layout for a clean transition.
2481     *
2482     * <p>If you are using ActionBar in
2483     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2484     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2485     * insets it adds to those given to the application.
2486     */
2487    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2488
2489    /**
2490     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2491     * to be layed out as if it has requested
2492     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2493     * allows it to avoid artifacts when switching in and out of that mode, at
2494     * the expense that some of its user interface may be covered by screen
2495     * decorations when they are shown.  You can perform layout of your inner
2496     * UI elements to account for the navigation system UI through the
2497     * {@link #fitSystemWindows(Rect)} method.
2498     */
2499    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2500
2501    /**
2502     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2503     * to be layed out as if it has requested
2504     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2505     * allows it to avoid artifacts when switching in and out of that mode, at
2506     * the expense that some of its user interface may be covered by screen
2507     * decorations when they are shown.  You can perform layout of your inner
2508     * UI elements to account for non-fullscreen system UI through the
2509     * {@link #fitSystemWindows(Rect)} method.
2510     */
2511    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2512
2513    /**
2514     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2515     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2516     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2517     * experience while also hiding the system bars.  If this flag is not set,
2518     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2519     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2520     * if the user swipes from the top of the screen.
2521     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2522     * system gestures, such as swiping from the top of the screen.  These transient system bars
2523     * will overlay app’s content, may have some degree of transparency, and will automatically
2524     * hide after a short timeout.
2525     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2526     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2527     * with one or both of those flags.</p>
2528     */
2529    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2530
2531    /**
2532     * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have
2533     * transparency.
2534     *
2535     * <p>The transparency request may be denied if the bar is in another mode with a specific
2536     * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}.
2537     */
2538    public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000;
2539
2540    /**
2541     * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have
2542     * transparency.
2543     *
2544     * <p>The transparency request may be denied if the bar is in another mode with a specific
2545     * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}.
2546     */
2547    public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000;
2548
2549    /**
2550     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2551     */
2552    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2553
2554    /**
2555     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2556     */
2557    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2558
2559    /**
2560     * @hide
2561     *
2562     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2563     * out of the public fields to keep the undefined bits out of the developer's way.
2564     *
2565     * Flag to make the status bar not expandable.  Unless you also
2566     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2567     */
2568    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2569
2570    /**
2571     * @hide
2572     *
2573     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2574     * out of the public fields to keep the undefined bits out of the developer's way.
2575     *
2576     * Flag to hide notification icons and scrolling ticker text.
2577     */
2578    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2579
2580    /**
2581     * @hide
2582     *
2583     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2584     * out of the public fields to keep the undefined bits out of the developer's way.
2585     *
2586     * Flag to disable incoming notification alerts.  This will not block
2587     * icons, but it will block sound, vibrating and other visual or aural notifications.
2588     */
2589    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2590
2591    /**
2592     * @hide
2593     *
2594     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2595     * out of the public fields to keep the undefined bits out of the developer's way.
2596     *
2597     * Flag to hide only the scrolling ticker.  Note that
2598     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2599     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2600     */
2601    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2602
2603    /**
2604     * @hide
2605     *
2606     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2607     * out of the public fields to keep the undefined bits out of the developer's way.
2608     *
2609     * Flag to hide the center system info area.
2610     */
2611    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2612
2613    /**
2614     * @hide
2615     *
2616     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2617     * out of the public fields to keep the undefined bits out of the developer's way.
2618     *
2619     * Flag to hide only the home button.  Don't use this
2620     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2621     */
2622    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2623
2624    /**
2625     * @hide
2626     *
2627     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2628     * out of the public fields to keep the undefined bits out of the developer's way.
2629     *
2630     * Flag to hide only the back button. Don't use this
2631     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2632     */
2633    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2634
2635    /**
2636     * @hide
2637     *
2638     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2639     * out of the public fields to keep the undefined bits out of the developer's way.
2640     *
2641     * Flag to hide only the clock.  You might use this if your activity has
2642     * its own clock making the status bar's clock redundant.
2643     */
2644    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2645
2646    /**
2647     * @hide
2648     *
2649     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2650     * out of the public fields to keep the undefined bits out of the developer's way.
2651     *
2652     * Flag to hide only the recent apps button. Don't use this
2653     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2654     */
2655    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2656
2657    /**
2658     * @hide
2659     *
2660     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2661     * out of the public fields to keep the undefined bits out of the developer's way.
2662     *
2663     * Flag to disable the global search gesture. Don't use this
2664     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2665     */
2666    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2667
2668    /**
2669     * @hide
2670     *
2671     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2672     * out of the public fields to keep the undefined bits out of the developer's way.
2673     *
2674     * Flag to specify that the status bar is displayed in transient mode.
2675     */
2676    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2677
2678    /**
2679     * @hide
2680     *
2681     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2682     * out of the public fields to keep the undefined bits out of the developer's way.
2683     *
2684     * Flag to specify that the navigation bar is displayed in transient mode.
2685     */
2686    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2687
2688    /**
2689     * @hide
2690     *
2691     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2692     * out of the public fields to keep the undefined bits out of the developer's way.
2693     *
2694     * Flag to specify that the hidden status bar would like to be shown.
2695     */
2696    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2697
2698    /**
2699     * @hide
2700     *
2701     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2702     * out of the public fields to keep the undefined bits out of the developer's way.
2703     *
2704     * Flag to specify that the hidden navigation bar would like to be shown.
2705     */
2706    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2707
2708    /**
2709     * @hide
2710     */
2711    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2712
2713    /**
2714     * These are the system UI flags that can be cleared by events outside
2715     * of an application.  Currently this is just the ability to tap on the
2716     * screen while hiding the navigation bar to have it return.
2717     * @hide
2718     */
2719    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2720            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2721            | SYSTEM_UI_FLAG_FULLSCREEN;
2722
2723    /**
2724     * Flags that can impact the layout in relation to system UI.
2725     */
2726    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2727            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2728            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2729
2730    /** @hide */
2731    @IntDef(flag = true,
2732            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2733    @Retention(RetentionPolicy.SOURCE)
2734    public @interface FindViewFlags {}
2735
2736    /**
2737     * Find views that render the specified text.
2738     *
2739     * @see #findViewsWithText(ArrayList, CharSequence, int)
2740     */
2741    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2742
2743    /**
2744     * Find find views that contain the specified content description.
2745     *
2746     * @see #findViewsWithText(ArrayList, CharSequence, int)
2747     */
2748    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2749
2750    /**
2751     * Find views that contain {@link AccessibilityNodeProvider}. Such
2752     * a View is a root of virtual view hierarchy and may contain the searched
2753     * text. If this flag is set Views with providers are automatically
2754     * added and it is a responsibility of the client to call the APIs of
2755     * the provider to determine whether the virtual tree rooted at this View
2756     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2757     * representing the virtual views with this text.
2758     *
2759     * @see #findViewsWithText(ArrayList, CharSequence, int)
2760     *
2761     * @hide
2762     */
2763    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2764
2765    /**
2766     * The undefined cursor position.
2767     *
2768     * @hide
2769     */
2770    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2771
2772    /**
2773     * Indicates that the screen has changed state and is now off.
2774     *
2775     * @see #onScreenStateChanged(int)
2776     */
2777    public static final int SCREEN_STATE_OFF = 0x0;
2778
2779    /**
2780     * Indicates that the screen has changed state and is now on.
2781     *
2782     * @see #onScreenStateChanged(int)
2783     */
2784    public static final int SCREEN_STATE_ON = 0x1;
2785
2786    /**
2787     * Controls the over-scroll mode for this view.
2788     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2789     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2790     * and {@link #OVER_SCROLL_NEVER}.
2791     */
2792    private int mOverScrollMode;
2793
2794    /**
2795     * The parent this view is attached to.
2796     * {@hide}
2797     *
2798     * @see #getParent()
2799     */
2800    protected ViewParent mParent;
2801
2802    /**
2803     * {@hide}
2804     */
2805    AttachInfo mAttachInfo;
2806
2807    /**
2808     * {@hide}
2809     */
2810    @ViewDebug.ExportedProperty(flagMapping = {
2811        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2812                name = "FORCE_LAYOUT"),
2813        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2814                name = "LAYOUT_REQUIRED"),
2815        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2816            name = "DRAWING_CACHE_INVALID", outputIf = false),
2817        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2818        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2819        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2820        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2821    })
2822    int mPrivateFlags;
2823    int mPrivateFlags2;
2824    int mPrivateFlags3;
2825
2826    /**
2827     * This view's request for the visibility of the status bar.
2828     * @hide
2829     */
2830    @ViewDebug.ExportedProperty(flagMapping = {
2831        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2832                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2833                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2834        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2835                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2836                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2837        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2838                                equals = SYSTEM_UI_FLAG_VISIBLE,
2839                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2840    })
2841    int mSystemUiVisibility;
2842
2843    /**
2844     * Reference count for transient state.
2845     * @see #setHasTransientState(boolean)
2846     */
2847    int mTransientStateCount = 0;
2848
2849    /**
2850     * Count of how many windows this view has been attached to.
2851     */
2852    int mWindowAttachCount;
2853
2854    /**
2855     * The layout parameters associated with this view and used by the parent
2856     * {@link android.view.ViewGroup} to determine how this view should be
2857     * laid out.
2858     * {@hide}
2859     */
2860    protected ViewGroup.LayoutParams mLayoutParams;
2861
2862    /**
2863     * The view flags hold various views states.
2864     * {@hide}
2865     */
2866    @ViewDebug.ExportedProperty
2867    int mViewFlags;
2868
2869    static class TransformationInfo {
2870        /**
2871         * The transform matrix for the View. This transform is calculated internally
2872         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2873         * is used by default. Do *not* use this variable directly; instead call
2874         * getMatrix(), which will automatically recalculate the matrix if necessary
2875         * to get the correct matrix based on the latest rotation and scale properties.
2876         */
2877        private final Matrix mMatrix = new Matrix();
2878
2879        /**
2880         * The transform matrix for the View. This transform is calculated internally
2881         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2882         * is used by default. Do *not* use this variable directly; instead call
2883         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2884         * to get the correct matrix based on the latest rotation and scale properties.
2885         */
2886        private Matrix mInverseMatrix;
2887
2888        /**
2889         * An internal variable that tracks whether we need to recalculate the
2890         * transform matrix, based on whether the rotation or scaleX/Y properties
2891         * have changed since the matrix was last calculated.
2892         */
2893        boolean mMatrixDirty = false;
2894
2895        /**
2896         * An internal variable that tracks whether we need to recalculate the
2897         * transform matrix, based on whether the rotation or scaleX/Y properties
2898         * have changed since the matrix was last calculated.
2899         */
2900        private boolean mInverseMatrixDirty = true;
2901
2902        /**
2903         * A variable that tracks whether we need to recalculate the
2904         * transform matrix, based on whether the rotation or scaleX/Y properties
2905         * have changed since the matrix was last calculated. This variable
2906         * is only valid after a call to updateMatrix() or to a function that
2907         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2908         */
2909        private boolean mMatrixIsIdentity = true;
2910
2911        /**
2912         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2913         */
2914        private Camera mCamera = null;
2915
2916        /**
2917         * This matrix is used when computing the matrix for 3D rotations.
2918         */
2919        private Matrix matrix3D = null;
2920
2921        /**
2922         * These prev values are used to recalculate a centered pivot point when necessary. The
2923         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2924         * set), so thes values are only used then as well.
2925         */
2926        private int mPrevWidth = -1;
2927        private int mPrevHeight = -1;
2928
2929        /**
2930         * The degrees rotation around the vertical axis through the pivot point.
2931         */
2932        @ViewDebug.ExportedProperty
2933        float mRotationY = 0f;
2934
2935        /**
2936         * The degrees rotation around the horizontal axis through the pivot point.
2937         */
2938        @ViewDebug.ExportedProperty
2939        float mRotationX = 0f;
2940
2941        /**
2942         * The degrees rotation around the pivot point.
2943         */
2944        @ViewDebug.ExportedProperty
2945        float mRotation = 0f;
2946
2947        /**
2948         * The amount of translation of the object away from its left property (post-layout).
2949         */
2950        @ViewDebug.ExportedProperty
2951        float mTranslationX = 0f;
2952
2953        /**
2954         * The amount of translation of the object away from its top property (post-layout).
2955         */
2956        @ViewDebug.ExportedProperty
2957        float mTranslationY = 0f;
2958
2959        /**
2960         * The amount of scale in the x direction around the pivot point. A
2961         * value of 1 means no scaling is applied.
2962         */
2963        @ViewDebug.ExportedProperty
2964        float mScaleX = 1f;
2965
2966        /**
2967         * The amount of scale in the y direction around the pivot point. A
2968         * value of 1 means no scaling is applied.
2969         */
2970        @ViewDebug.ExportedProperty
2971        float mScaleY = 1f;
2972
2973        /**
2974         * The x location of the point around which the view is rotated and scaled.
2975         */
2976        @ViewDebug.ExportedProperty
2977        float mPivotX = 0f;
2978
2979        /**
2980         * The y location of the point around which the view is rotated and scaled.
2981         */
2982        @ViewDebug.ExportedProperty
2983        float mPivotY = 0f;
2984
2985        /**
2986         * The opacity of the View. This is a value from 0 to 1, where 0 means
2987         * completely transparent and 1 means completely opaque.
2988         */
2989        @ViewDebug.ExportedProperty
2990        float mAlpha = 1f;
2991
2992        /**
2993         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2994         * property only used by transitions, which is composited with the other alpha
2995         * values to calculate the final visual alpha value.
2996         */
2997        float mTransitionAlpha = 1f;
2998    }
2999
3000    TransformationInfo mTransformationInfo;
3001
3002    /**
3003     * Current clip bounds. to which all drawing of this view are constrained.
3004     */
3005    private Rect mClipBounds = null;
3006
3007    private boolean mLastIsOpaque;
3008
3009    /**
3010     * Convenience value to check for float values that are close enough to zero to be considered
3011     * zero.
3012     */
3013    private static final float NONZERO_EPSILON = .001f;
3014
3015    /**
3016     * The distance in pixels from the left edge of this view's parent
3017     * to the left edge of this view.
3018     * {@hide}
3019     */
3020    @ViewDebug.ExportedProperty(category = "layout")
3021    protected int mLeft;
3022    /**
3023     * The distance in pixels from the left edge of this view's parent
3024     * to the right edge of this view.
3025     * {@hide}
3026     */
3027    @ViewDebug.ExportedProperty(category = "layout")
3028    protected int mRight;
3029    /**
3030     * The distance in pixels from the top edge of this view's parent
3031     * to the top edge of this view.
3032     * {@hide}
3033     */
3034    @ViewDebug.ExportedProperty(category = "layout")
3035    protected int mTop;
3036    /**
3037     * The distance in pixels from the top edge of this view's parent
3038     * to the bottom edge of this view.
3039     * {@hide}
3040     */
3041    @ViewDebug.ExportedProperty(category = "layout")
3042    protected int mBottom;
3043
3044    /**
3045     * The offset, in pixels, by which the content of this view is scrolled
3046     * horizontally.
3047     * {@hide}
3048     */
3049    @ViewDebug.ExportedProperty(category = "scrolling")
3050    protected int mScrollX;
3051    /**
3052     * The offset, in pixels, by which the content of this view is scrolled
3053     * vertically.
3054     * {@hide}
3055     */
3056    @ViewDebug.ExportedProperty(category = "scrolling")
3057    protected int mScrollY;
3058
3059    /**
3060     * The left padding in pixels, that is the distance in pixels between the
3061     * left edge of this view and the left edge of its content.
3062     * {@hide}
3063     */
3064    @ViewDebug.ExportedProperty(category = "padding")
3065    protected int mPaddingLeft = 0;
3066    /**
3067     * The right padding in pixels, that is the distance in pixels between the
3068     * right edge of this view and the right edge of its content.
3069     * {@hide}
3070     */
3071    @ViewDebug.ExportedProperty(category = "padding")
3072    protected int mPaddingRight = 0;
3073    /**
3074     * The top padding in pixels, that is the distance in pixels between the
3075     * top edge of this view and the top edge of its content.
3076     * {@hide}
3077     */
3078    @ViewDebug.ExportedProperty(category = "padding")
3079    protected int mPaddingTop;
3080    /**
3081     * The bottom padding in pixels, that is the distance in pixels between the
3082     * bottom edge of this view and the bottom edge of its content.
3083     * {@hide}
3084     */
3085    @ViewDebug.ExportedProperty(category = "padding")
3086    protected int mPaddingBottom;
3087
3088    /**
3089     * The layout insets in pixels, that is the distance in pixels between the
3090     * visible edges of this view its bounds.
3091     */
3092    private Insets mLayoutInsets;
3093
3094    /**
3095     * Briefly describes the view and is primarily used for accessibility support.
3096     */
3097    private CharSequence mContentDescription;
3098
3099    /**
3100     * Specifies the id of a view for which this view serves as a label for
3101     * accessibility purposes.
3102     */
3103    private int mLabelForId = View.NO_ID;
3104
3105    /**
3106     * Predicate for matching labeled view id with its label for
3107     * accessibility purposes.
3108     */
3109    private MatchLabelForPredicate mMatchLabelForPredicate;
3110
3111    /**
3112     * Predicate for matching a view by its id.
3113     */
3114    private MatchIdPredicate mMatchIdPredicate;
3115
3116    /**
3117     * Cache the paddingRight set by the user to append to the scrollbar's size.
3118     *
3119     * @hide
3120     */
3121    @ViewDebug.ExportedProperty(category = "padding")
3122    protected int mUserPaddingRight;
3123
3124    /**
3125     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3126     *
3127     * @hide
3128     */
3129    @ViewDebug.ExportedProperty(category = "padding")
3130    protected int mUserPaddingBottom;
3131
3132    /**
3133     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3134     *
3135     * @hide
3136     */
3137    @ViewDebug.ExportedProperty(category = "padding")
3138    protected int mUserPaddingLeft;
3139
3140    /**
3141     * Cache the paddingStart set by the user to append to the scrollbar's size.
3142     *
3143     */
3144    @ViewDebug.ExportedProperty(category = "padding")
3145    int mUserPaddingStart;
3146
3147    /**
3148     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3149     *
3150     */
3151    @ViewDebug.ExportedProperty(category = "padding")
3152    int mUserPaddingEnd;
3153
3154    /**
3155     * Cache initial left padding.
3156     *
3157     * @hide
3158     */
3159    int mUserPaddingLeftInitial;
3160
3161    /**
3162     * Cache initial right padding.
3163     *
3164     * @hide
3165     */
3166    int mUserPaddingRightInitial;
3167
3168    /**
3169     * Default undefined padding
3170     */
3171    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3172
3173    /**
3174     * @hide
3175     */
3176    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3177    /**
3178     * @hide
3179     */
3180    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3181
3182    private LongSparseLongArray mMeasureCache;
3183
3184    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3185    private Drawable mBackground;
3186
3187    private int mBackgroundResource;
3188    private boolean mBackgroundSizeChanged;
3189
3190    static class ListenerInfo {
3191        /**
3192         * Listener used to dispatch focus change events.
3193         * This field should be made private, so it is hidden from the SDK.
3194         * {@hide}
3195         */
3196        protected OnFocusChangeListener mOnFocusChangeListener;
3197
3198        /**
3199         * Listeners for layout change events.
3200         */
3201        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3202
3203        /**
3204         * Listeners for attach events.
3205         */
3206        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3207
3208        /**
3209         * Listener used to dispatch click events.
3210         * This field should be made private, so it is hidden from the SDK.
3211         * {@hide}
3212         */
3213        public OnClickListener mOnClickListener;
3214
3215        /**
3216         * Listener used to dispatch long click events.
3217         * This field should be made private, so it is hidden from the SDK.
3218         * {@hide}
3219         */
3220        protected OnLongClickListener mOnLongClickListener;
3221
3222        /**
3223         * Listener used to build the context menu.
3224         * This field should be made private, so it is hidden from the SDK.
3225         * {@hide}
3226         */
3227        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3228
3229        private OnKeyListener mOnKeyListener;
3230
3231        private OnTouchListener mOnTouchListener;
3232
3233        private OnHoverListener mOnHoverListener;
3234
3235        private OnGenericMotionListener mOnGenericMotionListener;
3236
3237        private OnDragListener mOnDragListener;
3238
3239        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3240    }
3241
3242    ListenerInfo mListenerInfo;
3243
3244    /**
3245     * The application environment this view lives in.
3246     * This field should be made private, so it is hidden from the SDK.
3247     * {@hide}
3248     */
3249    protected Context mContext;
3250
3251    private final Resources mResources;
3252
3253    private ScrollabilityCache mScrollCache;
3254
3255    private int[] mDrawableState = null;
3256
3257    /**
3258     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3259     * the user may specify which view to go to next.
3260     */
3261    private int mNextFocusLeftId = View.NO_ID;
3262
3263    /**
3264     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3265     * the user may specify which view to go to next.
3266     */
3267    private int mNextFocusRightId = View.NO_ID;
3268
3269    /**
3270     * When this view has focus and the next focus is {@link #FOCUS_UP},
3271     * the user may specify which view to go to next.
3272     */
3273    private int mNextFocusUpId = View.NO_ID;
3274
3275    /**
3276     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3277     * the user may specify which view to go to next.
3278     */
3279    private int mNextFocusDownId = View.NO_ID;
3280
3281    /**
3282     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3283     * the user may specify which view to go to next.
3284     */
3285    int mNextFocusForwardId = View.NO_ID;
3286
3287    private CheckForLongPress mPendingCheckForLongPress;
3288    private CheckForTap mPendingCheckForTap = null;
3289    private PerformClick mPerformClick;
3290    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3291
3292    private UnsetPressedState mUnsetPressedState;
3293
3294    /**
3295     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3296     * up event while a long press is invoked as soon as the long press duration is reached, so
3297     * a long press could be performed before the tap is checked, in which case the tap's action
3298     * should not be invoked.
3299     */
3300    private boolean mHasPerformedLongPress;
3301
3302    /**
3303     * The minimum height of the view. We'll try our best to have the height
3304     * of this view to at least this amount.
3305     */
3306    @ViewDebug.ExportedProperty(category = "measurement")
3307    private int mMinHeight;
3308
3309    /**
3310     * The minimum width of the view. We'll try our best to have the width
3311     * of this view to at least this amount.
3312     */
3313    @ViewDebug.ExportedProperty(category = "measurement")
3314    private int mMinWidth;
3315
3316    /**
3317     * The delegate to handle touch events that are physically in this view
3318     * but should be handled by another view.
3319     */
3320    private TouchDelegate mTouchDelegate = null;
3321
3322    /**
3323     * Solid color to use as a background when creating the drawing cache. Enables
3324     * the cache to use 16 bit bitmaps instead of 32 bit.
3325     */
3326    private int mDrawingCacheBackgroundColor = 0;
3327
3328    /**
3329     * Special tree observer used when mAttachInfo is null.
3330     */
3331    private ViewTreeObserver mFloatingTreeObserver;
3332
3333    /**
3334     * Cache the touch slop from the context that created the view.
3335     */
3336    private int mTouchSlop;
3337
3338    /**
3339     * Object that handles automatic animation of view properties.
3340     */
3341    private ViewPropertyAnimator mAnimator = null;
3342
3343    /**
3344     * Flag indicating that a drag can cross window boundaries.  When
3345     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3346     * with this flag set, all visible applications will be able to participate
3347     * in the drag operation and receive the dragged content.
3348     *
3349     * @hide
3350     */
3351    public static final int DRAG_FLAG_GLOBAL = 1;
3352
3353    /**
3354     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3355     */
3356    private float mVerticalScrollFactor;
3357
3358    /**
3359     * Position of the vertical scroll bar.
3360     */
3361    private int mVerticalScrollbarPosition;
3362
3363    /**
3364     * Position the scroll bar at the default position as determined by the system.
3365     */
3366    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3367
3368    /**
3369     * Position the scroll bar along the left edge.
3370     */
3371    public static final int SCROLLBAR_POSITION_LEFT = 1;
3372
3373    /**
3374     * Position the scroll bar along the right edge.
3375     */
3376    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3377
3378    /**
3379     * Indicates that the view does not have a layer.
3380     *
3381     * @see #getLayerType()
3382     * @see #setLayerType(int, android.graphics.Paint)
3383     * @see #LAYER_TYPE_SOFTWARE
3384     * @see #LAYER_TYPE_HARDWARE
3385     */
3386    public static final int LAYER_TYPE_NONE = 0;
3387
3388    /**
3389     * <p>Indicates that the view has a software layer. A software layer is backed
3390     * by a bitmap and causes the view to be rendered using Android's software
3391     * rendering pipeline, even if hardware acceleration is enabled.</p>
3392     *
3393     * <p>Software layers have various usages:</p>
3394     * <p>When the application is not using hardware acceleration, a software layer
3395     * is useful to apply a specific color filter and/or blending mode and/or
3396     * translucency to a view and all its children.</p>
3397     * <p>When the application is using hardware acceleration, a software layer
3398     * is useful to render drawing primitives not supported by the hardware
3399     * accelerated pipeline. It can also be used to cache a complex view tree
3400     * into a texture and reduce the complexity of drawing operations. For instance,
3401     * when animating a complex view tree with a translation, a software layer can
3402     * be used to render the view tree only once.</p>
3403     * <p>Software layers should be avoided when the affected view tree updates
3404     * often. Every update will require to re-render the software layer, which can
3405     * potentially be slow (particularly when hardware acceleration is turned on
3406     * since the layer will have to be uploaded into a hardware texture after every
3407     * update.)</p>
3408     *
3409     * @see #getLayerType()
3410     * @see #setLayerType(int, android.graphics.Paint)
3411     * @see #LAYER_TYPE_NONE
3412     * @see #LAYER_TYPE_HARDWARE
3413     */
3414    public static final int LAYER_TYPE_SOFTWARE = 1;
3415
3416    /**
3417     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3418     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3419     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3420     * rendering pipeline, but only if hardware acceleration is turned on for the
3421     * view hierarchy. When hardware acceleration is turned off, hardware layers
3422     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3423     *
3424     * <p>A hardware layer is useful to apply a specific color filter and/or
3425     * blending mode and/or translucency to a view and all its children.</p>
3426     * <p>A hardware layer can be used to cache a complex view tree into a
3427     * texture and reduce the complexity of drawing operations. For instance,
3428     * when animating a complex view tree with a translation, a hardware layer can
3429     * be used to render the view tree only once.</p>
3430     * <p>A hardware layer can also be used to increase the rendering quality when
3431     * rotation transformations are applied on a view. It can also be used to
3432     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3433     *
3434     * @see #getLayerType()
3435     * @see #setLayerType(int, android.graphics.Paint)
3436     * @see #LAYER_TYPE_NONE
3437     * @see #LAYER_TYPE_SOFTWARE
3438     */
3439    public static final int LAYER_TYPE_HARDWARE = 2;
3440
3441    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3442            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3443            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3444            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3445    })
3446    int mLayerType = LAYER_TYPE_NONE;
3447    Paint mLayerPaint;
3448    Rect mLocalDirtyRect;
3449    private HardwareLayer mHardwareLayer;
3450
3451    /**
3452     * Set to true when drawing cache is enabled and cannot be created.
3453     *
3454     * @hide
3455     */
3456    public boolean mCachingFailed;
3457    private Bitmap mDrawingCache;
3458    private Bitmap mUnscaledDrawingCache;
3459
3460    DisplayList mDisplayList;
3461
3462    /**
3463     * Set to true when the view is sending hover accessibility events because it
3464     * is the innermost hovered view.
3465     */
3466    private boolean mSendingHoverAccessibilityEvents;
3467
3468    /**
3469     * Delegate for injecting accessibility functionality.
3470     */
3471    AccessibilityDelegate mAccessibilityDelegate;
3472
3473    /**
3474     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3475     * and add/remove objects to/from the overlay directly through the Overlay methods.
3476     */
3477    ViewOverlay mOverlay;
3478
3479    /**
3480     * Consistency verifier for debugging purposes.
3481     * @hide
3482     */
3483    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3484            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3485                    new InputEventConsistencyVerifier(this, 0) : null;
3486
3487    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3488
3489    /**
3490     * Simple constructor to use when creating a view from code.
3491     *
3492     * @param context The Context the view is running in, through which it can
3493     *        access the current theme, resources, etc.
3494     */
3495    public View(Context context) {
3496        mContext = context;
3497        mResources = context != null ? context.getResources() : null;
3498        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3499        // Set some flags defaults
3500        mPrivateFlags2 =
3501                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3502                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3503                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3504                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3505                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3506                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3507        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3508        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3509        mUserPaddingStart = UNDEFINED_PADDING;
3510        mUserPaddingEnd = UNDEFINED_PADDING;
3511
3512        if (!sUseBrokenMakeMeasureSpec && context != null &&
3513                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3514            // Older apps may need this compatibility hack for measurement.
3515            sUseBrokenMakeMeasureSpec = true;
3516        }
3517    }
3518
3519    /**
3520     * Constructor that is called when inflating a view from XML. This is called
3521     * when a view is being constructed from an XML file, supplying attributes
3522     * that were specified in the XML file. This version uses a default style of
3523     * 0, so the only attribute values applied are those in the Context's Theme
3524     * and the given AttributeSet.
3525     *
3526     * <p>
3527     * The method onFinishInflate() will be called after all children have been
3528     * added.
3529     *
3530     * @param context The Context the view is running in, through which it can
3531     *        access the current theme, resources, etc.
3532     * @param attrs The attributes of the XML tag that is inflating the view.
3533     * @see #View(Context, AttributeSet, int)
3534     */
3535    public View(Context context, AttributeSet attrs) {
3536        this(context, attrs, 0);
3537    }
3538
3539    /**
3540     * Perform inflation from XML and apply a class-specific base style from a
3541     * theme attribute. This constructor of View allows subclasses to use their
3542     * own base style when they are inflating. For example, a Button class's
3543     * constructor would call this version of the super class constructor and
3544     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3545     * allows the theme's button style to modify all of the base view attributes
3546     * (in particular its background) as well as the Button class's attributes.
3547     *
3548     * @param context The Context the view is running in, through which it can
3549     *        access the current theme, resources, etc.
3550     * @param attrs The attributes of the XML tag that is inflating the view.
3551     * @param defStyleAttr An attribute in the current theme that contains a
3552     *        reference to a style resource that supplies default values for
3553     *        the view. Can be 0 to not look for defaults.
3554     * @see #View(Context, AttributeSet)
3555     */
3556    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3557        this(context, attrs, defStyleAttr, 0);
3558    }
3559
3560    /**
3561     * Perform inflation from XML and apply a class-specific base style from a
3562     * theme attribute or style resource. This constructor of View allows
3563     * subclasses to use their own base style when they are inflating.
3564     * <p>
3565     * When determining the final value of a particular attribute, there are
3566     * four inputs that come into play:
3567     * <ol>
3568     * <li>Any attribute values in the given AttributeSet.
3569     * <li>The style resource specified in the AttributeSet (named "style").
3570     * <li>The default style specified by <var>defStyleAttr</var>.
3571     * <li>The default style specified by <var>defStyleRes</var>.
3572     * <li>The base values in this theme.
3573     * </ol>
3574     * <p>
3575     * Each of these inputs is considered in-order, with the first listed taking
3576     * precedence over the following ones. In other words, if in the
3577     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3578     * , then the button's text will <em>always</em> be black, regardless of
3579     * what is specified in any of the styles.
3580     *
3581     * @param context The Context the view is running in, through which it can
3582     *        access the current theme, resources, etc.
3583     * @param attrs The attributes of the XML tag that is inflating the view.
3584     * @param defStyleAttr An attribute in the current theme that contains a
3585     *        reference to a style resource that supplies default values for
3586     *        the view. Can be 0 to not look for defaults.
3587     * @param defStyleRes A resource identifier of a style resource that
3588     *        supplies default values for the view, used only if
3589     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3590     *        to not look for defaults.
3591     * @see #View(Context, AttributeSet, int)
3592     */
3593    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3594        this(context);
3595
3596        final TypedArray a = context.obtainStyledAttributes(
3597                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3598
3599        Drawable background = null;
3600
3601        int leftPadding = -1;
3602        int topPadding = -1;
3603        int rightPadding = -1;
3604        int bottomPadding = -1;
3605        int startPadding = UNDEFINED_PADDING;
3606        int endPadding = UNDEFINED_PADDING;
3607
3608        int padding = -1;
3609
3610        int viewFlagValues = 0;
3611        int viewFlagMasks = 0;
3612
3613        boolean setScrollContainer = false;
3614
3615        int x = 0;
3616        int y = 0;
3617
3618        float tx = 0;
3619        float ty = 0;
3620        float rotation = 0;
3621        float rotationX = 0;
3622        float rotationY = 0;
3623        float sx = 1f;
3624        float sy = 1f;
3625        boolean transformSet = false;
3626
3627        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3628        int overScrollMode = mOverScrollMode;
3629        boolean initializeScrollbars = false;
3630
3631        boolean leftPaddingDefined = false;
3632        boolean rightPaddingDefined = false;
3633        boolean startPaddingDefined = false;
3634        boolean endPaddingDefined = false;
3635
3636        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3637
3638        final int N = a.getIndexCount();
3639        for (int i = 0; i < N; i++) {
3640            int attr = a.getIndex(i);
3641            switch (attr) {
3642                case com.android.internal.R.styleable.View_background:
3643                    background = a.getDrawable(attr);
3644                    break;
3645                case com.android.internal.R.styleable.View_padding:
3646                    padding = a.getDimensionPixelSize(attr, -1);
3647                    mUserPaddingLeftInitial = padding;
3648                    mUserPaddingRightInitial = padding;
3649                    leftPaddingDefined = true;
3650                    rightPaddingDefined = true;
3651                    break;
3652                 case com.android.internal.R.styleable.View_paddingLeft:
3653                    leftPadding = a.getDimensionPixelSize(attr, -1);
3654                    mUserPaddingLeftInitial = leftPadding;
3655                    leftPaddingDefined = true;
3656                    break;
3657                case com.android.internal.R.styleable.View_paddingTop:
3658                    topPadding = a.getDimensionPixelSize(attr, -1);
3659                    break;
3660                case com.android.internal.R.styleable.View_paddingRight:
3661                    rightPadding = a.getDimensionPixelSize(attr, -1);
3662                    mUserPaddingRightInitial = rightPadding;
3663                    rightPaddingDefined = true;
3664                    break;
3665                case com.android.internal.R.styleable.View_paddingBottom:
3666                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3667                    break;
3668                case com.android.internal.R.styleable.View_paddingStart:
3669                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3670                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3671                    break;
3672                case com.android.internal.R.styleable.View_paddingEnd:
3673                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3674                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3675                    break;
3676                case com.android.internal.R.styleable.View_scrollX:
3677                    x = a.getDimensionPixelOffset(attr, 0);
3678                    break;
3679                case com.android.internal.R.styleable.View_scrollY:
3680                    y = a.getDimensionPixelOffset(attr, 0);
3681                    break;
3682                case com.android.internal.R.styleable.View_alpha:
3683                    setAlpha(a.getFloat(attr, 1f));
3684                    break;
3685                case com.android.internal.R.styleable.View_transformPivotX:
3686                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3687                    break;
3688                case com.android.internal.R.styleable.View_transformPivotY:
3689                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3690                    break;
3691                case com.android.internal.R.styleable.View_translationX:
3692                    tx = a.getDimensionPixelOffset(attr, 0);
3693                    transformSet = true;
3694                    break;
3695                case com.android.internal.R.styleable.View_translationY:
3696                    ty = a.getDimensionPixelOffset(attr, 0);
3697                    transformSet = true;
3698                    break;
3699                case com.android.internal.R.styleable.View_rotation:
3700                    rotation = a.getFloat(attr, 0);
3701                    transformSet = true;
3702                    break;
3703                case com.android.internal.R.styleable.View_rotationX:
3704                    rotationX = a.getFloat(attr, 0);
3705                    transformSet = true;
3706                    break;
3707                case com.android.internal.R.styleable.View_rotationY:
3708                    rotationY = a.getFloat(attr, 0);
3709                    transformSet = true;
3710                    break;
3711                case com.android.internal.R.styleable.View_scaleX:
3712                    sx = a.getFloat(attr, 1f);
3713                    transformSet = true;
3714                    break;
3715                case com.android.internal.R.styleable.View_scaleY:
3716                    sy = a.getFloat(attr, 1f);
3717                    transformSet = true;
3718                    break;
3719                case com.android.internal.R.styleable.View_id:
3720                    mID = a.getResourceId(attr, NO_ID);
3721                    break;
3722                case com.android.internal.R.styleable.View_tag:
3723                    mTag = a.getText(attr);
3724                    break;
3725                case com.android.internal.R.styleable.View_fitsSystemWindows:
3726                    if (a.getBoolean(attr, false)) {
3727                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3728                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3729                    }
3730                    break;
3731                case com.android.internal.R.styleable.View_focusable:
3732                    if (a.getBoolean(attr, false)) {
3733                        viewFlagValues |= FOCUSABLE;
3734                        viewFlagMasks |= FOCUSABLE_MASK;
3735                    }
3736                    break;
3737                case com.android.internal.R.styleable.View_focusableInTouchMode:
3738                    if (a.getBoolean(attr, false)) {
3739                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3740                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3741                    }
3742                    break;
3743                case com.android.internal.R.styleable.View_clickable:
3744                    if (a.getBoolean(attr, false)) {
3745                        viewFlagValues |= CLICKABLE;
3746                        viewFlagMasks |= CLICKABLE;
3747                    }
3748                    break;
3749                case com.android.internal.R.styleable.View_longClickable:
3750                    if (a.getBoolean(attr, false)) {
3751                        viewFlagValues |= LONG_CLICKABLE;
3752                        viewFlagMasks |= LONG_CLICKABLE;
3753                    }
3754                    break;
3755                case com.android.internal.R.styleable.View_saveEnabled:
3756                    if (!a.getBoolean(attr, true)) {
3757                        viewFlagValues |= SAVE_DISABLED;
3758                        viewFlagMasks |= SAVE_DISABLED_MASK;
3759                    }
3760                    break;
3761                case com.android.internal.R.styleable.View_duplicateParentState:
3762                    if (a.getBoolean(attr, false)) {
3763                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3764                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3765                    }
3766                    break;
3767                case com.android.internal.R.styleable.View_visibility:
3768                    final int visibility = a.getInt(attr, 0);
3769                    if (visibility != 0) {
3770                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3771                        viewFlagMasks |= VISIBILITY_MASK;
3772                    }
3773                    break;
3774                case com.android.internal.R.styleable.View_layoutDirection:
3775                    // Clear any layout direction flags (included resolved bits) already set
3776                    mPrivateFlags2 &=
3777                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3778                    // Set the layout direction flags depending on the value of the attribute
3779                    final int layoutDirection = a.getInt(attr, -1);
3780                    final int value = (layoutDirection != -1) ?
3781                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3782                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3783                    break;
3784                case com.android.internal.R.styleable.View_drawingCacheQuality:
3785                    final int cacheQuality = a.getInt(attr, 0);
3786                    if (cacheQuality != 0) {
3787                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3788                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3789                    }
3790                    break;
3791                case com.android.internal.R.styleable.View_contentDescription:
3792                    setContentDescription(a.getString(attr));
3793                    break;
3794                case com.android.internal.R.styleable.View_labelFor:
3795                    setLabelFor(a.getResourceId(attr, NO_ID));
3796                    break;
3797                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3798                    if (!a.getBoolean(attr, true)) {
3799                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3800                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3801                    }
3802                    break;
3803                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3804                    if (!a.getBoolean(attr, true)) {
3805                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3806                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3807                    }
3808                    break;
3809                case R.styleable.View_scrollbars:
3810                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3811                    if (scrollbars != SCROLLBARS_NONE) {
3812                        viewFlagValues |= scrollbars;
3813                        viewFlagMasks |= SCROLLBARS_MASK;
3814                        initializeScrollbars = true;
3815                    }
3816                    break;
3817                //noinspection deprecation
3818                case R.styleable.View_fadingEdge:
3819                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3820                        // Ignore the attribute starting with ICS
3821                        break;
3822                    }
3823                    // With builds < ICS, fall through and apply fading edges
3824                case R.styleable.View_requiresFadingEdge:
3825                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3826                    if (fadingEdge != FADING_EDGE_NONE) {
3827                        viewFlagValues |= fadingEdge;
3828                        viewFlagMasks |= FADING_EDGE_MASK;
3829                        initializeFadingEdge(a);
3830                    }
3831                    break;
3832                case R.styleable.View_scrollbarStyle:
3833                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3834                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3835                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3836                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3837                    }
3838                    break;
3839                case R.styleable.View_isScrollContainer:
3840                    setScrollContainer = true;
3841                    if (a.getBoolean(attr, false)) {
3842                        setScrollContainer(true);
3843                    }
3844                    break;
3845                case com.android.internal.R.styleable.View_keepScreenOn:
3846                    if (a.getBoolean(attr, false)) {
3847                        viewFlagValues |= KEEP_SCREEN_ON;
3848                        viewFlagMasks |= KEEP_SCREEN_ON;
3849                    }
3850                    break;
3851                case R.styleable.View_filterTouchesWhenObscured:
3852                    if (a.getBoolean(attr, false)) {
3853                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3854                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3855                    }
3856                    break;
3857                case R.styleable.View_nextFocusLeft:
3858                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3859                    break;
3860                case R.styleable.View_nextFocusRight:
3861                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3862                    break;
3863                case R.styleable.View_nextFocusUp:
3864                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3865                    break;
3866                case R.styleable.View_nextFocusDown:
3867                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3868                    break;
3869                case R.styleable.View_nextFocusForward:
3870                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3871                    break;
3872                case R.styleable.View_minWidth:
3873                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3874                    break;
3875                case R.styleable.View_minHeight:
3876                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3877                    break;
3878                case R.styleable.View_onClick:
3879                    if (context.isRestricted()) {
3880                        throw new IllegalStateException("The android:onClick attribute cannot "
3881                                + "be used within a restricted context");
3882                    }
3883
3884                    final String handlerName = a.getString(attr);
3885                    if (handlerName != null) {
3886                        setOnClickListener(new OnClickListener() {
3887                            private Method mHandler;
3888
3889                            public void onClick(View v) {
3890                                if (mHandler == null) {
3891                                    try {
3892                                        mHandler = getContext().getClass().getMethod(handlerName,
3893                                                View.class);
3894                                    } catch (NoSuchMethodException e) {
3895                                        int id = getId();
3896                                        String idText = id == NO_ID ? "" : " with id '"
3897                                                + getContext().getResources().getResourceEntryName(
3898                                                    id) + "'";
3899                                        throw new IllegalStateException("Could not find a method " +
3900                                                handlerName + "(View) in the activity "
3901                                                + getContext().getClass() + " for onClick handler"
3902                                                + " on view " + View.this.getClass() + idText, e);
3903                                    }
3904                                }
3905
3906                                try {
3907                                    mHandler.invoke(getContext(), View.this);
3908                                } catch (IllegalAccessException e) {
3909                                    throw new IllegalStateException("Could not execute non "
3910                                            + "public method of the activity", e);
3911                                } catch (InvocationTargetException e) {
3912                                    throw new IllegalStateException("Could not execute "
3913                                            + "method of the activity", e);
3914                                }
3915                            }
3916                        });
3917                    }
3918                    break;
3919                case R.styleable.View_overScrollMode:
3920                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3921                    break;
3922                case R.styleable.View_verticalScrollbarPosition:
3923                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3924                    break;
3925                case R.styleable.View_layerType:
3926                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3927                    break;
3928                case R.styleable.View_textDirection:
3929                    // Clear any text direction flag already set
3930                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3931                    // Set the text direction flags depending on the value of the attribute
3932                    final int textDirection = a.getInt(attr, -1);
3933                    if (textDirection != -1) {
3934                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3935                    }
3936                    break;
3937                case R.styleable.View_textAlignment:
3938                    // Clear any text alignment flag already set
3939                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3940                    // Set the text alignment flag depending on the value of the attribute
3941                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3942                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3943                    break;
3944                case R.styleable.View_importantForAccessibility:
3945                    setImportantForAccessibility(a.getInt(attr,
3946                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3947                    break;
3948                case R.styleable.View_accessibilityLiveRegion:
3949                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
3950                    break;
3951            }
3952        }
3953
3954        setOverScrollMode(overScrollMode);
3955
3956        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3957        // the resolved layout direction). Those cached values will be used later during padding
3958        // resolution.
3959        mUserPaddingStart = startPadding;
3960        mUserPaddingEnd = endPadding;
3961
3962        if (background != null) {
3963            setBackground(background);
3964        }
3965
3966        if (padding >= 0) {
3967            leftPadding = padding;
3968            topPadding = padding;
3969            rightPadding = padding;
3970            bottomPadding = padding;
3971            mUserPaddingLeftInitial = padding;
3972            mUserPaddingRightInitial = padding;
3973        }
3974
3975        if (isRtlCompatibilityMode()) {
3976            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3977            // left / right padding are used if defined (meaning here nothing to do). If they are not
3978            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3979            // start / end and resolve them as left / right (layout direction is not taken into account).
3980            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3981            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3982            // defined.
3983            if (!leftPaddingDefined && startPaddingDefined) {
3984                leftPadding = startPadding;
3985            }
3986            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3987            if (!rightPaddingDefined && endPaddingDefined) {
3988                rightPadding = endPadding;
3989            }
3990            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3991        } else {
3992            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3993            // values defined. Otherwise, left /right values are used.
3994            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3995            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3996            // defined.
3997            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3998
3999            if (leftPaddingDefined && !hasRelativePadding) {
4000                mUserPaddingLeftInitial = leftPadding;
4001            }
4002            if (rightPaddingDefined && !hasRelativePadding) {
4003                mUserPaddingRightInitial = rightPadding;
4004            }
4005        }
4006
4007        internalSetPadding(
4008                mUserPaddingLeftInitial,
4009                topPadding >= 0 ? topPadding : mPaddingTop,
4010                mUserPaddingRightInitial,
4011                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4012
4013        if (viewFlagMasks != 0) {
4014            setFlags(viewFlagValues, viewFlagMasks);
4015        }
4016
4017        if (initializeScrollbars) {
4018            initializeScrollbars(a);
4019        }
4020
4021        a.recycle();
4022
4023        // Needs to be called after mViewFlags is set
4024        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4025            recomputePadding();
4026        }
4027
4028        if (x != 0 || y != 0) {
4029            scrollTo(x, y);
4030        }
4031
4032        if (transformSet) {
4033            setTranslationX(tx);
4034            setTranslationY(ty);
4035            setRotation(rotation);
4036            setRotationX(rotationX);
4037            setRotationY(rotationY);
4038            setScaleX(sx);
4039            setScaleY(sy);
4040        }
4041
4042        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4043            setScrollContainer(true);
4044        }
4045
4046        computeOpaqueFlags();
4047    }
4048
4049    /**
4050     * Non-public constructor for use in testing
4051     */
4052    View() {
4053        mResources = null;
4054    }
4055
4056    public String toString() {
4057        StringBuilder out = new StringBuilder(128);
4058        out.append(getClass().getName());
4059        out.append('{');
4060        out.append(Integer.toHexString(System.identityHashCode(this)));
4061        out.append(' ');
4062        switch (mViewFlags&VISIBILITY_MASK) {
4063            case VISIBLE: out.append('V'); break;
4064            case INVISIBLE: out.append('I'); break;
4065            case GONE: out.append('G'); break;
4066            default: out.append('.'); break;
4067        }
4068        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4069        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4070        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4071        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4072        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4073        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4074        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4075        out.append(' ');
4076        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4077        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4078        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4079        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4080            out.append('p');
4081        } else {
4082            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4083        }
4084        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4085        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4086        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4087        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4088        out.append(' ');
4089        out.append(mLeft);
4090        out.append(',');
4091        out.append(mTop);
4092        out.append('-');
4093        out.append(mRight);
4094        out.append(',');
4095        out.append(mBottom);
4096        final int id = getId();
4097        if (id != NO_ID) {
4098            out.append(" #");
4099            out.append(Integer.toHexString(id));
4100            final Resources r = mResources;
4101            if (id != 0 && r != null) {
4102                try {
4103                    String pkgname;
4104                    switch (id&0xff000000) {
4105                        case 0x7f000000:
4106                            pkgname="app";
4107                            break;
4108                        case 0x01000000:
4109                            pkgname="android";
4110                            break;
4111                        default:
4112                            pkgname = r.getResourcePackageName(id);
4113                            break;
4114                    }
4115                    String typename = r.getResourceTypeName(id);
4116                    String entryname = r.getResourceEntryName(id);
4117                    out.append(" ");
4118                    out.append(pkgname);
4119                    out.append(":");
4120                    out.append(typename);
4121                    out.append("/");
4122                    out.append(entryname);
4123                } catch (Resources.NotFoundException e) {
4124                }
4125            }
4126        }
4127        out.append("}");
4128        return out.toString();
4129    }
4130
4131    /**
4132     * <p>
4133     * Initializes the fading edges from a given set of styled attributes. This
4134     * method should be called by subclasses that need fading edges and when an
4135     * instance of these subclasses is created programmatically rather than
4136     * being inflated from XML. This method is automatically called when the XML
4137     * is inflated.
4138     * </p>
4139     *
4140     * @param a the styled attributes set to initialize the fading edges from
4141     */
4142    protected void initializeFadingEdge(TypedArray a) {
4143        initScrollCache();
4144
4145        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4146                R.styleable.View_fadingEdgeLength,
4147                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4148    }
4149
4150    /**
4151     * Returns the size of the vertical faded edges used to indicate that more
4152     * content in this view is visible.
4153     *
4154     * @return The size in pixels of the vertical faded edge or 0 if vertical
4155     *         faded edges are not enabled for this view.
4156     * @attr ref android.R.styleable#View_fadingEdgeLength
4157     */
4158    public int getVerticalFadingEdgeLength() {
4159        if (isVerticalFadingEdgeEnabled()) {
4160            ScrollabilityCache cache = mScrollCache;
4161            if (cache != null) {
4162                return cache.fadingEdgeLength;
4163            }
4164        }
4165        return 0;
4166    }
4167
4168    /**
4169     * Set the size of the faded edge used to indicate that more content in this
4170     * view is available.  Will not change whether the fading edge is enabled; use
4171     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4172     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4173     * for the vertical or horizontal fading edges.
4174     *
4175     * @param length The size in pixels of the faded edge used to indicate that more
4176     *        content in this view is visible.
4177     */
4178    public void setFadingEdgeLength(int length) {
4179        initScrollCache();
4180        mScrollCache.fadingEdgeLength = length;
4181    }
4182
4183    /**
4184     * Returns the size of the horizontal faded edges used to indicate that more
4185     * content in this view is visible.
4186     *
4187     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4188     *         faded edges are not enabled for this view.
4189     * @attr ref android.R.styleable#View_fadingEdgeLength
4190     */
4191    public int getHorizontalFadingEdgeLength() {
4192        if (isHorizontalFadingEdgeEnabled()) {
4193            ScrollabilityCache cache = mScrollCache;
4194            if (cache != null) {
4195                return cache.fadingEdgeLength;
4196            }
4197        }
4198        return 0;
4199    }
4200
4201    /**
4202     * Returns the width of the vertical scrollbar.
4203     *
4204     * @return The width in pixels of the vertical scrollbar or 0 if there
4205     *         is no vertical scrollbar.
4206     */
4207    public int getVerticalScrollbarWidth() {
4208        ScrollabilityCache cache = mScrollCache;
4209        if (cache != null) {
4210            ScrollBarDrawable scrollBar = cache.scrollBar;
4211            if (scrollBar != null) {
4212                int size = scrollBar.getSize(true);
4213                if (size <= 0) {
4214                    size = cache.scrollBarSize;
4215                }
4216                return size;
4217            }
4218            return 0;
4219        }
4220        return 0;
4221    }
4222
4223    /**
4224     * Returns the height of the horizontal scrollbar.
4225     *
4226     * @return The height in pixels of the horizontal scrollbar or 0 if
4227     *         there is no horizontal scrollbar.
4228     */
4229    protected int getHorizontalScrollbarHeight() {
4230        ScrollabilityCache cache = mScrollCache;
4231        if (cache != null) {
4232            ScrollBarDrawable scrollBar = cache.scrollBar;
4233            if (scrollBar != null) {
4234                int size = scrollBar.getSize(false);
4235                if (size <= 0) {
4236                    size = cache.scrollBarSize;
4237                }
4238                return size;
4239            }
4240            return 0;
4241        }
4242        return 0;
4243    }
4244
4245    /**
4246     * <p>
4247     * Initializes the scrollbars from a given set of styled attributes. This
4248     * method should be called by subclasses that need scrollbars and when an
4249     * instance of these subclasses is created programmatically rather than
4250     * being inflated from XML. This method is automatically called when the XML
4251     * is inflated.
4252     * </p>
4253     *
4254     * @param a the styled attributes set to initialize the scrollbars from
4255     */
4256    protected void initializeScrollbars(TypedArray a) {
4257        initScrollCache();
4258
4259        final ScrollabilityCache scrollabilityCache = mScrollCache;
4260
4261        if (scrollabilityCache.scrollBar == null) {
4262            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4263        }
4264
4265        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4266
4267        if (!fadeScrollbars) {
4268            scrollabilityCache.state = ScrollabilityCache.ON;
4269        }
4270        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4271
4272
4273        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4274                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4275                        .getScrollBarFadeDuration());
4276        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4277                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4278                ViewConfiguration.getScrollDefaultDelay());
4279
4280
4281        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4282                com.android.internal.R.styleable.View_scrollbarSize,
4283                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4284
4285        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4286        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4287
4288        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4289        if (thumb != null) {
4290            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4291        }
4292
4293        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4294                false);
4295        if (alwaysDraw) {
4296            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4297        }
4298
4299        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4300        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4301
4302        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4303        if (thumb != null) {
4304            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4305        }
4306
4307        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4308                false);
4309        if (alwaysDraw) {
4310            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4311        }
4312
4313        // Apply layout direction to the new Drawables if needed
4314        final int layoutDirection = getLayoutDirection();
4315        if (track != null) {
4316            track.setLayoutDirection(layoutDirection);
4317        }
4318        if (thumb != null) {
4319            thumb.setLayoutDirection(layoutDirection);
4320        }
4321
4322        // Re-apply user/background padding so that scrollbar(s) get added
4323        resolvePadding();
4324    }
4325
4326    /**
4327     * <p>
4328     * Initalizes the scrollability cache if necessary.
4329     * </p>
4330     */
4331    private void initScrollCache() {
4332        if (mScrollCache == null) {
4333            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4334        }
4335    }
4336
4337    private ScrollabilityCache getScrollCache() {
4338        initScrollCache();
4339        return mScrollCache;
4340    }
4341
4342    /**
4343     * Set the position of the vertical scroll bar. Should be one of
4344     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4345     * {@link #SCROLLBAR_POSITION_RIGHT}.
4346     *
4347     * @param position Where the vertical scroll bar should be positioned.
4348     */
4349    public void setVerticalScrollbarPosition(int position) {
4350        if (mVerticalScrollbarPosition != position) {
4351            mVerticalScrollbarPosition = position;
4352            computeOpaqueFlags();
4353            resolvePadding();
4354        }
4355    }
4356
4357    /**
4358     * @return The position where the vertical scroll bar will show, if applicable.
4359     * @see #setVerticalScrollbarPosition(int)
4360     */
4361    public int getVerticalScrollbarPosition() {
4362        return mVerticalScrollbarPosition;
4363    }
4364
4365    ListenerInfo getListenerInfo() {
4366        if (mListenerInfo != null) {
4367            return mListenerInfo;
4368        }
4369        mListenerInfo = new ListenerInfo();
4370        return mListenerInfo;
4371    }
4372
4373    /**
4374     * Register a callback to be invoked when focus of this view changed.
4375     *
4376     * @param l The callback that will run.
4377     */
4378    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4379        getListenerInfo().mOnFocusChangeListener = l;
4380    }
4381
4382    /**
4383     * Add a listener that will be called when the bounds of the view change due to
4384     * layout processing.
4385     *
4386     * @param listener The listener that will be called when layout bounds change.
4387     */
4388    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4389        ListenerInfo li = getListenerInfo();
4390        if (li.mOnLayoutChangeListeners == null) {
4391            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4392        }
4393        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4394            li.mOnLayoutChangeListeners.add(listener);
4395        }
4396    }
4397
4398    /**
4399     * Remove a listener for layout changes.
4400     *
4401     * @param listener The listener for layout bounds change.
4402     */
4403    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4404        ListenerInfo li = mListenerInfo;
4405        if (li == null || li.mOnLayoutChangeListeners == null) {
4406            return;
4407        }
4408        li.mOnLayoutChangeListeners.remove(listener);
4409    }
4410
4411    /**
4412     * Add a listener for attach state changes.
4413     *
4414     * This listener will be called whenever this view is attached or detached
4415     * from a window. Remove the listener using
4416     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4417     *
4418     * @param listener Listener to attach
4419     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4420     */
4421    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4422        ListenerInfo li = getListenerInfo();
4423        if (li.mOnAttachStateChangeListeners == null) {
4424            li.mOnAttachStateChangeListeners
4425                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4426        }
4427        li.mOnAttachStateChangeListeners.add(listener);
4428    }
4429
4430    /**
4431     * Remove a listener for attach state changes. The listener will receive no further
4432     * notification of window attach/detach events.
4433     *
4434     * @param listener Listener to remove
4435     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4436     */
4437    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4438        ListenerInfo li = mListenerInfo;
4439        if (li == null || li.mOnAttachStateChangeListeners == null) {
4440            return;
4441        }
4442        li.mOnAttachStateChangeListeners.remove(listener);
4443    }
4444
4445    /**
4446     * Returns the focus-change callback registered for this view.
4447     *
4448     * @return The callback, or null if one is not registered.
4449     */
4450    public OnFocusChangeListener getOnFocusChangeListener() {
4451        ListenerInfo li = mListenerInfo;
4452        return li != null ? li.mOnFocusChangeListener : null;
4453    }
4454
4455    /**
4456     * Register a callback to be invoked when this view is clicked. If this view is not
4457     * clickable, it becomes clickable.
4458     *
4459     * @param l The callback that will run
4460     *
4461     * @see #setClickable(boolean)
4462     */
4463    public void setOnClickListener(OnClickListener l) {
4464        if (!isClickable()) {
4465            setClickable(true);
4466        }
4467        getListenerInfo().mOnClickListener = l;
4468    }
4469
4470    /**
4471     * Return whether this view has an attached OnClickListener.  Returns
4472     * true if there is a listener, false if there is none.
4473     */
4474    public boolean hasOnClickListeners() {
4475        ListenerInfo li = mListenerInfo;
4476        return (li != null && li.mOnClickListener != null);
4477    }
4478
4479    /**
4480     * Register a callback to be invoked when this view is clicked and held. If this view is not
4481     * long clickable, it becomes long clickable.
4482     *
4483     * @param l The callback that will run
4484     *
4485     * @see #setLongClickable(boolean)
4486     */
4487    public void setOnLongClickListener(OnLongClickListener l) {
4488        if (!isLongClickable()) {
4489            setLongClickable(true);
4490        }
4491        getListenerInfo().mOnLongClickListener = l;
4492    }
4493
4494    /**
4495     * Register a callback to be invoked when the context menu for this view is
4496     * being built. If this view is not long clickable, it becomes long clickable.
4497     *
4498     * @param l The callback that will run
4499     *
4500     */
4501    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4502        if (!isLongClickable()) {
4503            setLongClickable(true);
4504        }
4505        getListenerInfo().mOnCreateContextMenuListener = l;
4506    }
4507
4508    /**
4509     * Call this view's OnClickListener, if it is defined.  Performs all normal
4510     * actions associated with clicking: reporting accessibility event, playing
4511     * a sound, etc.
4512     *
4513     * @return True there was an assigned OnClickListener that was called, false
4514     *         otherwise is returned.
4515     */
4516    public boolean performClick() {
4517        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4518
4519        ListenerInfo li = mListenerInfo;
4520        if (li != null && li.mOnClickListener != null) {
4521            playSoundEffect(SoundEffectConstants.CLICK);
4522            li.mOnClickListener.onClick(this);
4523            return true;
4524        }
4525
4526        return false;
4527    }
4528
4529    /**
4530     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4531     * this only calls the listener, and does not do any associated clicking
4532     * actions like reporting an accessibility event.
4533     *
4534     * @return True there was an assigned OnClickListener that was called, false
4535     *         otherwise is returned.
4536     */
4537    public boolean callOnClick() {
4538        ListenerInfo li = mListenerInfo;
4539        if (li != null && li.mOnClickListener != null) {
4540            li.mOnClickListener.onClick(this);
4541            return true;
4542        }
4543        return false;
4544    }
4545
4546    /**
4547     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4548     * OnLongClickListener did not consume the event.
4549     *
4550     * @return True if one of the above receivers consumed the event, false otherwise.
4551     */
4552    public boolean performLongClick() {
4553        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4554
4555        boolean handled = false;
4556        ListenerInfo li = mListenerInfo;
4557        if (li != null && li.mOnLongClickListener != null) {
4558            handled = li.mOnLongClickListener.onLongClick(View.this);
4559        }
4560        if (!handled) {
4561            handled = showContextMenu();
4562        }
4563        if (handled) {
4564            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4565        }
4566        return handled;
4567    }
4568
4569    /**
4570     * Performs button-related actions during a touch down event.
4571     *
4572     * @param event The event.
4573     * @return True if the down was consumed.
4574     *
4575     * @hide
4576     */
4577    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4578        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4579            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4580                return true;
4581            }
4582        }
4583        return false;
4584    }
4585
4586    /**
4587     * Bring up the context menu for this view.
4588     *
4589     * @return Whether a context menu was displayed.
4590     */
4591    public boolean showContextMenu() {
4592        return getParent().showContextMenuForChild(this);
4593    }
4594
4595    /**
4596     * Bring up the context menu for this view, referring to the item under the specified point.
4597     *
4598     * @param x The referenced x coordinate.
4599     * @param y The referenced y coordinate.
4600     * @param metaState The keyboard modifiers that were pressed.
4601     * @return Whether a context menu was displayed.
4602     *
4603     * @hide
4604     */
4605    public boolean showContextMenu(float x, float y, int metaState) {
4606        return showContextMenu();
4607    }
4608
4609    /**
4610     * Start an action mode.
4611     *
4612     * @param callback Callback that will control the lifecycle of the action mode
4613     * @return The new action mode if it is started, null otherwise
4614     *
4615     * @see ActionMode
4616     */
4617    public ActionMode startActionMode(ActionMode.Callback callback) {
4618        ViewParent parent = getParent();
4619        if (parent == null) return null;
4620        return parent.startActionModeForChild(this, callback);
4621    }
4622
4623    /**
4624     * Register a callback to be invoked when a hardware key is pressed in this view.
4625     * Key presses in software input methods will generally not trigger the methods of
4626     * this listener.
4627     * @param l the key listener to attach to this view
4628     */
4629    public void setOnKeyListener(OnKeyListener l) {
4630        getListenerInfo().mOnKeyListener = l;
4631    }
4632
4633    /**
4634     * Register a callback to be invoked when a touch event is sent to this view.
4635     * @param l the touch listener to attach to this view
4636     */
4637    public void setOnTouchListener(OnTouchListener l) {
4638        getListenerInfo().mOnTouchListener = l;
4639    }
4640
4641    /**
4642     * Register a callback to be invoked when a generic motion event is sent to this view.
4643     * @param l the generic motion listener to attach to this view
4644     */
4645    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4646        getListenerInfo().mOnGenericMotionListener = l;
4647    }
4648
4649    /**
4650     * Register a callback to be invoked when a hover event is sent to this view.
4651     * @param l the hover listener to attach to this view
4652     */
4653    public void setOnHoverListener(OnHoverListener l) {
4654        getListenerInfo().mOnHoverListener = l;
4655    }
4656
4657    /**
4658     * Register a drag event listener callback object for this View. The parameter is
4659     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4660     * View, the system calls the
4661     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4662     * @param l An implementation of {@link android.view.View.OnDragListener}.
4663     */
4664    public void setOnDragListener(OnDragListener l) {
4665        getListenerInfo().mOnDragListener = l;
4666    }
4667
4668    /**
4669     * Give this view focus. This will cause
4670     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4671     *
4672     * Note: this does not check whether this {@link View} should get focus, it just
4673     * gives it focus no matter what.  It should only be called internally by framework
4674     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4675     *
4676     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4677     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4678     *        focus moved when requestFocus() is called. It may not always
4679     *        apply, in which case use the default View.FOCUS_DOWN.
4680     * @param previouslyFocusedRect The rectangle of the view that had focus
4681     *        prior in this View's coordinate system.
4682     */
4683    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4684        if (DBG) {
4685            System.out.println(this + " requestFocus()");
4686        }
4687
4688        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4689            mPrivateFlags |= PFLAG_FOCUSED;
4690
4691            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4692
4693            if (mParent != null) {
4694                mParent.requestChildFocus(this, this);
4695            }
4696
4697            if (mAttachInfo != null) {
4698                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4699            }
4700
4701            onFocusChanged(true, direction, previouslyFocusedRect);
4702            refreshDrawableState();
4703        }
4704    }
4705
4706    /**
4707     * Request that a rectangle of this view be visible on the screen,
4708     * scrolling if necessary just enough.
4709     *
4710     * <p>A View should call this if it maintains some notion of which part
4711     * of its content is interesting.  For example, a text editing view
4712     * should call this when its cursor moves.
4713     *
4714     * @param rectangle The rectangle.
4715     * @return Whether any parent scrolled.
4716     */
4717    public boolean requestRectangleOnScreen(Rect rectangle) {
4718        return requestRectangleOnScreen(rectangle, false);
4719    }
4720
4721    /**
4722     * Request that a rectangle of this view be visible on the screen,
4723     * scrolling if necessary just enough.
4724     *
4725     * <p>A View should call this if it maintains some notion of which part
4726     * of its content is interesting.  For example, a text editing view
4727     * should call this when its cursor moves.
4728     *
4729     * <p>When <code>immediate</code> is set to true, scrolling will not be
4730     * animated.
4731     *
4732     * @param rectangle The rectangle.
4733     * @param immediate True to forbid animated scrolling, false otherwise
4734     * @return Whether any parent scrolled.
4735     */
4736    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4737        if (mParent == null) {
4738            return false;
4739        }
4740
4741        View child = this;
4742
4743        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4744        position.set(rectangle);
4745
4746        ViewParent parent = mParent;
4747        boolean scrolled = false;
4748        while (parent != null) {
4749            rectangle.set((int) position.left, (int) position.top,
4750                    (int) position.right, (int) position.bottom);
4751
4752            scrolled |= parent.requestChildRectangleOnScreen(child,
4753                    rectangle, immediate);
4754
4755            if (!child.hasIdentityMatrix()) {
4756                child.getMatrix().mapRect(position);
4757            }
4758
4759            position.offset(child.mLeft, child.mTop);
4760
4761            if (!(parent instanceof View)) {
4762                break;
4763            }
4764
4765            View parentView = (View) parent;
4766
4767            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4768
4769            child = parentView;
4770            parent = child.getParent();
4771        }
4772
4773        return scrolled;
4774    }
4775
4776    /**
4777     * Called when this view wants to give up focus. If focus is cleared
4778     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4779     * <p>
4780     * <strong>Note:</strong> When a View clears focus the framework is trying
4781     * to give focus to the first focusable View from the top. Hence, if this
4782     * View is the first from the top that can take focus, then all callbacks
4783     * related to clearing focus will be invoked after wich the framework will
4784     * give focus to this view.
4785     * </p>
4786     */
4787    public void clearFocus() {
4788        if (DBG) {
4789            System.out.println(this + " clearFocus()");
4790        }
4791
4792        clearFocusInternal(true, true);
4793    }
4794
4795    /**
4796     * Clears focus from the view, optionally propagating the change up through
4797     * the parent hierarchy and requesting that the root view place new focus.
4798     *
4799     * @param propagate whether to propagate the change up through the parent
4800     *            hierarchy
4801     * @param refocus when propagate is true, specifies whether to request the
4802     *            root view place new focus
4803     */
4804    void clearFocusInternal(boolean propagate, boolean refocus) {
4805        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4806            mPrivateFlags &= ~PFLAG_FOCUSED;
4807
4808            if (propagate && mParent != null) {
4809                mParent.clearChildFocus(this);
4810            }
4811
4812            onFocusChanged(false, 0, null);
4813
4814            refreshDrawableState();
4815
4816            if (propagate && (!refocus || !rootViewRequestFocus())) {
4817                notifyGlobalFocusCleared(this);
4818            }
4819        }
4820    }
4821
4822    void notifyGlobalFocusCleared(View oldFocus) {
4823        if (oldFocus != null && mAttachInfo != null) {
4824            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4825        }
4826    }
4827
4828    boolean rootViewRequestFocus() {
4829        final View root = getRootView();
4830        return root != null && root.requestFocus();
4831    }
4832
4833    /**
4834     * Called internally by the view system when a new view is getting focus.
4835     * This is what clears the old focus.
4836     * <p>
4837     * <b>NOTE:</b> The parent view's focused child must be updated manually
4838     * after calling this method. Otherwise, the view hierarchy may be left in
4839     * an inconstent state.
4840     */
4841    void unFocus() {
4842        if (DBG) {
4843            System.out.println(this + " unFocus()");
4844        }
4845
4846        clearFocusInternal(false, false);
4847    }
4848
4849    /**
4850     * Returns true if this view has focus iteself, or is the ancestor of the
4851     * view that has focus.
4852     *
4853     * @return True if this view has or contains focus, false otherwise.
4854     */
4855    @ViewDebug.ExportedProperty(category = "focus")
4856    public boolean hasFocus() {
4857        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4858    }
4859
4860    /**
4861     * Returns true if this view is focusable or if it contains a reachable View
4862     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4863     * is a View whose parents do not block descendants focus.
4864     *
4865     * Only {@link #VISIBLE} views are considered focusable.
4866     *
4867     * @return True if the view is focusable or if the view contains a focusable
4868     *         View, false otherwise.
4869     *
4870     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4871     */
4872    public boolean hasFocusable() {
4873        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4874    }
4875
4876    /**
4877     * Called by the view system when the focus state of this view changes.
4878     * When the focus change event is caused by directional navigation, direction
4879     * and previouslyFocusedRect provide insight into where the focus is coming from.
4880     * When overriding, be sure to call up through to the super class so that
4881     * the standard focus handling will occur.
4882     *
4883     * @param gainFocus True if the View has focus; false otherwise.
4884     * @param direction The direction focus has moved when requestFocus()
4885     *                  is called to give this view focus. Values are
4886     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4887     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4888     *                  It may not always apply, in which case use the default.
4889     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4890     *        system, of the previously focused view.  If applicable, this will be
4891     *        passed in as finer grained information about where the focus is coming
4892     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4893     */
4894    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
4895            @Nullable Rect previouslyFocusedRect) {
4896        if (gainFocus) {
4897            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4898        } else {
4899            notifyViewAccessibilityStateChangedIfNeeded(
4900                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
4901        }
4902
4903        InputMethodManager imm = InputMethodManager.peekInstance();
4904        if (!gainFocus) {
4905            if (isPressed()) {
4906                setPressed(false);
4907            }
4908            if (imm != null && mAttachInfo != null
4909                    && mAttachInfo.mHasWindowFocus) {
4910                imm.focusOut(this);
4911            }
4912            onFocusLost();
4913        } else if (imm != null && mAttachInfo != null
4914                && mAttachInfo.mHasWindowFocus) {
4915            imm.focusIn(this);
4916        }
4917
4918        invalidate(true);
4919        ListenerInfo li = mListenerInfo;
4920        if (li != null && li.mOnFocusChangeListener != null) {
4921            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4922        }
4923
4924        if (mAttachInfo != null) {
4925            mAttachInfo.mKeyDispatchState.reset(this);
4926        }
4927    }
4928
4929    /**
4930     * Sends an accessibility event of the given type. If accessibility is
4931     * not enabled this method has no effect. The default implementation calls
4932     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4933     * to populate information about the event source (this View), then calls
4934     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4935     * populate the text content of the event source including its descendants,
4936     * and last calls
4937     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4938     * on its parent to resuest sending of the event to interested parties.
4939     * <p>
4940     * If an {@link AccessibilityDelegate} has been specified via calling
4941     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4942     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4943     * responsible for handling this call.
4944     * </p>
4945     *
4946     * @param eventType The type of the event to send, as defined by several types from
4947     * {@link android.view.accessibility.AccessibilityEvent}, such as
4948     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4949     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4950     *
4951     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4952     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4953     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4954     * @see AccessibilityDelegate
4955     */
4956    public void sendAccessibilityEvent(int eventType) {
4957        // Excluded views do not send accessibility events.
4958        if (!includeForAccessibility()) {
4959            return;
4960        }
4961        if (mAccessibilityDelegate != null) {
4962            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4963        } else {
4964            sendAccessibilityEventInternal(eventType);
4965        }
4966    }
4967
4968    /**
4969     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4970     * {@link AccessibilityEvent} to make an announcement which is related to some
4971     * sort of a context change for which none of the events representing UI transitions
4972     * is a good fit. For example, announcing a new page in a book. If accessibility
4973     * is not enabled this method does nothing.
4974     *
4975     * @param text The announcement text.
4976     */
4977    public void announceForAccessibility(CharSequence text) {
4978        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4979            AccessibilityEvent event = AccessibilityEvent.obtain(
4980                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4981            onInitializeAccessibilityEvent(event);
4982            event.getText().add(text);
4983            event.setContentDescription(null);
4984            mParent.requestSendAccessibilityEvent(this, event);
4985        }
4986    }
4987
4988    /**
4989     * @see #sendAccessibilityEvent(int)
4990     *
4991     * Note: Called from the default {@link AccessibilityDelegate}.
4992     */
4993    void sendAccessibilityEventInternal(int eventType) {
4994        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4995            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4996        }
4997    }
4998
4999    /**
5000     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5001     * takes as an argument an empty {@link AccessibilityEvent} and does not
5002     * perform a check whether accessibility is enabled.
5003     * <p>
5004     * If an {@link AccessibilityDelegate} has been specified via calling
5005     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5006     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5007     * is responsible for handling this call.
5008     * </p>
5009     *
5010     * @param event The event to send.
5011     *
5012     * @see #sendAccessibilityEvent(int)
5013     */
5014    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5015        if (mAccessibilityDelegate != null) {
5016            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5017        } else {
5018            sendAccessibilityEventUncheckedInternal(event);
5019        }
5020    }
5021
5022    /**
5023     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5024     *
5025     * Note: Called from the default {@link AccessibilityDelegate}.
5026     */
5027    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5028        if (!isShown()) {
5029            return;
5030        }
5031        onInitializeAccessibilityEvent(event);
5032        // Only a subset of accessibility events populates text content.
5033        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5034            dispatchPopulateAccessibilityEvent(event);
5035        }
5036        // In the beginning we called #isShown(), so we know that getParent() is not null.
5037        getParent().requestSendAccessibilityEvent(this, event);
5038    }
5039
5040    /**
5041     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5042     * to its children for adding their text content to the event. Note that the
5043     * event text is populated in a separate dispatch path since we add to the
5044     * event not only the text of the source but also the text of all its descendants.
5045     * A typical implementation will call
5046     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5047     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5048     * on each child. Override this method if custom population of the event text
5049     * content is required.
5050     * <p>
5051     * If an {@link AccessibilityDelegate} has been specified via calling
5052     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5053     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5054     * is responsible for handling this call.
5055     * </p>
5056     * <p>
5057     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5058     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5059     * </p>
5060     *
5061     * @param event The event.
5062     *
5063     * @return True if the event population was completed.
5064     */
5065    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5066        if (mAccessibilityDelegate != null) {
5067            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5068        } else {
5069            return dispatchPopulateAccessibilityEventInternal(event);
5070        }
5071    }
5072
5073    /**
5074     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5075     *
5076     * Note: Called from the default {@link AccessibilityDelegate}.
5077     */
5078    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5079        onPopulateAccessibilityEvent(event);
5080        return false;
5081    }
5082
5083    /**
5084     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5085     * giving a chance to this View to populate the accessibility event with its
5086     * text content. While this method is free to modify event
5087     * attributes other than text content, doing so should normally be performed in
5088     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5089     * <p>
5090     * Example: Adding formatted date string to an accessibility event in addition
5091     *          to the text added by the super implementation:
5092     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5093     *     super.onPopulateAccessibilityEvent(event);
5094     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5095     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5096     *         mCurrentDate.getTimeInMillis(), flags);
5097     *     event.getText().add(selectedDateUtterance);
5098     * }</pre>
5099     * <p>
5100     * If an {@link AccessibilityDelegate} has been specified via calling
5101     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5102     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5103     * is responsible for handling this call.
5104     * </p>
5105     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5106     * information to the event, in case the default implementation has basic information to add.
5107     * </p>
5108     *
5109     * @param event The accessibility event which to populate.
5110     *
5111     * @see #sendAccessibilityEvent(int)
5112     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5113     */
5114    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5115        if (mAccessibilityDelegate != null) {
5116            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5117        } else {
5118            onPopulateAccessibilityEventInternal(event);
5119        }
5120    }
5121
5122    /**
5123     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5124     *
5125     * Note: Called from the default {@link AccessibilityDelegate}.
5126     */
5127    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5128    }
5129
5130    /**
5131     * Initializes an {@link AccessibilityEvent} with information about
5132     * this View which is the event source. In other words, the source of
5133     * an accessibility event is the view whose state change triggered firing
5134     * the event.
5135     * <p>
5136     * Example: Setting the password property of an event in addition
5137     *          to properties set by the super implementation:
5138     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5139     *     super.onInitializeAccessibilityEvent(event);
5140     *     event.setPassword(true);
5141     * }</pre>
5142     * <p>
5143     * If an {@link AccessibilityDelegate} has been specified via calling
5144     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5145     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5146     * is responsible for handling this call.
5147     * </p>
5148     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5149     * information to the event, in case the default implementation has basic information to add.
5150     * </p>
5151     * @param event The event to initialize.
5152     *
5153     * @see #sendAccessibilityEvent(int)
5154     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5155     */
5156    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5157        if (mAccessibilityDelegate != null) {
5158            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5159        } else {
5160            onInitializeAccessibilityEventInternal(event);
5161        }
5162    }
5163
5164    /**
5165     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5166     *
5167     * Note: Called from the default {@link AccessibilityDelegate}.
5168     */
5169    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5170        event.setSource(this);
5171        event.setClassName(View.class.getName());
5172        event.setPackageName(getContext().getPackageName());
5173        event.setEnabled(isEnabled());
5174        event.setContentDescription(mContentDescription);
5175
5176        switch (event.getEventType()) {
5177            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5178                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5179                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5180                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5181                event.setItemCount(focusablesTempList.size());
5182                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5183                if (mAttachInfo != null) {
5184                    focusablesTempList.clear();
5185                }
5186            } break;
5187            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5188                CharSequence text = getIterableTextForAccessibility();
5189                if (text != null && text.length() > 0) {
5190                    event.setFromIndex(getAccessibilitySelectionStart());
5191                    event.setToIndex(getAccessibilitySelectionEnd());
5192                    event.setItemCount(text.length());
5193                }
5194            } break;
5195        }
5196    }
5197
5198    /**
5199     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5200     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5201     * This method is responsible for obtaining an accessibility node info from a
5202     * pool of reusable instances and calling
5203     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5204     * initialize the former.
5205     * <p>
5206     * Note: The client is responsible for recycling the obtained instance by calling
5207     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5208     * </p>
5209     *
5210     * @return A populated {@link AccessibilityNodeInfo}.
5211     *
5212     * @see AccessibilityNodeInfo
5213     */
5214    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5215        if (mAccessibilityDelegate != null) {
5216            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5217        } else {
5218            return createAccessibilityNodeInfoInternal();
5219        }
5220    }
5221
5222    /**
5223     * @see #createAccessibilityNodeInfo()
5224     */
5225    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5226        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5227        if (provider != null) {
5228            return provider.createAccessibilityNodeInfo(View.NO_ID);
5229        } else {
5230            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5231            onInitializeAccessibilityNodeInfo(info);
5232            return info;
5233        }
5234    }
5235
5236    /**
5237     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5238     * The base implementation sets:
5239     * <ul>
5240     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5241     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5242     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5243     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5244     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5245     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5246     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5247     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5248     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5249     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5250     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5251     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5252     * </ul>
5253     * <p>
5254     * Subclasses should override this method, call the super implementation,
5255     * and set additional attributes.
5256     * </p>
5257     * <p>
5258     * If an {@link AccessibilityDelegate} has been specified via calling
5259     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5260     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5261     * is responsible for handling this call.
5262     * </p>
5263     *
5264     * @param info The instance to initialize.
5265     */
5266    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5267        if (mAccessibilityDelegate != null) {
5268            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5269        } else {
5270            onInitializeAccessibilityNodeInfoInternal(info);
5271        }
5272    }
5273
5274    /**
5275     * Gets the location of this view in screen coordintates.
5276     *
5277     * @param outRect The output location
5278     */
5279    void getBoundsOnScreen(Rect outRect) {
5280        if (mAttachInfo == null) {
5281            return;
5282        }
5283
5284        RectF position = mAttachInfo.mTmpTransformRect;
5285        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5286
5287        if (!hasIdentityMatrix()) {
5288            getMatrix().mapRect(position);
5289        }
5290
5291        position.offset(mLeft, mTop);
5292
5293        ViewParent parent = mParent;
5294        while (parent instanceof View) {
5295            View parentView = (View) parent;
5296
5297            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5298
5299            if (!parentView.hasIdentityMatrix()) {
5300                parentView.getMatrix().mapRect(position);
5301            }
5302
5303            position.offset(parentView.mLeft, parentView.mTop);
5304
5305            parent = parentView.mParent;
5306        }
5307
5308        if (parent instanceof ViewRootImpl) {
5309            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5310            position.offset(0, -viewRootImpl.mCurScrollY);
5311        }
5312
5313        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5314
5315        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5316                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5317    }
5318
5319    /**
5320     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5321     *
5322     * Note: Called from the default {@link AccessibilityDelegate}.
5323     */
5324    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5325        Rect bounds = mAttachInfo.mTmpInvalRect;
5326
5327        getDrawingRect(bounds);
5328        info.setBoundsInParent(bounds);
5329
5330        getBoundsOnScreen(bounds);
5331        info.setBoundsInScreen(bounds);
5332
5333        ViewParent parent = getParentForAccessibility();
5334        if (parent instanceof View) {
5335            info.setParent((View) parent);
5336        }
5337
5338        if (mID != View.NO_ID) {
5339            View rootView = getRootView();
5340            if (rootView == null) {
5341                rootView = this;
5342            }
5343            View label = rootView.findLabelForView(this, mID);
5344            if (label != null) {
5345                info.setLabeledBy(label);
5346            }
5347
5348            if ((mAttachInfo.mAccessibilityFetchFlags
5349                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5350                    && Resources.resourceHasPackage(mID)) {
5351                try {
5352                    String viewId = getResources().getResourceName(mID);
5353                    info.setViewIdResourceName(viewId);
5354                } catch (Resources.NotFoundException nfe) {
5355                    /* ignore */
5356                }
5357            }
5358        }
5359
5360        if (mLabelForId != View.NO_ID) {
5361            View rootView = getRootView();
5362            if (rootView == null) {
5363                rootView = this;
5364            }
5365            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5366            if (labeled != null) {
5367                info.setLabelFor(labeled);
5368            }
5369        }
5370
5371        info.setVisibleToUser(isVisibleToUser());
5372
5373        info.setPackageName(mContext.getPackageName());
5374        info.setClassName(View.class.getName());
5375        info.setContentDescription(getContentDescription());
5376
5377        info.setEnabled(isEnabled());
5378        info.setClickable(isClickable());
5379        info.setFocusable(isFocusable());
5380        info.setFocused(isFocused());
5381        info.setAccessibilityFocused(isAccessibilityFocused());
5382        info.setSelected(isSelected());
5383        info.setLongClickable(isLongClickable());
5384
5385        // TODO: These make sense only if we are in an AdapterView but all
5386        // views can be selected. Maybe from accessibility perspective
5387        // we should report as selectable view in an AdapterView.
5388        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5389        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5390
5391        if (isFocusable()) {
5392            if (isFocused()) {
5393                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5394            } else {
5395                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5396            }
5397        }
5398
5399        if (!isAccessibilityFocused()) {
5400            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5401        } else {
5402            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5403        }
5404
5405        if (isClickable() && isEnabled()) {
5406            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5407        }
5408
5409        if (isLongClickable() && isEnabled()) {
5410            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5411        }
5412
5413        CharSequence text = getIterableTextForAccessibility();
5414        if (text != null && text.length() > 0) {
5415            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5416
5417            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5418            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5419            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5420            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5421                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5422                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5423        }
5424    }
5425
5426    private View findLabelForView(View view, int labeledId) {
5427        if (mMatchLabelForPredicate == null) {
5428            mMatchLabelForPredicate = new MatchLabelForPredicate();
5429        }
5430        mMatchLabelForPredicate.mLabeledId = labeledId;
5431        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5432    }
5433
5434    /**
5435     * Computes whether this view is visible to the user. Such a view is
5436     * attached, visible, all its predecessors are visible, it is not clipped
5437     * entirely by its predecessors, and has an alpha greater than zero.
5438     *
5439     * @return Whether the view is visible on the screen.
5440     *
5441     * @hide
5442     */
5443    protected boolean isVisibleToUser() {
5444        return isVisibleToUser(null);
5445    }
5446
5447    /**
5448     * Computes whether the given portion of this view is visible to the user.
5449     * Such a view is attached, visible, all its predecessors are visible,
5450     * has an alpha greater than zero, and the specified portion is not
5451     * clipped entirely by its predecessors.
5452     *
5453     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5454     *                    <code>null</code>, and the entire view will be tested in this case.
5455     *                    When <code>true</code> is returned by the function, the actual visible
5456     *                    region will be stored in this parameter; that is, if boundInView is fully
5457     *                    contained within the view, no modification will be made, otherwise regions
5458     *                    outside of the visible area of the view will be clipped.
5459     *
5460     * @return Whether the specified portion of the view is visible on the screen.
5461     *
5462     * @hide
5463     */
5464    protected boolean isVisibleToUser(Rect boundInView) {
5465        if (mAttachInfo != null) {
5466            // Attached to invisible window means this view is not visible.
5467            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5468                return false;
5469            }
5470            // An invisible predecessor or one with alpha zero means
5471            // that this view is not visible to the user.
5472            Object current = this;
5473            while (current instanceof View) {
5474                View view = (View) current;
5475                // We have attach info so this view is attached and there is no
5476                // need to check whether we reach to ViewRootImpl on the way up.
5477                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5478                        view.getVisibility() != VISIBLE) {
5479                    return false;
5480                }
5481                current = view.mParent;
5482            }
5483            // Check if the view is entirely covered by its predecessors.
5484            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5485            Point offset = mAttachInfo.mPoint;
5486            if (!getGlobalVisibleRect(visibleRect, offset)) {
5487                return false;
5488            }
5489            // Check if the visible portion intersects the rectangle of interest.
5490            if (boundInView != null) {
5491                visibleRect.offset(-offset.x, -offset.y);
5492                return boundInView.intersect(visibleRect);
5493            }
5494            return true;
5495        }
5496        return false;
5497    }
5498
5499    /**
5500     * Returns the delegate for implementing accessibility support via
5501     * composition. For more details see {@link AccessibilityDelegate}.
5502     *
5503     * @return The delegate, or null if none set.
5504     *
5505     * @hide
5506     */
5507    public AccessibilityDelegate getAccessibilityDelegate() {
5508        return mAccessibilityDelegate;
5509    }
5510
5511    /**
5512     * Sets a delegate for implementing accessibility support via composition as
5513     * opposed to inheritance. The delegate's primary use is for implementing
5514     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5515     *
5516     * @param delegate The delegate instance.
5517     *
5518     * @see AccessibilityDelegate
5519     */
5520    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5521        mAccessibilityDelegate = delegate;
5522    }
5523
5524    /**
5525     * Gets the provider for managing a virtual view hierarchy rooted at this View
5526     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5527     * that explore the window content.
5528     * <p>
5529     * If this method returns an instance, this instance is responsible for managing
5530     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5531     * View including the one representing the View itself. Similarly the returned
5532     * instance is responsible for performing accessibility actions on any virtual
5533     * view or the root view itself.
5534     * </p>
5535     * <p>
5536     * If an {@link AccessibilityDelegate} has been specified via calling
5537     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5538     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5539     * is responsible for handling this call.
5540     * </p>
5541     *
5542     * @return The provider.
5543     *
5544     * @see AccessibilityNodeProvider
5545     */
5546    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5547        if (mAccessibilityDelegate != null) {
5548            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5549        } else {
5550            return null;
5551        }
5552    }
5553
5554    /**
5555     * Gets the unique identifier of this view on the screen for accessibility purposes.
5556     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5557     *
5558     * @return The view accessibility id.
5559     *
5560     * @hide
5561     */
5562    public int getAccessibilityViewId() {
5563        if (mAccessibilityViewId == NO_ID) {
5564            mAccessibilityViewId = sNextAccessibilityViewId++;
5565        }
5566        return mAccessibilityViewId;
5567    }
5568
5569    /**
5570     * Gets the unique identifier of the window in which this View reseides.
5571     *
5572     * @return The window accessibility id.
5573     *
5574     * @hide
5575     */
5576    public int getAccessibilityWindowId() {
5577        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5578    }
5579
5580    /**
5581     * Gets the {@link View} description. It briefly describes the view and is
5582     * primarily used for accessibility support. Set this property to enable
5583     * better accessibility support for your application. This is especially
5584     * true for views that do not have textual representation (For example,
5585     * ImageButton).
5586     *
5587     * @return The content description.
5588     *
5589     * @attr ref android.R.styleable#View_contentDescription
5590     */
5591    @ViewDebug.ExportedProperty(category = "accessibility")
5592    public CharSequence getContentDescription() {
5593        return mContentDescription;
5594    }
5595
5596    /**
5597     * Sets the {@link View} description. It briefly describes the view and is
5598     * primarily used for accessibility support. Set this property to enable
5599     * better accessibility support for your application. This is especially
5600     * true for views that do not have textual representation (For example,
5601     * ImageButton).
5602     *
5603     * @param contentDescription The content description.
5604     *
5605     * @attr ref android.R.styleable#View_contentDescription
5606     */
5607    @RemotableViewMethod
5608    public void setContentDescription(CharSequence contentDescription) {
5609        if (mContentDescription == null) {
5610            if (contentDescription == null) {
5611                return;
5612            }
5613        } else if (mContentDescription.equals(contentDescription)) {
5614            return;
5615        }
5616        mContentDescription = contentDescription;
5617        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5618        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5619            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5620            notifySubtreeAccessibilityStateChangedIfNeeded();
5621        } else {
5622            notifyViewAccessibilityStateChangedIfNeeded(
5623                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5624        }
5625    }
5626
5627    /**
5628     * Gets the id of a view for which this view serves as a label for
5629     * accessibility purposes.
5630     *
5631     * @return The labeled view id.
5632     */
5633    @ViewDebug.ExportedProperty(category = "accessibility")
5634    public int getLabelFor() {
5635        return mLabelForId;
5636    }
5637
5638    /**
5639     * Sets the id of a view for which this view serves as a label for
5640     * accessibility purposes.
5641     *
5642     * @param id The labeled view id.
5643     */
5644    @RemotableViewMethod
5645    public void setLabelFor(int id) {
5646        mLabelForId = id;
5647        if (mLabelForId != View.NO_ID
5648                && mID == View.NO_ID) {
5649            mID = generateViewId();
5650        }
5651    }
5652
5653    /**
5654     * Invoked whenever this view loses focus, either by losing window focus or by losing
5655     * focus within its window. This method can be used to clear any state tied to the
5656     * focus. For instance, if a button is held pressed with the trackball and the window
5657     * loses focus, this method can be used to cancel the press.
5658     *
5659     * Subclasses of View overriding this method should always call super.onFocusLost().
5660     *
5661     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5662     * @see #onWindowFocusChanged(boolean)
5663     *
5664     * @hide pending API council approval
5665     */
5666    protected void onFocusLost() {
5667        resetPressedState();
5668    }
5669
5670    private void resetPressedState() {
5671        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5672            return;
5673        }
5674
5675        if (isPressed()) {
5676            setPressed(false);
5677
5678            if (!mHasPerformedLongPress) {
5679                removeLongPressCallback();
5680            }
5681        }
5682    }
5683
5684    /**
5685     * Returns true if this view has focus
5686     *
5687     * @return True if this view has focus, false otherwise.
5688     */
5689    @ViewDebug.ExportedProperty(category = "focus")
5690    public boolean isFocused() {
5691        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5692    }
5693
5694    /**
5695     * Find the view in the hierarchy rooted at this view that currently has
5696     * focus.
5697     *
5698     * @return The view that currently has focus, or null if no focused view can
5699     *         be found.
5700     */
5701    public View findFocus() {
5702        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5703    }
5704
5705    /**
5706     * Indicates whether this view is one of the set of scrollable containers in
5707     * its window.
5708     *
5709     * @return whether this view is one of the set of scrollable containers in
5710     * its window
5711     *
5712     * @attr ref android.R.styleable#View_isScrollContainer
5713     */
5714    public boolean isScrollContainer() {
5715        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5716    }
5717
5718    /**
5719     * Change whether this view is one of the set of scrollable containers in
5720     * its window.  This will be used to determine whether the window can
5721     * resize or must pan when a soft input area is open -- scrollable
5722     * containers allow the window to use resize mode since the container
5723     * will appropriately shrink.
5724     *
5725     * @attr ref android.R.styleable#View_isScrollContainer
5726     */
5727    public void setScrollContainer(boolean isScrollContainer) {
5728        if (isScrollContainer) {
5729            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5730                mAttachInfo.mScrollContainers.add(this);
5731                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5732            }
5733            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5734        } else {
5735            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5736                mAttachInfo.mScrollContainers.remove(this);
5737            }
5738            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5739        }
5740    }
5741
5742    /**
5743     * Returns the quality of the drawing cache.
5744     *
5745     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5746     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5747     *
5748     * @see #setDrawingCacheQuality(int)
5749     * @see #setDrawingCacheEnabled(boolean)
5750     * @see #isDrawingCacheEnabled()
5751     *
5752     * @attr ref android.R.styleable#View_drawingCacheQuality
5753     */
5754    @DrawingCacheQuality
5755    public int getDrawingCacheQuality() {
5756        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5757    }
5758
5759    /**
5760     * Set the drawing cache quality of this view. This value is used only when the
5761     * drawing cache is enabled
5762     *
5763     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5764     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5765     *
5766     * @see #getDrawingCacheQuality()
5767     * @see #setDrawingCacheEnabled(boolean)
5768     * @see #isDrawingCacheEnabled()
5769     *
5770     * @attr ref android.R.styleable#View_drawingCacheQuality
5771     */
5772    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5773        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5774    }
5775
5776    /**
5777     * Returns whether the screen should remain on, corresponding to the current
5778     * value of {@link #KEEP_SCREEN_ON}.
5779     *
5780     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5781     *
5782     * @see #setKeepScreenOn(boolean)
5783     *
5784     * @attr ref android.R.styleable#View_keepScreenOn
5785     */
5786    public boolean getKeepScreenOn() {
5787        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5788    }
5789
5790    /**
5791     * Controls whether the screen should remain on, modifying the
5792     * value of {@link #KEEP_SCREEN_ON}.
5793     *
5794     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5795     *
5796     * @see #getKeepScreenOn()
5797     *
5798     * @attr ref android.R.styleable#View_keepScreenOn
5799     */
5800    public void setKeepScreenOn(boolean keepScreenOn) {
5801        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5802    }
5803
5804    /**
5805     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5806     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5807     *
5808     * @attr ref android.R.styleable#View_nextFocusLeft
5809     */
5810    public int getNextFocusLeftId() {
5811        return mNextFocusLeftId;
5812    }
5813
5814    /**
5815     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5816     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5817     * decide automatically.
5818     *
5819     * @attr ref android.R.styleable#View_nextFocusLeft
5820     */
5821    public void setNextFocusLeftId(int nextFocusLeftId) {
5822        mNextFocusLeftId = nextFocusLeftId;
5823    }
5824
5825    /**
5826     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5827     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5828     *
5829     * @attr ref android.R.styleable#View_nextFocusRight
5830     */
5831    public int getNextFocusRightId() {
5832        return mNextFocusRightId;
5833    }
5834
5835    /**
5836     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5837     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5838     * decide automatically.
5839     *
5840     * @attr ref android.R.styleable#View_nextFocusRight
5841     */
5842    public void setNextFocusRightId(int nextFocusRightId) {
5843        mNextFocusRightId = nextFocusRightId;
5844    }
5845
5846    /**
5847     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5848     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5849     *
5850     * @attr ref android.R.styleable#View_nextFocusUp
5851     */
5852    public int getNextFocusUpId() {
5853        return mNextFocusUpId;
5854    }
5855
5856    /**
5857     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5858     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5859     * decide automatically.
5860     *
5861     * @attr ref android.R.styleable#View_nextFocusUp
5862     */
5863    public void setNextFocusUpId(int nextFocusUpId) {
5864        mNextFocusUpId = nextFocusUpId;
5865    }
5866
5867    /**
5868     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5869     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5870     *
5871     * @attr ref android.R.styleable#View_nextFocusDown
5872     */
5873    public int getNextFocusDownId() {
5874        return mNextFocusDownId;
5875    }
5876
5877    /**
5878     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5879     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5880     * decide automatically.
5881     *
5882     * @attr ref android.R.styleable#View_nextFocusDown
5883     */
5884    public void setNextFocusDownId(int nextFocusDownId) {
5885        mNextFocusDownId = nextFocusDownId;
5886    }
5887
5888    /**
5889     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5890     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5891     *
5892     * @attr ref android.R.styleable#View_nextFocusForward
5893     */
5894    public int getNextFocusForwardId() {
5895        return mNextFocusForwardId;
5896    }
5897
5898    /**
5899     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5900     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5901     * decide automatically.
5902     *
5903     * @attr ref android.R.styleable#View_nextFocusForward
5904     */
5905    public void setNextFocusForwardId(int nextFocusForwardId) {
5906        mNextFocusForwardId = nextFocusForwardId;
5907    }
5908
5909    /**
5910     * Returns the visibility of this view and all of its ancestors
5911     *
5912     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5913     */
5914    public boolean isShown() {
5915        View current = this;
5916        //noinspection ConstantConditions
5917        do {
5918            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5919                return false;
5920            }
5921            ViewParent parent = current.mParent;
5922            if (parent == null) {
5923                return false; // We are not attached to the view root
5924            }
5925            if (!(parent instanceof View)) {
5926                return true;
5927            }
5928            current = (View) parent;
5929        } while (current != null);
5930
5931        return false;
5932    }
5933
5934    /**
5935     * Called by the view hierarchy when the content insets for a window have
5936     * changed, to allow it to adjust its content to fit within those windows.
5937     * The content insets tell you the space that the status bar, input method,
5938     * and other system windows infringe on the application's window.
5939     *
5940     * <p>You do not normally need to deal with this function, since the default
5941     * window decoration given to applications takes care of applying it to the
5942     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5943     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5944     * and your content can be placed under those system elements.  You can then
5945     * use this method within your view hierarchy if you have parts of your UI
5946     * which you would like to ensure are not being covered.
5947     *
5948     * <p>The default implementation of this method simply applies the content
5949     * insets to the view's padding, consuming that content (modifying the
5950     * insets to be 0), and returning true.  This behavior is off by default, but can
5951     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5952     *
5953     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5954     * insets object is propagated down the hierarchy, so any changes made to it will
5955     * be seen by all following views (including potentially ones above in
5956     * the hierarchy since this is a depth-first traversal).  The first view
5957     * that returns true will abort the entire traversal.
5958     *
5959     * <p>The default implementation works well for a situation where it is
5960     * used with a container that covers the entire window, allowing it to
5961     * apply the appropriate insets to its content on all edges.  If you need
5962     * a more complicated layout (such as two different views fitting system
5963     * windows, one on the top of the window, and one on the bottom),
5964     * you can override the method and handle the insets however you would like.
5965     * Note that the insets provided by the framework are always relative to the
5966     * far edges of the window, not accounting for the location of the called view
5967     * within that window.  (In fact when this method is called you do not yet know
5968     * where the layout will place the view, as it is done before layout happens.)
5969     *
5970     * <p>Note: unlike many View methods, there is no dispatch phase to this
5971     * call.  If you are overriding it in a ViewGroup and want to allow the
5972     * call to continue to your children, you must be sure to call the super
5973     * implementation.
5974     *
5975     * <p>Here is a sample layout that makes use of fitting system windows
5976     * to have controls for a video view placed inside of the window decorations
5977     * that it hides and shows.  This can be used with code like the second
5978     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5979     *
5980     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5981     *
5982     * @param insets Current content insets of the window.  Prior to
5983     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5984     * the insets or else you and Android will be unhappy.
5985     *
5986     * @return {@code true} if this view applied the insets and it should not
5987     * continue propagating further down the hierarchy, {@code false} otherwise.
5988     * @see #getFitsSystemWindows()
5989     * @see #setFitsSystemWindows(boolean)
5990     * @see #setSystemUiVisibility(int)
5991     */
5992    protected boolean fitSystemWindows(Rect insets) {
5993        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5994            mUserPaddingStart = UNDEFINED_PADDING;
5995            mUserPaddingEnd = UNDEFINED_PADDING;
5996            Rect localInsets = sThreadLocal.get();
5997            if (localInsets == null) {
5998                localInsets = new Rect();
5999                sThreadLocal.set(localInsets);
6000            }
6001            boolean res = computeFitSystemWindows(insets, localInsets);
6002            internalSetPadding(localInsets.left, localInsets.top,
6003                    localInsets.right, localInsets.bottom);
6004            return res;
6005        }
6006        return false;
6007    }
6008
6009    /**
6010     * @hide Compute the insets that should be consumed by this view and the ones
6011     * that should propagate to those under it.
6012     */
6013    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6014        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6015                || mAttachInfo == null
6016                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6017                        && !mAttachInfo.mOverscanRequested)) {
6018            outLocalInsets.set(inoutInsets);
6019            inoutInsets.set(0, 0, 0, 0);
6020            return true;
6021        } else {
6022            // The application wants to take care of fitting system window for
6023            // the content...  however we still need to take care of any overscan here.
6024            final Rect overscan = mAttachInfo.mOverscanInsets;
6025            outLocalInsets.set(overscan);
6026            inoutInsets.left -= overscan.left;
6027            inoutInsets.top -= overscan.top;
6028            inoutInsets.right -= overscan.right;
6029            inoutInsets.bottom -= overscan.bottom;
6030            return false;
6031        }
6032    }
6033
6034    /**
6035     * Sets whether or not this view should account for system screen decorations
6036     * such as the status bar and inset its content; that is, controlling whether
6037     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6038     * executed.  See that method for more details.
6039     *
6040     * <p>Note that if you are providing your own implementation of
6041     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6042     * flag to true -- your implementation will be overriding the default
6043     * implementation that checks this flag.
6044     *
6045     * @param fitSystemWindows If true, then the default implementation of
6046     * {@link #fitSystemWindows(Rect)} will be executed.
6047     *
6048     * @attr ref android.R.styleable#View_fitsSystemWindows
6049     * @see #getFitsSystemWindows()
6050     * @see #fitSystemWindows(Rect)
6051     * @see #setSystemUiVisibility(int)
6052     */
6053    public void setFitsSystemWindows(boolean fitSystemWindows) {
6054        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6055    }
6056
6057    /**
6058     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6059     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6060     * will be executed.
6061     *
6062     * @return {@code true} if the default implementation of
6063     * {@link #fitSystemWindows(Rect)} will be executed.
6064     *
6065     * @attr ref android.R.styleable#View_fitsSystemWindows
6066     * @see #setFitsSystemWindows(boolean)
6067     * @see #fitSystemWindows(Rect)
6068     * @see #setSystemUiVisibility(int)
6069     */
6070    public boolean getFitsSystemWindows() {
6071        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6072    }
6073
6074    /** @hide */
6075    public boolean fitsSystemWindows() {
6076        return getFitsSystemWindows();
6077    }
6078
6079    /**
6080     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6081     */
6082    public void requestFitSystemWindows() {
6083        if (mParent != null) {
6084            mParent.requestFitSystemWindows();
6085        }
6086    }
6087
6088    /**
6089     * For use by PhoneWindow to make its own system window fitting optional.
6090     * @hide
6091     */
6092    public void makeOptionalFitsSystemWindows() {
6093        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6094    }
6095
6096    /**
6097     * Returns the visibility status for this view.
6098     *
6099     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6100     * @attr ref android.R.styleable#View_visibility
6101     */
6102    @ViewDebug.ExportedProperty(mapping = {
6103        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6104        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6105        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6106    })
6107    @Visibility
6108    public int getVisibility() {
6109        return mViewFlags & VISIBILITY_MASK;
6110    }
6111
6112    /**
6113     * Set the enabled state of this view.
6114     *
6115     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6116     * @attr ref android.R.styleable#View_visibility
6117     */
6118    @RemotableViewMethod
6119    public void setVisibility(@Visibility int visibility) {
6120        setFlags(visibility, VISIBILITY_MASK);
6121        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6122    }
6123
6124    /**
6125     * Returns the enabled status for this view. The interpretation of the
6126     * enabled state varies by subclass.
6127     *
6128     * @return True if this view is enabled, false otherwise.
6129     */
6130    @ViewDebug.ExportedProperty
6131    public boolean isEnabled() {
6132        return (mViewFlags & ENABLED_MASK) == ENABLED;
6133    }
6134
6135    /**
6136     * Set the enabled state of this view. The interpretation of the enabled
6137     * state varies by subclass.
6138     *
6139     * @param enabled True if this view is enabled, false otherwise.
6140     */
6141    @RemotableViewMethod
6142    public void setEnabled(boolean enabled) {
6143        if (enabled == isEnabled()) return;
6144
6145        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6146
6147        /*
6148         * The View most likely has to change its appearance, so refresh
6149         * the drawable state.
6150         */
6151        refreshDrawableState();
6152
6153        // Invalidate too, since the default behavior for views is to be
6154        // be drawn at 50% alpha rather than to change the drawable.
6155        invalidate(true);
6156
6157        if (!enabled) {
6158            cancelPendingInputEvents();
6159        }
6160    }
6161
6162    /**
6163     * Set whether this view can receive the focus.
6164     *
6165     * Setting this to false will also ensure that this view is not focusable
6166     * in touch mode.
6167     *
6168     * @param focusable If true, this view can receive the focus.
6169     *
6170     * @see #setFocusableInTouchMode(boolean)
6171     * @attr ref android.R.styleable#View_focusable
6172     */
6173    public void setFocusable(boolean focusable) {
6174        if (!focusable) {
6175            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6176        }
6177        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6178    }
6179
6180    /**
6181     * Set whether this view can receive focus while in touch mode.
6182     *
6183     * Setting this to true will also ensure that this view is focusable.
6184     *
6185     * @param focusableInTouchMode If true, this view can receive the focus while
6186     *   in touch mode.
6187     *
6188     * @see #setFocusable(boolean)
6189     * @attr ref android.R.styleable#View_focusableInTouchMode
6190     */
6191    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6192        // Focusable in touch mode should always be set before the focusable flag
6193        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6194        // which, in touch mode, will not successfully request focus on this view
6195        // because the focusable in touch mode flag is not set
6196        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6197        if (focusableInTouchMode) {
6198            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6199        }
6200    }
6201
6202    /**
6203     * Set whether this view should have sound effects enabled for events such as
6204     * clicking and touching.
6205     *
6206     * <p>You may wish to disable sound effects for a view if you already play sounds,
6207     * for instance, a dial key that plays dtmf tones.
6208     *
6209     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6210     * @see #isSoundEffectsEnabled()
6211     * @see #playSoundEffect(int)
6212     * @attr ref android.R.styleable#View_soundEffectsEnabled
6213     */
6214    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6215        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6216    }
6217
6218    /**
6219     * @return whether this view should have sound effects enabled for events such as
6220     *     clicking and touching.
6221     *
6222     * @see #setSoundEffectsEnabled(boolean)
6223     * @see #playSoundEffect(int)
6224     * @attr ref android.R.styleable#View_soundEffectsEnabled
6225     */
6226    @ViewDebug.ExportedProperty
6227    public boolean isSoundEffectsEnabled() {
6228        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6229    }
6230
6231    /**
6232     * Set whether this view should have haptic feedback for events such as
6233     * long presses.
6234     *
6235     * <p>You may wish to disable haptic feedback if your view already controls
6236     * its own haptic feedback.
6237     *
6238     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6239     * @see #isHapticFeedbackEnabled()
6240     * @see #performHapticFeedback(int)
6241     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6242     */
6243    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6244        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6245    }
6246
6247    /**
6248     * @return whether this view should have haptic feedback enabled for events
6249     * long presses.
6250     *
6251     * @see #setHapticFeedbackEnabled(boolean)
6252     * @see #performHapticFeedback(int)
6253     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6254     */
6255    @ViewDebug.ExportedProperty
6256    public boolean isHapticFeedbackEnabled() {
6257        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6258    }
6259
6260    /**
6261     * Returns the layout direction for this view.
6262     *
6263     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6264     *   {@link #LAYOUT_DIRECTION_RTL},
6265     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6266     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6267     *
6268     * @attr ref android.R.styleable#View_layoutDirection
6269     *
6270     * @hide
6271     */
6272    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6273        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6274        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6275        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6276        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6277    })
6278    @LayoutDir
6279    public int getRawLayoutDirection() {
6280        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6281    }
6282
6283    /**
6284     * Set the layout direction for this view. This will propagate a reset of layout direction
6285     * resolution to the view's children and resolve layout direction for this view.
6286     *
6287     * @param layoutDirection the layout direction to set. Should be one of:
6288     *
6289     * {@link #LAYOUT_DIRECTION_LTR},
6290     * {@link #LAYOUT_DIRECTION_RTL},
6291     * {@link #LAYOUT_DIRECTION_INHERIT},
6292     * {@link #LAYOUT_DIRECTION_LOCALE}.
6293     *
6294     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6295     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6296     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6297     *
6298     * @attr ref android.R.styleable#View_layoutDirection
6299     */
6300    @RemotableViewMethod
6301    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6302        if (getRawLayoutDirection() != layoutDirection) {
6303            // Reset the current layout direction and the resolved one
6304            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6305            resetRtlProperties();
6306            // Set the new layout direction (filtered)
6307            mPrivateFlags2 |=
6308                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6309            // We need to resolve all RTL properties as they all depend on layout direction
6310            resolveRtlPropertiesIfNeeded();
6311            requestLayout();
6312            invalidate(true);
6313        }
6314    }
6315
6316    /**
6317     * Returns the resolved layout direction for this view.
6318     *
6319     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6320     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6321     *
6322     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6323     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6324     *
6325     * @attr ref android.R.styleable#View_layoutDirection
6326     */
6327    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6328        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6329        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6330    })
6331    @ResolvedLayoutDir
6332    public int getLayoutDirection() {
6333        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6334        if (targetSdkVersion < JELLY_BEAN_MR1) {
6335            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6336            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6337        }
6338        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6339                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6340    }
6341
6342    /**
6343     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6344     * layout attribute and/or the inherited value from the parent
6345     *
6346     * @return true if the layout is right-to-left.
6347     *
6348     * @hide
6349     */
6350    @ViewDebug.ExportedProperty(category = "layout")
6351    public boolean isLayoutRtl() {
6352        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6353    }
6354
6355    /**
6356     * Indicates whether the view is currently tracking transient state that the
6357     * app should not need to concern itself with saving and restoring, but that
6358     * the framework should take special note to preserve when possible.
6359     *
6360     * <p>A view with transient state cannot be trivially rebound from an external
6361     * data source, such as an adapter binding item views in a list. This may be
6362     * because the view is performing an animation, tracking user selection
6363     * of content, or similar.</p>
6364     *
6365     * @return true if the view has transient state
6366     */
6367    @ViewDebug.ExportedProperty(category = "layout")
6368    public boolean hasTransientState() {
6369        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6370    }
6371
6372    /**
6373     * Set whether this view is currently tracking transient state that the
6374     * framework should attempt to preserve when possible. This flag is reference counted,
6375     * so every call to setHasTransientState(true) should be paired with a later call
6376     * to setHasTransientState(false).
6377     *
6378     * <p>A view with transient state cannot be trivially rebound from an external
6379     * data source, such as an adapter binding item views in a list. This may be
6380     * because the view is performing an animation, tracking user selection
6381     * of content, or similar.</p>
6382     *
6383     * @param hasTransientState true if this view has transient state
6384     */
6385    public void setHasTransientState(boolean hasTransientState) {
6386        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6387                mTransientStateCount - 1;
6388        if (mTransientStateCount < 0) {
6389            mTransientStateCount = 0;
6390            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6391                    "unmatched pair of setHasTransientState calls");
6392        } else if ((hasTransientState && mTransientStateCount == 1) ||
6393                (!hasTransientState && mTransientStateCount == 0)) {
6394            // update flag if we've just incremented up from 0 or decremented down to 0
6395            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6396                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6397            if (mParent != null) {
6398                try {
6399                    mParent.childHasTransientStateChanged(this, hasTransientState);
6400                } catch (AbstractMethodError e) {
6401                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6402                            " does not fully implement ViewParent", e);
6403                }
6404            }
6405        }
6406    }
6407
6408    /**
6409     * Returns true if this view is currently attached to a window.
6410     */
6411    public boolean isAttachedToWindow() {
6412        return mAttachInfo != null;
6413    }
6414
6415    /**
6416     * Returns true if this view has been through at least one layout since it
6417     * was last attached to or detached from a window.
6418     */
6419    public boolean isLaidOut() {
6420        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6421    }
6422
6423    /**
6424     * If this view doesn't do any drawing on its own, set this flag to
6425     * allow further optimizations. By default, this flag is not set on
6426     * View, but could be set on some View subclasses such as ViewGroup.
6427     *
6428     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6429     * you should clear this flag.
6430     *
6431     * @param willNotDraw whether or not this View draw on its own
6432     */
6433    public void setWillNotDraw(boolean willNotDraw) {
6434        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6435    }
6436
6437    /**
6438     * Returns whether or not this View draws on its own.
6439     *
6440     * @return true if this view has nothing to draw, false otherwise
6441     */
6442    @ViewDebug.ExportedProperty(category = "drawing")
6443    public boolean willNotDraw() {
6444        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6445    }
6446
6447    /**
6448     * When a View's drawing cache is enabled, drawing is redirected to an
6449     * offscreen bitmap. Some views, like an ImageView, must be able to
6450     * bypass this mechanism if they already draw a single bitmap, to avoid
6451     * unnecessary usage of the memory.
6452     *
6453     * @param willNotCacheDrawing true if this view does not cache its
6454     *        drawing, false otherwise
6455     */
6456    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6457        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6458    }
6459
6460    /**
6461     * Returns whether or not this View can cache its drawing or not.
6462     *
6463     * @return true if this view does not cache its drawing, false otherwise
6464     */
6465    @ViewDebug.ExportedProperty(category = "drawing")
6466    public boolean willNotCacheDrawing() {
6467        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6468    }
6469
6470    /**
6471     * Indicates whether this view reacts to click events or not.
6472     *
6473     * @return true if the view is clickable, false otherwise
6474     *
6475     * @see #setClickable(boolean)
6476     * @attr ref android.R.styleable#View_clickable
6477     */
6478    @ViewDebug.ExportedProperty
6479    public boolean isClickable() {
6480        return (mViewFlags & CLICKABLE) == CLICKABLE;
6481    }
6482
6483    /**
6484     * Enables or disables click events for this view. When a view
6485     * is clickable it will change its state to "pressed" on every click.
6486     * Subclasses should set the view clickable to visually react to
6487     * user's clicks.
6488     *
6489     * @param clickable true to make the view clickable, false otherwise
6490     *
6491     * @see #isClickable()
6492     * @attr ref android.R.styleable#View_clickable
6493     */
6494    public void setClickable(boolean clickable) {
6495        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6496    }
6497
6498    /**
6499     * Indicates whether this view reacts to long click events or not.
6500     *
6501     * @return true if the view is long clickable, false otherwise
6502     *
6503     * @see #setLongClickable(boolean)
6504     * @attr ref android.R.styleable#View_longClickable
6505     */
6506    public boolean isLongClickable() {
6507        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6508    }
6509
6510    /**
6511     * Enables or disables long click events for this view. When a view is long
6512     * clickable it reacts to the user holding down the button for a longer
6513     * duration than a tap. This event can either launch the listener or a
6514     * context menu.
6515     *
6516     * @param longClickable true to make the view long clickable, false otherwise
6517     * @see #isLongClickable()
6518     * @attr ref android.R.styleable#View_longClickable
6519     */
6520    public void setLongClickable(boolean longClickable) {
6521        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6522    }
6523
6524    /**
6525     * Sets the pressed state for this view.
6526     *
6527     * @see #isClickable()
6528     * @see #setClickable(boolean)
6529     *
6530     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6531     *        the View's internal state from a previously set "pressed" state.
6532     */
6533    public void setPressed(boolean pressed) {
6534        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6535
6536        if (pressed) {
6537            mPrivateFlags |= PFLAG_PRESSED;
6538        } else {
6539            mPrivateFlags &= ~PFLAG_PRESSED;
6540        }
6541
6542        if (needsRefresh) {
6543            refreshDrawableState();
6544        }
6545        dispatchSetPressed(pressed);
6546    }
6547
6548    /**
6549     * Dispatch setPressed to all of this View's children.
6550     *
6551     * @see #setPressed(boolean)
6552     *
6553     * @param pressed The new pressed state
6554     */
6555    protected void dispatchSetPressed(boolean pressed) {
6556    }
6557
6558    /**
6559     * Indicates whether the view is currently in pressed state. Unless
6560     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6561     * the pressed state.
6562     *
6563     * @see #setPressed(boolean)
6564     * @see #isClickable()
6565     * @see #setClickable(boolean)
6566     *
6567     * @return true if the view is currently pressed, false otherwise
6568     */
6569    public boolean isPressed() {
6570        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6571    }
6572
6573    /**
6574     * Indicates whether this view will save its state (that is,
6575     * whether its {@link #onSaveInstanceState} method will be called).
6576     *
6577     * @return Returns true if the view state saving is enabled, else false.
6578     *
6579     * @see #setSaveEnabled(boolean)
6580     * @attr ref android.R.styleable#View_saveEnabled
6581     */
6582    public boolean isSaveEnabled() {
6583        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6584    }
6585
6586    /**
6587     * Controls whether the saving of this view's state is
6588     * enabled (that is, whether its {@link #onSaveInstanceState} method
6589     * will be called).  Note that even if freezing is enabled, the
6590     * view still must have an id assigned to it (via {@link #setId(int)})
6591     * for its state to be saved.  This flag can only disable the
6592     * saving of this view; any child views may still have their state saved.
6593     *
6594     * @param enabled Set to false to <em>disable</em> state saving, or true
6595     * (the default) to allow it.
6596     *
6597     * @see #isSaveEnabled()
6598     * @see #setId(int)
6599     * @see #onSaveInstanceState()
6600     * @attr ref android.R.styleable#View_saveEnabled
6601     */
6602    public void setSaveEnabled(boolean enabled) {
6603        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6604    }
6605
6606    /**
6607     * Gets whether the framework should discard touches when the view's
6608     * window is obscured by another visible window.
6609     * Refer to the {@link View} security documentation for more details.
6610     *
6611     * @return True if touch filtering is enabled.
6612     *
6613     * @see #setFilterTouchesWhenObscured(boolean)
6614     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6615     */
6616    @ViewDebug.ExportedProperty
6617    public boolean getFilterTouchesWhenObscured() {
6618        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6619    }
6620
6621    /**
6622     * Sets whether the framework should discard touches when the view's
6623     * window is obscured by another visible window.
6624     * Refer to the {@link View} security documentation for more details.
6625     *
6626     * @param enabled True if touch filtering should be enabled.
6627     *
6628     * @see #getFilterTouchesWhenObscured
6629     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6630     */
6631    public void setFilterTouchesWhenObscured(boolean enabled) {
6632        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6633                FILTER_TOUCHES_WHEN_OBSCURED);
6634    }
6635
6636    /**
6637     * Indicates whether the entire hierarchy under this view will save its
6638     * state when a state saving traversal occurs from its parent.  The default
6639     * is true; if false, these views will not be saved unless
6640     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6641     *
6642     * @return Returns true if the view state saving from parent is enabled, else false.
6643     *
6644     * @see #setSaveFromParentEnabled(boolean)
6645     */
6646    public boolean isSaveFromParentEnabled() {
6647        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6648    }
6649
6650    /**
6651     * Controls whether the entire hierarchy under this view will save its
6652     * state when a state saving traversal occurs from its parent.  The default
6653     * is true; if false, these views will not be saved unless
6654     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6655     *
6656     * @param enabled Set to false to <em>disable</em> state saving, or true
6657     * (the default) to allow it.
6658     *
6659     * @see #isSaveFromParentEnabled()
6660     * @see #setId(int)
6661     * @see #onSaveInstanceState()
6662     */
6663    public void setSaveFromParentEnabled(boolean enabled) {
6664        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6665    }
6666
6667
6668    /**
6669     * Returns whether this View is able to take focus.
6670     *
6671     * @return True if this view can take focus, or false otherwise.
6672     * @attr ref android.R.styleable#View_focusable
6673     */
6674    @ViewDebug.ExportedProperty(category = "focus")
6675    public final boolean isFocusable() {
6676        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6677    }
6678
6679    /**
6680     * When a view is focusable, it may not want to take focus when in touch mode.
6681     * For example, a button would like focus when the user is navigating via a D-pad
6682     * so that the user can click on it, but once the user starts touching the screen,
6683     * the button shouldn't take focus
6684     * @return Whether the view is focusable in touch mode.
6685     * @attr ref android.R.styleable#View_focusableInTouchMode
6686     */
6687    @ViewDebug.ExportedProperty
6688    public final boolean isFocusableInTouchMode() {
6689        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6690    }
6691
6692    /**
6693     * Find the nearest view in the specified direction that can take focus.
6694     * This does not actually give focus to that view.
6695     *
6696     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6697     *
6698     * @return The nearest focusable in the specified direction, or null if none
6699     *         can be found.
6700     */
6701    public View focusSearch(@FocusRealDirection int direction) {
6702        if (mParent != null) {
6703            return mParent.focusSearch(this, direction);
6704        } else {
6705            return null;
6706        }
6707    }
6708
6709    /**
6710     * This method is the last chance for the focused view and its ancestors to
6711     * respond to an arrow key. This is called when the focused view did not
6712     * consume the key internally, nor could the view system find a new view in
6713     * the requested direction to give focus to.
6714     *
6715     * @param focused The currently focused view.
6716     * @param direction The direction focus wants to move. One of FOCUS_UP,
6717     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6718     * @return True if the this view consumed this unhandled move.
6719     */
6720    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6721        return false;
6722    }
6723
6724    /**
6725     * If a user manually specified the next view id for a particular direction,
6726     * use the root to look up the view.
6727     * @param root The root view of the hierarchy containing this view.
6728     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6729     * or FOCUS_BACKWARD.
6730     * @return The user specified next view, or null if there is none.
6731     */
6732    View findUserSetNextFocus(View root, @FocusDirection int direction) {
6733        switch (direction) {
6734            case FOCUS_LEFT:
6735                if (mNextFocusLeftId == View.NO_ID) return null;
6736                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6737            case FOCUS_RIGHT:
6738                if (mNextFocusRightId == View.NO_ID) return null;
6739                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6740            case FOCUS_UP:
6741                if (mNextFocusUpId == View.NO_ID) return null;
6742                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6743            case FOCUS_DOWN:
6744                if (mNextFocusDownId == View.NO_ID) return null;
6745                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6746            case FOCUS_FORWARD:
6747                if (mNextFocusForwardId == View.NO_ID) return null;
6748                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6749            case FOCUS_BACKWARD: {
6750                if (mID == View.NO_ID) return null;
6751                final int id = mID;
6752                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6753                    @Override
6754                    public boolean apply(View t) {
6755                        return t.mNextFocusForwardId == id;
6756                    }
6757                });
6758            }
6759        }
6760        return null;
6761    }
6762
6763    private View findViewInsideOutShouldExist(View root, int id) {
6764        if (mMatchIdPredicate == null) {
6765            mMatchIdPredicate = new MatchIdPredicate();
6766        }
6767        mMatchIdPredicate.mId = id;
6768        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6769        if (result == null) {
6770            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6771        }
6772        return result;
6773    }
6774
6775    /**
6776     * Find and return all focusable views that are descendants of this view,
6777     * possibly including this view if it is focusable itself.
6778     *
6779     * @param direction The direction of the focus
6780     * @return A list of focusable views
6781     */
6782    public ArrayList<View> getFocusables(@FocusDirection int direction) {
6783        ArrayList<View> result = new ArrayList<View>(24);
6784        addFocusables(result, direction);
6785        return result;
6786    }
6787
6788    /**
6789     * Add any focusable views that are descendants of this view (possibly
6790     * including this view if it is focusable itself) to views.  If we are in touch mode,
6791     * only add views that are also focusable in touch mode.
6792     *
6793     * @param views Focusable views found so far
6794     * @param direction The direction of the focus
6795     */
6796    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
6797        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6798    }
6799
6800    /**
6801     * Adds any focusable views that are descendants of this view (possibly
6802     * including this view if it is focusable itself) to views. This method
6803     * adds all focusable views regardless if we are in touch mode or
6804     * only views focusable in touch mode if we are in touch mode or
6805     * only views that can take accessibility focus if accessibility is enabeld
6806     * depending on the focusable mode paramater.
6807     *
6808     * @param views Focusable views found so far or null if all we are interested is
6809     *        the number of focusables.
6810     * @param direction The direction of the focus.
6811     * @param focusableMode The type of focusables to be added.
6812     *
6813     * @see #FOCUSABLES_ALL
6814     * @see #FOCUSABLES_TOUCH_MODE
6815     */
6816    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
6817            @FocusableMode int focusableMode) {
6818        if (views == null) {
6819            return;
6820        }
6821        if (!isFocusable()) {
6822            return;
6823        }
6824        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6825                && isInTouchMode() && !isFocusableInTouchMode()) {
6826            return;
6827        }
6828        views.add(this);
6829    }
6830
6831    /**
6832     * Finds the Views that contain given text. The containment is case insensitive.
6833     * The search is performed by either the text that the View renders or the content
6834     * description that describes the view for accessibility purposes and the view does
6835     * not render or both. Clients can specify how the search is to be performed via
6836     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6837     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6838     *
6839     * @param outViews The output list of matching Views.
6840     * @param searched The text to match against.
6841     *
6842     * @see #FIND_VIEWS_WITH_TEXT
6843     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6844     * @see #setContentDescription(CharSequence)
6845     */
6846    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
6847            @FindViewFlags int flags) {
6848        if (getAccessibilityNodeProvider() != null) {
6849            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6850                outViews.add(this);
6851            }
6852        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6853                && (searched != null && searched.length() > 0)
6854                && (mContentDescription != null && mContentDescription.length() > 0)) {
6855            String searchedLowerCase = searched.toString().toLowerCase();
6856            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6857            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6858                outViews.add(this);
6859            }
6860        }
6861    }
6862
6863    /**
6864     * Find and return all touchable views that are descendants of this view,
6865     * possibly including this view if it is touchable itself.
6866     *
6867     * @return A list of touchable views
6868     */
6869    public ArrayList<View> getTouchables() {
6870        ArrayList<View> result = new ArrayList<View>();
6871        addTouchables(result);
6872        return result;
6873    }
6874
6875    /**
6876     * Add any touchable views that are descendants of this view (possibly
6877     * including this view if it is touchable itself) to views.
6878     *
6879     * @param views Touchable views found so far
6880     */
6881    public void addTouchables(ArrayList<View> views) {
6882        final int viewFlags = mViewFlags;
6883
6884        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6885                && (viewFlags & ENABLED_MASK) == ENABLED) {
6886            views.add(this);
6887        }
6888    }
6889
6890    /**
6891     * Returns whether this View is accessibility focused.
6892     *
6893     * @return True if this View is accessibility focused.
6894     * @hide
6895     */
6896    public boolean isAccessibilityFocused() {
6897        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6898    }
6899
6900    /**
6901     * Call this to try to give accessibility focus to this view.
6902     *
6903     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6904     * returns false or the view is no visible or the view already has accessibility
6905     * focus.
6906     *
6907     * See also {@link #focusSearch(int)}, which is what you call to say that you
6908     * have focus, and you want your parent to look for the next one.
6909     *
6910     * @return Whether this view actually took accessibility focus.
6911     *
6912     * @hide
6913     */
6914    public boolean requestAccessibilityFocus() {
6915        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6916        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6917            return false;
6918        }
6919        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6920            return false;
6921        }
6922        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6923            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6924            ViewRootImpl viewRootImpl = getViewRootImpl();
6925            if (viewRootImpl != null) {
6926                viewRootImpl.setAccessibilityFocus(this, null);
6927            }
6928            invalidate();
6929            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6930            return true;
6931        }
6932        return false;
6933    }
6934
6935    /**
6936     * Call this to try to clear accessibility focus of this view.
6937     *
6938     * See also {@link #focusSearch(int)}, which is what you call to say that you
6939     * have focus, and you want your parent to look for the next one.
6940     *
6941     * @hide
6942     */
6943    public void clearAccessibilityFocus() {
6944        clearAccessibilityFocusNoCallbacks();
6945        // Clear the global reference of accessibility focus if this
6946        // view or any of its descendants had accessibility focus.
6947        ViewRootImpl viewRootImpl = getViewRootImpl();
6948        if (viewRootImpl != null) {
6949            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6950            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6951                viewRootImpl.setAccessibilityFocus(null, null);
6952            }
6953        }
6954    }
6955
6956    private void sendAccessibilityHoverEvent(int eventType) {
6957        // Since we are not delivering to a client accessibility events from not
6958        // important views (unless the clinet request that) we need to fire the
6959        // event from the deepest view exposed to the client. As a consequence if
6960        // the user crosses a not exposed view the client will see enter and exit
6961        // of the exposed predecessor followed by and enter and exit of that same
6962        // predecessor when entering and exiting the not exposed descendant. This
6963        // is fine since the client has a clear idea which view is hovered at the
6964        // price of a couple more events being sent. This is a simple and
6965        // working solution.
6966        View source = this;
6967        while (true) {
6968            if (source.includeForAccessibility()) {
6969                source.sendAccessibilityEvent(eventType);
6970                return;
6971            }
6972            ViewParent parent = source.getParent();
6973            if (parent instanceof View) {
6974                source = (View) parent;
6975            } else {
6976                return;
6977            }
6978        }
6979    }
6980
6981    /**
6982     * Clears accessibility focus without calling any callback methods
6983     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6984     * is used for clearing accessibility focus when giving this focus to
6985     * another view.
6986     */
6987    void clearAccessibilityFocusNoCallbacks() {
6988        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6989            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6990            invalidate();
6991            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6992        }
6993    }
6994
6995    /**
6996     * Call this to try to give focus to a specific view or to one of its
6997     * descendants.
6998     *
6999     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7000     * false), or if it is focusable and it is not focusable in touch mode
7001     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7002     *
7003     * See also {@link #focusSearch(int)}, which is what you call to say that you
7004     * have focus, and you want your parent to look for the next one.
7005     *
7006     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7007     * {@link #FOCUS_DOWN} and <code>null</code>.
7008     *
7009     * @return Whether this view or one of its descendants actually took focus.
7010     */
7011    public final boolean requestFocus() {
7012        return requestFocus(View.FOCUS_DOWN);
7013    }
7014
7015    /**
7016     * Call this to try to give focus to a specific view or to one of its
7017     * descendants and give it a hint about what direction focus is heading.
7018     *
7019     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7020     * false), or if it is focusable and it is not focusable in touch mode
7021     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7022     *
7023     * See also {@link #focusSearch(int)}, which is what you call to say that you
7024     * have focus, and you want your parent to look for the next one.
7025     *
7026     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7027     * <code>null</code> set for the previously focused rectangle.
7028     *
7029     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7030     * @return Whether this view or one of its descendants actually took focus.
7031     */
7032    public final boolean requestFocus(int direction) {
7033        return requestFocus(direction, null);
7034    }
7035
7036    /**
7037     * Call this to try to give focus to a specific view or to one of its descendants
7038     * and give it hints about the direction and a specific rectangle that the focus
7039     * is coming from.  The rectangle can help give larger views a finer grained hint
7040     * about where focus is coming from, and therefore, where to show selection, or
7041     * forward focus change internally.
7042     *
7043     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7044     * false), or if it is focusable and it is not focusable in touch mode
7045     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7046     *
7047     * A View will not take focus if it is not visible.
7048     *
7049     * A View will not take focus if one of its parents has
7050     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7051     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
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     * You may wish to override this method if your custom {@link View} has an internal
7057     * {@link View} that it wishes to forward the request to.
7058     *
7059     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7060     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7061     *        to give a finer grained hint about where focus is coming from.  May be null
7062     *        if there is no hint.
7063     * @return Whether this view or one of its descendants actually took focus.
7064     */
7065    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7066        return requestFocusNoSearch(direction, previouslyFocusedRect);
7067    }
7068
7069    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7070        // need to be focusable
7071        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7072                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7073            return false;
7074        }
7075
7076        // need to be focusable in touch mode if in touch mode
7077        if (isInTouchMode() &&
7078            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7079               return false;
7080        }
7081
7082        // need to not have any parents blocking us
7083        if (hasAncestorThatBlocksDescendantFocus()) {
7084            return false;
7085        }
7086
7087        handleFocusGainInternal(direction, previouslyFocusedRect);
7088        return true;
7089    }
7090
7091    /**
7092     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7093     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7094     * touch mode to request focus when they are touched.
7095     *
7096     * @return Whether this view or one of its descendants actually took focus.
7097     *
7098     * @see #isInTouchMode()
7099     *
7100     */
7101    public final boolean requestFocusFromTouch() {
7102        // Leave touch mode if we need to
7103        if (isInTouchMode()) {
7104            ViewRootImpl viewRoot = getViewRootImpl();
7105            if (viewRoot != null) {
7106                viewRoot.ensureTouchMode(false);
7107            }
7108        }
7109        return requestFocus(View.FOCUS_DOWN);
7110    }
7111
7112    /**
7113     * @return Whether any ancestor of this view blocks descendant focus.
7114     */
7115    private boolean hasAncestorThatBlocksDescendantFocus() {
7116        ViewParent ancestor = mParent;
7117        while (ancestor instanceof ViewGroup) {
7118            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7119            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7120                return true;
7121            } else {
7122                ancestor = vgAncestor.getParent();
7123            }
7124        }
7125        return false;
7126    }
7127
7128    /**
7129     * Gets the mode for determining whether this View is important for accessibility
7130     * which is if it fires accessibility events and if it is reported to
7131     * accessibility services that query the screen.
7132     *
7133     * @return The mode for determining whether a View is important for accessibility.
7134     *
7135     * @attr ref android.R.styleable#View_importantForAccessibility
7136     *
7137     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7138     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7139     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7140     */
7141    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7142            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7143            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7144            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
7145        })
7146    public int getImportantForAccessibility() {
7147        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7148                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7149    }
7150
7151    /**
7152     * Sets the live region mode for this view. This indicates to accessibility
7153     * services whether they should automatically notify the user about changes
7154     * to the view's content description or text, or to the content descriptions
7155     * or text of the view's children (where applicable).
7156     * <p>
7157     * For example, in a login screen with a TextView that displays an "incorrect
7158     * password" notification, that view should be marked as a live region with
7159     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7160     * <p>
7161     * To disable change notifications for this view, use
7162     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7163     * mode for most views.
7164     * <p>
7165     * To indicate that the user should be notified of changes, use
7166     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7167     * <p>
7168     * If the view's changes should interrupt ongoing speech and notify the user
7169     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7170     *
7171     * @param mode The live region mode for this view, one of:
7172     *        <ul>
7173     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7174     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7175     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7176     *        </ul>
7177     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7178     */
7179    public void setAccessibilityLiveRegion(int mode) {
7180        if (mode != getAccessibilityLiveRegion()) {
7181            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7182            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7183                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7184            notifyViewAccessibilityStateChangedIfNeeded(
7185                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7186        }
7187    }
7188
7189    /**
7190     * Gets the live region mode for this View.
7191     *
7192     * @return The live region mode for the view.
7193     *
7194     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7195     *
7196     * @see #setAccessibilityLiveRegion(int)
7197     */
7198    public int getAccessibilityLiveRegion() {
7199        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7200                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7201    }
7202
7203    /**
7204     * Sets how to determine whether this view is important for accessibility
7205     * which is if it fires accessibility events and if it is reported to
7206     * accessibility services that query the screen.
7207     *
7208     * @param mode How to determine whether this view is important for accessibility.
7209     *
7210     * @attr ref android.R.styleable#View_importantForAccessibility
7211     *
7212     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7213     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7214     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7215     */
7216    public void setImportantForAccessibility(int mode) {
7217        final boolean oldIncludeForAccessibility = includeForAccessibility();
7218        if (mode != getImportantForAccessibility()) {
7219            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7220            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7221                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7222            if (oldIncludeForAccessibility != includeForAccessibility()) {
7223                notifySubtreeAccessibilityStateChangedIfNeeded();
7224            } else {
7225                notifyViewAccessibilityStateChangedIfNeeded(
7226                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7227            }
7228        }
7229    }
7230
7231    /**
7232     * Gets whether this view should be exposed for accessibility.
7233     *
7234     * @return Whether the view is exposed for accessibility.
7235     *
7236     * @hide
7237     */
7238    public boolean isImportantForAccessibility() {
7239        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7240                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7241        switch (mode) {
7242            case IMPORTANT_FOR_ACCESSIBILITY_YES:
7243                return true;
7244            case IMPORTANT_FOR_ACCESSIBILITY_NO:
7245                return false;
7246            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
7247                return isActionableForAccessibility() || hasListenersForAccessibility()
7248                        || getAccessibilityNodeProvider() != null
7249                        || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7250            default:
7251                throw new IllegalArgumentException("Unknown important for accessibility mode: "
7252                        + mode);
7253        }
7254    }
7255
7256    /**
7257     * Gets the parent for accessibility purposes. Note that the parent for
7258     * accessibility is not necessary the immediate parent. It is the first
7259     * predecessor that is important for accessibility.
7260     *
7261     * @return The parent for accessibility purposes.
7262     */
7263    public ViewParent getParentForAccessibility() {
7264        if (mParent instanceof View) {
7265            View parentView = (View) mParent;
7266            if (parentView.includeForAccessibility()) {
7267                return mParent;
7268            } else {
7269                return mParent.getParentForAccessibility();
7270            }
7271        }
7272        return null;
7273    }
7274
7275    /**
7276     * Adds the children of a given View for accessibility. Since some Views are
7277     * not important for accessibility the children for accessibility are not
7278     * necessarily direct children of the view, rather they are the first level of
7279     * descendants important for accessibility.
7280     *
7281     * @param children The list of children for accessibility.
7282     */
7283    public void addChildrenForAccessibility(ArrayList<View> children) {
7284        if (includeForAccessibility()) {
7285            children.add(this);
7286        }
7287    }
7288
7289    /**
7290     * Whether to regard this view for accessibility. A view is regarded for
7291     * accessibility if it is important for accessibility or the querying
7292     * accessibility service has explicitly requested that view not
7293     * important for accessibility are regarded.
7294     *
7295     * @return Whether to regard the view for accessibility.
7296     *
7297     * @hide
7298     */
7299    public boolean includeForAccessibility() {
7300        //noinspection SimplifiableIfStatement
7301        if (mAttachInfo != null) {
7302            return (mAttachInfo.mAccessibilityFetchFlags
7303                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7304                    || isImportantForAccessibility();
7305        }
7306        return false;
7307    }
7308
7309    /**
7310     * Returns whether the View is considered actionable from
7311     * accessibility perspective. Such view are important for
7312     * accessibility.
7313     *
7314     * @return True if the view is actionable for accessibility.
7315     *
7316     * @hide
7317     */
7318    public boolean isActionableForAccessibility() {
7319        return (isClickable() || isLongClickable() || isFocusable());
7320    }
7321
7322    /**
7323     * Returns whether the View has registered callbacks which makes it
7324     * important for accessibility.
7325     *
7326     * @return True if the view is actionable for accessibility.
7327     */
7328    private boolean hasListenersForAccessibility() {
7329        ListenerInfo info = getListenerInfo();
7330        return mTouchDelegate != null || info.mOnKeyListener != null
7331                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7332                || info.mOnHoverListener != null || info.mOnDragListener != null;
7333    }
7334
7335    /**
7336     * Notifies that the accessibility state of this view changed. The change
7337     * is local to this view and does not represent structural changes such
7338     * as children and parent. For example, the view became focusable. The
7339     * notification is at at most once every
7340     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7341     * to avoid unnecessary load to the system. Also once a view has a pending
7342     * notification this method is a NOP until the notification has been sent.
7343     *
7344     * @hide
7345     */
7346    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7347        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7348            return;
7349        }
7350        if (mSendViewStateChangedAccessibilityEvent == null) {
7351            mSendViewStateChangedAccessibilityEvent =
7352                    new SendViewStateChangedAccessibilityEvent();
7353        }
7354        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7355    }
7356
7357    /**
7358     * Notifies that the accessibility state of this view changed. The change
7359     * is *not* local to this view and does represent structural changes such
7360     * as children and parent. For example, the view size changed. The
7361     * notification is at at most once every
7362     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7363     * to avoid unnecessary load to the system. Also once a view has a pending
7364     * notifucation this method is a NOP until the notification has been sent.
7365     *
7366     * @hide
7367     */
7368    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7369        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7370            return;
7371        }
7372        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7373            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7374            if (mParent != null) {
7375                try {
7376                    mParent.notifySubtreeAccessibilityStateChanged(
7377                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7378                } catch (AbstractMethodError e) {
7379                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7380                            " does not fully implement ViewParent", e);
7381                }
7382            }
7383        }
7384    }
7385
7386    /**
7387     * Reset the flag indicating the accessibility state of the subtree rooted
7388     * at this view changed.
7389     */
7390    void resetSubtreeAccessibilityStateChanged() {
7391        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7392    }
7393
7394    /**
7395     * Performs the specified accessibility action on the view. For
7396     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7397     * <p>
7398     * If an {@link AccessibilityDelegate} has been specified via calling
7399     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7400     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7401     * is responsible for handling this call.
7402     * </p>
7403     *
7404     * @param action The action to perform.
7405     * @param arguments Optional action arguments.
7406     * @return Whether the action was performed.
7407     */
7408    public boolean performAccessibilityAction(int action, Bundle arguments) {
7409      if (mAccessibilityDelegate != null) {
7410          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7411      } else {
7412          return performAccessibilityActionInternal(action, arguments);
7413      }
7414    }
7415
7416   /**
7417    * @see #performAccessibilityAction(int, Bundle)
7418    *
7419    * Note: Called from the default {@link AccessibilityDelegate}.
7420    */
7421    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7422        switch (action) {
7423            case AccessibilityNodeInfo.ACTION_CLICK: {
7424                if (isClickable()) {
7425                    performClick();
7426                    return true;
7427                }
7428            } break;
7429            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7430                if (isLongClickable()) {
7431                    performLongClick();
7432                    return true;
7433                }
7434            } break;
7435            case AccessibilityNodeInfo.ACTION_FOCUS: {
7436                if (!hasFocus()) {
7437                    // Get out of touch mode since accessibility
7438                    // wants to move focus around.
7439                    getViewRootImpl().ensureTouchMode(false);
7440                    return requestFocus();
7441                }
7442            } break;
7443            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7444                if (hasFocus()) {
7445                    clearFocus();
7446                    return !isFocused();
7447                }
7448            } break;
7449            case AccessibilityNodeInfo.ACTION_SELECT: {
7450                if (!isSelected()) {
7451                    setSelected(true);
7452                    return isSelected();
7453                }
7454            } break;
7455            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7456                if (isSelected()) {
7457                    setSelected(false);
7458                    return !isSelected();
7459                }
7460            } break;
7461            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7462                if (!isAccessibilityFocused()) {
7463                    return requestAccessibilityFocus();
7464                }
7465            } break;
7466            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7467                if (isAccessibilityFocused()) {
7468                    clearAccessibilityFocus();
7469                    return true;
7470                }
7471            } break;
7472            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7473                if (arguments != null) {
7474                    final int granularity = arguments.getInt(
7475                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7476                    final boolean extendSelection = arguments.getBoolean(
7477                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7478                    return traverseAtGranularity(granularity, true, extendSelection);
7479                }
7480            } break;
7481            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7482                if (arguments != null) {
7483                    final int granularity = arguments.getInt(
7484                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7485                    final boolean extendSelection = arguments.getBoolean(
7486                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7487                    return traverseAtGranularity(granularity, false, extendSelection);
7488                }
7489            } break;
7490            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7491                CharSequence text = getIterableTextForAccessibility();
7492                if (text == null) {
7493                    return false;
7494                }
7495                final int start = (arguments != null) ? arguments.getInt(
7496                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7497                final int end = (arguments != null) ? arguments.getInt(
7498                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7499                // Only cursor position can be specified (selection length == 0)
7500                if ((getAccessibilitySelectionStart() != start
7501                        || getAccessibilitySelectionEnd() != end)
7502                        && (start == end)) {
7503                    setAccessibilitySelection(start, end);
7504                    notifyViewAccessibilityStateChangedIfNeeded(
7505                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7506                    return true;
7507                }
7508            } break;
7509        }
7510        return false;
7511    }
7512
7513    private boolean traverseAtGranularity(int granularity, boolean forward,
7514            boolean extendSelection) {
7515        CharSequence text = getIterableTextForAccessibility();
7516        if (text == null || text.length() == 0) {
7517            return false;
7518        }
7519        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7520        if (iterator == null) {
7521            return false;
7522        }
7523        int current = getAccessibilitySelectionEnd();
7524        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7525            current = forward ? 0 : text.length();
7526        }
7527        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7528        if (range == null) {
7529            return false;
7530        }
7531        final int segmentStart = range[0];
7532        final int segmentEnd = range[1];
7533        int selectionStart;
7534        int selectionEnd;
7535        if (extendSelection && isAccessibilitySelectionExtendable()) {
7536            selectionStart = getAccessibilitySelectionStart();
7537            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7538                selectionStart = forward ? segmentStart : segmentEnd;
7539            }
7540            selectionEnd = forward ? segmentEnd : segmentStart;
7541        } else {
7542            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7543        }
7544        setAccessibilitySelection(selectionStart, selectionEnd);
7545        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7546                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7547        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7548        return true;
7549    }
7550
7551    /**
7552     * Gets the text reported for accessibility purposes.
7553     *
7554     * @return The accessibility text.
7555     *
7556     * @hide
7557     */
7558    public CharSequence getIterableTextForAccessibility() {
7559        return getContentDescription();
7560    }
7561
7562    /**
7563     * Gets whether accessibility selection can be extended.
7564     *
7565     * @return If selection is extensible.
7566     *
7567     * @hide
7568     */
7569    public boolean isAccessibilitySelectionExtendable() {
7570        return false;
7571    }
7572
7573    /**
7574     * @hide
7575     */
7576    public int getAccessibilitySelectionStart() {
7577        return mAccessibilityCursorPosition;
7578    }
7579
7580    /**
7581     * @hide
7582     */
7583    public int getAccessibilitySelectionEnd() {
7584        return getAccessibilitySelectionStart();
7585    }
7586
7587    /**
7588     * @hide
7589     */
7590    public void setAccessibilitySelection(int start, int end) {
7591        if (start ==  end && end == mAccessibilityCursorPosition) {
7592            return;
7593        }
7594        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7595            mAccessibilityCursorPosition = start;
7596        } else {
7597            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7598        }
7599        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7600    }
7601
7602    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7603            int fromIndex, int toIndex) {
7604        if (mParent == null) {
7605            return;
7606        }
7607        AccessibilityEvent event = AccessibilityEvent.obtain(
7608                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7609        onInitializeAccessibilityEvent(event);
7610        onPopulateAccessibilityEvent(event);
7611        event.setFromIndex(fromIndex);
7612        event.setToIndex(toIndex);
7613        event.setAction(action);
7614        event.setMovementGranularity(granularity);
7615        mParent.requestSendAccessibilityEvent(this, event);
7616    }
7617
7618    /**
7619     * @hide
7620     */
7621    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7622        switch (granularity) {
7623            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7624                CharSequence text = getIterableTextForAccessibility();
7625                if (text != null && text.length() > 0) {
7626                    CharacterTextSegmentIterator iterator =
7627                        CharacterTextSegmentIterator.getInstance(
7628                                mContext.getResources().getConfiguration().locale);
7629                    iterator.initialize(text.toString());
7630                    return iterator;
7631                }
7632            } break;
7633            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7634                CharSequence text = getIterableTextForAccessibility();
7635                if (text != null && text.length() > 0) {
7636                    WordTextSegmentIterator iterator =
7637                        WordTextSegmentIterator.getInstance(
7638                                mContext.getResources().getConfiguration().locale);
7639                    iterator.initialize(text.toString());
7640                    return iterator;
7641                }
7642            } break;
7643            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7644                CharSequence text = getIterableTextForAccessibility();
7645                if (text != null && text.length() > 0) {
7646                    ParagraphTextSegmentIterator iterator =
7647                        ParagraphTextSegmentIterator.getInstance();
7648                    iterator.initialize(text.toString());
7649                    return iterator;
7650                }
7651            } break;
7652        }
7653        return null;
7654    }
7655
7656    /**
7657     * @hide
7658     */
7659    public void dispatchStartTemporaryDetach() {
7660        clearDisplayList();
7661
7662        onStartTemporaryDetach();
7663    }
7664
7665    /**
7666     * This is called when a container is going to temporarily detach a child, with
7667     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7668     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7669     * {@link #onDetachedFromWindow()} when the container is done.
7670     */
7671    public void onStartTemporaryDetach() {
7672        removeUnsetPressCallback();
7673        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7674    }
7675
7676    /**
7677     * @hide
7678     */
7679    public void dispatchFinishTemporaryDetach() {
7680        onFinishTemporaryDetach();
7681    }
7682
7683    /**
7684     * Called after {@link #onStartTemporaryDetach} when the container is done
7685     * changing the view.
7686     */
7687    public void onFinishTemporaryDetach() {
7688    }
7689
7690    /**
7691     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7692     * for this view's window.  Returns null if the view is not currently attached
7693     * to the window.  Normally you will not need to use this directly, but
7694     * just use the standard high-level event callbacks like
7695     * {@link #onKeyDown(int, KeyEvent)}.
7696     */
7697    public KeyEvent.DispatcherState getKeyDispatcherState() {
7698        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7699    }
7700
7701    /**
7702     * Dispatch a key event before it is processed by any input method
7703     * associated with the view hierarchy.  This can be used to intercept
7704     * key events in special situations before the IME consumes them; a
7705     * typical example would be handling the BACK key to update the application's
7706     * UI instead of allowing the IME to see it and close itself.
7707     *
7708     * @param event The key event to be dispatched.
7709     * @return True if the event was handled, false otherwise.
7710     */
7711    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7712        return onKeyPreIme(event.getKeyCode(), event);
7713    }
7714
7715    /**
7716     * Dispatch a key event to the next view on the focus path. This path runs
7717     * from the top of the view tree down to the currently focused view. If this
7718     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7719     * the next node down the focus path. This method also fires any key
7720     * listeners.
7721     *
7722     * @param event The key event to be dispatched.
7723     * @return True if the event was handled, false otherwise.
7724     */
7725    public boolean dispatchKeyEvent(KeyEvent event) {
7726        if (mInputEventConsistencyVerifier != null) {
7727            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7728        }
7729
7730        // Give any attached key listener a first crack at the event.
7731        //noinspection SimplifiableIfStatement
7732        ListenerInfo li = mListenerInfo;
7733        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7734                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7735            return true;
7736        }
7737
7738        if (event.dispatch(this, mAttachInfo != null
7739                ? mAttachInfo.mKeyDispatchState : null, this)) {
7740            return true;
7741        }
7742
7743        if (mInputEventConsistencyVerifier != null) {
7744            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7745        }
7746        return false;
7747    }
7748
7749    /**
7750     * Dispatches a key shortcut event.
7751     *
7752     * @param event The key event to be dispatched.
7753     * @return True if the event was handled by the view, false otherwise.
7754     */
7755    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7756        return onKeyShortcut(event.getKeyCode(), event);
7757    }
7758
7759    /**
7760     * Pass the touch screen motion event down to the target view, or this
7761     * view if it is the target.
7762     *
7763     * @param event The motion event to be dispatched.
7764     * @return True if the event was handled by the view, false otherwise.
7765     */
7766    public boolean dispatchTouchEvent(MotionEvent event) {
7767        if (mInputEventConsistencyVerifier != null) {
7768            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7769        }
7770
7771        if (onFilterTouchEventForSecurity(event)) {
7772            //noinspection SimplifiableIfStatement
7773            ListenerInfo li = mListenerInfo;
7774            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7775                    && li.mOnTouchListener.onTouch(this, event)) {
7776                return true;
7777            }
7778
7779            if (onTouchEvent(event)) {
7780                return true;
7781            }
7782        }
7783
7784        if (mInputEventConsistencyVerifier != null) {
7785            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7786        }
7787        return false;
7788    }
7789
7790    /**
7791     * Filter the touch event to apply security policies.
7792     *
7793     * @param event The motion event to be filtered.
7794     * @return True if the event should be dispatched, false if the event should be dropped.
7795     *
7796     * @see #getFilterTouchesWhenObscured
7797     */
7798    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7799        //noinspection RedundantIfStatement
7800        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7801                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7802            // Window is obscured, drop this touch.
7803            return false;
7804        }
7805        return true;
7806    }
7807
7808    /**
7809     * Pass a trackball motion event down to the focused view.
7810     *
7811     * @param event The motion event to be dispatched.
7812     * @return True if the event was handled by the view, false otherwise.
7813     */
7814    public boolean dispatchTrackballEvent(MotionEvent event) {
7815        if (mInputEventConsistencyVerifier != null) {
7816            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7817        }
7818
7819        return onTrackballEvent(event);
7820    }
7821
7822    /**
7823     * Dispatch a generic motion event.
7824     * <p>
7825     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7826     * are delivered to the view under the pointer.  All other generic motion events are
7827     * delivered to the focused view.  Hover events are handled specially and are delivered
7828     * to {@link #onHoverEvent(MotionEvent)}.
7829     * </p>
7830     *
7831     * @param event The motion event to be dispatched.
7832     * @return True if the event was handled by the view, false otherwise.
7833     */
7834    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7835        if (mInputEventConsistencyVerifier != null) {
7836            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7837        }
7838
7839        final int source = event.getSource();
7840        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7841            final int action = event.getAction();
7842            if (action == MotionEvent.ACTION_HOVER_ENTER
7843                    || action == MotionEvent.ACTION_HOVER_MOVE
7844                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7845                if (dispatchHoverEvent(event)) {
7846                    return true;
7847                }
7848            } else if (dispatchGenericPointerEvent(event)) {
7849                return true;
7850            }
7851        } else if (dispatchGenericFocusedEvent(event)) {
7852            return true;
7853        }
7854
7855        if (dispatchGenericMotionEventInternal(event)) {
7856            return true;
7857        }
7858
7859        if (mInputEventConsistencyVerifier != null) {
7860            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7861        }
7862        return false;
7863    }
7864
7865    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7866        //noinspection SimplifiableIfStatement
7867        ListenerInfo li = mListenerInfo;
7868        if (li != null && li.mOnGenericMotionListener != null
7869                && (mViewFlags & ENABLED_MASK) == ENABLED
7870                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7871            return true;
7872        }
7873
7874        if (onGenericMotionEvent(event)) {
7875            return true;
7876        }
7877
7878        if (mInputEventConsistencyVerifier != null) {
7879            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7880        }
7881        return false;
7882    }
7883
7884    /**
7885     * Dispatch a hover event.
7886     * <p>
7887     * Do not call this method directly.
7888     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7889     * </p>
7890     *
7891     * @param event The motion event to be dispatched.
7892     * @return True if the event was handled by the view, false otherwise.
7893     */
7894    protected boolean dispatchHoverEvent(MotionEvent event) {
7895        ListenerInfo li = mListenerInfo;
7896        //noinspection SimplifiableIfStatement
7897        if (li != null && li.mOnHoverListener != null
7898                && (mViewFlags & ENABLED_MASK) == ENABLED
7899                && li.mOnHoverListener.onHover(this, event)) {
7900            return true;
7901        }
7902
7903        return onHoverEvent(event);
7904    }
7905
7906    /**
7907     * Returns true if the view has a child to which it has recently sent
7908     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7909     * it does not have a hovered child, then it must be the innermost hovered view.
7910     * @hide
7911     */
7912    protected boolean hasHoveredChild() {
7913        return false;
7914    }
7915
7916    /**
7917     * Dispatch a generic motion event to the view under the first pointer.
7918     * <p>
7919     * Do not call this method directly.
7920     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7921     * </p>
7922     *
7923     * @param event The motion event to be dispatched.
7924     * @return True if the event was handled by the view, false otherwise.
7925     */
7926    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7927        return false;
7928    }
7929
7930    /**
7931     * Dispatch a generic motion event to the currently focused view.
7932     * <p>
7933     * Do not call this method directly.
7934     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7935     * </p>
7936     *
7937     * @param event The motion event to be dispatched.
7938     * @return True if the event was handled by the view, false otherwise.
7939     */
7940    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7941        return false;
7942    }
7943
7944    /**
7945     * Dispatch a pointer event.
7946     * <p>
7947     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7948     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7949     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7950     * and should not be expected to handle other pointing device features.
7951     * </p>
7952     *
7953     * @param event The motion event to be dispatched.
7954     * @return True if the event was handled by the view, false otherwise.
7955     * @hide
7956     */
7957    public final boolean dispatchPointerEvent(MotionEvent event) {
7958        if (event.isTouchEvent()) {
7959            return dispatchTouchEvent(event);
7960        } else {
7961            return dispatchGenericMotionEvent(event);
7962        }
7963    }
7964
7965    /**
7966     * Called when the window containing this view gains or loses window focus.
7967     * ViewGroups should override to route to their children.
7968     *
7969     * @param hasFocus True if the window containing this view now has focus,
7970     *        false otherwise.
7971     */
7972    public void dispatchWindowFocusChanged(boolean hasFocus) {
7973        onWindowFocusChanged(hasFocus);
7974    }
7975
7976    /**
7977     * Called when the window containing this view gains or loses focus.  Note
7978     * that this is separate from view focus: to receive key events, both
7979     * your view and its window must have focus.  If a window is displayed
7980     * on top of yours that takes input focus, then your own window will lose
7981     * focus but the view focus will remain unchanged.
7982     *
7983     * @param hasWindowFocus True if the window containing this view now has
7984     *        focus, false otherwise.
7985     */
7986    public void onWindowFocusChanged(boolean hasWindowFocus) {
7987        InputMethodManager imm = InputMethodManager.peekInstance();
7988        if (!hasWindowFocus) {
7989            if (isPressed()) {
7990                setPressed(false);
7991            }
7992            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7993                imm.focusOut(this);
7994            }
7995            removeLongPressCallback();
7996            removeTapCallback();
7997            onFocusLost();
7998        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7999            imm.focusIn(this);
8000        }
8001        refreshDrawableState();
8002    }
8003
8004    /**
8005     * Returns true if this view is in a window that currently has window focus.
8006     * Note that this is not the same as the view itself having focus.
8007     *
8008     * @return True if this view is in a window that currently has window focus.
8009     */
8010    public boolean hasWindowFocus() {
8011        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8012    }
8013
8014    /**
8015     * Dispatch a view visibility change down the view hierarchy.
8016     * ViewGroups should override to route to their children.
8017     * @param changedView The view whose visibility changed. Could be 'this' or
8018     * an ancestor view.
8019     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8020     * {@link #INVISIBLE} or {@link #GONE}.
8021     */
8022    protected void dispatchVisibilityChanged(@NonNull View changedView,
8023            @Visibility int visibility) {
8024        onVisibilityChanged(changedView, visibility);
8025    }
8026
8027    /**
8028     * Called when the visibility of the view or an ancestor of the view is changed.
8029     * @param changedView The view whose visibility changed. Could be 'this' or
8030     * an ancestor view.
8031     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8032     * {@link #INVISIBLE} or {@link #GONE}.
8033     */
8034    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8035        if (visibility == VISIBLE) {
8036            if (mAttachInfo != null) {
8037                initialAwakenScrollBars();
8038            } else {
8039                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8040            }
8041        }
8042    }
8043
8044    /**
8045     * Dispatch a hint about whether this view is displayed. For instance, when
8046     * a View moves out of the screen, it might receives a display hint indicating
8047     * the view is not displayed. Applications should not <em>rely</em> on this hint
8048     * as there is no guarantee that they will receive one.
8049     *
8050     * @param hint A hint about whether or not this view is displayed:
8051     * {@link #VISIBLE} or {@link #INVISIBLE}.
8052     */
8053    public void dispatchDisplayHint(@Visibility int hint) {
8054        onDisplayHint(hint);
8055    }
8056
8057    /**
8058     * Gives this view a hint about whether is displayed or not. For instance, when
8059     * a View moves out of the screen, it might receives a display hint indicating
8060     * the view is not displayed. Applications should not <em>rely</em> on this hint
8061     * as there is no guarantee that they will receive one.
8062     *
8063     * @param hint A hint about whether or not this view is displayed:
8064     * {@link #VISIBLE} or {@link #INVISIBLE}.
8065     */
8066    protected void onDisplayHint(@Visibility int hint) {
8067    }
8068
8069    /**
8070     * Dispatch a window visibility change down the view hierarchy.
8071     * ViewGroups should override to route to their children.
8072     *
8073     * @param visibility The new visibility of the window.
8074     *
8075     * @see #onWindowVisibilityChanged(int)
8076     */
8077    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8078        onWindowVisibilityChanged(visibility);
8079    }
8080
8081    /**
8082     * Called when the window containing has change its visibility
8083     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8084     * that this tells you whether or not your window is being made visible
8085     * to the window manager; this does <em>not</em> tell you whether or not
8086     * your window is obscured by other windows on the screen, even if it
8087     * is itself visible.
8088     *
8089     * @param visibility The new visibility of the window.
8090     */
8091    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8092        if (visibility == VISIBLE) {
8093            initialAwakenScrollBars();
8094        }
8095    }
8096
8097    /**
8098     * Returns the current visibility of the window this view is attached to
8099     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8100     *
8101     * @return Returns the current visibility of the view's window.
8102     */
8103    @Visibility
8104    public int getWindowVisibility() {
8105        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8106    }
8107
8108    /**
8109     * Retrieve the overall visible display size in which the window this view is
8110     * attached to has been positioned in.  This takes into account screen
8111     * decorations above the window, for both cases where the window itself
8112     * is being position inside of them or the window is being placed under
8113     * then and covered insets are used for the window to position its content
8114     * inside.  In effect, this tells you the available area where content can
8115     * be placed and remain visible to users.
8116     *
8117     * <p>This function requires an IPC back to the window manager to retrieve
8118     * the requested information, so should not be used in performance critical
8119     * code like drawing.
8120     *
8121     * @param outRect Filled in with the visible display frame.  If the view
8122     * is not attached to a window, this is simply the raw display size.
8123     */
8124    public void getWindowVisibleDisplayFrame(Rect outRect) {
8125        if (mAttachInfo != null) {
8126            try {
8127                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8128            } catch (RemoteException e) {
8129                return;
8130            }
8131            // XXX This is really broken, and probably all needs to be done
8132            // in the window manager, and we need to know more about whether
8133            // we want the area behind or in front of the IME.
8134            final Rect insets = mAttachInfo.mVisibleInsets;
8135            outRect.left += insets.left;
8136            outRect.top += insets.top;
8137            outRect.right -= insets.right;
8138            outRect.bottom -= insets.bottom;
8139            return;
8140        }
8141        // The view is not attached to a display so we don't have a context.
8142        // Make a best guess about the display size.
8143        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8144        d.getRectSize(outRect);
8145    }
8146
8147    /**
8148     * Dispatch a notification about a resource configuration change down
8149     * the view hierarchy.
8150     * ViewGroups should override to route to their children.
8151     *
8152     * @param newConfig The new resource configuration.
8153     *
8154     * @see #onConfigurationChanged(android.content.res.Configuration)
8155     */
8156    public void dispatchConfigurationChanged(Configuration newConfig) {
8157        onConfigurationChanged(newConfig);
8158    }
8159
8160    /**
8161     * Called when the current configuration of the resources being used
8162     * by the application have changed.  You can use this to decide when
8163     * to reload resources that can changed based on orientation and other
8164     * configuration characterstics.  You only need to use this if you are
8165     * not relying on the normal {@link android.app.Activity} mechanism of
8166     * recreating the activity instance upon a configuration change.
8167     *
8168     * @param newConfig The new resource configuration.
8169     */
8170    protected void onConfigurationChanged(Configuration newConfig) {
8171    }
8172
8173    /**
8174     * Private function to aggregate all per-view attributes in to the view
8175     * root.
8176     */
8177    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8178        performCollectViewAttributes(attachInfo, visibility);
8179    }
8180
8181    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8182        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8183            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8184                attachInfo.mKeepScreenOn = true;
8185            }
8186            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8187            ListenerInfo li = mListenerInfo;
8188            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8189                attachInfo.mHasSystemUiListeners = true;
8190            }
8191        }
8192    }
8193
8194    void needGlobalAttributesUpdate(boolean force) {
8195        final AttachInfo ai = mAttachInfo;
8196        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8197            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8198                    || ai.mHasSystemUiListeners) {
8199                ai.mRecomputeGlobalAttributes = true;
8200            }
8201        }
8202    }
8203
8204    /**
8205     * Returns whether the device is currently in touch mode.  Touch mode is entered
8206     * once the user begins interacting with the device by touch, and affects various
8207     * things like whether focus is always visible to the user.
8208     *
8209     * @return Whether the device is in touch mode.
8210     */
8211    @ViewDebug.ExportedProperty
8212    public boolean isInTouchMode() {
8213        if (mAttachInfo != null) {
8214            return mAttachInfo.mInTouchMode;
8215        } else {
8216            return ViewRootImpl.isInTouchMode();
8217        }
8218    }
8219
8220    /**
8221     * Returns the context the view is running in, through which it can
8222     * access the current theme, resources, etc.
8223     *
8224     * @return The view's Context.
8225     */
8226    @ViewDebug.CapturedViewProperty
8227    public final Context getContext() {
8228        return mContext;
8229    }
8230
8231    /**
8232     * Handle a key event before it is processed by any input method
8233     * associated with the view hierarchy.  This can be used to intercept
8234     * key events in special situations before the IME consumes them; a
8235     * typical example would be handling the BACK key to update the application's
8236     * UI instead of allowing the IME to see it and close itself.
8237     *
8238     * @param keyCode The value in event.getKeyCode().
8239     * @param event Description of the key event.
8240     * @return If you handled the event, return true. If you want to allow the
8241     *         event to be handled by the next receiver, return false.
8242     */
8243    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8244        return false;
8245    }
8246
8247    /**
8248     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8249     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8250     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8251     * is released, if the view is enabled and clickable.
8252     *
8253     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8254     * although some may elect to do so in some situations. Do not rely on this to
8255     * catch software key presses.
8256     *
8257     * @param keyCode A key code that represents the button pressed, from
8258     *                {@link android.view.KeyEvent}.
8259     * @param event   The KeyEvent object that defines the button action.
8260     */
8261    public boolean onKeyDown(int keyCode, KeyEvent event) {
8262        boolean result = false;
8263
8264        if (KeyEvent.isConfirmKey(keyCode)) {
8265            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8266                return true;
8267            }
8268            // Long clickable items don't necessarily have to be clickable
8269            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8270                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8271                    (event.getRepeatCount() == 0)) {
8272                setPressed(true);
8273                checkForLongClick(0);
8274                return true;
8275            }
8276        }
8277        return result;
8278    }
8279
8280    /**
8281     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8282     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8283     * the event).
8284     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8285     * although some may elect to do so in some situations. Do not rely on this to
8286     * catch software key presses.
8287     */
8288    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8289        return false;
8290    }
8291
8292    /**
8293     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8294     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8295     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8296     * {@link KeyEvent#KEYCODE_ENTER} is released.
8297     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8298     * although some may elect to do so in some situations. Do not rely on this to
8299     * catch software key presses.
8300     *
8301     * @param keyCode A key code that represents the button pressed, from
8302     *                {@link android.view.KeyEvent}.
8303     * @param event   The KeyEvent object that defines the button action.
8304     */
8305    public boolean onKeyUp(int keyCode, KeyEvent event) {
8306        if (KeyEvent.isConfirmKey(keyCode)) {
8307            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8308                return true;
8309            }
8310            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8311                setPressed(false);
8312
8313                if (!mHasPerformedLongPress) {
8314                    // This is a tap, so remove the longpress check
8315                    removeLongPressCallback();
8316                    return performClick();
8317                }
8318            }
8319        }
8320        return false;
8321    }
8322
8323    /**
8324     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8325     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8326     * the event).
8327     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8328     * although some may elect to do so in some situations. Do not rely on this to
8329     * catch software key presses.
8330     *
8331     * @param keyCode     A key code that represents the button pressed, from
8332     *                    {@link android.view.KeyEvent}.
8333     * @param repeatCount The number of times the action was made.
8334     * @param event       The KeyEvent object that defines the button action.
8335     */
8336    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8337        return false;
8338    }
8339
8340    /**
8341     * Called on the focused view when a key shortcut event is not handled.
8342     * Override this method to implement local key shortcuts for the View.
8343     * Key shortcuts can also be implemented by setting the
8344     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8345     *
8346     * @param keyCode The value in event.getKeyCode().
8347     * @param event Description of the key event.
8348     * @return If you handled the event, return true. If you want to allow the
8349     *         event to be handled by the next receiver, return false.
8350     */
8351    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8352        return false;
8353    }
8354
8355    /**
8356     * Check whether the called view is a text editor, in which case it
8357     * would make sense to automatically display a soft input window for
8358     * it.  Subclasses should override this if they implement
8359     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8360     * a call on that method would return a non-null InputConnection, and
8361     * they are really a first-class editor that the user would normally
8362     * start typing on when the go into a window containing your view.
8363     *
8364     * <p>The default implementation always returns false.  This does
8365     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8366     * will not be called or the user can not otherwise perform edits on your
8367     * view; it is just a hint to the system that this is not the primary
8368     * purpose of this view.
8369     *
8370     * @return Returns true if this view is a text editor, else false.
8371     */
8372    public boolean onCheckIsTextEditor() {
8373        return false;
8374    }
8375
8376    /**
8377     * Create a new InputConnection for an InputMethod to interact
8378     * with the view.  The default implementation returns null, since it doesn't
8379     * support input methods.  You can override this to implement such support.
8380     * This is only needed for views that take focus and text input.
8381     *
8382     * <p>When implementing this, you probably also want to implement
8383     * {@link #onCheckIsTextEditor()} to indicate you will return a
8384     * non-null InputConnection.
8385     *
8386     * @param outAttrs Fill in with attribute information about the connection.
8387     */
8388    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8389        return null;
8390    }
8391
8392    /**
8393     * Called by the {@link android.view.inputmethod.InputMethodManager}
8394     * when a view who is not the current
8395     * input connection target is trying to make a call on the manager.  The
8396     * default implementation returns false; you can override this to return
8397     * true for certain views if you are performing InputConnection proxying
8398     * to them.
8399     * @param view The View that is making the InputMethodManager call.
8400     * @return Return true to allow the call, false to reject.
8401     */
8402    public boolean checkInputConnectionProxy(View view) {
8403        return false;
8404    }
8405
8406    /**
8407     * Show the context menu for this view. It is not safe to hold on to the
8408     * menu after returning from this method.
8409     *
8410     * You should normally not overload this method. Overload
8411     * {@link #onCreateContextMenu(ContextMenu)} or define an
8412     * {@link OnCreateContextMenuListener} to add items to the context menu.
8413     *
8414     * @param menu The context menu to populate
8415     */
8416    public void createContextMenu(ContextMenu menu) {
8417        ContextMenuInfo menuInfo = getContextMenuInfo();
8418
8419        // Sets the current menu info so all items added to menu will have
8420        // my extra info set.
8421        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8422
8423        onCreateContextMenu(menu);
8424        ListenerInfo li = mListenerInfo;
8425        if (li != null && li.mOnCreateContextMenuListener != null) {
8426            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8427        }
8428
8429        // Clear the extra information so subsequent items that aren't mine don't
8430        // have my extra info.
8431        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8432
8433        if (mParent != null) {
8434            mParent.createContextMenu(menu);
8435        }
8436    }
8437
8438    /**
8439     * Views should implement this if they have extra information to associate
8440     * with the context menu. The return result is supplied as a parameter to
8441     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8442     * callback.
8443     *
8444     * @return Extra information about the item for which the context menu
8445     *         should be shown. This information will vary across different
8446     *         subclasses of View.
8447     */
8448    protected ContextMenuInfo getContextMenuInfo() {
8449        return null;
8450    }
8451
8452    /**
8453     * Views should implement this if the view itself is going to add items to
8454     * the context menu.
8455     *
8456     * @param menu the context menu to populate
8457     */
8458    protected void onCreateContextMenu(ContextMenu menu) {
8459    }
8460
8461    /**
8462     * Implement this method to handle trackball motion events.  The
8463     * <em>relative</em> movement of the trackball since the last event
8464     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8465     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8466     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8467     * they will often be fractional values, representing the more fine-grained
8468     * movement information available from a trackball).
8469     *
8470     * @param event The motion event.
8471     * @return True if the event was handled, false otherwise.
8472     */
8473    public boolean onTrackballEvent(MotionEvent event) {
8474        return false;
8475    }
8476
8477    /**
8478     * Implement this method to handle generic motion events.
8479     * <p>
8480     * Generic motion events describe joystick movements, mouse hovers, track pad
8481     * touches, scroll wheel movements and other input events.  The
8482     * {@link MotionEvent#getSource() source} of the motion event specifies
8483     * the class of input that was received.  Implementations of this method
8484     * must examine the bits in the source before processing the event.
8485     * The following code example shows how this is done.
8486     * </p><p>
8487     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8488     * are delivered to the view under the pointer.  All other generic motion events are
8489     * delivered to the focused view.
8490     * </p>
8491     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8492     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8493     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8494     *             // process the joystick movement...
8495     *             return true;
8496     *         }
8497     *     }
8498     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8499     *         switch (event.getAction()) {
8500     *             case MotionEvent.ACTION_HOVER_MOVE:
8501     *                 // process the mouse hover movement...
8502     *                 return true;
8503     *             case MotionEvent.ACTION_SCROLL:
8504     *                 // process the scroll wheel movement...
8505     *                 return true;
8506     *         }
8507     *     }
8508     *     return super.onGenericMotionEvent(event);
8509     * }</pre>
8510     *
8511     * @param event The generic motion event being processed.
8512     * @return True if the event was handled, false otherwise.
8513     */
8514    public boolean onGenericMotionEvent(MotionEvent event) {
8515        return false;
8516    }
8517
8518    /**
8519     * Implement this method to handle hover events.
8520     * <p>
8521     * This method is called whenever a pointer is hovering into, over, or out of the
8522     * bounds of a view and the view is not currently being touched.
8523     * Hover events are represented as pointer events with action
8524     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8525     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8526     * </p>
8527     * <ul>
8528     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8529     * when the pointer enters the bounds of the view.</li>
8530     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8531     * when the pointer has already entered the bounds of the view and has moved.</li>
8532     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8533     * when the pointer has exited the bounds of the view or when the pointer is
8534     * about to go down due to a button click, tap, or similar user action that
8535     * causes the view to be touched.</li>
8536     * </ul>
8537     * <p>
8538     * The view should implement this method to return true to indicate that it is
8539     * handling the hover event, such as by changing its drawable state.
8540     * </p><p>
8541     * The default implementation calls {@link #setHovered} to update the hovered state
8542     * of the view when a hover enter or hover exit event is received, if the view
8543     * is enabled and is clickable.  The default implementation also sends hover
8544     * accessibility events.
8545     * </p>
8546     *
8547     * @param event The motion event that describes the hover.
8548     * @return True if the view handled the hover event.
8549     *
8550     * @see #isHovered
8551     * @see #setHovered
8552     * @see #onHoverChanged
8553     */
8554    public boolean onHoverEvent(MotionEvent event) {
8555        // The root view may receive hover (or touch) events that are outside the bounds of
8556        // the window.  This code ensures that we only send accessibility events for
8557        // hovers that are actually within the bounds of the root view.
8558        final int action = event.getActionMasked();
8559        if (!mSendingHoverAccessibilityEvents) {
8560            if ((action == MotionEvent.ACTION_HOVER_ENTER
8561                    || action == MotionEvent.ACTION_HOVER_MOVE)
8562                    && !hasHoveredChild()
8563                    && pointInView(event.getX(), event.getY())) {
8564                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8565                mSendingHoverAccessibilityEvents = true;
8566            }
8567        } else {
8568            if (action == MotionEvent.ACTION_HOVER_EXIT
8569                    || (action == MotionEvent.ACTION_MOVE
8570                            && !pointInView(event.getX(), event.getY()))) {
8571                mSendingHoverAccessibilityEvents = false;
8572                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8573                // If the window does not have input focus we take away accessibility
8574                // focus as soon as the user stop hovering over the view.
8575                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8576                    getViewRootImpl().setAccessibilityFocus(null, null);
8577                }
8578            }
8579        }
8580
8581        if (isHoverable()) {
8582            switch (action) {
8583                case MotionEvent.ACTION_HOVER_ENTER:
8584                    setHovered(true);
8585                    break;
8586                case MotionEvent.ACTION_HOVER_EXIT:
8587                    setHovered(false);
8588                    break;
8589            }
8590
8591            // Dispatch the event to onGenericMotionEvent before returning true.
8592            // This is to provide compatibility with existing applications that
8593            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8594            // break because of the new default handling for hoverable views
8595            // in onHoverEvent.
8596            // Note that onGenericMotionEvent will be called by default when
8597            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8598            dispatchGenericMotionEventInternal(event);
8599            // The event was already handled by calling setHovered(), so always
8600            // return true.
8601            return true;
8602        }
8603
8604        return false;
8605    }
8606
8607    /**
8608     * Returns true if the view should handle {@link #onHoverEvent}
8609     * by calling {@link #setHovered} to change its hovered state.
8610     *
8611     * @return True if the view is hoverable.
8612     */
8613    private boolean isHoverable() {
8614        final int viewFlags = mViewFlags;
8615        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8616            return false;
8617        }
8618
8619        return (viewFlags & CLICKABLE) == CLICKABLE
8620                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8621    }
8622
8623    /**
8624     * Returns true if the view is currently hovered.
8625     *
8626     * @return True if the view is currently hovered.
8627     *
8628     * @see #setHovered
8629     * @see #onHoverChanged
8630     */
8631    @ViewDebug.ExportedProperty
8632    public boolean isHovered() {
8633        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8634    }
8635
8636    /**
8637     * Sets whether the view is currently hovered.
8638     * <p>
8639     * Calling this method also changes the drawable state of the view.  This
8640     * enables the view to react to hover by using different drawable resources
8641     * to change its appearance.
8642     * </p><p>
8643     * The {@link #onHoverChanged} method is called when the hovered state changes.
8644     * </p>
8645     *
8646     * @param hovered True if the view is hovered.
8647     *
8648     * @see #isHovered
8649     * @see #onHoverChanged
8650     */
8651    public void setHovered(boolean hovered) {
8652        if (hovered) {
8653            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8654                mPrivateFlags |= PFLAG_HOVERED;
8655                refreshDrawableState();
8656                onHoverChanged(true);
8657            }
8658        } else {
8659            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8660                mPrivateFlags &= ~PFLAG_HOVERED;
8661                refreshDrawableState();
8662                onHoverChanged(false);
8663            }
8664        }
8665    }
8666
8667    /**
8668     * Implement this method to handle hover state changes.
8669     * <p>
8670     * This method is called whenever the hover state changes as a result of a
8671     * call to {@link #setHovered}.
8672     * </p>
8673     *
8674     * @param hovered The current hover state, as returned by {@link #isHovered}.
8675     *
8676     * @see #isHovered
8677     * @see #setHovered
8678     */
8679    public void onHoverChanged(boolean hovered) {
8680    }
8681
8682    /**
8683     * Implement this method to handle touch screen motion events.
8684     * <p>
8685     * If this method is used to detect click actions, it is recommended that
8686     * the actions be performed by implementing and calling
8687     * {@link #performClick()}. This will ensure consistent system behavior,
8688     * including:
8689     * <ul>
8690     * <li>obeying click sound preferences
8691     * <li>dispatching OnClickListener calls
8692     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
8693     * accessibility features are enabled
8694     * </ul>
8695     *
8696     * @param event The motion event.
8697     * @return True if the event was handled, false otherwise.
8698     */
8699    public boolean onTouchEvent(MotionEvent event) {
8700        final int viewFlags = mViewFlags;
8701
8702        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8703            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8704                setPressed(false);
8705            }
8706            // A disabled view that is clickable still consumes the touch
8707            // events, it just doesn't respond to them.
8708            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8709                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8710        }
8711
8712        if (mTouchDelegate != null) {
8713            if (mTouchDelegate.onTouchEvent(event)) {
8714                return true;
8715            }
8716        }
8717
8718        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8719                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8720            switch (event.getAction()) {
8721                case MotionEvent.ACTION_UP:
8722                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8723                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8724                        // take focus if we don't have it already and we should in
8725                        // touch mode.
8726                        boolean focusTaken = false;
8727                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8728                            focusTaken = requestFocus();
8729                        }
8730
8731                        if (prepressed) {
8732                            // The button is being released before we actually
8733                            // showed it as pressed.  Make it show the pressed
8734                            // state now (before scheduling the click) to ensure
8735                            // the user sees it.
8736                            setPressed(true);
8737                       }
8738
8739                        if (!mHasPerformedLongPress) {
8740                            // This is a tap, so remove the longpress check
8741                            removeLongPressCallback();
8742
8743                            // Only perform take click actions if we were in the pressed state
8744                            if (!focusTaken) {
8745                                // Use a Runnable and post this rather than calling
8746                                // performClick directly. This lets other visual state
8747                                // of the view update before click actions start.
8748                                if (mPerformClick == null) {
8749                                    mPerformClick = new PerformClick();
8750                                }
8751                                if (!post(mPerformClick)) {
8752                                    performClick();
8753                                }
8754                            }
8755                        }
8756
8757                        if (mUnsetPressedState == null) {
8758                            mUnsetPressedState = new UnsetPressedState();
8759                        }
8760
8761                        if (prepressed) {
8762                            postDelayed(mUnsetPressedState,
8763                                    ViewConfiguration.getPressedStateDuration());
8764                        } else if (!post(mUnsetPressedState)) {
8765                            // If the post failed, unpress right now
8766                            mUnsetPressedState.run();
8767                        }
8768                        removeTapCallback();
8769                    }
8770                    break;
8771
8772                case MotionEvent.ACTION_DOWN:
8773                    mHasPerformedLongPress = false;
8774
8775                    if (performButtonActionOnTouchDown(event)) {
8776                        break;
8777                    }
8778
8779                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8780                    boolean isInScrollingContainer = isInScrollingContainer();
8781
8782                    // For views inside a scrolling container, delay the pressed feedback for
8783                    // a short period in case this is a scroll.
8784                    if (isInScrollingContainer) {
8785                        mPrivateFlags |= PFLAG_PREPRESSED;
8786                        if (mPendingCheckForTap == null) {
8787                            mPendingCheckForTap = new CheckForTap();
8788                        }
8789                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8790                    } else {
8791                        // Not inside a scrolling container, so show the feedback right away
8792                        setPressed(true);
8793                        checkForLongClick(0);
8794                    }
8795                    break;
8796
8797                case MotionEvent.ACTION_CANCEL:
8798                    setPressed(false);
8799                    removeTapCallback();
8800                    removeLongPressCallback();
8801                    break;
8802
8803                case MotionEvent.ACTION_MOVE:
8804                    final int x = (int) event.getX();
8805                    final int y = (int) event.getY();
8806
8807                    // Be lenient about moving outside of buttons
8808                    if (!pointInView(x, y, mTouchSlop)) {
8809                        // Outside button
8810                        removeTapCallback();
8811                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8812                            // Remove any future long press/tap checks
8813                            removeLongPressCallback();
8814
8815                            setPressed(false);
8816                        }
8817                    }
8818                    break;
8819            }
8820            return true;
8821        }
8822
8823        return false;
8824    }
8825
8826    /**
8827     * @hide
8828     */
8829    public boolean isInScrollingContainer() {
8830        ViewParent p = getParent();
8831        while (p != null && p instanceof ViewGroup) {
8832            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8833                return true;
8834            }
8835            p = p.getParent();
8836        }
8837        return false;
8838    }
8839
8840    /**
8841     * Remove the longpress detection timer.
8842     */
8843    private void removeLongPressCallback() {
8844        if (mPendingCheckForLongPress != null) {
8845          removeCallbacks(mPendingCheckForLongPress);
8846        }
8847    }
8848
8849    /**
8850     * Remove the pending click action
8851     */
8852    private void removePerformClickCallback() {
8853        if (mPerformClick != null) {
8854            removeCallbacks(mPerformClick);
8855        }
8856    }
8857
8858    /**
8859     * Remove the prepress detection timer.
8860     */
8861    private void removeUnsetPressCallback() {
8862        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8863            setPressed(false);
8864            removeCallbacks(mUnsetPressedState);
8865        }
8866    }
8867
8868    /**
8869     * Remove the tap detection timer.
8870     */
8871    private void removeTapCallback() {
8872        if (mPendingCheckForTap != null) {
8873            mPrivateFlags &= ~PFLAG_PREPRESSED;
8874            removeCallbacks(mPendingCheckForTap);
8875        }
8876    }
8877
8878    /**
8879     * Cancels a pending long press.  Your subclass can use this if you
8880     * want the context menu to come up if the user presses and holds
8881     * at the same place, but you don't want it to come up if they press
8882     * and then move around enough to cause scrolling.
8883     */
8884    public void cancelLongPress() {
8885        removeLongPressCallback();
8886
8887        /*
8888         * The prepressed state handled by the tap callback is a display
8889         * construct, but the tap callback will post a long press callback
8890         * less its own timeout. Remove it here.
8891         */
8892        removeTapCallback();
8893    }
8894
8895    /**
8896     * Remove the pending callback for sending a
8897     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8898     */
8899    private void removeSendViewScrolledAccessibilityEventCallback() {
8900        if (mSendViewScrolledAccessibilityEvent != null) {
8901            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8902            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8903        }
8904    }
8905
8906    /**
8907     * Sets the TouchDelegate for this View.
8908     */
8909    public void setTouchDelegate(TouchDelegate delegate) {
8910        mTouchDelegate = delegate;
8911    }
8912
8913    /**
8914     * Gets the TouchDelegate for this View.
8915     */
8916    public TouchDelegate getTouchDelegate() {
8917        return mTouchDelegate;
8918    }
8919
8920    /**
8921     * Set flags controlling behavior of this view.
8922     *
8923     * @param flags Constant indicating the value which should be set
8924     * @param mask Constant indicating the bit range that should be changed
8925     */
8926    void setFlags(int flags, int mask) {
8927        final boolean accessibilityEnabled =
8928                AccessibilityManager.getInstance(mContext).isEnabled();
8929        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8930
8931        int old = mViewFlags;
8932        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8933
8934        int changed = mViewFlags ^ old;
8935        if (changed == 0) {
8936            return;
8937        }
8938        int privateFlags = mPrivateFlags;
8939
8940        /* Check if the FOCUSABLE bit has changed */
8941        if (((changed & FOCUSABLE_MASK) != 0) &&
8942                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8943            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8944                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8945                /* Give up focus if we are no longer focusable */
8946                clearFocus();
8947            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8948                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8949                /*
8950                 * Tell the view system that we are now available to take focus
8951                 * if no one else already has it.
8952                 */
8953                if (mParent != null) mParent.focusableViewAvailable(this);
8954            }
8955        }
8956
8957        final int newVisibility = flags & VISIBILITY_MASK;
8958        if (newVisibility == VISIBLE) {
8959            if ((changed & VISIBILITY_MASK) != 0) {
8960                /*
8961                 * If this view is becoming visible, invalidate it in case it changed while
8962                 * it was not visible. Marking it drawn ensures that the invalidation will
8963                 * go through.
8964                 */
8965                mPrivateFlags |= PFLAG_DRAWN;
8966                invalidate(true);
8967
8968                needGlobalAttributesUpdate(true);
8969
8970                // a view becoming visible is worth notifying the parent
8971                // about in case nothing has focus.  even if this specific view
8972                // isn't focusable, it may contain something that is, so let
8973                // the root view try to give this focus if nothing else does.
8974                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8975                    mParent.focusableViewAvailable(this);
8976                }
8977            }
8978        }
8979
8980        /* Check if the GONE bit has changed */
8981        if ((changed & GONE) != 0) {
8982            needGlobalAttributesUpdate(false);
8983            requestLayout();
8984
8985            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8986                if (hasFocus()) clearFocus();
8987                clearAccessibilityFocus();
8988                destroyDrawingCache();
8989                if (mParent instanceof View) {
8990                    // GONE views noop invalidation, so invalidate the parent
8991                    ((View) mParent).invalidate(true);
8992                }
8993                // Mark the view drawn to ensure that it gets invalidated properly the next
8994                // time it is visible and gets invalidated
8995                mPrivateFlags |= PFLAG_DRAWN;
8996            }
8997            if (mAttachInfo != null) {
8998                mAttachInfo.mViewVisibilityChanged = true;
8999            }
9000        }
9001
9002        /* Check if the VISIBLE bit has changed */
9003        if ((changed & INVISIBLE) != 0) {
9004            needGlobalAttributesUpdate(false);
9005            /*
9006             * If this view is becoming invisible, set the DRAWN flag so that
9007             * the next invalidate() will not be skipped.
9008             */
9009            mPrivateFlags |= PFLAG_DRAWN;
9010
9011            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
9012                // root view becoming invisible shouldn't clear focus and accessibility focus
9013                if (getRootView() != this) {
9014                    clearFocus();
9015                    clearAccessibilityFocus();
9016                }
9017            }
9018            if (mAttachInfo != null) {
9019                mAttachInfo.mViewVisibilityChanged = true;
9020            }
9021        }
9022
9023        if ((changed & VISIBILITY_MASK) != 0) {
9024            // If the view is invisible, cleanup its display list to free up resources
9025            if (newVisibility != VISIBLE) {
9026                cleanupDraw();
9027            }
9028
9029            if (mParent instanceof ViewGroup) {
9030                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9031                        (changed & VISIBILITY_MASK), newVisibility);
9032                ((View) mParent).invalidate(true);
9033            } else if (mParent != null) {
9034                mParent.invalidateChild(this, null);
9035            }
9036            dispatchVisibilityChanged(this, newVisibility);
9037        }
9038
9039        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9040            destroyDrawingCache();
9041        }
9042
9043        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9044            destroyDrawingCache();
9045            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9046            invalidateParentCaches();
9047        }
9048
9049        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9050            destroyDrawingCache();
9051            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9052        }
9053
9054        if ((changed & DRAW_MASK) != 0) {
9055            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9056                if (mBackground != null) {
9057                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9058                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9059                } else {
9060                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9061                }
9062            } else {
9063                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9064            }
9065            requestLayout();
9066            invalidate(true);
9067        }
9068
9069        if ((changed & KEEP_SCREEN_ON) != 0) {
9070            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9071                mParent.recomputeViewAttributes(this);
9072            }
9073        }
9074
9075        if (accessibilityEnabled) {
9076            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9077                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9078                if (oldIncludeForAccessibility != includeForAccessibility()) {
9079                    notifySubtreeAccessibilityStateChangedIfNeeded();
9080                } else {
9081                    notifyViewAccessibilityStateChangedIfNeeded(
9082                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9083                }
9084            } else if ((changed & ENABLED_MASK) != 0) {
9085                notifyViewAccessibilityStateChangedIfNeeded(
9086                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9087            }
9088        }
9089    }
9090
9091    /**
9092     * Change the view's z order in the tree, so it's on top of other sibling
9093     * views. This ordering change may affect layout, if the parent container
9094     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9095     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9096     * method should be followed by calls to {@link #requestLayout()} and
9097     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9098     * with the new child ordering.
9099     *
9100     * @see ViewGroup#bringChildToFront(View)
9101     */
9102    public void bringToFront() {
9103        if (mParent != null) {
9104            mParent.bringChildToFront(this);
9105        }
9106    }
9107
9108    /**
9109     * This is called in response to an internal scroll in this view (i.e., the
9110     * view scrolled its own contents). This is typically as a result of
9111     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9112     * called.
9113     *
9114     * @param l Current horizontal scroll origin.
9115     * @param t Current vertical scroll origin.
9116     * @param oldl Previous horizontal scroll origin.
9117     * @param oldt Previous vertical scroll origin.
9118     */
9119    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9120        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9121            postSendViewScrolledAccessibilityEventCallback();
9122        }
9123
9124        mBackgroundSizeChanged = true;
9125
9126        final AttachInfo ai = mAttachInfo;
9127        if (ai != null) {
9128            ai.mViewScrollChanged = true;
9129        }
9130    }
9131
9132    /**
9133     * Interface definition for a callback to be invoked when the layout bounds of a view
9134     * changes due to layout processing.
9135     */
9136    public interface OnLayoutChangeListener {
9137        /**
9138         * Called when the focus state of a view has changed.
9139         *
9140         * @param v The view whose state has changed.
9141         * @param left The new value of the view's left property.
9142         * @param top The new value of the view's top property.
9143         * @param right The new value of the view's right property.
9144         * @param bottom The new value of the view's bottom property.
9145         * @param oldLeft The previous value of the view's left property.
9146         * @param oldTop The previous value of the view's top property.
9147         * @param oldRight The previous value of the view's right property.
9148         * @param oldBottom The previous value of the view's bottom property.
9149         */
9150        void onLayoutChange(View v, int left, int top, int right, int bottom,
9151            int oldLeft, int oldTop, int oldRight, int oldBottom);
9152    }
9153
9154    /**
9155     * This is called during layout when the size of this view has changed. If
9156     * you were just added to the view hierarchy, you're called with the old
9157     * values of 0.
9158     *
9159     * @param w Current width of this view.
9160     * @param h Current height of this view.
9161     * @param oldw Old width of this view.
9162     * @param oldh Old height of this view.
9163     */
9164    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9165    }
9166
9167    /**
9168     * Called by draw to draw the child views. This may be overridden
9169     * by derived classes to gain control just before its children are drawn
9170     * (but after its own view has been drawn).
9171     * @param canvas the canvas on which to draw the view
9172     */
9173    protected void dispatchDraw(Canvas canvas) {
9174
9175    }
9176
9177    /**
9178     * Gets the parent of this view. Note that the parent is a
9179     * ViewParent and not necessarily a View.
9180     *
9181     * @return Parent of this view.
9182     */
9183    public final ViewParent getParent() {
9184        return mParent;
9185    }
9186
9187    /**
9188     * Set the horizontal scrolled position of your view. This will cause a call to
9189     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9190     * invalidated.
9191     * @param value the x position to scroll to
9192     */
9193    public void setScrollX(int value) {
9194        scrollTo(value, mScrollY);
9195    }
9196
9197    /**
9198     * Set the vertical scrolled position of your view. This will cause a call to
9199     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9200     * invalidated.
9201     * @param value the y position to scroll to
9202     */
9203    public void setScrollY(int value) {
9204        scrollTo(mScrollX, value);
9205    }
9206
9207    /**
9208     * Return the scrolled left position of this view. This is the left edge of
9209     * the displayed part of your view. You do not need to draw any pixels
9210     * farther left, since those are outside of the frame of your view on
9211     * screen.
9212     *
9213     * @return The left edge of the displayed part of your view, in pixels.
9214     */
9215    public final int getScrollX() {
9216        return mScrollX;
9217    }
9218
9219    /**
9220     * Return the scrolled top position of this view. This is the top edge of
9221     * the displayed part of your view. You do not need to draw any pixels above
9222     * it, since those are outside of the frame of your view on screen.
9223     *
9224     * @return The top edge of the displayed part of your view, in pixels.
9225     */
9226    public final int getScrollY() {
9227        return mScrollY;
9228    }
9229
9230    /**
9231     * Return the width of the your view.
9232     *
9233     * @return The width of your view, in pixels.
9234     */
9235    @ViewDebug.ExportedProperty(category = "layout")
9236    public final int getWidth() {
9237        return mRight - mLeft;
9238    }
9239
9240    /**
9241     * Return the height of your view.
9242     *
9243     * @return The height of your view, in pixels.
9244     */
9245    @ViewDebug.ExportedProperty(category = "layout")
9246    public final int getHeight() {
9247        return mBottom - mTop;
9248    }
9249
9250    /**
9251     * Return the visible drawing bounds of your view. Fills in the output
9252     * rectangle with the values from getScrollX(), getScrollY(),
9253     * getWidth(), and getHeight(). These bounds do not account for any
9254     * transformation properties currently set on the view, such as
9255     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9256     *
9257     * @param outRect The (scrolled) drawing bounds of the view.
9258     */
9259    public void getDrawingRect(Rect outRect) {
9260        outRect.left = mScrollX;
9261        outRect.top = mScrollY;
9262        outRect.right = mScrollX + (mRight - mLeft);
9263        outRect.bottom = mScrollY + (mBottom - mTop);
9264    }
9265
9266    /**
9267     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9268     * raw width component (that is the result is masked by
9269     * {@link #MEASURED_SIZE_MASK}).
9270     *
9271     * @return The raw measured width of this view.
9272     */
9273    public final int getMeasuredWidth() {
9274        return mMeasuredWidth & MEASURED_SIZE_MASK;
9275    }
9276
9277    /**
9278     * Return the full width measurement information for this view as computed
9279     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9280     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9281     * This should be used during measurement and layout calculations only. Use
9282     * {@link #getWidth()} to see how wide a view is after layout.
9283     *
9284     * @return The measured width of this view as a bit mask.
9285     */
9286    public final int getMeasuredWidthAndState() {
9287        return mMeasuredWidth;
9288    }
9289
9290    /**
9291     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9292     * raw width component (that is the result is masked by
9293     * {@link #MEASURED_SIZE_MASK}).
9294     *
9295     * @return The raw measured height of this view.
9296     */
9297    public final int getMeasuredHeight() {
9298        return mMeasuredHeight & MEASURED_SIZE_MASK;
9299    }
9300
9301    /**
9302     * Return the full height measurement information for this view as computed
9303     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9304     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9305     * This should be used during measurement and layout calculations only. Use
9306     * {@link #getHeight()} to see how wide a view is after layout.
9307     *
9308     * @return The measured width of this view as a bit mask.
9309     */
9310    public final int getMeasuredHeightAndState() {
9311        return mMeasuredHeight;
9312    }
9313
9314    /**
9315     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9316     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9317     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9318     * and the height component is at the shifted bits
9319     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9320     */
9321    public final int getMeasuredState() {
9322        return (mMeasuredWidth&MEASURED_STATE_MASK)
9323                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9324                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9325    }
9326
9327    /**
9328     * The transform matrix of this view, which is calculated based on the current
9329     * roation, scale, and pivot properties.
9330     *
9331     * @see #getRotation()
9332     * @see #getScaleX()
9333     * @see #getScaleY()
9334     * @see #getPivotX()
9335     * @see #getPivotY()
9336     * @return The current transform matrix for the view
9337     */
9338    public Matrix getMatrix() {
9339        if (mTransformationInfo != null) {
9340            updateMatrix();
9341            return mTransformationInfo.mMatrix;
9342        }
9343        return Matrix.IDENTITY_MATRIX;
9344    }
9345
9346    /**
9347     * Utility function to determine if the value is far enough away from zero to be
9348     * considered non-zero.
9349     * @param value A floating point value to check for zero-ness
9350     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9351     */
9352    private static boolean nonzero(float value) {
9353        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9354    }
9355
9356    /**
9357     * Returns true if the transform matrix is the identity matrix.
9358     * Recomputes the matrix if necessary.
9359     *
9360     * @return True if the transform matrix is the identity matrix, false otherwise.
9361     */
9362    final boolean hasIdentityMatrix() {
9363        if (mTransformationInfo != null) {
9364            updateMatrix();
9365            return mTransformationInfo.mMatrixIsIdentity;
9366        }
9367        return true;
9368    }
9369
9370    void ensureTransformationInfo() {
9371        if (mTransformationInfo == null) {
9372            mTransformationInfo = new TransformationInfo();
9373        }
9374    }
9375
9376    /**
9377     * Recomputes the transform matrix if necessary.
9378     */
9379    private void updateMatrix() {
9380        final TransformationInfo info = mTransformationInfo;
9381        if (info == null) {
9382            return;
9383        }
9384        if (info.mMatrixDirty) {
9385            // transform-related properties have changed since the last time someone
9386            // asked for the matrix; recalculate it with the current values
9387
9388            // Figure out if we need to update the pivot point
9389            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9390                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9391                    info.mPrevWidth = mRight - mLeft;
9392                    info.mPrevHeight = mBottom - mTop;
9393                    info.mPivotX = info.mPrevWidth / 2f;
9394                    info.mPivotY = info.mPrevHeight / 2f;
9395                }
9396            }
9397            info.mMatrix.reset();
9398            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9399                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9400                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9401                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9402            } else {
9403                if (info.mCamera == null) {
9404                    info.mCamera = new Camera();
9405                    info.matrix3D = new Matrix();
9406                }
9407                info.mCamera.save();
9408                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9409                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9410                info.mCamera.getMatrix(info.matrix3D);
9411                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9412                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9413                        info.mPivotY + info.mTranslationY);
9414                info.mMatrix.postConcat(info.matrix3D);
9415                info.mCamera.restore();
9416            }
9417            info.mMatrixDirty = false;
9418            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9419            info.mInverseMatrixDirty = true;
9420        }
9421    }
9422
9423   /**
9424     * Utility method to retrieve the inverse of the current mMatrix property.
9425     * We cache the matrix to avoid recalculating it when transform properties
9426     * have not changed.
9427     *
9428     * @return The inverse of the current matrix of this view.
9429     */
9430    final Matrix getInverseMatrix() {
9431        final TransformationInfo info = mTransformationInfo;
9432        if (info != null) {
9433            updateMatrix();
9434            if (info.mInverseMatrixDirty) {
9435                if (info.mInverseMatrix == null) {
9436                    info.mInverseMatrix = new Matrix();
9437                }
9438                info.mMatrix.invert(info.mInverseMatrix);
9439                info.mInverseMatrixDirty = false;
9440            }
9441            return info.mInverseMatrix;
9442        }
9443        return Matrix.IDENTITY_MATRIX;
9444    }
9445
9446    /**
9447     * Gets the distance along the Z axis from the camera to this view.
9448     *
9449     * @see #setCameraDistance(float)
9450     *
9451     * @return The distance along the Z axis.
9452     */
9453    public float getCameraDistance() {
9454        ensureTransformationInfo();
9455        final float dpi = mResources.getDisplayMetrics().densityDpi;
9456        final TransformationInfo info = mTransformationInfo;
9457        if (info.mCamera == null) {
9458            info.mCamera = new Camera();
9459            info.matrix3D = new Matrix();
9460        }
9461        return -(info.mCamera.getLocationZ() * dpi);
9462    }
9463
9464    /**
9465     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9466     * views are drawn) from the camera to this view. The camera's distance
9467     * affects 3D transformations, for instance rotations around the X and Y
9468     * axis. If the rotationX or rotationY properties are changed and this view is
9469     * large (more than half the size of the screen), it is recommended to always
9470     * use a camera distance that's greater than the height (X axis rotation) or
9471     * the width (Y axis rotation) of this view.</p>
9472     *
9473     * <p>The distance of the camera from the view plane can have an affect on the
9474     * perspective distortion of the view when it is rotated around the x or y axis.
9475     * For example, a large distance will result in a large viewing angle, and there
9476     * will not be much perspective distortion of the view as it rotates. A short
9477     * distance may cause much more perspective distortion upon rotation, and can
9478     * also result in some drawing artifacts if the rotated view ends up partially
9479     * behind the camera (which is why the recommendation is to use a distance at
9480     * least as far as the size of the view, if the view is to be rotated.)</p>
9481     *
9482     * <p>The distance is expressed in "depth pixels." The default distance depends
9483     * on the screen density. For instance, on a medium density display, the
9484     * default distance is 1280. On a high density display, the default distance
9485     * is 1920.</p>
9486     *
9487     * <p>If you want to specify a distance that leads to visually consistent
9488     * results across various densities, use the following formula:</p>
9489     * <pre>
9490     * float scale = context.getResources().getDisplayMetrics().density;
9491     * view.setCameraDistance(distance * scale);
9492     * </pre>
9493     *
9494     * <p>The density scale factor of a high density display is 1.5,
9495     * and 1920 = 1280 * 1.5.</p>
9496     *
9497     * @param distance The distance in "depth pixels", if negative the opposite
9498     *        value is used
9499     *
9500     * @see #setRotationX(float)
9501     * @see #setRotationY(float)
9502     */
9503    public void setCameraDistance(float distance) {
9504        invalidateViewProperty(true, false);
9505
9506        ensureTransformationInfo();
9507        final float dpi = mResources.getDisplayMetrics().densityDpi;
9508        final TransformationInfo info = mTransformationInfo;
9509        if (info.mCamera == null) {
9510            info.mCamera = new Camera();
9511            info.matrix3D = new Matrix();
9512        }
9513
9514        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9515        info.mMatrixDirty = true;
9516
9517        invalidateViewProperty(false, false);
9518        if (mDisplayList != null) {
9519            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9520        }
9521        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9522            // View was rejected last time it was drawn by its parent; this may have changed
9523            invalidateParentIfNeeded();
9524        }
9525    }
9526
9527    /**
9528     * The degrees that the view is rotated around the pivot point.
9529     *
9530     * @see #setRotation(float)
9531     * @see #getPivotX()
9532     * @see #getPivotY()
9533     *
9534     * @return The degrees of rotation.
9535     */
9536    @ViewDebug.ExportedProperty(category = "drawing")
9537    public float getRotation() {
9538        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9539    }
9540
9541    /**
9542     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9543     * result in clockwise rotation.
9544     *
9545     * @param rotation The degrees of rotation.
9546     *
9547     * @see #getRotation()
9548     * @see #getPivotX()
9549     * @see #getPivotY()
9550     * @see #setRotationX(float)
9551     * @see #setRotationY(float)
9552     *
9553     * @attr ref android.R.styleable#View_rotation
9554     */
9555    public void setRotation(float rotation) {
9556        ensureTransformationInfo();
9557        final TransformationInfo info = mTransformationInfo;
9558        if (info.mRotation != rotation) {
9559            // Double-invalidation is necessary to capture view's old and new areas
9560            invalidateViewProperty(true, false);
9561            info.mRotation = rotation;
9562            info.mMatrixDirty = true;
9563            invalidateViewProperty(false, true);
9564            if (mDisplayList != null) {
9565                mDisplayList.setRotation(rotation);
9566            }
9567            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9568                // View was rejected last time it was drawn by its parent; this may have changed
9569                invalidateParentIfNeeded();
9570            }
9571        }
9572    }
9573
9574    /**
9575     * The degrees that the view is rotated around the vertical axis through the pivot point.
9576     *
9577     * @see #getPivotX()
9578     * @see #getPivotY()
9579     * @see #setRotationY(float)
9580     *
9581     * @return The degrees of Y rotation.
9582     */
9583    @ViewDebug.ExportedProperty(category = "drawing")
9584    public float getRotationY() {
9585        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9586    }
9587
9588    /**
9589     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9590     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9591     * down the y axis.
9592     *
9593     * When rotating large views, it is recommended to adjust the camera distance
9594     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9595     *
9596     * @param rotationY The degrees of Y rotation.
9597     *
9598     * @see #getRotationY()
9599     * @see #getPivotX()
9600     * @see #getPivotY()
9601     * @see #setRotation(float)
9602     * @see #setRotationX(float)
9603     * @see #setCameraDistance(float)
9604     *
9605     * @attr ref android.R.styleable#View_rotationY
9606     */
9607    public void setRotationY(float rotationY) {
9608        ensureTransformationInfo();
9609        final TransformationInfo info = mTransformationInfo;
9610        if (info.mRotationY != rotationY) {
9611            invalidateViewProperty(true, false);
9612            info.mRotationY = rotationY;
9613            info.mMatrixDirty = true;
9614            invalidateViewProperty(false, true);
9615            if (mDisplayList != null) {
9616                mDisplayList.setRotationY(rotationY);
9617            }
9618            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9619                // View was rejected last time it was drawn by its parent; this may have changed
9620                invalidateParentIfNeeded();
9621            }
9622        }
9623    }
9624
9625    /**
9626     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9627     *
9628     * @see #getPivotX()
9629     * @see #getPivotY()
9630     * @see #setRotationX(float)
9631     *
9632     * @return The degrees of X rotation.
9633     */
9634    @ViewDebug.ExportedProperty(category = "drawing")
9635    public float getRotationX() {
9636        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9637    }
9638
9639    /**
9640     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9641     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9642     * x axis.
9643     *
9644     * When rotating large views, it is recommended to adjust the camera distance
9645     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9646     *
9647     * @param rotationX The degrees of X rotation.
9648     *
9649     * @see #getRotationX()
9650     * @see #getPivotX()
9651     * @see #getPivotY()
9652     * @see #setRotation(float)
9653     * @see #setRotationY(float)
9654     * @see #setCameraDistance(float)
9655     *
9656     * @attr ref android.R.styleable#View_rotationX
9657     */
9658    public void setRotationX(float rotationX) {
9659        ensureTransformationInfo();
9660        final TransformationInfo info = mTransformationInfo;
9661        if (info.mRotationX != rotationX) {
9662            invalidateViewProperty(true, false);
9663            info.mRotationX = rotationX;
9664            info.mMatrixDirty = true;
9665            invalidateViewProperty(false, true);
9666            if (mDisplayList != null) {
9667                mDisplayList.setRotationX(rotationX);
9668            }
9669            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9670                // View was rejected last time it was drawn by its parent; this may have changed
9671                invalidateParentIfNeeded();
9672            }
9673        }
9674    }
9675
9676    /**
9677     * The amount that the view is scaled in x around the pivot point, as a proportion of
9678     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9679     *
9680     * <p>By default, this is 1.0f.
9681     *
9682     * @see #getPivotX()
9683     * @see #getPivotY()
9684     * @return The scaling factor.
9685     */
9686    @ViewDebug.ExportedProperty(category = "drawing")
9687    public float getScaleX() {
9688        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9689    }
9690
9691    /**
9692     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9693     * the view's unscaled width. A value of 1 means that no scaling is applied.
9694     *
9695     * @param scaleX The scaling factor.
9696     * @see #getPivotX()
9697     * @see #getPivotY()
9698     *
9699     * @attr ref android.R.styleable#View_scaleX
9700     */
9701    public void setScaleX(float scaleX) {
9702        ensureTransformationInfo();
9703        final TransformationInfo info = mTransformationInfo;
9704        if (info.mScaleX != scaleX) {
9705            invalidateViewProperty(true, false);
9706            info.mScaleX = scaleX;
9707            info.mMatrixDirty = true;
9708            invalidateViewProperty(false, true);
9709            if (mDisplayList != null) {
9710                mDisplayList.setScaleX(scaleX);
9711            }
9712            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9713                // View was rejected last time it was drawn by its parent; this may have changed
9714                invalidateParentIfNeeded();
9715            }
9716        }
9717    }
9718
9719    /**
9720     * The amount that the view is scaled in y around the pivot point, as a proportion of
9721     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9722     *
9723     * <p>By default, this is 1.0f.
9724     *
9725     * @see #getPivotX()
9726     * @see #getPivotY()
9727     * @return The scaling factor.
9728     */
9729    @ViewDebug.ExportedProperty(category = "drawing")
9730    public float getScaleY() {
9731        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9732    }
9733
9734    /**
9735     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9736     * the view's unscaled width. A value of 1 means that no scaling is applied.
9737     *
9738     * @param scaleY The scaling factor.
9739     * @see #getPivotX()
9740     * @see #getPivotY()
9741     *
9742     * @attr ref android.R.styleable#View_scaleY
9743     */
9744    public void setScaleY(float scaleY) {
9745        ensureTransformationInfo();
9746        final TransformationInfo info = mTransformationInfo;
9747        if (info.mScaleY != scaleY) {
9748            invalidateViewProperty(true, false);
9749            info.mScaleY = scaleY;
9750            info.mMatrixDirty = true;
9751            invalidateViewProperty(false, true);
9752            if (mDisplayList != null) {
9753                mDisplayList.setScaleY(scaleY);
9754            }
9755            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9756                // View was rejected last time it was drawn by its parent; this may have changed
9757                invalidateParentIfNeeded();
9758            }
9759        }
9760    }
9761
9762    /**
9763     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9764     * and {@link #setScaleX(float) scaled}.
9765     *
9766     * @see #getRotation()
9767     * @see #getScaleX()
9768     * @see #getScaleY()
9769     * @see #getPivotY()
9770     * @return The x location of the pivot point.
9771     *
9772     * @attr ref android.R.styleable#View_transformPivotX
9773     */
9774    @ViewDebug.ExportedProperty(category = "drawing")
9775    public float getPivotX() {
9776        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9777    }
9778
9779    /**
9780     * Sets the x location of the point around which the view is
9781     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9782     * By default, the pivot point is centered on the object.
9783     * Setting this property disables this behavior and causes the view to use only the
9784     * explicitly set pivotX and pivotY values.
9785     *
9786     * @param pivotX The x location of the pivot point.
9787     * @see #getRotation()
9788     * @see #getScaleX()
9789     * @see #getScaleY()
9790     * @see #getPivotY()
9791     *
9792     * @attr ref android.R.styleable#View_transformPivotX
9793     */
9794    public void setPivotX(float pivotX) {
9795        ensureTransformationInfo();
9796        final TransformationInfo info = mTransformationInfo;
9797        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9798                PFLAG_PIVOT_EXPLICITLY_SET;
9799        if (info.mPivotX != pivotX || !pivotSet) {
9800            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9801            invalidateViewProperty(true, false);
9802            info.mPivotX = pivotX;
9803            info.mMatrixDirty = true;
9804            invalidateViewProperty(false, true);
9805            if (mDisplayList != null) {
9806                mDisplayList.setPivotX(pivotX);
9807            }
9808            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9809                // View was rejected last time it was drawn by its parent; this may have changed
9810                invalidateParentIfNeeded();
9811            }
9812        }
9813    }
9814
9815    /**
9816     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9817     * and {@link #setScaleY(float) scaled}.
9818     *
9819     * @see #getRotation()
9820     * @see #getScaleX()
9821     * @see #getScaleY()
9822     * @see #getPivotY()
9823     * @return The y location of the pivot point.
9824     *
9825     * @attr ref android.R.styleable#View_transformPivotY
9826     */
9827    @ViewDebug.ExportedProperty(category = "drawing")
9828    public float getPivotY() {
9829        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9830    }
9831
9832    /**
9833     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9834     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9835     * Setting this property disables this behavior and causes the view to use only the
9836     * explicitly set pivotX and pivotY values.
9837     *
9838     * @param pivotY The y location of the pivot point.
9839     * @see #getRotation()
9840     * @see #getScaleX()
9841     * @see #getScaleY()
9842     * @see #getPivotY()
9843     *
9844     * @attr ref android.R.styleable#View_transformPivotY
9845     */
9846    public void setPivotY(float pivotY) {
9847        ensureTransformationInfo();
9848        final TransformationInfo info = mTransformationInfo;
9849        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9850                PFLAG_PIVOT_EXPLICITLY_SET;
9851        if (info.mPivotY != pivotY || !pivotSet) {
9852            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9853            invalidateViewProperty(true, false);
9854            info.mPivotY = pivotY;
9855            info.mMatrixDirty = true;
9856            invalidateViewProperty(false, true);
9857            if (mDisplayList != null) {
9858                mDisplayList.setPivotY(pivotY);
9859            }
9860            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9861                // View was rejected last time it was drawn by its parent; this may have changed
9862                invalidateParentIfNeeded();
9863            }
9864        }
9865    }
9866
9867    /**
9868     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9869     * completely transparent and 1 means the view is completely opaque.
9870     *
9871     * <p>By default this is 1.0f.
9872     * @return The opacity of the view.
9873     */
9874    @ViewDebug.ExportedProperty(category = "drawing")
9875    public float getAlpha() {
9876        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9877    }
9878
9879    /**
9880     * Returns whether this View has content which overlaps. This function, intended to be
9881     * overridden by specific View types, is an optimization when alpha is set on a view. If
9882     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9883     * and then composited it into place, which can be expensive. If the view has no overlapping
9884     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9885     * An example of overlapping rendering is a TextView with a background image, such as a
9886     * Button. An example of non-overlapping rendering is a TextView with no background, or
9887     * an ImageView with only the foreground image. The default implementation returns true;
9888     * subclasses should override if they have cases which can be optimized.
9889     *
9890     * @return true if the content in this view might overlap, false otherwise.
9891     */
9892    public boolean hasOverlappingRendering() {
9893        return true;
9894    }
9895
9896    /**
9897     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9898     * completely transparent and 1 means the view is completely opaque.</p>
9899     *
9900     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9901     * performance implications, especially for large views. It is best to use the alpha property
9902     * sparingly and transiently, as in the case of fading animations.</p>
9903     *
9904     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9905     * strongly recommended for performance reasons to either override
9906     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9907     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9908     *
9909     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9910     * responsible for applying the opacity itself.</p>
9911     *
9912     * <p>Note that if the view is backed by a
9913     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9914     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9915     * 1.0 will supercede the alpha of the layer paint.</p>
9916     *
9917     * @param alpha The opacity of the view.
9918     *
9919     * @see #hasOverlappingRendering()
9920     * @see #setLayerType(int, android.graphics.Paint)
9921     *
9922     * @attr ref android.R.styleable#View_alpha
9923     */
9924    public void setAlpha(float alpha) {
9925        ensureTransformationInfo();
9926        if (mTransformationInfo.mAlpha != alpha) {
9927            mTransformationInfo.mAlpha = alpha;
9928            if (onSetAlpha((int) (alpha * 255))) {
9929                mPrivateFlags |= PFLAG_ALPHA_SET;
9930                // subclass is handling alpha - don't optimize rendering cache invalidation
9931                invalidateParentCaches();
9932                invalidate(true);
9933            } else {
9934                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9935                invalidateViewProperty(true, false);
9936                if (mDisplayList != null) {
9937                    mDisplayList.setAlpha(getFinalAlpha());
9938                }
9939            }
9940        }
9941    }
9942
9943    /**
9944     * Faster version of setAlpha() which performs the same steps except there are
9945     * no calls to invalidate(). The caller of this function should perform proper invalidation
9946     * on the parent and this object. The return value indicates whether the subclass handles
9947     * alpha (the return value for onSetAlpha()).
9948     *
9949     * @param alpha The new value for the alpha property
9950     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9951     *         the new value for the alpha property is different from the old value
9952     */
9953    boolean setAlphaNoInvalidation(float alpha) {
9954        ensureTransformationInfo();
9955        if (mTransformationInfo.mAlpha != alpha) {
9956            mTransformationInfo.mAlpha = alpha;
9957            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9958            if (subclassHandlesAlpha) {
9959                mPrivateFlags |= PFLAG_ALPHA_SET;
9960                return true;
9961            } else {
9962                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9963                if (mDisplayList != null) {
9964                    mDisplayList.setAlpha(getFinalAlpha());
9965                }
9966            }
9967        }
9968        return false;
9969    }
9970
9971    /**
9972     * This property is hidden and intended only for use by the Fade transition, which
9973     * animates it to produce a visual translucency that does not side-effect (or get
9974     * affected by) the real alpha property. This value is composited with the other
9975     * alpha value (and the AlphaAnimation value, when that is present) to produce
9976     * a final visual translucency result, which is what is passed into the DisplayList.
9977     *
9978     * @hide
9979     */
9980    public void setTransitionAlpha(float alpha) {
9981        ensureTransformationInfo();
9982        if (mTransformationInfo.mTransitionAlpha != alpha) {
9983            mTransformationInfo.mTransitionAlpha = alpha;
9984            mPrivateFlags &= ~PFLAG_ALPHA_SET;
9985            invalidateViewProperty(true, false);
9986            if (mDisplayList != null) {
9987                mDisplayList.setAlpha(getFinalAlpha());
9988            }
9989        }
9990    }
9991
9992    /**
9993     * Calculates the visual alpha of this view, which is a combination of the actual
9994     * alpha value and the transitionAlpha value (if set).
9995     */
9996    private float getFinalAlpha() {
9997        if (mTransformationInfo != null) {
9998            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
9999        }
10000        return 1;
10001    }
10002
10003    /**
10004     * This property is hidden and intended only for use by the Fade transition, which
10005     * animates it to produce a visual translucency that does not side-effect (or get
10006     * affected by) the real alpha property. This value is composited with the other
10007     * alpha value (and the AlphaAnimation value, when that is present) to produce
10008     * a final visual translucency result, which is what is passed into the DisplayList.
10009     *
10010     * @hide
10011     */
10012    public float getTransitionAlpha() {
10013        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10014    }
10015
10016    /**
10017     * Top position of this view relative to its parent.
10018     *
10019     * @return The top of this view, in pixels.
10020     */
10021    @ViewDebug.CapturedViewProperty
10022    public final int getTop() {
10023        return mTop;
10024    }
10025
10026    /**
10027     * Sets the top position of this view relative to its parent. This method is meant to be called
10028     * by the layout system and should not generally be called otherwise, because the property
10029     * may be changed at any time by the layout.
10030     *
10031     * @param top The top of this view, in pixels.
10032     */
10033    public final void setTop(int top) {
10034        if (top != mTop) {
10035            updateMatrix();
10036            final boolean matrixIsIdentity = mTransformationInfo == null
10037                    || mTransformationInfo.mMatrixIsIdentity;
10038            if (matrixIsIdentity) {
10039                if (mAttachInfo != null) {
10040                    int minTop;
10041                    int yLoc;
10042                    if (top < mTop) {
10043                        minTop = top;
10044                        yLoc = top - mTop;
10045                    } else {
10046                        minTop = mTop;
10047                        yLoc = 0;
10048                    }
10049                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10050                }
10051            } else {
10052                // Double-invalidation is necessary to capture view's old and new areas
10053                invalidate(true);
10054            }
10055
10056            int width = mRight - mLeft;
10057            int oldHeight = mBottom - mTop;
10058
10059            mTop = top;
10060            if (mDisplayList != null) {
10061                mDisplayList.setTop(mTop);
10062            }
10063
10064            sizeChange(width, mBottom - mTop, width, oldHeight);
10065
10066            if (!matrixIsIdentity) {
10067                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10068                    // A change in dimension means an auto-centered pivot point changes, too
10069                    mTransformationInfo.mMatrixDirty = true;
10070                }
10071                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10072                invalidate(true);
10073            }
10074            mBackgroundSizeChanged = true;
10075            invalidateParentIfNeeded();
10076            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10077                // View was rejected last time it was drawn by its parent; this may have changed
10078                invalidateParentIfNeeded();
10079            }
10080        }
10081    }
10082
10083    /**
10084     * Bottom position of this view relative to its parent.
10085     *
10086     * @return The bottom of this view, in pixels.
10087     */
10088    @ViewDebug.CapturedViewProperty
10089    public final int getBottom() {
10090        return mBottom;
10091    }
10092
10093    /**
10094     * True if this view has changed since the last time being drawn.
10095     *
10096     * @return The dirty state of this view.
10097     */
10098    public boolean isDirty() {
10099        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10100    }
10101
10102    /**
10103     * Sets the bottom position of this view relative to its parent. This method is meant to be
10104     * called by the layout system and should not generally be called otherwise, because the
10105     * property may be changed at any time by the layout.
10106     *
10107     * @param bottom The bottom of this view, in pixels.
10108     */
10109    public final void setBottom(int bottom) {
10110        if (bottom != mBottom) {
10111            updateMatrix();
10112            final boolean matrixIsIdentity = mTransformationInfo == null
10113                    || mTransformationInfo.mMatrixIsIdentity;
10114            if (matrixIsIdentity) {
10115                if (mAttachInfo != null) {
10116                    int maxBottom;
10117                    if (bottom < mBottom) {
10118                        maxBottom = mBottom;
10119                    } else {
10120                        maxBottom = bottom;
10121                    }
10122                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10123                }
10124            } else {
10125                // Double-invalidation is necessary to capture view's old and new areas
10126                invalidate(true);
10127            }
10128
10129            int width = mRight - mLeft;
10130            int oldHeight = mBottom - mTop;
10131
10132            mBottom = bottom;
10133            if (mDisplayList != null) {
10134                mDisplayList.setBottom(mBottom);
10135            }
10136
10137            sizeChange(width, mBottom - mTop, width, oldHeight);
10138
10139            if (!matrixIsIdentity) {
10140                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10141                    // A change in dimension means an auto-centered pivot point changes, too
10142                    mTransformationInfo.mMatrixDirty = true;
10143                }
10144                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10145                invalidate(true);
10146            }
10147            mBackgroundSizeChanged = true;
10148            invalidateParentIfNeeded();
10149            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10150                // View was rejected last time it was drawn by its parent; this may have changed
10151                invalidateParentIfNeeded();
10152            }
10153        }
10154    }
10155
10156    /**
10157     * Left position of this view relative to its parent.
10158     *
10159     * @return The left edge of this view, in pixels.
10160     */
10161    @ViewDebug.CapturedViewProperty
10162    public final int getLeft() {
10163        return mLeft;
10164    }
10165
10166    /**
10167     * Sets the left position of this view relative to its parent. This method is meant to be called
10168     * by the layout system and should not generally be called otherwise, because the property
10169     * may be changed at any time by the layout.
10170     *
10171     * @param left The bottom of this view, in pixels.
10172     */
10173    public final void setLeft(int left) {
10174        if (left != mLeft) {
10175            updateMatrix();
10176            final boolean matrixIsIdentity = mTransformationInfo == null
10177                    || mTransformationInfo.mMatrixIsIdentity;
10178            if (matrixIsIdentity) {
10179                if (mAttachInfo != null) {
10180                    int minLeft;
10181                    int xLoc;
10182                    if (left < mLeft) {
10183                        minLeft = left;
10184                        xLoc = left - mLeft;
10185                    } else {
10186                        minLeft = mLeft;
10187                        xLoc = 0;
10188                    }
10189                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10190                }
10191            } else {
10192                // Double-invalidation is necessary to capture view's old and new areas
10193                invalidate(true);
10194            }
10195
10196            int oldWidth = mRight - mLeft;
10197            int height = mBottom - mTop;
10198
10199            mLeft = left;
10200            if (mDisplayList != null) {
10201                mDisplayList.setLeft(left);
10202            }
10203
10204            sizeChange(mRight - mLeft, height, oldWidth, height);
10205
10206            if (!matrixIsIdentity) {
10207                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10208                    // A change in dimension means an auto-centered pivot point changes, too
10209                    mTransformationInfo.mMatrixDirty = true;
10210                }
10211                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10212                invalidate(true);
10213            }
10214            mBackgroundSizeChanged = true;
10215            invalidateParentIfNeeded();
10216            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10217                // View was rejected last time it was drawn by its parent; this may have changed
10218                invalidateParentIfNeeded();
10219            }
10220        }
10221    }
10222
10223    /**
10224     * Right position of this view relative to its parent.
10225     *
10226     * @return The right edge of this view, in pixels.
10227     */
10228    @ViewDebug.CapturedViewProperty
10229    public final int getRight() {
10230        return mRight;
10231    }
10232
10233    /**
10234     * Sets the right position of this view relative to its parent. This method is meant to be called
10235     * by the layout system and should not generally be called otherwise, because the property
10236     * may be changed at any time by the layout.
10237     *
10238     * @param right The bottom of this view, in pixels.
10239     */
10240    public final void setRight(int right) {
10241        if (right != mRight) {
10242            updateMatrix();
10243            final boolean matrixIsIdentity = mTransformationInfo == null
10244                    || mTransformationInfo.mMatrixIsIdentity;
10245            if (matrixIsIdentity) {
10246                if (mAttachInfo != null) {
10247                    int maxRight;
10248                    if (right < mRight) {
10249                        maxRight = mRight;
10250                    } else {
10251                        maxRight = right;
10252                    }
10253                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10254                }
10255            } else {
10256                // Double-invalidation is necessary to capture view's old and new areas
10257                invalidate(true);
10258            }
10259
10260            int oldWidth = mRight - mLeft;
10261            int height = mBottom - mTop;
10262
10263            mRight = right;
10264            if (mDisplayList != null) {
10265                mDisplayList.setRight(mRight);
10266            }
10267
10268            sizeChange(mRight - mLeft, height, oldWidth, height);
10269
10270            if (!matrixIsIdentity) {
10271                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10272                    // A change in dimension means an auto-centered pivot point changes, too
10273                    mTransformationInfo.mMatrixDirty = true;
10274                }
10275                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10276                invalidate(true);
10277            }
10278            mBackgroundSizeChanged = true;
10279            invalidateParentIfNeeded();
10280            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10281                // View was rejected last time it was drawn by its parent; this may have changed
10282                invalidateParentIfNeeded();
10283            }
10284        }
10285    }
10286
10287    /**
10288     * The visual x position of this view, in pixels. This is equivalent to the
10289     * {@link #setTranslationX(float) translationX} property plus the current
10290     * {@link #getLeft() left} property.
10291     *
10292     * @return The visual x position of this view, in pixels.
10293     */
10294    @ViewDebug.ExportedProperty(category = "drawing")
10295    public float getX() {
10296        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10297    }
10298
10299    /**
10300     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10301     * {@link #setTranslationX(float) translationX} property to be the difference between
10302     * the x value passed in and the current {@link #getLeft() left} property.
10303     *
10304     * @param x The visual x position of this view, in pixels.
10305     */
10306    public void setX(float x) {
10307        setTranslationX(x - mLeft);
10308    }
10309
10310    /**
10311     * The visual y position of this view, in pixels. This is equivalent to the
10312     * {@link #setTranslationY(float) translationY} property plus the current
10313     * {@link #getTop() top} property.
10314     *
10315     * @return The visual y position of this view, in pixels.
10316     */
10317    @ViewDebug.ExportedProperty(category = "drawing")
10318    public float getY() {
10319        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10320    }
10321
10322    /**
10323     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10324     * {@link #setTranslationY(float) translationY} property to be the difference between
10325     * the y value passed in and the current {@link #getTop() top} property.
10326     *
10327     * @param y The visual y position of this view, in pixels.
10328     */
10329    public void setY(float y) {
10330        setTranslationY(y - mTop);
10331    }
10332
10333
10334    /**
10335     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10336     * This position is post-layout, in addition to wherever the object's
10337     * layout placed it.
10338     *
10339     * @return The horizontal position of this view relative to its left position, in pixels.
10340     */
10341    @ViewDebug.ExportedProperty(category = "drawing")
10342    public float getTranslationX() {
10343        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10344    }
10345
10346    /**
10347     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10348     * This effectively positions the object post-layout, in addition to wherever the object's
10349     * layout placed it.
10350     *
10351     * @param translationX The horizontal position of this view relative to its left position,
10352     * in pixels.
10353     *
10354     * @attr ref android.R.styleable#View_translationX
10355     */
10356    public void setTranslationX(float translationX) {
10357        ensureTransformationInfo();
10358        final TransformationInfo info = mTransformationInfo;
10359        if (info.mTranslationX != translationX) {
10360            // Double-invalidation is necessary to capture view's old and new areas
10361            invalidateViewProperty(true, false);
10362            info.mTranslationX = translationX;
10363            info.mMatrixDirty = true;
10364            invalidateViewProperty(false, true);
10365            if (mDisplayList != null) {
10366                mDisplayList.setTranslationX(translationX);
10367            }
10368            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10369                // View was rejected last time it was drawn by its parent; this may have changed
10370                invalidateParentIfNeeded();
10371            }
10372        }
10373    }
10374
10375    /**
10376     * The horizontal location of this view relative to its {@link #getTop() top} position.
10377     * This position is post-layout, in addition to wherever the object's
10378     * layout placed it.
10379     *
10380     * @return The vertical position of this view relative to its top position,
10381     * in pixels.
10382     */
10383    @ViewDebug.ExportedProperty(category = "drawing")
10384    public float getTranslationY() {
10385        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10386    }
10387
10388    /**
10389     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10390     * This effectively positions the object post-layout, in addition to wherever the object's
10391     * layout placed it.
10392     *
10393     * @param translationY The vertical position of this view relative to its top position,
10394     * in pixels.
10395     *
10396     * @attr ref android.R.styleable#View_translationY
10397     */
10398    public void setTranslationY(float translationY) {
10399        ensureTransformationInfo();
10400        final TransformationInfo info = mTransformationInfo;
10401        if (info.mTranslationY != translationY) {
10402            invalidateViewProperty(true, false);
10403            info.mTranslationY = translationY;
10404            info.mMatrixDirty = true;
10405            invalidateViewProperty(false, true);
10406            if (mDisplayList != null) {
10407                mDisplayList.setTranslationY(translationY);
10408            }
10409            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10410                // View was rejected last time it was drawn by its parent; this may have changed
10411                invalidateParentIfNeeded();
10412            }
10413        }
10414    }
10415
10416    /**
10417     * Hit rectangle in parent's coordinates
10418     *
10419     * @param outRect The hit rectangle of the view.
10420     */
10421    public void getHitRect(Rect outRect) {
10422        updateMatrix();
10423        final TransformationInfo info = mTransformationInfo;
10424        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10425            outRect.set(mLeft, mTop, mRight, mBottom);
10426        } else {
10427            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10428            tmpRect.set(0, 0, getWidth(), getHeight());
10429            info.mMatrix.mapRect(tmpRect);
10430            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10431                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10432        }
10433    }
10434
10435    /**
10436     * Determines whether the given point, in local coordinates is inside the view.
10437     */
10438    /*package*/ final boolean pointInView(float localX, float localY) {
10439        return localX >= 0 && localX < (mRight - mLeft)
10440                && localY >= 0 && localY < (mBottom - mTop);
10441    }
10442
10443    /**
10444     * Utility method to determine whether the given point, in local coordinates,
10445     * is inside the view, where the area of the view is expanded by the slop factor.
10446     * This method is called while processing touch-move events to determine if the event
10447     * is still within the view.
10448     *
10449     * @hide
10450     */
10451    public boolean pointInView(float localX, float localY, float slop) {
10452        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10453                localY < ((mBottom - mTop) + slop);
10454    }
10455
10456    /**
10457     * When a view has focus and the user navigates away from it, the next view is searched for
10458     * starting from the rectangle filled in by this method.
10459     *
10460     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10461     * of the view.  However, if your view maintains some idea of internal selection,
10462     * such as a cursor, or a selected row or column, you should override this method and
10463     * fill in a more specific rectangle.
10464     *
10465     * @param r The rectangle to fill in, in this view's coordinates.
10466     */
10467    public void getFocusedRect(Rect r) {
10468        getDrawingRect(r);
10469    }
10470
10471    /**
10472     * If some part of this view is not clipped by any of its parents, then
10473     * return that area in r in global (root) coordinates. To convert r to local
10474     * coordinates (without taking possible View rotations into account), offset
10475     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10476     * If the view is completely clipped or translated out, return false.
10477     *
10478     * @param r If true is returned, r holds the global coordinates of the
10479     *        visible portion of this view.
10480     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10481     *        between this view and its root. globalOffet may be null.
10482     * @return true if r is non-empty (i.e. part of the view is visible at the
10483     *         root level.
10484     */
10485    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10486        int width = mRight - mLeft;
10487        int height = mBottom - mTop;
10488        if (width > 0 && height > 0) {
10489            r.set(0, 0, width, height);
10490            if (globalOffset != null) {
10491                globalOffset.set(-mScrollX, -mScrollY);
10492            }
10493            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10494        }
10495        return false;
10496    }
10497
10498    public final boolean getGlobalVisibleRect(Rect r) {
10499        return getGlobalVisibleRect(r, null);
10500    }
10501
10502    public final boolean getLocalVisibleRect(Rect r) {
10503        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10504        if (getGlobalVisibleRect(r, offset)) {
10505            r.offset(-offset.x, -offset.y); // make r local
10506            return true;
10507        }
10508        return false;
10509    }
10510
10511    /**
10512     * Offset this view's vertical location by the specified number of pixels.
10513     *
10514     * @param offset the number of pixels to offset the view by
10515     */
10516    public void offsetTopAndBottom(int offset) {
10517        if (offset != 0) {
10518            updateMatrix();
10519            final boolean matrixIsIdentity = mTransformationInfo == null
10520                    || mTransformationInfo.mMatrixIsIdentity;
10521            if (matrixIsIdentity) {
10522                if (mDisplayList != null) {
10523                    invalidateViewProperty(false, false);
10524                } else {
10525                    final ViewParent p = mParent;
10526                    if (p != null && mAttachInfo != null) {
10527                        final Rect r = mAttachInfo.mTmpInvalRect;
10528                        int minTop;
10529                        int maxBottom;
10530                        int yLoc;
10531                        if (offset < 0) {
10532                            minTop = mTop + offset;
10533                            maxBottom = mBottom;
10534                            yLoc = offset;
10535                        } else {
10536                            minTop = mTop;
10537                            maxBottom = mBottom + offset;
10538                            yLoc = 0;
10539                        }
10540                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10541                        p.invalidateChild(this, r);
10542                    }
10543                }
10544            } else {
10545                invalidateViewProperty(false, false);
10546            }
10547
10548            mTop += offset;
10549            mBottom += offset;
10550            if (mDisplayList != null) {
10551                mDisplayList.offsetTopAndBottom(offset);
10552                invalidateViewProperty(false, false);
10553            } else {
10554                if (!matrixIsIdentity) {
10555                    invalidateViewProperty(false, true);
10556                }
10557                invalidateParentIfNeeded();
10558            }
10559        }
10560    }
10561
10562    /**
10563     * Offset this view's horizontal location by the specified amount of pixels.
10564     *
10565     * @param offset the number of pixels to offset the view by
10566     */
10567    public void offsetLeftAndRight(int offset) {
10568        if (offset != 0) {
10569            updateMatrix();
10570            final boolean matrixIsIdentity = mTransformationInfo == null
10571                    || mTransformationInfo.mMatrixIsIdentity;
10572            if (matrixIsIdentity) {
10573                if (mDisplayList != null) {
10574                    invalidateViewProperty(false, false);
10575                } else {
10576                    final ViewParent p = mParent;
10577                    if (p != null && mAttachInfo != null) {
10578                        final Rect r = mAttachInfo.mTmpInvalRect;
10579                        int minLeft;
10580                        int maxRight;
10581                        if (offset < 0) {
10582                            minLeft = mLeft + offset;
10583                            maxRight = mRight;
10584                        } else {
10585                            minLeft = mLeft;
10586                            maxRight = mRight + offset;
10587                        }
10588                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10589                        p.invalidateChild(this, r);
10590                    }
10591                }
10592            } else {
10593                invalidateViewProperty(false, false);
10594            }
10595
10596            mLeft += offset;
10597            mRight += offset;
10598            if (mDisplayList != null) {
10599                mDisplayList.offsetLeftAndRight(offset);
10600                invalidateViewProperty(false, false);
10601            } else {
10602                if (!matrixIsIdentity) {
10603                    invalidateViewProperty(false, true);
10604                }
10605                invalidateParentIfNeeded();
10606            }
10607        }
10608    }
10609
10610    /**
10611     * Get the LayoutParams associated with this view. All views should have
10612     * layout parameters. These supply parameters to the <i>parent</i> of this
10613     * view specifying how it should be arranged. There are many subclasses of
10614     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10615     * of ViewGroup that are responsible for arranging their children.
10616     *
10617     * This method may return null if this View is not attached to a parent
10618     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10619     * was not invoked successfully. When a View is attached to a parent
10620     * ViewGroup, this method must not return null.
10621     *
10622     * @return The LayoutParams associated with this view, or null if no
10623     *         parameters have been set yet
10624     */
10625    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10626    public ViewGroup.LayoutParams getLayoutParams() {
10627        return mLayoutParams;
10628    }
10629
10630    /**
10631     * Set the layout parameters associated with this view. These supply
10632     * parameters to the <i>parent</i> of this view specifying how it should be
10633     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10634     * correspond to the different subclasses of ViewGroup that are responsible
10635     * for arranging their children.
10636     *
10637     * @param params The layout parameters for this view, cannot be null
10638     */
10639    public void setLayoutParams(ViewGroup.LayoutParams params) {
10640        if (params == null) {
10641            throw new NullPointerException("Layout parameters cannot be null");
10642        }
10643        mLayoutParams = params;
10644        resolveLayoutParams();
10645        if (mParent instanceof ViewGroup) {
10646            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10647        }
10648        requestLayout();
10649    }
10650
10651    /**
10652     * Resolve the layout parameters depending on the resolved layout direction
10653     *
10654     * @hide
10655     */
10656    public void resolveLayoutParams() {
10657        if (mLayoutParams != null) {
10658            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10659        }
10660    }
10661
10662    /**
10663     * Set the scrolled position of your view. This will cause a call to
10664     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10665     * invalidated.
10666     * @param x the x position to scroll to
10667     * @param y the y position to scroll to
10668     */
10669    public void scrollTo(int x, int y) {
10670        if (mScrollX != x || mScrollY != y) {
10671            int oldX = mScrollX;
10672            int oldY = mScrollY;
10673            mScrollX = x;
10674            mScrollY = y;
10675            invalidateParentCaches();
10676            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10677            if (!awakenScrollBars()) {
10678                postInvalidateOnAnimation();
10679            }
10680        }
10681    }
10682
10683    /**
10684     * Move the scrolled position of your view. This will cause a call to
10685     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10686     * invalidated.
10687     * @param x the amount of pixels to scroll by horizontally
10688     * @param y the amount of pixels to scroll by vertically
10689     */
10690    public void scrollBy(int x, int y) {
10691        scrollTo(mScrollX + x, mScrollY + y);
10692    }
10693
10694    /**
10695     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10696     * animation to fade the scrollbars out after a default delay. If a subclass
10697     * provides animated scrolling, the start delay should equal the duration
10698     * of the scrolling animation.</p>
10699     *
10700     * <p>The animation starts only if at least one of the scrollbars is
10701     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10702     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10703     * this method returns true, and false otherwise. If the animation is
10704     * started, this method calls {@link #invalidate()}; in that case the
10705     * caller should not call {@link #invalidate()}.</p>
10706     *
10707     * <p>This method should be invoked every time a subclass directly updates
10708     * the scroll parameters.</p>
10709     *
10710     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10711     * and {@link #scrollTo(int, int)}.</p>
10712     *
10713     * @return true if the animation is played, false otherwise
10714     *
10715     * @see #awakenScrollBars(int)
10716     * @see #scrollBy(int, int)
10717     * @see #scrollTo(int, int)
10718     * @see #isHorizontalScrollBarEnabled()
10719     * @see #isVerticalScrollBarEnabled()
10720     * @see #setHorizontalScrollBarEnabled(boolean)
10721     * @see #setVerticalScrollBarEnabled(boolean)
10722     */
10723    protected boolean awakenScrollBars() {
10724        return mScrollCache != null &&
10725                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10726    }
10727
10728    /**
10729     * Trigger the scrollbars to draw.
10730     * This method differs from awakenScrollBars() only in its default duration.
10731     * initialAwakenScrollBars() will show the scroll bars for longer than
10732     * usual to give the user more of a chance to notice them.
10733     *
10734     * @return true if the animation is played, false otherwise.
10735     */
10736    private boolean initialAwakenScrollBars() {
10737        return mScrollCache != null &&
10738                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10739    }
10740
10741    /**
10742     * <p>
10743     * Trigger the scrollbars to draw. When invoked this method starts an
10744     * animation to fade the scrollbars out after a fixed delay. If a subclass
10745     * provides animated scrolling, the start delay should equal the duration of
10746     * the scrolling animation.
10747     * </p>
10748     *
10749     * <p>
10750     * The animation starts only if at least one of the scrollbars is enabled,
10751     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10752     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10753     * this method returns true, and false otherwise. If the animation is
10754     * started, this method calls {@link #invalidate()}; in that case the caller
10755     * should not call {@link #invalidate()}.
10756     * </p>
10757     *
10758     * <p>
10759     * This method should be invoked everytime a subclass directly updates the
10760     * scroll parameters.
10761     * </p>
10762     *
10763     * @param startDelay the delay, in milliseconds, after which the animation
10764     *        should start; when the delay is 0, the animation starts
10765     *        immediately
10766     * @return true if the animation is played, false otherwise
10767     *
10768     * @see #scrollBy(int, int)
10769     * @see #scrollTo(int, int)
10770     * @see #isHorizontalScrollBarEnabled()
10771     * @see #isVerticalScrollBarEnabled()
10772     * @see #setHorizontalScrollBarEnabled(boolean)
10773     * @see #setVerticalScrollBarEnabled(boolean)
10774     */
10775    protected boolean awakenScrollBars(int startDelay) {
10776        return awakenScrollBars(startDelay, true);
10777    }
10778
10779    /**
10780     * <p>
10781     * Trigger the scrollbars to draw. When invoked this method starts an
10782     * animation to fade the scrollbars out after a fixed delay. If a subclass
10783     * provides animated scrolling, the start delay should equal the duration of
10784     * the scrolling animation.
10785     * </p>
10786     *
10787     * <p>
10788     * The animation starts only if at least one of the scrollbars is enabled,
10789     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10790     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10791     * this method returns true, and false otherwise. If the animation is
10792     * started, this method calls {@link #invalidate()} if the invalidate parameter
10793     * is set to true; in that case the caller
10794     * should not call {@link #invalidate()}.
10795     * </p>
10796     *
10797     * <p>
10798     * This method should be invoked everytime a subclass directly updates the
10799     * scroll parameters.
10800     * </p>
10801     *
10802     * @param startDelay the delay, in milliseconds, after which the animation
10803     *        should start; when the delay is 0, the animation starts
10804     *        immediately
10805     *
10806     * @param invalidate Wheter this method should call invalidate
10807     *
10808     * @return true if the animation is played, false otherwise
10809     *
10810     * @see #scrollBy(int, int)
10811     * @see #scrollTo(int, int)
10812     * @see #isHorizontalScrollBarEnabled()
10813     * @see #isVerticalScrollBarEnabled()
10814     * @see #setHorizontalScrollBarEnabled(boolean)
10815     * @see #setVerticalScrollBarEnabled(boolean)
10816     */
10817    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10818        final ScrollabilityCache scrollCache = mScrollCache;
10819
10820        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10821            return false;
10822        }
10823
10824        if (scrollCache.scrollBar == null) {
10825            scrollCache.scrollBar = new ScrollBarDrawable();
10826        }
10827
10828        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10829
10830            if (invalidate) {
10831                // Invalidate to show the scrollbars
10832                postInvalidateOnAnimation();
10833            }
10834
10835            if (scrollCache.state == ScrollabilityCache.OFF) {
10836                // FIXME: this is copied from WindowManagerService.
10837                // We should get this value from the system when it
10838                // is possible to do so.
10839                final int KEY_REPEAT_FIRST_DELAY = 750;
10840                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10841            }
10842
10843            // Tell mScrollCache when we should start fading. This may
10844            // extend the fade start time if one was already scheduled
10845            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10846            scrollCache.fadeStartTime = fadeStartTime;
10847            scrollCache.state = ScrollabilityCache.ON;
10848
10849            // Schedule our fader to run, unscheduling any old ones first
10850            if (mAttachInfo != null) {
10851                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10852                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10853            }
10854
10855            return true;
10856        }
10857
10858        return false;
10859    }
10860
10861    /**
10862     * Do not invalidate views which are not visible and which are not running an animation. They
10863     * will not get drawn and they should not set dirty flags as if they will be drawn
10864     */
10865    private boolean skipInvalidate() {
10866        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10867                (!(mParent instanceof ViewGroup) ||
10868                        !((ViewGroup) mParent).isViewTransitioning(this));
10869    }
10870    /**
10871     * Mark the area defined by dirty as needing to be drawn. If the view is
10872     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10873     * in the future. This must be called from a UI thread. To call from a non-UI
10874     * thread, call {@link #postInvalidate()}.
10875     *
10876     * WARNING: This method is destructive to dirty.
10877     * @param dirty the rectangle representing the bounds of the dirty region
10878     */
10879    public void invalidate(Rect dirty) {
10880        if (skipInvalidate()) {
10881            return;
10882        }
10883        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10884                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10885                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10886            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10887            mPrivateFlags |= PFLAG_INVALIDATED;
10888            mPrivateFlags |= PFLAG_DIRTY;
10889            final ViewParent p = mParent;
10890            final AttachInfo ai = mAttachInfo;
10891            //noinspection PointlessBooleanExpression,ConstantConditions
10892            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10893                if (p != null && ai != null && ai.mHardwareAccelerated) {
10894                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10895                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10896                    p.invalidateChild(this, null);
10897                    return;
10898                }
10899            }
10900            if (p != null && ai != null) {
10901                final int scrollX = mScrollX;
10902                final int scrollY = mScrollY;
10903                final Rect r = ai.mTmpInvalRect;
10904                r.set(dirty.left - scrollX, dirty.top - scrollY,
10905                        dirty.right - scrollX, dirty.bottom - scrollY);
10906                mParent.invalidateChild(this, r);
10907            }
10908        }
10909    }
10910
10911    /**
10912     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10913     * The coordinates of the dirty rect are relative to the view.
10914     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10915     * will be called at some point in the future. This must be called from
10916     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10917     * @param l the left position of the dirty region
10918     * @param t the top position of the dirty region
10919     * @param r the right position of the dirty region
10920     * @param b the bottom position of the dirty region
10921     */
10922    public void invalidate(int l, int t, int r, int b) {
10923        if (skipInvalidate()) {
10924            return;
10925        }
10926        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10927                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10928                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10929            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10930            mPrivateFlags |= PFLAG_INVALIDATED;
10931            mPrivateFlags |= PFLAG_DIRTY;
10932            final ViewParent p = mParent;
10933            final AttachInfo ai = mAttachInfo;
10934            //noinspection PointlessBooleanExpression,ConstantConditions
10935            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10936                if (p != null && ai != null && ai.mHardwareAccelerated) {
10937                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10938                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10939                    p.invalidateChild(this, null);
10940                    return;
10941                }
10942            }
10943            if (p != null && ai != null && l < r && t < b) {
10944                final int scrollX = mScrollX;
10945                final int scrollY = mScrollY;
10946                final Rect tmpr = ai.mTmpInvalRect;
10947                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10948                p.invalidateChild(this, tmpr);
10949            }
10950        }
10951    }
10952
10953    /**
10954     * Invalidate the whole view. If the view is visible,
10955     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10956     * the future. This must be called from a UI thread. To call from a non-UI thread,
10957     * call {@link #postInvalidate()}.
10958     */
10959    public void invalidate() {
10960        invalidate(true);
10961    }
10962
10963    /**
10964     * This is where the invalidate() work actually happens. A full invalidate()
10965     * causes the drawing cache to be invalidated, but this function can be called with
10966     * invalidateCache set to false to skip that invalidation step for cases that do not
10967     * need it (for example, a component that remains at the same dimensions with the same
10968     * content).
10969     *
10970     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10971     * well. This is usually true for a full invalidate, but may be set to false if the
10972     * View's contents or dimensions have not changed.
10973     */
10974    void invalidate(boolean invalidateCache) {
10975        if (skipInvalidate()) {
10976            return;
10977        }
10978        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10979                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10980                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10981            mLastIsOpaque = isOpaque();
10982            mPrivateFlags &= ~PFLAG_DRAWN;
10983            mPrivateFlags |= PFLAG_DIRTY;
10984            if (invalidateCache) {
10985                mPrivateFlags |= PFLAG_INVALIDATED;
10986                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10987            }
10988            final AttachInfo ai = mAttachInfo;
10989            final ViewParent p = mParent;
10990            //noinspection PointlessBooleanExpression,ConstantConditions
10991            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10992                if (p != null && ai != null && ai.mHardwareAccelerated) {
10993                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10994                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10995                    p.invalidateChild(this, null);
10996                    return;
10997                }
10998            }
10999
11000            if (p != null && ai != null) {
11001                final Rect r = ai.mTmpInvalRect;
11002                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11003                // Don't call invalidate -- we don't want to internally scroll
11004                // our own bounds
11005                p.invalidateChild(this, r);
11006            }
11007        }
11008    }
11009
11010    /**
11011     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11012     * set any flags or handle all of the cases handled by the default invalidation methods.
11013     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11014     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11015     * walk up the hierarchy, transforming the dirty rect as necessary.
11016     *
11017     * The method also handles normal invalidation logic if display list properties are not
11018     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11019     * backup approach, to handle these cases used in the various property-setting methods.
11020     *
11021     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11022     * are not being used in this view
11023     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11024     * list properties are not being used in this view
11025     */
11026    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11027        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
11028            if (invalidateParent) {
11029                invalidateParentCaches();
11030            }
11031            if (forceRedraw) {
11032                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11033            }
11034            invalidate(false);
11035        } else {
11036            final AttachInfo ai = mAttachInfo;
11037            final ViewParent p = mParent;
11038            if (p != null && ai != null) {
11039                final Rect r = ai.mTmpInvalRect;
11040                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11041                if (mParent instanceof ViewGroup) {
11042                    ((ViewGroup) mParent).invalidateChildFast(this, r);
11043                } else {
11044                    mParent.invalidateChild(this, r);
11045                }
11046            }
11047        }
11048    }
11049
11050    /**
11051     * Utility method to transform a given Rect by the current matrix of this view.
11052     */
11053    void transformRect(final Rect rect) {
11054        if (!getMatrix().isIdentity()) {
11055            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11056            boundingRect.set(rect);
11057            getMatrix().mapRect(boundingRect);
11058            rect.set((int) Math.floor(boundingRect.left),
11059                    (int) Math.floor(boundingRect.top),
11060                    (int) Math.ceil(boundingRect.right),
11061                    (int) Math.ceil(boundingRect.bottom));
11062        }
11063    }
11064
11065    /**
11066     * Used to indicate that the parent of this view should clear its caches. This functionality
11067     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11068     * which is necessary when various parent-managed properties of the view change, such as
11069     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11070     * clears the parent caches and does not causes an invalidate event.
11071     *
11072     * @hide
11073     */
11074    protected void invalidateParentCaches() {
11075        if (mParent instanceof View) {
11076            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11077        }
11078    }
11079
11080    /**
11081     * Used to indicate that the parent of this view should be invalidated. This functionality
11082     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11083     * which is necessary when various parent-managed properties of the view change, such as
11084     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11085     * an invalidation event to the parent.
11086     *
11087     * @hide
11088     */
11089    protected void invalidateParentIfNeeded() {
11090        if (isHardwareAccelerated() && mParent instanceof View) {
11091            ((View) mParent).invalidate(true);
11092        }
11093    }
11094
11095    /**
11096     * Indicates whether this View is opaque. An opaque View guarantees that it will
11097     * draw all the pixels overlapping its bounds using a fully opaque color.
11098     *
11099     * Subclasses of View should override this method whenever possible to indicate
11100     * whether an instance is opaque. Opaque Views are treated in a special way by
11101     * the View hierarchy, possibly allowing it to perform optimizations during
11102     * invalidate/draw passes.
11103     *
11104     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11105     */
11106    @ViewDebug.ExportedProperty(category = "drawing")
11107    public boolean isOpaque() {
11108        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11109                getFinalAlpha() >= 1.0f;
11110    }
11111
11112    /**
11113     * @hide
11114     */
11115    protected void computeOpaqueFlags() {
11116        // Opaque if:
11117        //   - Has a background
11118        //   - Background is opaque
11119        //   - Doesn't have scrollbars or scrollbars overlay
11120
11121        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11122            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11123        } else {
11124            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11125        }
11126
11127        final int flags = mViewFlags;
11128        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11129                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11130                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11131            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11132        } else {
11133            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11134        }
11135    }
11136
11137    /**
11138     * @hide
11139     */
11140    protected boolean hasOpaqueScrollbars() {
11141        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11142    }
11143
11144    /**
11145     * @return A handler associated with the thread running the View. This
11146     * handler can be used to pump events in the UI events queue.
11147     */
11148    public Handler getHandler() {
11149        final AttachInfo attachInfo = mAttachInfo;
11150        if (attachInfo != null) {
11151            return attachInfo.mHandler;
11152        }
11153        return null;
11154    }
11155
11156    /**
11157     * Gets the view root associated with the View.
11158     * @return The view root, or null if none.
11159     * @hide
11160     */
11161    public ViewRootImpl getViewRootImpl() {
11162        if (mAttachInfo != null) {
11163            return mAttachInfo.mViewRootImpl;
11164        }
11165        return null;
11166    }
11167
11168    /**
11169     * <p>Causes the Runnable to be added to the message queue.
11170     * The runnable will be run on the user interface thread.</p>
11171     *
11172     * @param action The Runnable that will be executed.
11173     *
11174     * @return Returns true if the Runnable was successfully placed in to the
11175     *         message queue.  Returns false on failure, usually because the
11176     *         looper processing the message queue is exiting.
11177     *
11178     * @see #postDelayed
11179     * @see #removeCallbacks
11180     */
11181    public boolean post(Runnable action) {
11182        final AttachInfo attachInfo = mAttachInfo;
11183        if (attachInfo != null) {
11184            return attachInfo.mHandler.post(action);
11185        }
11186        // Assume that post will succeed later
11187        ViewRootImpl.getRunQueue().post(action);
11188        return true;
11189    }
11190
11191    /**
11192     * <p>Causes the Runnable to be added to the message queue, to be run
11193     * after the specified amount of time elapses.
11194     * The runnable will be run on the user interface thread.</p>
11195     *
11196     * @param action The Runnable that will be executed.
11197     * @param delayMillis The delay (in milliseconds) until the Runnable
11198     *        will be executed.
11199     *
11200     * @return true if the Runnable was successfully placed in to the
11201     *         message queue.  Returns false on failure, usually because the
11202     *         looper processing the message queue is exiting.  Note that a
11203     *         result of true does not mean the Runnable will be processed --
11204     *         if the looper is quit before the delivery time of the message
11205     *         occurs then the message will be dropped.
11206     *
11207     * @see #post
11208     * @see #removeCallbacks
11209     */
11210    public boolean postDelayed(Runnable action, long delayMillis) {
11211        final AttachInfo attachInfo = mAttachInfo;
11212        if (attachInfo != null) {
11213            return attachInfo.mHandler.postDelayed(action, delayMillis);
11214        }
11215        // Assume that post will succeed later
11216        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11217        return true;
11218    }
11219
11220    /**
11221     * <p>Causes the Runnable to execute on the next animation time step.
11222     * The runnable will be run on the user interface thread.</p>
11223     *
11224     * @param action The Runnable that will be executed.
11225     *
11226     * @see #postOnAnimationDelayed
11227     * @see #removeCallbacks
11228     */
11229    public void postOnAnimation(Runnable action) {
11230        final AttachInfo attachInfo = mAttachInfo;
11231        if (attachInfo != null) {
11232            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11233                    Choreographer.CALLBACK_ANIMATION, action, null);
11234        } else {
11235            // Assume that post will succeed later
11236            ViewRootImpl.getRunQueue().post(action);
11237        }
11238    }
11239
11240    /**
11241     * <p>Causes the Runnable to execute on the next animation time step,
11242     * after the specified amount of time elapses.
11243     * The runnable will be run on the user interface thread.</p>
11244     *
11245     * @param action The Runnable that will be executed.
11246     * @param delayMillis The delay (in milliseconds) until the Runnable
11247     *        will be executed.
11248     *
11249     * @see #postOnAnimation
11250     * @see #removeCallbacks
11251     */
11252    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11253        final AttachInfo attachInfo = mAttachInfo;
11254        if (attachInfo != null) {
11255            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11256                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11257        } else {
11258            // Assume that post will succeed later
11259            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11260        }
11261    }
11262
11263    /**
11264     * <p>Removes the specified Runnable from the message queue.</p>
11265     *
11266     * @param action The Runnable to remove from the message handling queue
11267     *
11268     * @return true if this view could ask the Handler to remove the Runnable,
11269     *         false otherwise. When the returned value is true, the Runnable
11270     *         may or may not have been actually removed from the message queue
11271     *         (for instance, if the Runnable was not in the queue already.)
11272     *
11273     * @see #post
11274     * @see #postDelayed
11275     * @see #postOnAnimation
11276     * @see #postOnAnimationDelayed
11277     */
11278    public boolean removeCallbacks(Runnable action) {
11279        if (action != null) {
11280            final AttachInfo attachInfo = mAttachInfo;
11281            if (attachInfo != null) {
11282                attachInfo.mHandler.removeCallbacks(action);
11283                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11284                        Choreographer.CALLBACK_ANIMATION, action, null);
11285            } else {
11286                // Assume that post will succeed later
11287                ViewRootImpl.getRunQueue().removeCallbacks(action);
11288            }
11289        }
11290        return true;
11291    }
11292
11293    /**
11294     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11295     * Use this to invalidate the View from a non-UI thread.</p>
11296     *
11297     * <p>This method can be invoked from outside of the UI thread
11298     * only when this View is attached to a window.</p>
11299     *
11300     * @see #invalidate()
11301     * @see #postInvalidateDelayed(long)
11302     */
11303    public void postInvalidate() {
11304        postInvalidateDelayed(0);
11305    }
11306
11307    /**
11308     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11309     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11310     *
11311     * <p>This method can be invoked from outside of the UI thread
11312     * only when this View is attached to a window.</p>
11313     *
11314     * @param left The left coordinate of the rectangle to invalidate.
11315     * @param top The top coordinate of the rectangle to invalidate.
11316     * @param right The right coordinate of the rectangle to invalidate.
11317     * @param bottom The bottom coordinate of the rectangle to invalidate.
11318     *
11319     * @see #invalidate(int, int, int, int)
11320     * @see #invalidate(Rect)
11321     * @see #postInvalidateDelayed(long, int, int, int, int)
11322     */
11323    public void postInvalidate(int left, int top, int right, int bottom) {
11324        postInvalidateDelayed(0, left, top, right, bottom);
11325    }
11326
11327    /**
11328     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11329     * loop. Waits for the specified amount of time.</p>
11330     *
11331     * <p>This method can be invoked from outside of the UI thread
11332     * only when this View is attached to a window.</p>
11333     *
11334     * @param delayMilliseconds the duration in milliseconds to delay the
11335     *         invalidation by
11336     *
11337     * @see #invalidate()
11338     * @see #postInvalidate()
11339     */
11340    public void postInvalidateDelayed(long delayMilliseconds) {
11341        // We try only with the AttachInfo because there's no point in invalidating
11342        // if we are not attached to our window
11343        final AttachInfo attachInfo = mAttachInfo;
11344        if (attachInfo != null) {
11345            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11346        }
11347    }
11348
11349    /**
11350     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11351     * through the event loop. Waits for the specified amount of time.</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 delayMilliseconds the duration in milliseconds to delay the
11357     *         invalidation by
11358     * @param left The left coordinate of the rectangle to invalidate.
11359     * @param top The top coordinate of the rectangle to invalidate.
11360     * @param right The right coordinate of the rectangle to invalidate.
11361     * @param bottom The bottom coordinate of the rectangle to invalidate.
11362     *
11363     * @see #invalidate(int, int, int, int)
11364     * @see #invalidate(Rect)
11365     * @see #postInvalidate(int, int, int, int)
11366     */
11367    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11368            int right, int bottom) {
11369
11370        // We try only with the AttachInfo because there's no point in invalidating
11371        // if we are not attached to our window
11372        final AttachInfo attachInfo = mAttachInfo;
11373        if (attachInfo != null) {
11374            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11375            info.target = this;
11376            info.left = left;
11377            info.top = top;
11378            info.right = right;
11379            info.bottom = bottom;
11380
11381            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11382        }
11383    }
11384
11385    /**
11386     * <p>Cause an invalidate to happen on the next animation time step, typically the
11387     * next display frame.</p>
11388     *
11389     * <p>This method can be invoked from outside of the UI thread
11390     * only when this View is attached to a window.</p>
11391     *
11392     * @see #invalidate()
11393     */
11394    public void postInvalidateOnAnimation() {
11395        // We try only with the AttachInfo because there's no point in invalidating
11396        // if we are not attached to our window
11397        final AttachInfo attachInfo = mAttachInfo;
11398        if (attachInfo != null) {
11399            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11400        }
11401    }
11402
11403    /**
11404     * <p>Cause an invalidate of the specified area to happen on the next animation
11405     * time step, typically the next display frame.</p>
11406     *
11407     * <p>This method can be invoked from outside of the UI thread
11408     * only when this View is attached to a window.</p>
11409     *
11410     * @param left The left coordinate of the rectangle to invalidate.
11411     * @param top The top coordinate of the rectangle to invalidate.
11412     * @param right The right coordinate of the rectangle to invalidate.
11413     * @param bottom The bottom coordinate of the rectangle to invalidate.
11414     *
11415     * @see #invalidate(int, int, int, int)
11416     * @see #invalidate(Rect)
11417     */
11418    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11419        // We try only with the AttachInfo because there's no point in invalidating
11420        // if we are not attached to our window
11421        final AttachInfo attachInfo = mAttachInfo;
11422        if (attachInfo != null) {
11423            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11424            info.target = this;
11425            info.left = left;
11426            info.top = top;
11427            info.right = right;
11428            info.bottom = bottom;
11429
11430            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11431        }
11432    }
11433
11434    /**
11435     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11436     * This event is sent at most once every
11437     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11438     */
11439    private void postSendViewScrolledAccessibilityEventCallback() {
11440        if (mSendViewScrolledAccessibilityEvent == null) {
11441            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11442        }
11443        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11444            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11445            postDelayed(mSendViewScrolledAccessibilityEvent,
11446                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11447        }
11448    }
11449
11450    /**
11451     * Called by a parent to request that a child update its values for mScrollX
11452     * and mScrollY if necessary. This will typically be done if the child is
11453     * animating a scroll using a {@link android.widget.Scroller Scroller}
11454     * object.
11455     */
11456    public void computeScroll() {
11457    }
11458
11459    /**
11460     * <p>Indicate whether the horizontal edges are faded when the view is
11461     * scrolled horizontally.</p>
11462     *
11463     * @return true if the horizontal edges should are faded on scroll, false
11464     *         otherwise
11465     *
11466     * @see #setHorizontalFadingEdgeEnabled(boolean)
11467     *
11468     * @attr ref android.R.styleable#View_requiresFadingEdge
11469     */
11470    public boolean isHorizontalFadingEdgeEnabled() {
11471        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11472    }
11473
11474    /**
11475     * <p>Define whether the horizontal edges should be faded when this view
11476     * is scrolled horizontally.</p>
11477     *
11478     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11479     *                                    be faded when the view is scrolled
11480     *                                    horizontally
11481     *
11482     * @see #isHorizontalFadingEdgeEnabled()
11483     *
11484     * @attr ref android.R.styleable#View_requiresFadingEdge
11485     */
11486    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11487        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11488            if (horizontalFadingEdgeEnabled) {
11489                initScrollCache();
11490            }
11491
11492            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11493        }
11494    }
11495
11496    /**
11497     * <p>Indicate whether the vertical edges are faded when the view is
11498     * scrolled horizontally.</p>
11499     *
11500     * @return true if the vertical edges should are faded on scroll, false
11501     *         otherwise
11502     *
11503     * @see #setVerticalFadingEdgeEnabled(boolean)
11504     *
11505     * @attr ref android.R.styleable#View_requiresFadingEdge
11506     */
11507    public boolean isVerticalFadingEdgeEnabled() {
11508        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11509    }
11510
11511    /**
11512     * <p>Define whether the vertical edges should be faded when this view
11513     * is scrolled vertically.</p>
11514     *
11515     * @param verticalFadingEdgeEnabled true if the vertical edges should
11516     *                                  be faded when the view is scrolled
11517     *                                  vertically
11518     *
11519     * @see #isVerticalFadingEdgeEnabled()
11520     *
11521     * @attr ref android.R.styleable#View_requiresFadingEdge
11522     */
11523    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11524        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11525            if (verticalFadingEdgeEnabled) {
11526                initScrollCache();
11527            }
11528
11529            mViewFlags ^= FADING_EDGE_VERTICAL;
11530        }
11531    }
11532
11533    /**
11534     * Returns the strength, or intensity, of the top faded edge. The strength is
11535     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11536     * returns 0.0 or 1.0 but no value in between.
11537     *
11538     * Subclasses should override this method to provide a smoother fade transition
11539     * when scrolling occurs.
11540     *
11541     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11542     */
11543    protected float getTopFadingEdgeStrength() {
11544        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11545    }
11546
11547    /**
11548     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11549     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11550     * returns 0.0 or 1.0 but no value in between.
11551     *
11552     * Subclasses should override this method to provide a smoother fade transition
11553     * when scrolling occurs.
11554     *
11555     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11556     */
11557    protected float getBottomFadingEdgeStrength() {
11558        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11559                computeVerticalScrollRange() ? 1.0f : 0.0f;
11560    }
11561
11562    /**
11563     * Returns the strength, or intensity, of the left faded edge. The strength is
11564     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11565     * returns 0.0 or 1.0 but no value in between.
11566     *
11567     * Subclasses should override this method to provide a smoother fade transition
11568     * when scrolling occurs.
11569     *
11570     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11571     */
11572    protected float getLeftFadingEdgeStrength() {
11573        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11574    }
11575
11576    /**
11577     * Returns the strength, or intensity, of the right faded edge. The strength is
11578     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11579     * returns 0.0 or 1.0 but no value in between.
11580     *
11581     * Subclasses should override this method to provide a smoother fade transition
11582     * when scrolling occurs.
11583     *
11584     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11585     */
11586    protected float getRightFadingEdgeStrength() {
11587        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11588                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11589    }
11590
11591    /**
11592     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11593     * scrollbar is not drawn by default.</p>
11594     *
11595     * @return true if the horizontal scrollbar should be painted, false
11596     *         otherwise
11597     *
11598     * @see #setHorizontalScrollBarEnabled(boolean)
11599     */
11600    public boolean isHorizontalScrollBarEnabled() {
11601        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11602    }
11603
11604    /**
11605     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11606     * scrollbar is not drawn by default.</p>
11607     *
11608     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11609     *                                   be painted
11610     *
11611     * @see #isHorizontalScrollBarEnabled()
11612     */
11613    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11614        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11615            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11616            computeOpaqueFlags();
11617            resolvePadding();
11618        }
11619    }
11620
11621    /**
11622     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11623     * scrollbar is not drawn by default.</p>
11624     *
11625     * @return true if the vertical scrollbar should be painted, false
11626     *         otherwise
11627     *
11628     * @see #setVerticalScrollBarEnabled(boolean)
11629     */
11630    public boolean isVerticalScrollBarEnabled() {
11631        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11632    }
11633
11634    /**
11635     * <p>Define whether the vertical scrollbar should be drawn or not. The
11636     * scrollbar is not drawn by default.</p>
11637     *
11638     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11639     *                                 be painted
11640     *
11641     * @see #isVerticalScrollBarEnabled()
11642     */
11643    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11644        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11645            mViewFlags ^= SCROLLBARS_VERTICAL;
11646            computeOpaqueFlags();
11647            resolvePadding();
11648        }
11649    }
11650
11651    /**
11652     * @hide
11653     */
11654    protected void recomputePadding() {
11655        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11656    }
11657
11658    /**
11659     * Define whether scrollbars will fade when the view is not scrolling.
11660     *
11661     * @param fadeScrollbars wheter to enable fading
11662     *
11663     * @attr ref android.R.styleable#View_fadeScrollbars
11664     */
11665    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11666        initScrollCache();
11667        final ScrollabilityCache scrollabilityCache = mScrollCache;
11668        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11669        if (fadeScrollbars) {
11670            scrollabilityCache.state = ScrollabilityCache.OFF;
11671        } else {
11672            scrollabilityCache.state = ScrollabilityCache.ON;
11673        }
11674    }
11675
11676    /**
11677     *
11678     * Returns true if scrollbars will fade when this view is not scrolling
11679     *
11680     * @return true if scrollbar fading is enabled
11681     *
11682     * @attr ref android.R.styleable#View_fadeScrollbars
11683     */
11684    public boolean isScrollbarFadingEnabled() {
11685        return mScrollCache != null && mScrollCache.fadeScrollBars;
11686    }
11687
11688    /**
11689     *
11690     * Returns the delay before scrollbars fade.
11691     *
11692     * @return the delay before scrollbars fade
11693     *
11694     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11695     */
11696    public int getScrollBarDefaultDelayBeforeFade() {
11697        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11698                mScrollCache.scrollBarDefaultDelayBeforeFade;
11699    }
11700
11701    /**
11702     * Define the delay before scrollbars fade.
11703     *
11704     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11705     *
11706     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11707     */
11708    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11709        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11710    }
11711
11712    /**
11713     *
11714     * Returns the scrollbar fade duration.
11715     *
11716     * @return the scrollbar fade duration
11717     *
11718     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11719     */
11720    public int getScrollBarFadeDuration() {
11721        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11722                mScrollCache.scrollBarFadeDuration;
11723    }
11724
11725    /**
11726     * Define the scrollbar fade duration.
11727     *
11728     * @param scrollBarFadeDuration - the scrollbar fade duration
11729     *
11730     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11731     */
11732    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11733        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11734    }
11735
11736    /**
11737     *
11738     * Returns the scrollbar size.
11739     *
11740     * @return the scrollbar size
11741     *
11742     * @attr ref android.R.styleable#View_scrollbarSize
11743     */
11744    public int getScrollBarSize() {
11745        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11746                mScrollCache.scrollBarSize;
11747    }
11748
11749    /**
11750     * Define the scrollbar size.
11751     *
11752     * @param scrollBarSize - the scrollbar size
11753     *
11754     * @attr ref android.R.styleable#View_scrollbarSize
11755     */
11756    public void setScrollBarSize(int scrollBarSize) {
11757        getScrollCache().scrollBarSize = scrollBarSize;
11758    }
11759
11760    /**
11761     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11762     * inset. When inset, they add to the padding of the view. And the scrollbars
11763     * can be drawn inside the padding area or on the edge of the view. For example,
11764     * if a view has a background drawable and you want to draw the scrollbars
11765     * inside the padding specified by the drawable, you can use
11766     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11767     * appear at the edge of the view, ignoring the padding, then you can use
11768     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11769     * @param style the style of the scrollbars. Should be one of
11770     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11771     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11772     * @see #SCROLLBARS_INSIDE_OVERLAY
11773     * @see #SCROLLBARS_INSIDE_INSET
11774     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11775     * @see #SCROLLBARS_OUTSIDE_INSET
11776     *
11777     * @attr ref android.R.styleable#View_scrollbarStyle
11778     */
11779    public void setScrollBarStyle(@ScrollBarStyle int style) {
11780        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11781            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11782            computeOpaqueFlags();
11783            resolvePadding();
11784        }
11785    }
11786
11787    /**
11788     * <p>Returns the current scrollbar style.</p>
11789     * @return the current scrollbar style
11790     * @see #SCROLLBARS_INSIDE_OVERLAY
11791     * @see #SCROLLBARS_INSIDE_INSET
11792     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11793     * @see #SCROLLBARS_OUTSIDE_INSET
11794     *
11795     * @attr ref android.R.styleable#View_scrollbarStyle
11796     */
11797    @ViewDebug.ExportedProperty(mapping = {
11798            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11799            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11800            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11801            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11802    })
11803    @ScrollBarStyle
11804    public int getScrollBarStyle() {
11805        return mViewFlags & SCROLLBARS_STYLE_MASK;
11806    }
11807
11808    /**
11809     * <p>Compute the horizontal range that the horizontal scrollbar
11810     * represents.</p>
11811     *
11812     * <p>The range is expressed in arbitrary units that must be the same as the
11813     * units used by {@link #computeHorizontalScrollExtent()} and
11814     * {@link #computeHorizontalScrollOffset()}.</p>
11815     *
11816     * <p>The default range is the drawing width of this view.</p>
11817     *
11818     * @return the total horizontal range represented by the horizontal
11819     *         scrollbar
11820     *
11821     * @see #computeHorizontalScrollExtent()
11822     * @see #computeHorizontalScrollOffset()
11823     * @see android.widget.ScrollBarDrawable
11824     */
11825    protected int computeHorizontalScrollRange() {
11826        return getWidth();
11827    }
11828
11829    /**
11830     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11831     * within the horizontal range. This value is used to compute the position
11832     * of the thumb within the scrollbar's track.</p>
11833     *
11834     * <p>The range is expressed in arbitrary units that must be the same as the
11835     * units used by {@link #computeHorizontalScrollRange()} and
11836     * {@link #computeHorizontalScrollExtent()}.</p>
11837     *
11838     * <p>The default offset is the scroll offset of this view.</p>
11839     *
11840     * @return the horizontal offset of the scrollbar's thumb
11841     *
11842     * @see #computeHorizontalScrollRange()
11843     * @see #computeHorizontalScrollExtent()
11844     * @see android.widget.ScrollBarDrawable
11845     */
11846    protected int computeHorizontalScrollOffset() {
11847        return mScrollX;
11848    }
11849
11850    /**
11851     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11852     * within the horizontal range. This value is used to compute the length
11853     * of the thumb within the scrollbar's track.</p>
11854     *
11855     * <p>The range is expressed in arbitrary units that must be the same as the
11856     * units used by {@link #computeHorizontalScrollRange()} and
11857     * {@link #computeHorizontalScrollOffset()}.</p>
11858     *
11859     * <p>The default extent is the drawing width of this view.</p>
11860     *
11861     * @return the horizontal extent of the scrollbar's thumb
11862     *
11863     * @see #computeHorizontalScrollRange()
11864     * @see #computeHorizontalScrollOffset()
11865     * @see android.widget.ScrollBarDrawable
11866     */
11867    protected int computeHorizontalScrollExtent() {
11868        return getWidth();
11869    }
11870
11871    /**
11872     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11873     *
11874     * <p>The range is expressed in arbitrary units that must be the same as the
11875     * units used by {@link #computeVerticalScrollExtent()} and
11876     * {@link #computeVerticalScrollOffset()}.</p>
11877     *
11878     * @return the total vertical range represented by the vertical scrollbar
11879     *
11880     * <p>The default range is the drawing height of this view.</p>
11881     *
11882     * @see #computeVerticalScrollExtent()
11883     * @see #computeVerticalScrollOffset()
11884     * @see android.widget.ScrollBarDrawable
11885     */
11886    protected int computeVerticalScrollRange() {
11887        return getHeight();
11888    }
11889
11890    /**
11891     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11892     * within the horizontal range. This value is used to compute the position
11893     * of the thumb within the scrollbar's track.</p>
11894     *
11895     * <p>The range is expressed in arbitrary units that must be the same as the
11896     * units used by {@link #computeVerticalScrollRange()} and
11897     * {@link #computeVerticalScrollExtent()}.</p>
11898     *
11899     * <p>The default offset is the scroll offset of this view.</p>
11900     *
11901     * @return the vertical offset of the scrollbar's thumb
11902     *
11903     * @see #computeVerticalScrollRange()
11904     * @see #computeVerticalScrollExtent()
11905     * @see android.widget.ScrollBarDrawable
11906     */
11907    protected int computeVerticalScrollOffset() {
11908        return mScrollY;
11909    }
11910
11911    /**
11912     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11913     * within the vertical range. This value is used to compute the length
11914     * of the thumb within the scrollbar's track.</p>
11915     *
11916     * <p>The range is expressed in arbitrary units that must be the same as the
11917     * units used by {@link #computeVerticalScrollRange()} and
11918     * {@link #computeVerticalScrollOffset()}.</p>
11919     *
11920     * <p>The default extent is the drawing height of this view.</p>
11921     *
11922     * @return the vertical extent of the scrollbar's thumb
11923     *
11924     * @see #computeVerticalScrollRange()
11925     * @see #computeVerticalScrollOffset()
11926     * @see android.widget.ScrollBarDrawable
11927     */
11928    protected int computeVerticalScrollExtent() {
11929        return getHeight();
11930    }
11931
11932    /**
11933     * Check if this view can be scrolled horizontally in a certain direction.
11934     *
11935     * @param direction Negative to check scrolling left, positive to check scrolling right.
11936     * @return true if this view can be scrolled in the specified direction, false otherwise.
11937     */
11938    public boolean canScrollHorizontally(int direction) {
11939        final int offset = computeHorizontalScrollOffset();
11940        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11941        if (range == 0) return false;
11942        if (direction < 0) {
11943            return offset > 0;
11944        } else {
11945            return offset < range - 1;
11946        }
11947    }
11948
11949    /**
11950     * Check if this view can be scrolled vertically in a certain direction.
11951     *
11952     * @param direction Negative to check scrolling up, positive to check scrolling down.
11953     * @return true if this view can be scrolled in the specified direction, false otherwise.
11954     */
11955    public boolean canScrollVertically(int direction) {
11956        final int offset = computeVerticalScrollOffset();
11957        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11958        if (range == 0) return false;
11959        if (direction < 0) {
11960            return offset > 0;
11961        } else {
11962            return offset < range - 1;
11963        }
11964    }
11965
11966    /**
11967     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11968     * scrollbars are painted only if they have been awakened first.</p>
11969     *
11970     * @param canvas the canvas on which to draw the scrollbars
11971     *
11972     * @see #awakenScrollBars(int)
11973     */
11974    protected final void onDrawScrollBars(Canvas canvas) {
11975        // scrollbars are drawn only when the animation is running
11976        final ScrollabilityCache cache = mScrollCache;
11977        if (cache != null) {
11978
11979            int state = cache.state;
11980
11981            if (state == ScrollabilityCache.OFF) {
11982                return;
11983            }
11984
11985            boolean invalidate = false;
11986
11987            if (state == ScrollabilityCache.FADING) {
11988                // We're fading -- get our fade interpolation
11989                if (cache.interpolatorValues == null) {
11990                    cache.interpolatorValues = new float[1];
11991                }
11992
11993                float[] values = cache.interpolatorValues;
11994
11995                // Stops the animation if we're done
11996                if (cache.scrollBarInterpolator.timeToValues(values) ==
11997                        Interpolator.Result.FREEZE_END) {
11998                    cache.state = ScrollabilityCache.OFF;
11999                } else {
12000                    cache.scrollBar.setAlpha(Math.round(values[0]));
12001                }
12002
12003                // This will make the scroll bars inval themselves after
12004                // drawing. We only want this when we're fading so that
12005                // we prevent excessive redraws
12006                invalidate = true;
12007            } else {
12008                // We're just on -- but we may have been fading before so
12009                // reset alpha
12010                cache.scrollBar.setAlpha(255);
12011            }
12012
12013
12014            final int viewFlags = mViewFlags;
12015
12016            final boolean drawHorizontalScrollBar =
12017                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12018            final boolean drawVerticalScrollBar =
12019                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12020                && !isVerticalScrollBarHidden();
12021
12022            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12023                final int width = mRight - mLeft;
12024                final int height = mBottom - mTop;
12025
12026                final ScrollBarDrawable scrollBar = cache.scrollBar;
12027
12028                final int scrollX = mScrollX;
12029                final int scrollY = mScrollY;
12030                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12031
12032                int left;
12033                int top;
12034                int right;
12035                int bottom;
12036
12037                if (drawHorizontalScrollBar) {
12038                    int size = scrollBar.getSize(false);
12039                    if (size <= 0) {
12040                        size = cache.scrollBarSize;
12041                    }
12042
12043                    scrollBar.setParameters(computeHorizontalScrollRange(),
12044                                            computeHorizontalScrollOffset(),
12045                                            computeHorizontalScrollExtent(), false);
12046                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12047                            getVerticalScrollbarWidth() : 0;
12048                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12049                    left = scrollX + (mPaddingLeft & inside);
12050                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12051                    bottom = top + size;
12052                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12053                    if (invalidate) {
12054                        invalidate(left, top, right, bottom);
12055                    }
12056                }
12057
12058                if (drawVerticalScrollBar) {
12059                    int size = scrollBar.getSize(true);
12060                    if (size <= 0) {
12061                        size = cache.scrollBarSize;
12062                    }
12063
12064                    scrollBar.setParameters(computeVerticalScrollRange(),
12065                                            computeVerticalScrollOffset(),
12066                                            computeVerticalScrollExtent(), true);
12067                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12068                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12069                        verticalScrollbarPosition = isLayoutRtl() ?
12070                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12071                    }
12072                    switch (verticalScrollbarPosition) {
12073                        default:
12074                        case SCROLLBAR_POSITION_RIGHT:
12075                            left = scrollX + width - size - (mUserPaddingRight & inside);
12076                            break;
12077                        case SCROLLBAR_POSITION_LEFT:
12078                            left = scrollX + (mUserPaddingLeft & inside);
12079                            break;
12080                    }
12081                    top = scrollY + (mPaddingTop & inside);
12082                    right = left + size;
12083                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12084                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12085                    if (invalidate) {
12086                        invalidate(left, top, right, bottom);
12087                    }
12088                }
12089            }
12090        }
12091    }
12092
12093    /**
12094     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12095     * FastScroller is visible.
12096     * @return whether to temporarily hide the vertical scrollbar
12097     * @hide
12098     */
12099    protected boolean isVerticalScrollBarHidden() {
12100        return false;
12101    }
12102
12103    /**
12104     * <p>Draw the horizontal scrollbar if
12105     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12106     *
12107     * @param canvas the canvas on which to draw the scrollbar
12108     * @param scrollBar the scrollbar's drawable
12109     *
12110     * @see #isHorizontalScrollBarEnabled()
12111     * @see #computeHorizontalScrollRange()
12112     * @see #computeHorizontalScrollExtent()
12113     * @see #computeHorizontalScrollOffset()
12114     * @see android.widget.ScrollBarDrawable
12115     * @hide
12116     */
12117    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12118            int l, int t, int r, int b) {
12119        scrollBar.setBounds(l, t, r, b);
12120        scrollBar.draw(canvas);
12121    }
12122
12123    /**
12124     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12125     * returns true.</p>
12126     *
12127     * @param canvas the canvas on which to draw the scrollbar
12128     * @param scrollBar the scrollbar's drawable
12129     *
12130     * @see #isVerticalScrollBarEnabled()
12131     * @see #computeVerticalScrollRange()
12132     * @see #computeVerticalScrollExtent()
12133     * @see #computeVerticalScrollOffset()
12134     * @see android.widget.ScrollBarDrawable
12135     * @hide
12136     */
12137    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12138            int l, int t, int r, int b) {
12139        scrollBar.setBounds(l, t, r, b);
12140        scrollBar.draw(canvas);
12141    }
12142
12143    /**
12144     * Implement this to do your drawing.
12145     *
12146     * @param canvas the canvas on which the background will be drawn
12147     */
12148    protected void onDraw(Canvas canvas) {
12149    }
12150
12151    /*
12152     * Caller is responsible for calling requestLayout if necessary.
12153     * (This allows addViewInLayout to not request a new layout.)
12154     */
12155    void assignParent(ViewParent parent) {
12156        if (mParent == null) {
12157            mParent = parent;
12158        } else if (parent == null) {
12159            mParent = null;
12160        } else {
12161            throw new RuntimeException("view " + this + " being added, but"
12162                    + " it already has a parent");
12163        }
12164    }
12165
12166    /**
12167     * This is called when the view is attached to a window.  At this point it
12168     * has a Surface and will start drawing.  Note that this function is
12169     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12170     * however it may be called any time before the first onDraw -- including
12171     * before or after {@link #onMeasure(int, int)}.
12172     *
12173     * @see #onDetachedFromWindow()
12174     */
12175    protected void onAttachedToWindow() {
12176        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12177            mParent.requestTransparentRegion(this);
12178        }
12179
12180        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12181            initialAwakenScrollBars();
12182            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12183        }
12184
12185        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12186
12187        jumpDrawablesToCurrentState();
12188
12189        resetSubtreeAccessibilityStateChanged();
12190
12191        if (isFocused()) {
12192            InputMethodManager imm = InputMethodManager.peekInstance();
12193            imm.focusIn(this);
12194        }
12195
12196        if (mDisplayList != null) {
12197            mDisplayList.clearDirty();
12198        }
12199    }
12200
12201    /**
12202     * Resolve all RTL related properties.
12203     *
12204     * @return true if resolution of RTL properties has been done
12205     *
12206     * @hide
12207     */
12208    public boolean resolveRtlPropertiesIfNeeded() {
12209        if (!needRtlPropertiesResolution()) return false;
12210
12211        // Order is important here: LayoutDirection MUST be resolved first
12212        if (!isLayoutDirectionResolved()) {
12213            resolveLayoutDirection();
12214            resolveLayoutParams();
12215        }
12216        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12217        if (!isTextDirectionResolved()) {
12218            resolveTextDirection();
12219        }
12220        if (!isTextAlignmentResolved()) {
12221            resolveTextAlignment();
12222        }
12223        if (!isPaddingResolved()) {
12224            resolvePadding();
12225        }
12226        if (!isDrawablesResolved()) {
12227            resolveDrawables();
12228        }
12229        onRtlPropertiesChanged(getLayoutDirection());
12230        return true;
12231    }
12232
12233    /**
12234     * Reset resolution of all RTL related properties.
12235     *
12236     * @hide
12237     */
12238    public void resetRtlProperties() {
12239        resetResolvedLayoutDirection();
12240        resetResolvedTextDirection();
12241        resetResolvedTextAlignment();
12242        resetResolvedPadding();
12243        resetResolvedDrawables();
12244    }
12245
12246    /**
12247     * @see #onScreenStateChanged(int)
12248     */
12249    void dispatchScreenStateChanged(int screenState) {
12250        onScreenStateChanged(screenState);
12251    }
12252
12253    /**
12254     * This method is called whenever the state of the screen this view is
12255     * attached to changes. A state change will usually occurs when the screen
12256     * turns on or off (whether it happens automatically or the user does it
12257     * manually.)
12258     *
12259     * @param screenState The new state of the screen. Can be either
12260     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12261     */
12262    public void onScreenStateChanged(int screenState) {
12263    }
12264
12265    /**
12266     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12267     */
12268    private boolean hasRtlSupport() {
12269        return mContext.getApplicationInfo().hasRtlSupport();
12270    }
12271
12272    /**
12273     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12274     * RTL not supported)
12275     */
12276    private boolean isRtlCompatibilityMode() {
12277        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12278        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12279    }
12280
12281    /**
12282     * @return true if RTL properties need resolution.
12283     *
12284     */
12285    private boolean needRtlPropertiesResolution() {
12286        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12287    }
12288
12289    /**
12290     * Called when any RTL property (layout direction or text direction or text alignment) has
12291     * been changed.
12292     *
12293     * Subclasses need to override this method to take care of cached information that depends on the
12294     * resolved layout direction, or to inform child views that inherit their layout direction.
12295     *
12296     * The default implementation does nothing.
12297     *
12298     * @param layoutDirection the direction of the layout
12299     *
12300     * @see #LAYOUT_DIRECTION_LTR
12301     * @see #LAYOUT_DIRECTION_RTL
12302     */
12303    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12304    }
12305
12306    /**
12307     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12308     * that the parent directionality can and will be resolved before its children.
12309     *
12310     * @return true if resolution has been done, false otherwise.
12311     *
12312     * @hide
12313     */
12314    public boolean resolveLayoutDirection() {
12315        // Clear any previous layout direction resolution
12316        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12317
12318        if (hasRtlSupport()) {
12319            // Set resolved depending on layout direction
12320            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12321                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12322                case LAYOUT_DIRECTION_INHERIT:
12323                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12324                    // later to get the correct resolved value
12325                    if (!canResolveLayoutDirection()) return false;
12326
12327                    // Parent has not yet resolved, LTR is still the default
12328                    try {
12329                        if (!mParent.isLayoutDirectionResolved()) return false;
12330
12331                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12332                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12333                        }
12334                    } catch (AbstractMethodError e) {
12335                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12336                                " does not fully implement ViewParent", e);
12337                    }
12338                    break;
12339                case LAYOUT_DIRECTION_RTL:
12340                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12341                    break;
12342                case LAYOUT_DIRECTION_LOCALE:
12343                    if((LAYOUT_DIRECTION_RTL ==
12344                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12345                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12346                    }
12347                    break;
12348                default:
12349                    // Nothing to do, LTR by default
12350            }
12351        }
12352
12353        // Set to resolved
12354        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12355        return true;
12356    }
12357
12358    /**
12359     * Check if layout direction resolution can be done.
12360     *
12361     * @return true if layout direction resolution can be done otherwise return false.
12362     */
12363    public boolean canResolveLayoutDirection() {
12364        switch (getRawLayoutDirection()) {
12365            case LAYOUT_DIRECTION_INHERIT:
12366                if (mParent != null) {
12367                    try {
12368                        return mParent.canResolveLayoutDirection();
12369                    } catch (AbstractMethodError e) {
12370                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12371                                " does not fully implement ViewParent", e);
12372                    }
12373                }
12374                return false;
12375
12376            default:
12377                return true;
12378        }
12379    }
12380
12381    /**
12382     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12383     * {@link #onMeasure(int, int)}.
12384     *
12385     * @hide
12386     */
12387    public void resetResolvedLayoutDirection() {
12388        // Reset the current resolved bits
12389        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12390    }
12391
12392    /**
12393     * @return true if the layout direction is inherited.
12394     *
12395     * @hide
12396     */
12397    public boolean isLayoutDirectionInherited() {
12398        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12399    }
12400
12401    /**
12402     * @return true if layout direction has been resolved.
12403     */
12404    public boolean isLayoutDirectionResolved() {
12405        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12406    }
12407
12408    /**
12409     * Return if padding has been resolved
12410     *
12411     * @hide
12412     */
12413    boolean isPaddingResolved() {
12414        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12415    }
12416
12417    /**
12418     * Resolves padding depending on layout direction, if applicable, and
12419     * recomputes internal padding values to adjust for scroll bars.
12420     *
12421     * @hide
12422     */
12423    public void resolvePadding() {
12424        final int resolvedLayoutDirection = getLayoutDirection();
12425
12426        if (!isRtlCompatibilityMode()) {
12427            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12428            // If start / end padding are defined, they will be resolved (hence overriding) to
12429            // left / right or right / left depending on the resolved layout direction.
12430            // If start / end padding are not defined, use the left / right ones.
12431            switch (resolvedLayoutDirection) {
12432                case LAYOUT_DIRECTION_RTL:
12433                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12434                        mUserPaddingRight = mUserPaddingStart;
12435                    } else {
12436                        mUserPaddingRight = mUserPaddingRightInitial;
12437                    }
12438                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12439                        mUserPaddingLeft = mUserPaddingEnd;
12440                    } else {
12441                        mUserPaddingLeft = mUserPaddingLeftInitial;
12442                    }
12443                    break;
12444                case LAYOUT_DIRECTION_LTR:
12445                default:
12446                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12447                        mUserPaddingLeft = mUserPaddingStart;
12448                    } else {
12449                        mUserPaddingLeft = mUserPaddingLeftInitial;
12450                    }
12451                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12452                        mUserPaddingRight = mUserPaddingEnd;
12453                    } else {
12454                        mUserPaddingRight = mUserPaddingRightInitial;
12455                    }
12456            }
12457
12458            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12459        }
12460
12461        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12462        onRtlPropertiesChanged(resolvedLayoutDirection);
12463
12464        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12465    }
12466
12467    /**
12468     * Reset the resolved layout direction.
12469     *
12470     * @hide
12471     */
12472    public void resetResolvedPadding() {
12473        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12474    }
12475
12476    /**
12477     * This is called when the view is detached from a window.  At this point it
12478     * no longer has a surface for drawing.
12479     *
12480     * @see #onAttachedToWindow()
12481     */
12482    protected void onDetachedFromWindow() {
12483        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12484        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12485
12486        removeUnsetPressCallback();
12487        removeLongPressCallback();
12488        removePerformClickCallback();
12489        removeSendViewScrolledAccessibilityEventCallback();
12490
12491        destroyDrawingCache();
12492        destroyLayer(false);
12493
12494        cleanupDraw();
12495
12496        mCurrentAnimation = null;
12497    }
12498
12499    private void cleanupDraw() {
12500        if (mAttachInfo != null) {
12501            if (mDisplayList != null) {
12502                mDisplayList.markDirty();
12503                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12504            }
12505            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12506        } else {
12507            // Should never happen
12508            resetDisplayList();
12509        }
12510    }
12511
12512    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12513    }
12514
12515    /**
12516     * @return The number of times this view has been attached to a window
12517     */
12518    protected int getWindowAttachCount() {
12519        return mWindowAttachCount;
12520    }
12521
12522    /**
12523     * Retrieve a unique token identifying the window this view is attached to.
12524     * @return Return the window's token for use in
12525     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12526     */
12527    public IBinder getWindowToken() {
12528        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12529    }
12530
12531    /**
12532     * Retrieve the {@link WindowId} for the window this view is
12533     * currently attached to.
12534     */
12535    public WindowId getWindowId() {
12536        if (mAttachInfo == null) {
12537            return null;
12538        }
12539        if (mAttachInfo.mWindowId == null) {
12540            try {
12541                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12542                        mAttachInfo.mWindowToken);
12543                mAttachInfo.mWindowId = new WindowId(
12544                        mAttachInfo.mIWindowId);
12545            } catch (RemoteException e) {
12546            }
12547        }
12548        return mAttachInfo.mWindowId;
12549    }
12550
12551    /**
12552     * Retrieve a unique token identifying the top-level "real" window of
12553     * the window that this view is attached to.  That is, this is like
12554     * {@link #getWindowToken}, except if the window this view in is a panel
12555     * window (attached to another containing window), then the token of
12556     * the containing window is returned instead.
12557     *
12558     * @return Returns the associated window token, either
12559     * {@link #getWindowToken()} or the containing window's token.
12560     */
12561    public IBinder getApplicationWindowToken() {
12562        AttachInfo ai = mAttachInfo;
12563        if (ai != null) {
12564            IBinder appWindowToken = ai.mPanelParentWindowToken;
12565            if (appWindowToken == null) {
12566                appWindowToken = ai.mWindowToken;
12567            }
12568            return appWindowToken;
12569        }
12570        return null;
12571    }
12572
12573    /**
12574     * Gets the logical display to which the view's window has been attached.
12575     *
12576     * @return The logical display, or null if the view is not currently attached to a window.
12577     */
12578    public Display getDisplay() {
12579        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12580    }
12581
12582    /**
12583     * Retrieve private session object this view hierarchy is using to
12584     * communicate with the window manager.
12585     * @return the session object to communicate with the window manager
12586     */
12587    /*package*/ IWindowSession getWindowSession() {
12588        return mAttachInfo != null ? mAttachInfo.mSession : null;
12589    }
12590
12591    /**
12592     * @param info the {@link android.view.View.AttachInfo} to associated with
12593     *        this view
12594     */
12595    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12596        //System.out.println("Attached! " + this);
12597        mAttachInfo = info;
12598        if (mOverlay != null) {
12599            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12600        }
12601        mWindowAttachCount++;
12602        // We will need to evaluate the drawable state at least once.
12603        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12604        if (mFloatingTreeObserver != null) {
12605            info.mTreeObserver.merge(mFloatingTreeObserver);
12606            mFloatingTreeObserver = null;
12607        }
12608        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12609            mAttachInfo.mScrollContainers.add(this);
12610            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12611        }
12612        performCollectViewAttributes(mAttachInfo, visibility);
12613        onAttachedToWindow();
12614
12615        ListenerInfo li = mListenerInfo;
12616        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12617                li != null ? li.mOnAttachStateChangeListeners : null;
12618        if (listeners != null && listeners.size() > 0) {
12619            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12620            // perform the dispatching. The iterator is a safe guard against listeners that
12621            // could mutate the list by calling the various add/remove methods. This prevents
12622            // the array from being modified while we iterate it.
12623            for (OnAttachStateChangeListener listener : listeners) {
12624                listener.onViewAttachedToWindow(this);
12625            }
12626        }
12627
12628        int vis = info.mWindowVisibility;
12629        if (vis != GONE) {
12630            onWindowVisibilityChanged(vis);
12631        }
12632        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12633            // If nobody has evaluated the drawable state yet, then do it now.
12634            refreshDrawableState();
12635        }
12636        needGlobalAttributesUpdate(false);
12637    }
12638
12639    void dispatchDetachedFromWindow() {
12640        AttachInfo info = mAttachInfo;
12641        if (info != null) {
12642            int vis = info.mWindowVisibility;
12643            if (vis != GONE) {
12644                onWindowVisibilityChanged(GONE);
12645            }
12646        }
12647
12648        onDetachedFromWindow();
12649
12650        ListenerInfo li = mListenerInfo;
12651        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12652                li != null ? li.mOnAttachStateChangeListeners : null;
12653        if (listeners != null && listeners.size() > 0) {
12654            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12655            // perform the dispatching. The iterator is a safe guard against listeners that
12656            // could mutate the list by calling the various add/remove methods. This prevents
12657            // the array from being modified while we iterate it.
12658            for (OnAttachStateChangeListener listener : listeners) {
12659                listener.onViewDetachedFromWindow(this);
12660            }
12661        }
12662
12663        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12664            mAttachInfo.mScrollContainers.remove(this);
12665            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12666        }
12667
12668        mAttachInfo = null;
12669        if (mOverlay != null) {
12670            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12671        }
12672    }
12673
12674    /**
12675     * Cancel any deferred high-level input events that were previously posted to the event queue.
12676     *
12677     * <p>Many views post high-level events such as click handlers to the event queue
12678     * to run deferred in order to preserve a desired user experience - clearing visible
12679     * pressed states before executing, etc. This method will abort any events of this nature
12680     * that are currently in flight.</p>
12681     *
12682     * <p>Custom views that generate their own high-level deferred input events should override
12683     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
12684     *
12685     * <p>This will also cancel pending input events for any child views.</p>
12686     *
12687     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
12688     * This will not impact newer events posted after this call that may occur as a result of
12689     * lower-level input events still waiting in the queue. If you are trying to prevent
12690     * double-submitted  events for the duration of some sort of asynchronous transaction
12691     * you should also take other steps to protect against unexpected double inputs e.g. calling
12692     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
12693     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
12694     */
12695    public final void cancelPendingInputEvents() {
12696        dispatchCancelPendingInputEvents();
12697    }
12698
12699    /**
12700     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
12701     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
12702     */
12703    void dispatchCancelPendingInputEvents() {
12704        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
12705        onCancelPendingInputEvents();
12706        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
12707            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
12708                    " did not call through to super.onCancelPendingInputEvents()");
12709        }
12710    }
12711
12712    /**
12713     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
12714     * a parent view.
12715     *
12716     * <p>This method is responsible for removing any pending high-level input events that were
12717     * posted to the event queue to run later. Custom view classes that post their own deferred
12718     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
12719     * {@link android.os.Handler} should override this method, call
12720     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
12721     * </p>
12722     */
12723    public void onCancelPendingInputEvents() {
12724        removePerformClickCallback();
12725        cancelLongPress();
12726        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
12727    }
12728
12729    /**
12730     * Store this view hierarchy's frozen state into the given container.
12731     *
12732     * @param container The SparseArray in which to save the view's state.
12733     *
12734     * @see #restoreHierarchyState(android.util.SparseArray)
12735     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12736     * @see #onSaveInstanceState()
12737     */
12738    public void saveHierarchyState(SparseArray<Parcelable> container) {
12739        dispatchSaveInstanceState(container);
12740    }
12741
12742    /**
12743     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12744     * this view and its children. May be overridden to modify how freezing happens to a
12745     * view's children; for example, some views may want to not store state for their children.
12746     *
12747     * @param container The SparseArray in which to save the view's state.
12748     *
12749     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12750     * @see #saveHierarchyState(android.util.SparseArray)
12751     * @see #onSaveInstanceState()
12752     */
12753    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12754        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12755            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12756            Parcelable state = onSaveInstanceState();
12757            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12758                throw new IllegalStateException(
12759                        "Derived class did not call super.onSaveInstanceState()");
12760            }
12761            if (state != null) {
12762                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12763                // + ": " + state);
12764                container.put(mID, state);
12765            }
12766        }
12767    }
12768
12769    /**
12770     * Hook allowing a view to generate a representation of its internal state
12771     * that can later be used to create a new instance with that same state.
12772     * This state should only contain information that is not persistent or can
12773     * not be reconstructed later. For example, you will never store your
12774     * current position on screen because that will be computed again when a
12775     * new instance of the view is placed in its view hierarchy.
12776     * <p>
12777     * Some examples of things you may store here: the current cursor position
12778     * in a text view (but usually not the text itself since that is stored in a
12779     * content provider or other persistent storage), the currently selected
12780     * item in a list view.
12781     *
12782     * @return Returns a Parcelable object containing the view's current dynamic
12783     *         state, or null if there is nothing interesting to save. The
12784     *         default implementation returns null.
12785     * @see #onRestoreInstanceState(android.os.Parcelable)
12786     * @see #saveHierarchyState(android.util.SparseArray)
12787     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12788     * @see #setSaveEnabled(boolean)
12789     */
12790    protected Parcelable onSaveInstanceState() {
12791        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12792        return BaseSavedState.EMPTY_STATE;
12793    }
12794
12795    /**
12796     * Restore this view hierarchy's frozen state from the given container.
12797     *
12798     * @param container The SparseArray which holds previously frozen states.
12799     *
12800     * @see #saveHierarchyState(android.util.SparseArray)
12801     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12802     * @see #onRestoreInstanceState(android.os.Parcelable)
12803     */
12804    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12805        dispatchRestoreInstanceState(container);
12806    }
12807
12808    /**
12809     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12810     * state for this view and its children. May be overridden to modify how restoring
12811     * happens to a view's children; for example, some views may want to not store state
12812     * for their children.
12813     *
12814     * @param container The SparseArray which holds previously saved state.
12815     *
12816     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12817     * @see #restoreHierarchyState(android.util.SparseArray)
12818     * @see #onRestoreInstanceState(android.os.Parcelable)
12819     */
12820    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12821        if (mID != NO_ID) {
12822            Parcelable state = container.get(mID);
12823            if (state != null) {
12824                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12825                // + ": " + state);
12826                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12827                onRestoreInstanceState(state);
12828                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12829                    throw new IllegalStateException(
12830                            "Derived class did not call super.onRestoreInstanceState()");
12831                }
12832            }
12833        }
12834    }
12835
12836    /**
12837     * Hook allowing a view to re-apply a representation of its internal state that had previously
12838     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12839     * null state.
12840     *
12841     * @param state The frozen state that had previously been returned by
12842     *        {@link #onSaveInstanceState}.
12843     *
12844     * @see #onSaveInstanceState()
12845     * @see #restoreHierarchyState(android.util.SparseArray)
12846     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12847     */
12848    protected void onRestoreInstanceState(Parcelable state) {
12849        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12850        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12851            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12852                    + "received " + state.getClass().toString() + " instead. This usually happens "
12853                    + "when two views of different type have the same id in the same hierarchy. "
12854                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12855                    + "other views do not use the same id.");
12856        }
12857    }
12858
12859    /**
12860     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12861     *
12862     * @return the drawing start time in milliseconds
12863     */
12864    public long getDrawingTime() {
12865        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12866    }
12867
12868    /**
12869     * <p>Enables or disables the duplication of the parent's state into this view. When
12870     * duplication is enabled, this view gets its drawable state from its parent rather
12871     * than from its own internal properties.</p>
12872     *
12873     * <p>Note: in the current implementation, setting this property to true after the
12874     * view was added to a ViewGroup might have no effect at all. This property should
12875     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12876     *
12877     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12878     * property is enabled, an exception will be thrown.</p>
12879     *
12880     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12881     * parent, these states should not be affected by this method.</p>
12882     *
12883     * @param enabled True to enable duplication of the parent's drawable state, false
12884     *                to disable it.
12885     *
12886     * @see #getDrawableState()
12887     * @see #isDuplicateParentStateEnabled()
12888     */
12889    public void setDuplicateParentStateEnabled(boolean enabled) {
12890        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12891    }
12892
12893    /**
12894     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12895     *
12896     * @return True if this view's drawable state is duplicated from the parent,
12897     *         false otherwise
12898     *
12899     * @see #getDrawableState()
12900     * @see #setDuplicateParentStateEnabled(boolean)
12901     */
12902    public boolean isDuplicateParentStateEnabled() {
12903        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12904    }
12905
12906    /**
12907     * <p>Specifies the type of layer backing this view. The layer can be
12908     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12909     * {@link #LAYER_TYPE_HARDWARE}.</p>
12910     *
12911     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12912     * instance that controls how the layer is composed on screen. The following
12913     * properties of the paint are taken into account when composing the layer:</p>
12914     * <ul>
12915     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12916     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12917     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12918     * </ul>
12919     *
12920     * <p>If this view has an alpha value set to < 1.0 by calling
12921     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12922     * by this view's alpha value.</p>
12923     *
12924     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12925     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12926     * for more information on when and how to use layers.</p>
12927     *
12928     * @param layerType The type of layer to use with this view, must be one of
12929     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12930     *        {@link #LAYER_TYPE_HARDWARE}
12931     * @param paint The paint used to compose the layer. This argument is optional
12932     *        and can be null. It is ignored when the layer type is
12933     *        {@link #LAYER_TYPE_NONE}
12934     *
12935     * @see #getLayerType()
12936     * @see #LAYER_TYPE_NONE
12937     * @see #LAYER_TYPE_SOFTWARE
12938     * @see #LAYER_TYPE_HARDWARE
12939     * @see #setAlpha(float)
12940     *
12941     * @attr ref android.R.styleable#View_layerType
12942     */
12943    public void setLayerType(int layerType, Paint paint) {
12944        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12945            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12946                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12947        }
12948
12949        if (layerType == mLayerType) {
12950            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12951                mLayerPaint = paint == null ? new Paint() : paint;
12952                invalidateParentCaches();
12953                invalidate(true);
12954            }
12955            return;
12956        }
12957
12958        // Destroy any previous software drawing cache if needed
12959        switch (mLayerType) {
12960            case LAYER_TYPE_HARDWARE:
12961                destroyLayer(false);
12962                // fall through - non-accelerated views may use software layer mechanism instead
12963            case LAYER_TYPE_SOFTWARE:
12964                destroyDrawingCache();
12965                break;
12966            default:
12967                break;
12968        }
12969
12970        mLayerType = layerType;
12971        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12972        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12973        mLocalDirtyRect = layerDisabled ? null : new Rect();
12974
12975        invalidateParentCaches();
12976        invalidate(true);
12977    }
12978
12979    /**
12980     * Updates the {@link Paint} object used with the current layer (used only if the current
12981     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12982     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12983     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12984     * ensure that the view gets redrawn immediately.
12985     *
12986     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12987     * instance that controls how the layer is composed on screen. The following
12988     * properties of the paint are taken into account when composing the layer:</p>
12989     * <ul>
12990     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12991     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12992     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12993     * </ul>
12994     *
12995     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12996     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12997     *
12998     * @param paint The paint used to compose the layer. This argument is optional
12999     *        and can be null. It is ignored when the layer type is
13000     *        {@link #LAYER_TYPE_NONE}
13001     *
13002     * @see #setLayerType(int, android.graphics.Paint)
13003     */
13004    public void setLayerPaint(Paint paint) {
13005        int layerType = getLayerType();
13006        if (layerType != LAYER_TYPE_NONE) {
13007            mLayerPaint = paint == null ? new Paint() : paint;
13008            if (layerType == LAYER_TYPE_HARDWARE) {
13009                HardwareLayer layer = getHardwareLayer();
13010                if (layer != null) {
13011                    layer.setLayerPaint(paint);
13012                }
13013                invalidateViewProperty(false, false);
13014            } else {
13015                invalidate();
13016            }
13017        }
13018    }
13019
13020    /**
13021     * Indicates whether this view has a static layer. A view with layer type
13022     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13023     * dynamic.
13024     */
13025    boolean hasStaticLayer() {
13026        return true;
13027    }
13028
13029    /**
13030     * Indicates what type of layer is currently associated with this view. By default
13031     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13032     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13033     * for more information on the different types of layers.
13034     *
13035     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13036     *         {@link #LAYER_TYPE_HARDWARE}
13037     *
13038     * @see #setLayerType(int, android.graphics.Paint)
13039     * @see #buildLayer()
13040     * @see #LAYER_TYPE_NONE
13041     * @see #LAYER_TYPE_SOFTWARE
13042     * @see #LAYER_TYPE_HARDWARE
13043     */
13044    public int getLayerType() {
13045        return mLayerType;
13046    }
13047
13048    /**
13049     * Forces this view's layer to be created and this view to be rendered
13050     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13051     * invoking this method will have no effect.
13052     *
13053     * This method can for instance be used to render a view into its layer before
13054     * starting an animation. If this view is complex, rendering into the layer
13055     * before starting the animation will avoid skipping frames.
13056     *
13057     * @throws IllegalStateException If this view is not attached to a window
13058     *
13059     * @see #setLayerType(int, android.graphics.Paint)
13060     */
13061    public void buildLayer() {
13062        if (mLayerType == LAYER_TYPE_NONE) return;
13063
13064        final AttachInfo attachInfo = mAttachInfo;
13065        if (attachInfo == null) {
13066            throw new IllegalStateException("This view must be attached to a window first");
13067        }
13068
13069        switch (mLayerType) {
13070            case LAYER_TYPE_HARDWARE:
13071                if (attachInfo.mHardwareRenderer != null &&
13072                        attachInfo.mHardwareRenderer.isEnabled() &&
13073                        attachInfo.mHardwareRenderer.validate()) {
13074                    getHardwareLayer();
13075                    // TODO: We need a better way to handle this case
13076                    // If views have registered pre-draw listeners they need
13077                    // to be notified before we build the layer. Those listeners
13078                    // may however rely on other events to happen first so we
13079                    // cannot just invoke them here until they don't cancel the
13080                    // current frame
13081                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13082                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13083                    }
13084                }
13085                break;
13086            case LAYER_TYPE_SOFTWARE:
13087                buildDrawingCache(true);
13088                break;
13089        }
13090    }
13091
13092    /**
13093     * <p>Returns a hardware layer that can be used to draw this view again
13094     * without executing its draw method.</p>
13095     *
13096     * @return A HardwareLayer ready to render, or null if an error occurred.
13097     */
13098    HardwareLayer getHardwareLayer() {
13099        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13100                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13101            return null;
13102        }
13103
13104        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
13105
13106        final int width = mRight - mLeft;
13107        final int height = mBottom - mTop;
13108
13109        if (width == 0 || height == 0) {
13110            return null;
13111        }
13112
13113        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13114            if (mHardwareLayer == null) {
13115                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
13116                        width, height, isOpaque());
13117                mLocalDirtyRect.set(0, 0, width, height);
13118            } else {
13119                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
13120                    if (mHardwareLayer.resize(width, height)) {
13121                        mLocalDirtyRect.set(0, 0, width, height);
13122                    }
13123                }
13124
13125                // This should not be necessary but applications that change
13126                // the parameters of their background drawable without calling
13127                // this.setBackground(Drawable) can leave the view in a bad state
13128                // (for instance isOpaque() returns true, but the background is
13129                // not opaque.)
13130                computeOpaqueFlags();
13131
13132                final boolean opaque = isOpaque();
13133                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
13134                    mHardwareLayer.setOpaque(opaque);
13135                    mLocalDirtyRect.set(0, 0, width, height);
13136                }
13137            }
13138
13139            // The layer is not valid if the underlying GPU resources cannot be allocated
13140            if (!mHardwareLayer.isValid()) {
13141                return null;
13142            }
13143
13144            mHardwareLayer.setLayerPaint(mLayerPaint);
13145            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
13146            ViewRootImpl viewRoot = getViewRootImpl();
13147            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
13148
13149            mLocalDirtyRect.setEmpty();
13150        }
13151
13152        return mHardwareLayer;
13153    }
13154
13155    /**
13156     * Destroys this View's hardware layer if possible.
13157     *
13158     * @return True if the layer was destroyed, false otherwise.
13159     *
13160     * @see #setLayerType(int, android.graphics.Paint)
13161     * @see #LAYER_TYPE_HARDWARE
13162     */
13163    boolean destroyLayer(boolean valid) {
13164        if (mHardwareLayer != null) {
13165            AttachInfo info = mAttachInfo;
13166            if (info != null && info.mHardwareRenderer != null &&
13167                    info.mHardwareRenderer.isEnabled() &&
13168                    (valid || info.mHardwareRenderer.validate())) {
13169
13170                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
13171                mHardwareLayer.destroy();
13172                mHardwareLayer = null;
13173
13174                invalidate(true);
13175                invalidateParentCaches();
13176            }
13177            return true;
13178        }
13179        return false;
13180    }
13181
13182    /**
13183     * Destroys all hardware rendering resources. This method is invoked
13184     * when the system needs to reclaim resources. Upon execution of this
13185     * method, you should free any OpenGL resources created by the view.
13186     *
13187     * Note: you <strong>must</strong> call
13188     * <code>super.destroyHardwareResources()</code> when overriding
13189     * this method.
13190     *
13191     * @hide
13192     */
13193    protected void destroyHardwareResources() {
13194        resetDisplayList();
13195        destroyLayer(true);
13196    }
13197
13198    /**
13199     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13200     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13201     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13202     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13203     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13204     * null.</p>
13205     *
13206     * <p>Enabling the drawing cache is similar to
13207     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13208     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13209     * drawing cache has no effect on rendering because the system uses a different mechanism
13210     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13211     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13212     * for information on how to enable software and hardware layers.</p>
13213     *
13214     * <p>This API can be used to manually generate
13215     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13216     * {@link #getDrawingCache()}.</p>
13217     *
13218     * @param enabled true to enable the drawing cache, false otherwise
13219     *
13220     * @see #isDrawingCacheEnabled()
13221     * @see #getDrawingCache()
13222     * @see #buildDrawingCache()
13223     * @see #setLayerType(int, android.graphics.Paint)
13224     */
13225    public void setDrawingCacheEnabled(boolean enabled) {
13226        mCachingFailed = false;
13227        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13228    }
13229
13230    /**
13231     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13232     *
13233     * @return true if the drawing cache is enabled
13234     *
13235     * @see #setDrawingCacheEnabled(boolean)
13236     * @see #getDrawingCache()
13237     */
13238    @ViewDebug.ExportedProperty(category = "drawing")
13239    public boolean isDrawingCacheEnabled() {
13240        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13241    }
13242
13243    /**
13244     * Debugging utility which recursively outputs the dirty state of a view and its
13245     * descendants.
13246     *
13247     * @hide
13248     */
13249    @SuppressWarnings({"UnusedDeclaration"})
13250    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13251        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13252                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13253                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13254                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13255        if (clear) {
13256            mPrivateFlags &= clearMask;
13257        }
13258        if (this instanceof ViewGroup) {
13259            ViewGroup parent = (ViewGroup) this;
13260            final int count = parent.getChildCount();
13261            for (int i = 0; i < count; i++) {
13262                final View child = parent.getChildAt(i);
13263                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13264            }
13265        }
13266    }
13267
13268    /**
13269     * This method is used by ViewGroup to cause its children to restore or recreate their
13270     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13271     * to recreate its own display list, which would happen if it went through the normal
13272     * draw/dispatchDraw mechanisms.
13273     *
13274     * @hide
13275     */
13276    protected void dispatchGetDisplayList() {}
13277
13278    /**
13279     * A view that is not attached or hardware accelerated cannot create a display list.
13280     * This method checks these conditions and returns the appropriate result.
13281     *
13282     * @return true if view has the ability to create a display list, false otherwise.
13283     *
13284     * @hide
13285     */
13286    public boolean canHaveDisplayList() {
13287        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13288    }
13289
13290    /**
13291     * @return The {@link HardwareRenderer} associated with that view or null if
13292     *         hardware rendering is not supported or this view is not attached
13293     *         to a window.
13294     *
13295     * @hide
13296     */
13297    public HardwareRenderer getHardwareRenderer() {
13298        if (mAttachInfo != null) {
13299            return mAttachInfo.mHardwareRenderer;
13300        }
13301        return null;
13302    }
13303
13304    /**
13305     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13306     * Otherwise, the same display list will be returned (after having been rendered into
13307     * along the way, depending on the invalidation state of the view).
13308     *
13309     * @param displayList The previous version of this displayList, could be null.
13310     * @param isLayer Whether the requester of the display list is a layer. If so,
13311     * the view will avoid creating a layer inside the resulting display list.
13312     * @return A new or reused DisplayList object.
13313     */
13314    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13315        if (!canHaveDisplayList()) {
13316            return null;
13317        }
13318
13319        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13320                displayList == null || !displayList.isValid() ||
13321                (!isLayer && mRecreateDisplayList))) {
13322            // Don't need to recreate the display list, just need to tell our
13323            // children to restore/recreate theirs
13324            if (displayList != null && displayList.isValid() &&
13325                    !isLayer && !mRecreateDisplayList) {
13326                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13327                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13328                dispatchGetDisplayList();
13329
13330                return displayList;
13331            }
13332
13333            if (!isLayer) {
13334                // If we got here, we're recreating it. Mark it as such to ensure that
13335                // we copy in child display lists into ours in drawChild()
13336                mRecreateDisplayList = true;
13337            }
13338            if (displayList == null) {
13339                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
13340                // If we're creating a new display list, make sure our parent gets invalidated
13341                // since they will need to recreate their display list to account for this
13342                // new child display list.
13343                invalidateParentCaches();
13344            }
13345
13346            boolean caching = false;
13347            int width = mRight - mLeft;
13348            int height = mBottom - mTop;
13349            int layerType = getLayerType();
13350
13351            final HardwareCanvas canvas = displayList.start(width, height);
13352
13353            try {
13354                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13355                    if (layerType == LAYER_TYPE_HARDWARE) {
13356                        final HardwareLayer layer = getHardwareLayer();
13357                        if (layer != null && layer.isValid()) {
13358                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13359                        } else {
13360                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13361                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13362                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13363                        }
13364                        caching = true;
13365                    } else {
13366                        buildDrawingCache(true);
13367                        Bitmap cache = getDrawingCache(true);
13368                        if (cache != null) {
13369                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13370                            caching = true;
13371                        }
13372                    }
13373                } else {
13374
13375                    computeScroll();
13376
13377                    canvas.translate(-mScrollX, -mScrollY);
13378                    if (!isLayer) {
13379                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13380                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13381                    }
13382
13383                    // Fast path for layouts with no backgrounds
13384                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13385                        dispatchDraw(canvas);
13386                        if (mOverlay != null && !mOverlay.isEmpty()) {
13387                            mOverlay.getOverlayView().draw(canvas);
13388                        }
13389                    } else {
13390                        draw(canvas);
13391                    }
13392                }
13393            } finally {
13394                displayList.end();
13395                displayList.setCaching(caching);
13396                if (isLayer) {
13397                    displayList.setLeftTopRightBottom(0, 0, width, height);
13398                } else {
13399                    setDisplayListProperties(displayList);
13400                }
13401            }
13402        } else if (!isLayer) {
13403            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13404            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13405        }
13406
13407        return displayList;
13408    }
13409
13410    /**
13411     * Get the DisplayList for the HardwareLayer
13412     *
13413     * @param layer The HardwareLayer whose DisplayList we want
13414     * @return A DisplayList fopr the specified HardwareLayer
13415     */
13416    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13417        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13418        layer.setDisplayList(displayList);
13419        return displayList;
13420    }
13421
13422
13423    /**
13424     * <p>Returns a display list that can be used to draw this view again
13425     * without executing its draw method.</p>
13426     *
13427     * @return A DisplayList ready to replay, or null if caching is not enabled.
13428     *
13429     * @hide
13430     */
13431    public DisplayList getDisplayList() {
13432        mDisplayList = getDisplayList(mDisplayList, false);
13433        return mDisplayList;
13434    }
13435
13436    private void clearDisplayList() {
13437        if (mDisplayList != null) {
13438            mDisplayList.clear();
13439        }
13440    }
13441
13442    private void resetDisplayList() {
13443        if (mDisplayList != null) {
13444            mDisplayList.reset();
13445        }
13446    }
13447
13448    /**
13449     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13450     *
13451     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13452     *
13453     * @see #getDrawingCache(boolean)
13454     */
13455    public Bitmap getDrawingCache() {
13456        return getDrawingCache(false);
13457    }
13458
13459    /**
13460     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13461     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13462     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13463     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13464     * request the drawing cache by calling this method and draw it on screen if the
13465     * returned bitmap is not null.</p>
13466     *
13467     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13468     * this method will create a bitmap of the same size as this view. Because this bitmap
13469     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13470     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13471     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13472     * size than the view. This implies that your application must be able to handle this
13473     * size.</p>
13474     *
13475     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13476     *        the current density of the screen when the application is in compatibility
13477     *        mode.
13478     *
13479     * @return A bitmap representing this view or null if cache is disabled.
13480     *
13481     * @see #setDrawingCacheEnabled(boolean)
13482     * @see #isDrawingCacheEnabled()
13483     * @see #buildDrawingCache(boolean)
13484     * @see #destroyDrawingCache()
13485     */
13486    public Bitmap getDrawingCache(boolean autoScale) {
13487        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13488            return null;
13489        }
13490        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13491            buildDrawingCache(autoScale);
13492        }
13493        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13494    }
13495
13496    /**
13497     * <p>Frees the resources used by the drawing cache. If you call
13498     * {@link #buildDrawingCache()} manually without calling
13499     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13500     * should cleanup the cache with this method afterwards.</p>
13501     *
13502     * @see #setDrawingCacheEnabled(boolean)
13503     * @see #buildDrawingCache()
13504     * @see #getDrawingCache()
13505     */
13506    public void destroyDrawingCache() {
13507        if (mDrawingCache != null) {
13508            mDrawingCache.recycle();
13509            mDrawingCache = null;
13510        }
13511        if (mUnscaledDrawingCache != null) {
13512            mUnscaledDrawingCache.recycle();
13513            mUnscaledDrawingCache = null;
13514        }
13515    }
13516
13517    /**
13518     * Setting a solid background color for the drawing cache's bitmaps will improve
13519     * performance and memory usage. Note, though that this should only be used if this
13520     * view will always be drawn on top of a solid color.
13521     *
13522     * @param color The background color to use for the drawing cache's bitmap
13523     *
13524     * @see #setDrawingCacheEnabled(boolean)
13525     * @see #buildDrawingCache()
13526     * @see #getDrawingCache()
13527     */
13528    public void setDrawingCacheBackgroundColor(int color) {
13529        if (color != mDrawingCacheBackgroundColor) {
13530            mDrawingCacheBackgroundColor = color;
13531            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13532        }
13533    }
13534
13535    /**
13536     * @see #setDrawingCacheBackgroundColor(int)
13537     *
13538     * @return The background color to used for the drawing cache's bitmap
13539     */
13540    public int getDrawingCacheBackgroundColor() {
13541        return mDrawingCacheBackgroundColor;
13542    }
13543
13544    /**
13545     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13546     *
13547     * @see #buildDrawingCache(boolean)
13548     */
13549    public void buildDrawingCache() {
13550        buildDrawingCache(false);
13551    }
13552
13553    /**
13554     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13555     *
13556     * <p>If you call {@link #buildDrawingCache()} manually without calling
13557     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13558     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13559     *
13560     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13561     * this method will create a bitmap of the same size as this view. Because this bitmap
13562     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13563     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13564     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13565     * size than the view. This implies that your application must be able to handle this
13566     * size.</p>
13567     *
13568     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13569     * you do not need the drawing cache bitmap, calling this method will increase memory
13570     * usage and cause the view to be rendered in software once, thus negatively impacting
13571     * performance.</p>
13572     *
13573     * @see #getDrawingCache()
13574     * @see #destroyDrawingCache()
13575     */
13576    public void buildDrawingCache(boolean autoScale) {
13577        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13578                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13579            mCachingFailed = false;
13580
13581            int width = mRight - mLeft;
13582            int height = mBottom - mTop;
13583
13584            final AttachInfo attachInfo = mAttachInfo;
13585            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13586
13587            if (autoScale && scalingRequired) {
13588                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13589                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13590            }
13591
13592            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13593            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13594            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13595
13596            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13597            final long drawingCacheSize =
13598                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13599            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13600                if (width > 0 && height > 0) {
13601                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13602                            + projectedBitmapSize + " bytes, only "
13603                            + drawingCacheSize + " available");
13604                }
13605                destroyDrawingCache();
13606                mCachingFailed = true;
13607                return;
13608            }
13609
13610            boolean clear = true;
13611            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13612
13613            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13614                Bitmap.Config quality;
13615                if (!opaque) {
13616                    // Never pick ARGB_4444 because it looks awful
13617                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13618                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13619                        case DRAWING_CACHE_QUALITY_AUTO:
13620                        case DRAWING_CACHE_QUALITY_LOW:
13621                        case DRAWING_CACHE_QUALITY_HIGH:
13622                        default:
13623                            quality = Bitmap.Config.ARGB_8888;
13624                            break;
13625                    }
13626                } else {
13627                    // Optimization for translucent windows
13628                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13629                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13630                }
13631
13632                // Try to cleanup memory
13633                if (bitmap != null) bitmap.recycle();
13634
13635                try {
13636                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13637                            width, height, quality);
13638                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13639                    if (autoScale) {
13640                        mDrawingCache = bitmap;
13641                    } else {
13642                        mUnscaledDrawingCache = bitmap;
13643                    }
13644                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13645                } catch (OutOfMemoryError e) {
13646                    // If there is not enough memory to create the bitmap cache, just
13647                    // ignore the issue as bitmap caches are not required to draw the
13648                    // view hierarchy
13649                    if (autoScale) {
13650                        mDrawingCache = null;
13651                    } else {
13652                        mUnscaledDrawingCache = null;
13653                    }
13654                    mCachingFailed = true;
13655                    return;
13656                }
13657
13658                clear = drawingCacheBackgroundColor != 0;
13659            }
13660
13661            Canvas canvas;
13662            if (attachInfo != null) {
13663                canvas = attachInfo.mCanvas;
13664                if (canvas == null) {
13665                    canvas = new Canvas();
13666                }
13667                canvas.setBitmap(bitmap);
13668                // Temporarily clobber the cached Canvas in case one of our children
13669                // is also using a drawing cache. Without this, the children would
13670                // steal the canvas by attaching their own bitmap to it and bad, bad
13671                // thing would happen (invisible views, corrupted drawings, etc.)
13672                attachInfo.mCanvas = null;
13673            } else {
13674                // This case should hopefully never or seldom happen
13675                canvas = new Canvas(bitmap);
13676            }
13677
13678            if (clear) {
13679                bitmap.eraseColor(drawingCacheBackgroundColor);
13680            }
13681
13682            computeScroll();
13683            final int restoreCount = canvas.save();
13684
13685            if (autoScale && scalingRequired) {
13686                final float scale = attachInfo.mApplicationScale;
13687                canvas.scale(scale, scale);
13688            }
13689
13690            canvas.translate(-mScrollX, -mScrollY);
13691
13692            mPrivateFlags |= PFLAG_DRAWN;
13693            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13694                    mLayerType != LAYER_TYPE_NONE) {
13695                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13696            }
13697
13698            // Fast path for layouts with no backgrounds
13699            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13700                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13701                dispatchDraw(canvas);
13702                if (mOverlay != null && !mOverlay.isEmpty()) {
13703                    mOverlay.getOverlayView().draw(canvas);
13704                }
13705            } else {
13706                draw(canvas);
13707            }
13708
13709            canvas.restoreToCount(restoreCount);
13710            canvas.setBitmap(null);
13711
13712            if (attachInfo != null) {
13713                // Restore the cached Canvas for our siblings
13714                attachInfo.mCanvas = canvas;
13715            }
13716        }
13717    }
13718
13719    /**
13720     * Create a snapshot of the view into a bitmap.  We should probably make
13721     * some form of this public, but should think about the API.
13722     */
13723    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13724        int width = mRight - mLeft;
13725        int height = mBottom - mTop;
13726
13727        final AttachInfo attachInfo = mAttachInfo;
13728        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13729        width = (int) ((width * scale) + 0.5f);
13730        height = (int) ((height * scale) + 0.5f);
13731
13732        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13733                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13734        if (bitmap == null) {
13735            throw new OutOfMemoryError();
13736        }
13737
13738        Resources resources = getResources();
13739        if (resources != null) {
13740            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13741        }
13742
13743        Canvas canvas;
13744        if (attachInfo != null) {
13745            canvas = attachInfo.mCanvas;
13746            if (canvas == null) {
13747                canvas = new Canvas();
13748            }
13749            canvas.setBitmap(bitmap);
13750            // Temporarily clobber the cached Canvas in case one of our children
13751            // is also using a drawing cache. Without this, the children would
13752            // steal the canvas by attaching their own bitmap to it and bad, bad
13753            // things would happen (invisible views, corrupted drawings, etc.)
13754            attachInfo.mCanvas = null;
13755        } else {
13756            // This case should hopefully never or seldom happen
13757            canvas = new Canvas(bitmap);
13758        }
13759
13760        if ((backgroundColor & 0xff000000) != 0) {
13761            bitmap.eraseColor(backgroundColor);
13762        }
13763
13764        computeScroll();
13765        final int restoreCount = canvas.save();
13766        canvas.scale(scale, scale);
13767        canvas.translate(-mScrollX, -mScrollY);
13768
13769        // Temporarily remove the dirty mask
13770        int flags = mPrivateFlags;
13771        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13772
13773        // Fast path for layouts with no backgrounds
13774        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13775            dispatchDraw(canvas);
13776            if (mOverlay != null && !mOverlay.isEmpty()) {
13777                mOverlay.getOverlayView().draw(canvas);
13778            }
13779        } else {
13780            draw(canvas);
13781        }
13782
13783        mPrivateFlags = flags;
13784
13785        canvas.restoreToCount(restoreCount);
13786        canvas.setBitmap(null);
13787
13788        if (attachInfo != null) {
13789            // Restore the cached Canvas for our siblings
13790            attachInfo.mCanvas = canvas;
13791        }
13792
13793        return bitmap;
13794    }
13795
13796    /**
13797     * Indicates whether this View is currently in edit mode. A View is usually
13798     * in edit mode when displayed within a developer tool. For instance, if
13799     * this View is being drawn by a visual user interface builder, this method
13800     * should return true.
13801     *
13802     * Subclasses should check the return value of this method to provide
13803     * different behaviors if their normal behavior might interfere with the
13804     * host environment. For instance: the class spawns a thread in its
13805     * constructor, the drawing code relies on device-specific features, etc.
13806     *
13807     * This method is usually checked in the drawing code of custom widgets.
13808     *
13809     * @return True if this View is in edit mode, false otherwise.
13810     */
13811    public boolean isInEditMode() {
13812        return false;
13813    }
13814
13815    /**
13816     * If the View draws content inside its padding and enables fading edges,
13817     * it needs to support padding offsets. Padding offsets are added to the
13818     * fading edges to extend the length of the fade so that it covers pixels
13819     * drawn inside the padding.
13820     *
13821     * Subclasses of this class should override this method if they need
13822     * to draw content inside the padding.
13823     *
13824     * @return True if padding offset must be applied, false otherwise.
13825     *
13826     * @see #getLeftPaddingOffset()
13827     * @see #getRightPaddingOffset()
13828     * @see #getTopPaddingOffset()
13829     * @see #getBottomPaddingOffset()
13830     *
13831     * @since CURRENT
13832     */
13833    protected boolean isPaddingOffsetRequired() {
13834        return false;
13835    }
13836
13837    /**
13838     * Amount by which to extend the left fading region. Called only when
13839     * {@link #isPaddingOffsetRequired()} returns true.
13840     *
13841     * @return The left padding offset in pixels.
13842     *
13843     * @see #isPaddingOffsetRequired()
13844     *
13845     * @since CURRENT
13846     */
13847    protected int getLeftPaddingOffset() {
13848        return 0;
13849    }
13850
13851    /**
13852     * Amount by which to extend the right fading region. Called only when
13853     * {@link #isPaddingOffsetRequired()} returns true.
13854     *
13855     * @return The right padding offset in pixels.
13856     *
13857     * @see #isPaddingOffsetRequired()
13858     *
13859     * @since CURRENT
13860     */
13861    protected int getRightPaddingOffset() {
13862        return 0;
13863    }
13864
13865    /**
13866     * Amount by which to extend the top fading region. Called only when
13867     * {@link #isPaddingOffsetRequired()} returns true.
13868     *
13869     * @return The top padding offset in pixels.
13870     *
13871     * @see #isPaddingOffsetRequired()
13872     *
13873     * @since CURRENT
13874     */
13875    protected int getTopPaddingOffset() {
13876        return 0;
13877    }
13878
13879    /**
13880     * Amount by which to extend the bottom fading region. Called only when
13881     * {@link #isPaddingOffsetRequired()} returns true.
13882     *
13883     * @return The bottom padding offset in pixels.
13884     *
13885     * @see #isPaddingOffsetRequired()
13886     *
13887     * @since CURRENT
13888     */
13889    protected int getBottomPaddingOffset() {
13890        return 0;
13891    }
13892
13893    /**
13894     * @hide
13895     * @param offsetRequired
13896     */
13897    protected int getFadeTop(boolean offsetRequired) {
13898        int top = mPaddingTop;
13899        if (offsetRequired) top += getTopPaddingOffset();
13900        return top;
13901    }
13902
13903    /**
13904     * @hide
13905     * @param offsetRequired
13906     */
13907    protected int getFadeHeight(boolean offsetRequired) {
13908        int padding = mPaddingTop;
13909        if (offsetRequired) padding += getTopPaddingOffset();
13910        return mBottom - mTop - mPaddingBottom - padding;
13911    }
13912
13913    /**
13914     * <p>Indicates whether this view is attached to a hardware accelerated
13915     * window or not.</p>
13916     *
13917     * <p>Even if this method returns true, it does not mean that every call
13918     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13919     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13920     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13921     * window is hardware accelerated,
13922     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13923     * return false, and this method will return true.</p>
13924     *
13925     * @return True if the view is attached to a window and the window is
13926     *         hardware accelerated; false in any other case.
13927     */
13928    public boolean isHardwareAccelerated() {
13929        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13930    }
13931
13932    /**
13933     * Sets a rectangular area on this view to which the view will be clipped
13934     * when it is drawn. Setting the value to null will remove the clip bounds
13935     * and the view will draw normally, using its full bounds.
13936     *
13937     * @param clipBounds The rectangular area, in the local coordinates of
13938     * this view, to which future drawing operations will be clipped.
13939     */
13940    public void setClipBounds(Rect clipBounds) {
13941        if (clipBounds != null) {
13942            if (clipBounds.equals(mClipBounds)) {
13943                return;
13944            }
13945            if (mClipBounds == null) {
13946                invalidate();
13947                mClipBounds = new Rect(clipBounds);
13948            } else {
13949                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13950                        Math.min(mClipBounds.top, clipBounds.top),
13951                        Math.max(mClipBounds.right, clipBounds.right),
13952                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13953                mClipBounds.set(clipBounds);
13954            }
13955        } else {
13956            if (mClipBounds != null) {
13957                invalidate();
13958                mClipBounds = null;
13959            }
13960        }
13961    }
13962
13963    /**
13964     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13965     *
13966     * @return A copy of the current clip bounds if clip bounds are set,
13967     * otherwise null.
13968     */
13969    public Rect getClipBounds() {
13970        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13971    }
13972
13973    /**
13974     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13975     * case of an active Animation being run on the view.
13976     */
13977    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13978            Animation a, boolean scalingRequired) {
13979        Transformation invalidationTransform;
13980        final int flags = parent.mGroupFlags;
13981        final boolean initialized = a.isInitialized();
13982        if (!initialized) {
13983            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13984            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13985            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13986            onAnimationStart();
13987        }
13988
13989        final Transformation t = parent.getChildTransformation();
13990        boolean more = a.getTransformation(drawingTime, t, 1f);
13991        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13992            if (parent.mInvalidationTransformation == null) {
13993                parent.mInvalidationTransformation = new Transformation();
13994            }
13995            invalidationTransform = parent.mInvalidationTransformation;
13996            a.getTransformation(drawingTime, invalidationTransform, 1f);
13997        } else {
13998            invalidationTransform = t;
13999        }
14000
14001        if (more) {
14002            if (!a.willChangeBounds()) {
14003                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14004                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14005                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14006                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14007                    // The child need to draw an animation, potentially offscreen, so
14008                    // make sure we do not cancel invalidate requests
14009                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14010                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14011                }
14012            } else {
14013                if (parent.mInvalidateRegion == null) {
14014                    parent.mInvalidateRegion = new RectF();
14015                }
14016                final RectF region = parent.mInvalidateRegion;
14017                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14018                        invalidationTransform);
14019
14020                // The child need to draw an animation, potentially offscreen, so
14021                // make sure we do not cancel invalidate requests
14022                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14023
14024                final int left = mLeft + (int) region.left;
14025                final int top = mTop + (int) region.top;
14026                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14027                        top + (int) (region.height() + .5f));
14028            }
14029        }
14030        return more;
14031    }
14032
14033    /**
14034     * This method is called by getDisplayList() when a display list is created or re-rendered.
14035     * It sets or resets the current value of all properties on that display list (resetting is
14036     * necessary when a display list is being re-created, because we need to make sure that
14037     * previously-set transform values
14038     */
14039    void setDisplayListProperties(DisplayList displayList) {
14040        if (displayList != null) {
14041            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14042            displayList.setHasOverlappingRendering(hasOverlappingRendering());
14043            if (mParent instanceof ViewGroup) {
14044                displayList.setClipToBounds(
14045                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14046            }
14047            float alpha = 1;
14048            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14049                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14050                ViewGroup parentVG = (ViewGroup) mParent;
14051                final Transformation t = parentVG.getChildTransformation();
14052                if (parentVG.getChildStaticTransformation(this, t)) {
14053                    final int transformType = t.getTransformationType();
14054                    if (transformType != Transformation.TYPE_IDENTITY) {
14055                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14056                            alpha = t.getAlpha();
14057                        }
14058                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14059                            displayList.setMatrix(t.getMatrix());
14060                        }
14061                    }
14062                }
14063            }
14064            if (mTransformationInfo != null) {
14065                alpha *= getFinalAlpha();
14066                if (alpha < 1) {
14067                    final int multipliedAlpha = (int) (255 * alpha);
14068                    if (onSetAlpha(multipliedAlpha)) {
14069                        alpha = 1;
14070                    }
14071                }
14072                displayList.setTransformationInfo(alpha,
14073                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14074                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14075                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14076                        mTransformationInfo.mScaleY);
14077                if (mTransformationInfo.mCamera == null) {
14078                    mTransformationInfo.mCamera = new Camera();
14079                    mTransformationInfo.matrix3D = new Matrix();
14080                }
14081                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14082                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14083                    displayList.setPivotX(getPivotX());
14084                    displayList.setPivotY(getPivotY());
14085                }
14086            } else if (alpha < 1) {
14087                displayList.setAlpha(alpha);
14088            }
14089        }
14090    }
14091
14092    /**
14093     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14094     * This draw() method is an implementation detail and is not intended to be overridden or
14095     * to be called from anywhere else other than ViewGroup.drawChild().
14096     */
14097    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14098        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14099        boolean more = false;
14100        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14101        final int flags = parent.mGroupFlags;
14102
14103        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14104            parent.getChildTransformation().clear();
14105            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14106        }
14107
14108        Transformation transformToApply = null;
14109        boolean concatMatrix = false;
14110
14111        boolean scalingRequired = false;
14112        boolean caching;
14113        int layerType = getLayerType();
14114
14115        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14116        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14117                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14118            caching = true;
14119            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14120            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14121        } else {
14122            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14123        }
14124
14125        final Animation a = getAnimation();
14126        if (a != null) {
14127            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14128            concatMatrix = a.willChangeTransformationMatrix();
14129            if (concatMatrix) {
14130                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14131            }
14132            transformToApply = parent.getChildTransformation();
14133        } else {
14134            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14135                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14136                // No longer animating: clear out old animation matrix
14137                mDisplayList.setAnimationMatrix(null);
14138                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14139            }
14140            if (!useDisplayListProperties &&
14141                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14142                final Transformation t = parent.getChildTransformation();
14143                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14144                if (hasTransform) {
14145                    final int transformType = t.getTransformationType();
14146                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14147                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14148                }
14149            }
14150        }
14151
14152        concatMatrix |= !childHasIdentityMatrix;
14153
14154        // Sets the flag as early as possible to allow draw() implementations
14155        // to call invalidate() successfully when doing animations
14156        mPrivateFlags |= PFLAG_DRAWN;
14157
14158        if (!concatMatrix &&
14159                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14160                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14161                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14162                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14163            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14164            return more;
14165        }
14166        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14167
14168        if (hardwareAccelerated) {
14169            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14170            // retain the flag's value temporarily in the mRecreateDisplayList flag
14171            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14172            mPrivateFlags &= ~PFLAG_INVALIDATED;
14173        }
14174
14175        DisplayList displayList = null;
14176        Bitmap cache = null;
14177        boolean hasDisplayList = false;
14178        if (caching) {
14179            if (!hardwareAccelerated) {
14180                if (layerType != LAYER_TYPE_NONE) {
14181                    layerType = LAYER_TYPE_SOFTWARE;
14182                    buildDrawingCache(true);
14183                }
14184                cache = getDrawingCache(true);
14185            } else {
14186                switch (layerType) {
14187                    case LAYER_TYPE_SOFTWARE:
14188                        if (useDisplayListProperties) {
14189                            hasDisplayList = canHaveDisplayList();
14190                        } else {
14191                            buildDrawingCache(true);
14192                            cache = getDrawingCache(true);
14193                        }
14194                        break;
14195                    case LAYER_TYPE_HARDWARE:
14196                        if (useDisplayListProperties) {
14197                            hasDisplayList = canHaveDisplayList();
14198                        }
14199                        break;
14200                    case LAYER_TYPE_NONE:
14201                        // Delay getting the display list until animation-driven alpha values are
14202                        // set up and possibly passed on to the view
14203                        hasDisplayList = canHaveDisplayList();
14204                        break;
14205                }
14206            }
14207        }
14208        useDisplayListProperties &= hasDisplayList;
14209        if (useDisplayListProperties) {
14210            displayList = getDisplayList();
14211            if (!displayList.isValid()) {
14212                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14213                // to getDisplayList(), the display list will be marked invalid and we should not
14214                // try to use it again.
14215                displayList = null;
14216                hasDisplayList = false;
14217                useDisplayListProperties = false;
14218            }
14219        }
14220
14221        int sx = 0;
14222        int sy = 0;
14223        if (!hasDisplayList) {
14224            computeScroll();
14225            sx = mScrollX;
14226            sy = mScrollY;
14227        }
14228
14229        final boolean hasNoCache = cache == null || hasDisplayList;
14230        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14231                layerType != LAYER_TYPE_HARDWARE;
14232
14233        int restoreTo = -1;
14234        if (!useDisplayListProperties || transformToApply != null) {
14235            restoreTo = canvas.save();
14236        }
14237        if (offsetForScroll) {
14238            canvas.translate(mLeft - sx, mTop - sy);
14239        } else {
14240            if (!useDisplayListProperties) {
14241                canvas.translate(mLeft, mTop);
14242            }
14243            if (scalingRequired) {
14244                if (useDisplayListProperties) {
14245                    // TODO: Might not need this if we put everything inside the DL
14246                    restoreTo = canvas.save();
14247                }
14248                // mAttachInfo cannot be null, otherwise scalingRequired == false
14249                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14250                canvas.scale(scale, scale);
14251            }
14252        }
14253
14254        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14255        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14256                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14257            if (transformToApply != null || !childHasIdentityMatrix) {
14258                int transX = 0;
14259                int transY = 0;
14260
14261                if (offsetForScroll) {
14262                    transX = -sx;
14263                    transY = -sy;
14264                }
14265
14266                if (transformToApply != null) {
14267                    if (concatMatrix) {
14268                        if (useDisplayListProperties) {
14269                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14270                        } else {
14271                            // Undo the scroll translation, apply the transformation matrix,
14272                            // then redo the scroll translate to get the correct result.
14273                            canvas.translate(-transX, -transY);
14274                            canvas.concat(transformToApply.getMatrix());
14275                            canvas.translate(transX, transY);
14276                        }
14277                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14278                    }
14279
14280                    float transformAlpha = transformToApply.getAlpha();
14281                    if (transformAlpha < 1) {
14282                        alpha *= transformAlpha;
14283                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14284                    }
14285                }
14286
14287                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14288                    canvas.translate(-transX, -transY);
14289                    canvas.concat(getMatrix());
14290                    canvas.translate(transX, transY);
14291                }
14292            }
14293
14294            // Deal with alpha if it is or used to be <1
14295            if (alpha < 1 ||
14296                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14297                if (alpha < 1) {
14298                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14299                } else {
14300                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14301                }
14302                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14303                if (hasNoCache) {
14304                    final int multipliedAlpha = (int) (255 * alpha);
14305                    if (!onSetAlpha(multipliedAlpha)) {
14306                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14307                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14308                                layerType != LAYER_TYPE_NONE) {
14309                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14310                        }
14311                        if (useDisplayListProperties) {
14312                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14313                        } else  if (layerType == LAYER_TYPE_NONE) {
14314                            final int scrollX = hasDisplayList ? 0 : sx;
14315                            final int scrollY = hasDisplayList ? 0 : sy;
14316                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14317                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14318                        }
14319                    } else {
14320                        // Alpha is handled by the child directly, clobber the layer's alpha
14321                        mPrivateFlags |= PFLAG_ALPHA_SET;
14322                    }
14323                }
14324            }
14325        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14326            onSetAlpha(255);
14327            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14328        }
14329
14330        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14331                !useDisplayListProperties && cache == null) {
14332            if (offsetForScroll) {
14333                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14334            } else {
14335                if (!scalingRequired || cache == null) {
14336                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14337                } else {
14338                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14339                }
14340            }
14341        }
14342
14343        if (!useDisplayListProperties && hasDisplayList) {
14344            displayList = getDisplayList();
14345            if (!displayList.isValid()) {
14346                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14347                // to getDisplayList(), the display list will be marked invalid and we should not
14348                // try to use it again.
14349                displayList = null;
14350                hasDisplayList = false;
14351            }
14352        }
14353
14354        if (hasNoCache) {
14355            boolean layerRendered = false;
14356            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14357                final HardwareLayer layer = getHardwareLayer();
14358                if (layer != null && layer.isValid()) {
14359                    mLayerPaint.setAlpha((int) (alpha * 255));
14360                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14361                    layerRendered = true;
14362                } else {
14363                    final int scrollX = hasDisplayList ? 0 : sx;
14364                    final int scrollY = hasDisplayList ? 0 : sy;
14365                    canvas.saveLayer(scrollX, scrollY,
14366                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14367                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14368                }
14369            }
14370
14371            if (!layerRendered) {
14372                if (!hasDisplayList) {
14373                    // Fast path for layouts with no backgrounds
14374                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14375                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14376                        dispatchDraw(canvas);
14377                    } else {
14378                        draw(canvas);
14379                    }
14380                } else {
14381                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14382                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14383                }
14384            }
14385        } else if (cache != null) {
14386            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14387            Paint cachePaint;
14388
14389            if (layerType == LAYER_TYPE_NONE) {
14390                cachePaint = parent.mCachePaint;
14391                if (cachePaint == null) {
14392                    cachePaint = new Paint();
14393                    cachePaint.setDither(false);
14394                    parent.mCachePaint = cachePaint;
14395                }
14396                if (alpha < 1) {
14397                    cachePaint.setAlpha((int) (alpha * 255));
14398                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14399                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14400                    cachePaint.setAlpha(255);
14401                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14402                }
14403            } else {
14404                cachePaint = mLayerPaint;
14405                cachePaint.setAlpha((int) (alpha * 255));
14406            }
14407            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14408        }
14409
14410        if (restoreTo >= 0) {
14411            canvas.restoreToCount(restoreTo);
14412        }
14413
14414        if (a != null && !more) {
14415            if (!hardwareAccelerated && !a.getFillAfter()) {
14416                onSetAlpha(255);
14417            }
14418            parent.finishAnimatingView(this, a);
14419        }
14420
14421        if (more && hardwareAccelerated) {
14422            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14423                // alpha animations should cause the child to recreate its display list
14424                invalidate(true);
14425            }
14426        }
14427
14428        mRecreateDisplayList = false;
14429
14430        return more;
14431    }
14432
14433    /**
14434     * Manually render this view (and all of its children) to the given Canvas.
14435     * The view must have already done a full layout before this function is
14436     * called.  When implementing a view, implement
14437     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14438     * If you do need to override this method, call the superclass version.
14439     *
14440     * @param canvas The Canvas to which the View is rendered.
14441     */
14442    public void draw(Canvas canvas) {
14443        if (mClipBounds != null) {
14444            canvas.clipRect(mClipBounds);
14445        }
14446        final int privateFlags = mPrivateFlags;
14447        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14448                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14449        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14450
14451        /*
14452         * Draw traversal performs several drawing steps which must be executed
14453         * in the appropriate order:
14454         *
14455         *      1. Draw the background
14456         *      2. If necessary, save the canvas' layers to prepare for fading
14457         *      3. Draw view's content
14458         *      4. Draw children
14459         *      5. If necessary, draw the fading edges and restore layers
14460         *      6. Draw decorations (scrollbars for instance)
14461         */
14462
14463        // Step 1, draw the background, if needed
14464        int saveCount;
14465
14466        if (!dirtyOpaque) {
14467            final Drawable background = mBackground;
14468            if (background != null) {
14469                final int scrollX = mScrollX;
14470                final int scrollY = mScrollY;
14471
14472                if (mBackgroundSizeChanged) {
14473                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14474                    mBackgroundSizeChanged = false;
14475                }
14476
14477                if ((scrollX | scrollY) == 0) {
14478                    background.draw(canvas);
14479                } else {
14480                    canvas.translate(scrollX, scrollY);
14481                    background.draw(canvas);
14482                    canvas.translate(-scrollX, -scrollY);
14483                }
14484            }
14485        }
14486
14487        // skip step 2 & 5 if possible (common case)
14488        final int viewFlags = mViewFlags;
14489        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14490        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14491        if (!verticalEdges && !horizontalEdges) {
14492            // Step 3, draw the content
14493            if (!dirtyOpaque) onDraw(canvas);
14494
14495            // Step 4, draw the children
14496            dispatchDraw(canvas);
14497
14498            // Step 6, draw decorations (scrollbars)
14499            onDrawScrollBars(canvas);
14500
14501            if (mOverlay != null && !mOverlay.isEmpty()) {
14502                mOverlay.getOverlayView().dispatchDraw(canvas);
14503            }
14504
14505            // we're done...
14506            return;
14507        }
14508
14509        /*
14510         * Here we do the full fledged routine...
14511         * (this is an uncommon case where speed matters less,
14512         * this is why we repeat some of the tests that have been
14513         * done above)
14514         */
14515
14516        boolean drawTop = false;
14517        boolean drawBottom = false;
14518        boolean drawLeft = false;
14519        boolean drawRight = false;
14520
14521        float topFadeStrength = 0.0f;
14522        float bottomFadeStrength = 0.0f;
14523        float leftFadeStrength = 0.0f;
14524        float rightFadeStrength = 0.0f;
14525
14526        // Step 2, save the canvas' layers
14527        int paddingLeft = mPaddingLeft;
14528
14529        final boolean offsetRequired = isPaddingOffsetRequired();
14530        if (offsetRequired) {
14531            paddingLeft += getLeftPaddingOffset();
14532        }
14533
14534        int left = mScrollX + paddingLeft;
14535        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14536        int top = mScrollY + getFadeTop(offsetRequired);
14537        int bottom = top + getFadeHeight(offsetRequired);
14538
14539        if (offsetRequired) {
14540            right += getRightPaddingOffset();
14541            bottom += getBottomPaddingOffset();
14542        }
14543
14544        final ScrollabilityCache scrollabilityCache = mScrollCache;
14545        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14546        int length = (int) fadeHeight;
14547
14548        // clip the fade length if top and bottom fades overlap
14549        // overlapping fades produce odd-looking artifacts
14550        if (verticalEdges && (top + length > bottom - length)) {
14551            length = (bottom - top) / 2;
14552        }
14553
14554        // also clip horizontal fades if necessary
14555        if (horizontalEdges && (left + length > right - length)) {
14556            length = (right - left) / 2;
14557        }
14558
14559        if (verticalEdges) {
14560            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14561            drawTop = topFadeStrength * fadeHeight > 1.0f;
14562            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14563            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14564        }
14565
14566        if (horizontalEdges) {
14567            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14568            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14569            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14570            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14571        }
14572
14573        saveCount = canvas.getSaveCount();
14574
14575        int solidColor = getSolidColor();
14576        if (solidColor == 0) {
14577            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14578
14579            if (drawTop) {
14580                canvas.saveLayer(left, top, right, top + length, null, flags);
14581            }
14582
14583            if (drawBottom) {
14584                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14585            }
14586
14587            if (drawLeft) {
14588                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14589            }
14590
14591            if (drawRight) {
14592                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14593            }
14594        } else {
14595            scrollabilityCache.setFadeColor(solidColor);
14596        }
14597
14598        // Step 3, draw the content
14599        if (!dirtyOpaque) onDraw(canvas);
14600
14601        // Step 4, draw the children
14602        dispatchDraw(canvas);
14603
14604        // Step 5, draw the fade effect and restore layers
14605        final Paint p = scrollabilityCache.paint;
14606        final Matrix matrix = scrollabilityCache.matrix;
14607        final Shader fade = scrollabilityCache.shader;
14608
14609        if (drawTop) {
14610            matrix.setScale(1, fadeHeight * topFadeStrength);
14611            matrix.postTranslate(left, top);
14612            fade.setLocalMatrix(matrix);
14613            canvas.drawRect(left, top, right, top + length, p);
14614        }
14615
14616        if (drawBottom) {
14617            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14618            matrix.postRotate(180);
14619            matrix.postTranslate(left, bottom);
14620            fade.setLocalMatrix(matrix);
14621            canvas.drawRect(left, bottom - length, right, bottom, p);
14622        }
14623
14624        if (drawLeft) {
14625            matrix.setScale(1, fadeHeight * leftFadeStrength);
14626            matrix.postRotate(-90);
14627            matrix.postTranslate(left, top);
14628            fade.setLocalMatrix(matrix);
14629            canvas.drawRect(left, top, left + length, bottom, p);
14630        }
14631
14632        if (drawRight) {
14633            matrix.setScale(1, fadeHeight * rightFadeStrength);
14634            matrix.postRotate(90);
14635            matrix.postTranslate(right, top);
14636            fade.setLocalMatrix(matrix);
14637            canvas.drawRect(right - length, top, right, bottom, p);
14638        }
14639
14640        canvas.restoreToCount(saveCount);
14641
14642        // Step 6, draw decorations (scrollbars)
14643        onDrawScrollBars(canvas);
14644
14645        if (mOverlay != null && !mOverlay.isEmpty()) {
14646            mOverlay.getOverlayView().dispatchDraw(canvas);
14647        }
14648    }
14649
14650    /**
14651     * Returns the overlay for this view, creating it if it does not yet exist.
14652     * Adding drawables to the overlay will cause them to be displayed whenever
14653     * the view itself is redrawn. Objects in the overlay should be actively
14654     * managed: remove them when they should not be displayed anymore. The
14655     * overlay will always have the same size as its host view.
14656     *
14657     * <p>Note: Overlays do not currently work correctly with {@link
14658     * SurfaceView} or {@link TextureView}; contents in overlays for these
14659     * types of views may not display correctly.</p>
14660     *
14661     * @return The ViewOverlay object for this view.
14662     * @see ViewOverlay
14663     */
14664    public ViewOverlay getOverlay() {
14665        if (mOverlay == null) {
14666            mOverlay = new ViewOverlay(mContext, this);
14667        }
14668        return mOverlay;
14669    }
14670
14671    /**
14672     * Override this if your view is known to always be drawn on top of a solid color background,
14673     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14674     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14675     * should be set to 0xFF.
14676     *
14677     * @see #setVerticalFadingEdgeEnabled(boolean)
14678     * @see #setHorizontalFadingEdgeEnabled(boolean)
14679     *
14680     * @return The known solid color background for this view, or 0 if the color may vary
14681     */
14682    @ViewDebug.ExportedProperty(category = "drawing")
14683    public int getSolidColor() {
14684        return 0;
14685    }
14686
14687    /**
14688     * Build a human readable string representation of the specified view flags.
14689     *
14690     * @param flags the view flags to convert to a string
14691     * @return a String representing the supplied flags
14692     */
14693    private static String printFlags(int flags) {
14694        String output = "";
14695        int numFlags = 0;
14696        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14697            output += "TAKES_FOCUS";
14698            numFlags++;
14699        }
14700
14701        switch (flags & VISIBILITY_MASK) {
14702        case INVISIBLE:
14703            if (numFlags > 0) {
14704                output += " ";
14705            }
14706            output += "INVISIBLE";
14707            // USELESS HERE numFlags++;
14708            break;
14709        case GONE:
14710            if (numFlags > 0) {
14711                output += " ";
14712            }
14713            output += "GONE";
14714            // USELESS HERE numFlags++;
14715            break;
14716        default:
14717            break;
14718        }
14719        return output;
14720    }
14721
14722    /**
14723     * Build a human readable string representation of the specified private
14724     * view flags.
14725     *
14726     * @param privateFlags the private view flags to convert to a string
14727     * @return a String representing the supplied flags
14728     */
14729    private static String printPrivateFlags(int privateFlags) {
14730        String output = "";
14731        int numFlags = 0;
14732
14733        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14734            output += "WANTS_FOCUS";
14735            numFlags++;
14736        }
14737
14738        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14739            if (numFlags > 0) {
14740                output += " ";
14741            }
14742            output += "FOCUSED";
14743            numFlags++;
14744        }
14745
14746        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14747            if (numFlags > 0) {
14748                output += " ";
14749            }
14750            output += "SELECTED";
14751            numFlags++;
14752        }
14753
14754        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14755            if (numFlags > 0) {
14756                output += " ";
14757            }
14758            output += "IS_ROOT_NAMESPACE";
14759            numFlags++;
14760        }
14761
14762        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14763            if (numFlags > 0) {
14764                output += " ";
14765            }
14766            output += "HAS_BOUNDS";
14767            numFlags++;
14768        }
14769
14770        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14771            if (numFlags > 0) {
14772                output += " ";
14773            }
14774            output += "DRAWN";
14775            // USELESS HERE numFlags++;
14776        }
14777        return output;
14778    }
14779
14780    /**
14781     * <p>Indicates whether or not this view's layout will be requested during
14782     * the next hierarchy layout pass.</p>
14783     *
14784     * @return true if the layout will be forced during next layout pass
14785     */
14786    public boolean isLayoutRequested() {
14787        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14788    }
14789
14790    /**
14791     * Return true if o is a ViewGroup that is laying out using optical bounds.
14792     * @hide
14793     */
14794    public static boolean isLayoutModeOptical(Object o) {
14795        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14796    }
14797
14798    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14799        Insets parentInsets = mParent instanceof View ?
14800                ((View) mParent).getOpticalInsets() : Insets.NONE;
14801        Insets childInsets = getOpticalInsets();
14802        return setFrame(
14803                left   + parentInsets.left - childInsets.left,
14804                top    + parentInsets.top  - childInsets.top,
14805                right  + parentInsets.left + childInsets.right,
14806                bottom + parentInsets.top  + childInsets.bottom);
14807    }
14808
14809    /**
14810     * Assign a size and position to a view and all of its
14811     * descendants
14812     *
14813     * <p>This is the second phase of the layout mechanism.
14814     * (The first is measuring). In this phase, each parent calls
14815     * layout on all of its children to position them.
14816     * This is typically done using the child measurements
14817     * that were stored in the measure pass().</p>
14818     *
14819     * <p>Derived classes should not override this method.
14820     * Derived classes with children should override
14821     * onLayout. In that method, they should
14822     * call layout on each of their children.</p>
14823     *
14824     * @param l Left position, relative to parent
14825     * @param t Top position, relative to parent
14826     * @param r Right position, relative to parent
14827     * @param b Bottom position, relative to parent
14828     */
14829    @SuppressWarnings({"unchecked"})
14830    public void layout(int l, int t, int r, int b) {
14831        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14832            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14833            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14834        }
14835
14836        int oldL = mLeft;
14837        int oldT = mTop;
14838        int oldB = mBottom;
14839        int oldR = mRight;
14840
14841        boolean changed = isLayoutModeOptical(mParent) ?
14842                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14843
14844        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14845            onLayout(changed, l, t, r, b);
14846            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14847
14848            ListenerInfo li = mListenerInfo;
14849            if (li != null && li.mOnLayoutChangeListeners != null) {
14850                ArrayList<OnLayoutChangeListener> listenersCopy =
14851                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14852                int numListeners = listenersCopy.size();
14853                for (int i = 0; i < numListeners; ++i) {
14854                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14855                }
14856            }
14857        }
14858
14859        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14860        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14861    }
14862
14863    /**
14864     * Called from layout when this view should
14865     * assign a size and position to each of its children.
14866     *
14867     * Derived classes with children should override
14868     * this method and call layout on each of
14869     * their children.
14870     * @param changed This is a new size or position for this view
14871     * @param left Left position, relative to parent
14872     * @param top Top position, relative to parent
14873     * @param right Right position, relative to parent
14874     * @param bottom Bottom position, relative to parent
14875     */
14876    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14877    }
14878
14879    /**
14880     * Assign a size and position to this view.
14881     *
14882     * This is called from layout.
14883     *
14884     * @param left Left position, relative to parent
14885     * @param top Top position, relative to parent
14886     * @param right Right position, relative to parent
14887     * @param bottom Bottom position, relative to parent
14888     * @return true if the new size and position are different than the
14889     *         previous ones
14890     * {@hide}
14891     */
14892    protected boolean setFrame(int left, int top, int right, int bottom) {
14893        boolean changed = false;
14894
14895        if (DBG) {
14896            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14897                    + right + "," + bottom + ")");
14898        }
14899
14900        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14901            changed = true;
14902
14903            // Remember our drawn bit
14904            int drawn = mPrivateFlags & PFLAG_DRAWN;
14905
14906            int oldWidth = mRight - mLeft;
14907            int oldHeight = mBottom - mTop;
14908            int newWidth = right - left;
14909            int newHeight = bottom - top;
14910            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14911
14912            // Invalidate our old position
14913            invalidate(sizeChanged);
14914
14915            mLeft = left;
14916            mTop = top;
14917            mRight = right;
14918            mBottom = bottom;
14919            if (mDisplayList != null) {
14920                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14921            }
14922
14923            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14924
14925
14926            if (sizeChanged) {
14927                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14928                    // A change in dimension means an auto-centered pivot point changes, too
14929                    if (mTransformationInfo != null) {
14930                        mTransformationInfo.mMatrixDirty = true;
14931                    }
14932                }
14933                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14934            }
14935
14936            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14937                // If we are visible, force the DRAWN bit to on so that
14938                // this invalidate will go through (at least to our parent).
14939                // This is because someone may have invalidated this view
14940                // before this call to setFrame came in, thereby clearing
14941                // the DRAWN bit.
14942                mPrivateFlags |= PFLAG_DRAWN;
14943                invalidate(sizeChanged);
14944                // parent display list may need to be recreated based on a change in the bounds
14945                // of any child
14946                invalidateParentCaches();
14947            }
14948
14949            // Reset drawn bit to original value (invalidate turns it off)
14950            mPrivateFlags |= drawn;
14951
14952            mBackgroundSizeChanged = true;
14953
14954            notifySubtreeAccessibilityStateChangedIfNeeded();
14955        }
14956        return changed;
14957    }
14958
14959    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14960        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14961        if (mOverlay != null) {
14962            mOverlay.getOverlayView().setRight(newWidth);
14963            mOverlay.getOverlayView().setBottom(newHeight);
14964        }
14965    }
14966
14967    /**
14968     * Finalize inflating a view from XML.  This is called as the last phase
14969     * of inflation, after all child views have been added.
14970     *
14971     * <p>Even if the subclass overrides onFinishInflate, they should always be
14972     * sure to call the super method, so that we get called.
14973     */
14974    protected void onFinishInflate() {
14975    }
14976
14977    /**
14978     * Returns the resources associated with this view.
14979     *
14980     * @return Resources object.
14981     */
14982    public Resources getResources() {
14983        return mResources;
14984    }
14985
14986    /**
14987     * Invalidates the specified Drawable.
14988     *
14989     * @param drawable the drawable to invalidate
14990     */
14991    public void invalidateDrawable(Drawable drawable) {
14992        if (verifyDrawable(drawable)) {
14993            final Rect dirty = drawable.getBounds();
14994            final int scrollX = mScrollX;
14995            final int scrollY = mScrollY;
14996
14997            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14998                    dirty.right + scrollX, dirty.bottom + scrollY);
14999        }
15000    }
15001
15002    /**
15003     * Schedules an action on a drawable to occur at a specified time.
15004     *
15005     * @param who the recipient of the action
15006     * @param what the action to run on the drawable
15007     * @param when the time at which the action must occur. Uses the
15008     *        {@link SystemClock#uptimeMillis} timebase.
15009     */
15010    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15011        if (verifyDrawable(who) && what != null) {
15012            final long delay = when - SystemClock.uptimeMillis();
15013            if (mAttachInfo != null) {
15014                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15015                        Choreographer.CALLBACK_ANIMATION, what, who,
15016                        Choreographer.subtractFrameDelay(delay));
15017            } else {
15018                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15019            }
15020        }
15021    }
15022
15023    /**
15024     * Cancels a scheduled action on a drawable.
15025     *
15026     * @param who the recipient of the action
15027     * @param what the action to cancel
15028     */
15029    public void unscheduleDrawable(Drawable who, Runnable what) {
15030        if (verifyDrawable(who) && what != null) {
15031            if (mAttachInfo != null) {
15032                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15033                        Choreographer.CALLBACK_ANIMATION, what, who);
15034            } else {
15035                ViewRootImpl.getRunQueue().removeCallbacks(what);
15036            }
15037        }
15038    }
15039
15040    /**
15041     * Unschedule any events associated with the given Drawable.  This can be
15042     * used when selecting a new Drawable into a view, so that the previous
15043     * one is completely unscheduled.
15044     *
15045     * @param who The Drawable to unschedule.
15046     *
15047     * @see #drawableStateChanged
15048     */
15049    public void unscheduleDrawable(Drawable who) {
15050        if (mAttachInfo != null && who != null) {
15051            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15052                    Choreographer.CALLBACK_ANIMATION, null, who);
15053        }
15054    }
15055
15056    /**
15057     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15058     * that the View directionality can and will be resolved before its Drawables.
15059     *
15060     * Will call {@link View#onResolveDrawables} when resolution is done.
15061     *
15062     * @hide
15063     */
15064    protected void resolveDrawables() {
15065        // Drawables resolution may need to happen before resolving the layout direction (which is
15066        // done only during the measure() call).
15067        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15068        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15069        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15070        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15071        // direction to be resolved as its resolved value will be the same as its raw value.
15072        if (!isLayoutDirectionResolved() &&
15073                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15074            return;
15075        }
15076
15077        final int layoutDirection = isLayoutDirectionResolved() ?
15078                getLayoutDirection() : getRawLayoutDirection();
15079
15080        if (mBackground != null) {
15081            mBackground.setLayoutDirection(layoutDirection);
15082        }
15083        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15084        onResolveDrawables(layoutDirection);
15085    }
15086
15087    /**
15088     * Called when layout direction has been resolved.
15089     *
15090     * The default implementation does nothing.
15091     *
15092     * @param layoutDirection The resolved layout direction.
15093     *
15094     * @see #LAYOUT_DIRECTION_LTR
15095     * @see #LAYOUT_DIRECTION_RTL
15096     *
15097     * @hide
15098     */
15099    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15100    }
15101
15102    /**
15103     * @hide
15104     */
15105    protected void resetResolvedDrawables() {
15106        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15107    }
15108
15109    private boolean isDrawablesResolved() {
15110        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15111    }
15112
15113    /**
15114     * If your view subclass is displaying its own Drawable objects, it should
15115     * override this function and return true for any Drawable it is
15116     * displaying.  This allows animations for those drawables to be
15117     * scheduled.
15118     *
15119     * <p>Be sure to call through to the super class when overriding this
15120     * function.
15121     *
15122     * @param who The Drawable to verify.  Return true if it is one you are
15123     *            displaying, else return the result of calling through to the
15124     *            super class.
15125     *
15126     * @return boolean If true than the Drawable is being displayed in the
15127     *         view; else false and it is not allowed to animate.
15128     *
15129     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15130     * @see #drawableStateChanged()
15131     */
15132    protected boolean verifyDrawable(Drawable who) {
15133        return who == mBackground;
15134    }
15135
15136    /**
15137     * This function is called whenever the state of the view changes in such
15138     * a way that it impacts the state of drawables being shown.
15139     *
15140     * <p>Be sure to call through to the superclass when overriding this
15141     * function.
15142     *
15143     * @see Drawable#setState(int[])
15144     */
15145    protected void drawableStateChanged() {
15146        Drawable d = mBackground;
15147        if (d != null && d.isStateful()) {
15148            d.setState(getDrawableState());
15149        }
15150    }
15151
15152    /**
15153     * Call this to force a view to update its drawable state. This will cause
15154     * drawableStateChanged to be called on this view. Views that are interested
15155     * in the new state should call getDrawableState.
15156     *
15157     * @see #drawableStateChanged
15158     * @see #getDrawableState
15159     */
15160    public void refreshDrawableState() {
15161        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15162        drawableStateChanged();
15163
15164        ViewParent parent = mParent;
15165        if (parent != null) {
15166            parent.childDrawableStateChanged(this);
15167        }
15168    }
15169
15170    /**
15171     * Return an array of resource IDs of the drawable states representing the
15172     * current state of the view.
15173     *
15174     * @return The current drawable state
15175     *
15176     * @see Drawable#setState(int[])
15177     * @see #drawableStateChanged()
15178     * @see #onCreateDrawableState(int)
15179     */
15180    public final int[] getDrawableState() {
15181        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15182            return mDrawableState;
15183        } else {
15184            mDrawableState = onCreateDrawableState(0);
15185            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15186            return mDrawableState;
15187        }
15188    }
15189
15190    /**
15191     * Generate the new {@link android.graphics.drawable.Drawable} state for
15192     * this view. This is called by the view
15193     * system when the cached Drawable state is determined to be invalid.  To
15194     * retrieve the current state, you should use {@link #getDrawableState}.
15195     *
15196     * @param extraSpace if non-zero, this is the number of extra entries you
15197     * would like in the returned array in which you can place your own
15198     * states.
15199     *
15200     * @return Returns an array holding the current {@link Drawable} state of
15201     * the view.
15202     *
15203     * @see #mergeDrawableStates(int[], int[])
15204     */
15205    protected int[] onCreateDrawableState(int extraSpace) {
15206        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15207                mParent instanceof View) {
15208            return ((View) mParent).onCreateDrawableState(extraSpace);
15209        }
15210
15211        int[] drawableState;
15212
15213        int privateFlags = mPrivateFlags;
15214
15215        int viewStateIndex = 0;
15216        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15217        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15218        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15219        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15220        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15221        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15222        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15223                HardwareRenderer.isAvailable()) {
15224            // This is set if HW acceleration is requested, even if the current
15225            // process doesn't allow it.  This is just to allow app preview
15226            // windows to better match their app.
15227            viewStateIndex |= VIEW_STATE_ACCELERATED;
15228        }
15229        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15230
15231        final int privateFlags2 = mPrivateFlags2;
15232        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15233        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15234
15235        drawableState = VIEW_STATE_SETS[viewStateIndex];
15236
15237        //noinspection ConstantIfStatement
15238        if (false) {
15239            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15240            Log.i("View", toString()
15241                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15242                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15243                    + " fo=" + hasFocus()
15244                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15245                    + " wf=" + hasWindowFocus()
15246                    + ": " + Arrays.toString(drawableState));
15247        }
15248
15249        if (extraSpace == 0) {
15250            return drawableState;
15251        }
15252
15253        final int[] fullState;
15254        if (drawableState != null) {
15255            fullState = new int[drawableState.length + extraSpace];
15256            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15257        } else {
15258            fullState = new int[extraSpace];
15259        }
15260
15261        return fullState;
15262    }
15263
15264    /**
15265     * Merge your own state values in <var>additionalState</var> into the base
15266     * state values <var>baseState</var> that were returned by
15267     * {@link #onCreateDrawableState(int)}.
15268     *
15269     * @param baseState The base state values returned by
15270     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15271     * own additional state values.
15272     *
15273     * @param additionalState The additional state values you would like
15274     * added to <var>baseState</var>; this array is not modified.
15275     *
15276     * @return As a convenience, the <var>baseState</var> array you originally
15277     * passed into the function is returned.
15278     *
15279     * @see #onCreateDrawableState(int)
15280     */
15281    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15282        final int N = baseState.length;
15283        int i = N - 1;
15284        while (i >= 0 && baseState[i] == 0) {
15285            i--;
15286        }
15287        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15288        return baseState;
15289    }
15290
15291    /**
15292     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15293     * on all Drawable objects associated with this view.
15294     */
15295    public void jumpDrawablesToCurrentState() {
15296        if (mBackground != null) {
15297            mBackground.jumpToCurrentState();
15298        }
15299    }
15300
15301    /**
15302     * Sets the background color for this view.
15303     * @param color the color of the background
15304     */
15305    @RemotableViewMethod
15306    public void setBackgroundColor(int color) {
15307        if (mBackground instanceof ColorDrawable) {
15308            ((ColorDrawable) mBackground.mutate()).setColor(color);
15309            computeOpaqueFlags();
15310            mBackgroundResource = 0;
15311        } else {
15312            setBackground(new ColorDrawable(color));
15313        }
15314    }
15315
15316    /**
15317     * Set the background to a given resource. The resource should refer to
15318     * a Drawable object or 0 to remove the background.
15319     * @param resid The identifier of the resource.
15320     *
15321     * @attr ref android.R.styleable#View_background
15322     */
15323    @RemotableViewMethod
15324    public void setBackgroundResource(int resid) {
15325        if (resid != 0 && resid == mBackgroundResource) {
15326            return;
15327        }
15328
15329        Drawable d= null;
15330        if (resid != 0) {
15331            d = mResources.getDrawable(resid);
15332        }
15333        setBackground(d);
15334
15335        mBackgroundResource = resid;
15336    }
15337
15338    /**
15339     * Set the background to a given Drawable, or remove the background. If the
15340     * background has padding, this View's padding is set to the background's
15341     * padding. However, when a background is removed, this View's padding isn't
15342     * touched. If setting the padding is desired, please use
15343     * {@link #setPadding(int, int, int, int)}.
15344     *
15345     * @param background The Drawable to use as the background, or null to remove the
15346     *        background
15347     */
15348    public void setBackground(Drawable background) {
15349        //noinspection deprecation
15350        setBackgroundDrawable(background);
15351    }
15352
15353    /**
15354     * @deprecated use {@link #setBackground(Drawable)} instead
15355     */
15356    @Deprecated
15357    public void setBackgroundDrawable(Drawable background) {
15358        computeOpaqueFlags();
15359
15360        if (background == mBackground) {
15361            return;
15362        }
15363
15364        boolean requestLayout = false;
15365
15366        mBackgroundResource = 0;
15367
15368        /*
15369         * Regardless of whether we're setting a new background or not, we want
15370         * to clear the previous drawable.
15371         */
15372        if (mBackground != null) {
15373            mBackground.setCallback(null);
15374            unscheduleDrawable(mBackground);
15375        }
15376
15377        if (background != null) {
15378            Rect padding = sThreadLocal.get();
15379            if (padding == null) {
15380                padding = new Rect();
15381                sThreadLocal.set(padding);
15382            }
15383            resetResolvedDrawables();
15384            background.setLayoutDirection(getLayoutDirection());
15385            if (background.getPadding(padding)) {
15386                resetResolvedPadding();
15387                switch (background.getLayoutDirection()) {
15388                    case LAYOUT_DIRECTION_RTL:
15389                        mUserPaddingLeftInitial = padding.right;
15390                        mUserPaddingRightInitial = padding.left;
15391                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15392                        break;
15393                    case LAYOUT_DIRECTION_LTR:
15394                    default:
15395                        mUserPaddingLeftInitial = padding.left;
15396                        mUserPaddingRightInitial = padding.right;
15397                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15398                }
15399            }
15400
15401            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15402            // if it has a different minimum size, we should layout again
15403            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15404                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15405                requestLayout = true;
15406            }
15407
15408            background.setCallback(this);
15409            if (background.isStateful()) {
15410                background.setState(getDrawableState());
15411            }
15412            background.setVisible(getVisibility() == VISIBLE, false);
15413            mBackground = background;
15414
15415            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15416                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15417                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15418                requestLayout = true;
15419            }
15420        } else {
15421            /* Remove the background */
15422            mBackground = null;
15423
15424            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15425                /*
15426                 * This view ONLY drew the background before and we're removing
15427                 * the background, so now it won't draw anything
15428                 * (hence we SKIP_DRAW)
15429                 */
15430                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15431                mPrivateFlags |= PFLAG_SKIP_DRAW;
15432            }
15433
15434            /*
15435             * When the background is set, we try to apply its padding to this
15436             * View. When the background is removed, we don't touch this View's
15437             * padding. This is noted in the Javadocs. Hence, we don't need to
15438             * requestLayout(), the invalidate() below is sufficient.
15439             */
15440
15441            // The old background's minimum size could have affected this
15442            // View's layout, so let's requestLayout
15443            requestLayout = true;
15444        }
15445
15446        computeOpaqueFlags();
15447
15448        if (requestLayout) {
15449            requestLayout();
15450        }
15451
15452        mBackgroundSizeChanged = true;
15453        invalidate(true);
15454    }
15455
15456    /**
15457     * Gets the background drawable
15458     *
15459     * @return The drawable used as the background for this view, if any.
15460     *
15461     * @see #setBackground(Drawable)
15462     *
15463     * @attr ref android.R.styleable#View_background
15464     */
15465    public Drawable getBackground() {
15466        return mBackground;
15467    }
15468
15469    /**
15470     * Sets the padding. The view may add on the space required to display
15471     * the scrollbars, depending on the style and visibility of the scrollbars.
15472     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15473     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15474     * from the values set in this call.
15475     *
15476     * @attr ref android.R.styleable#View_padding
15477     * @attr ref android.R.styleable#View_paddingBottom
15478     * @attr ref android.R.styleable#View_paddingLeft
15479     * @attr ref android.R.styleable#View_paddingRight
15480     * @attr ref android.R.styleable#View_paddingTop
15481     * @param left the left padding in pixels
15482     * @param top the top padding in pixels
15483     * @param right the right padding in pixels
15484     * @param bottom the bottom padding in pixels
15485     */
15486    public void setPadding(int left, int top, int right, int bottom) {
15487        resetResolvedPadding();
15488
15489        mUserPaddingStart = UNDEFINED_PADDING;
15490        mUserPaddingEnd = UNDEFINED_PADDING;
15491
15492        mUserPaddingLeftInitial = left;
15493        mUserPaddingRightInitial = right;
15494
15495        internalSetPadding(left, top, right, bottom);
15496    }
15497
15498    /**
15499     * @hide
15500     */
15501    protected void internalSetPadding(int left, int top, int right, int bottom) {
15502        mUserPaddingLeft = left;
15503        mUserPaddingRight = right;
15504        mUserPaddingBottom = bottom;
15505
15506        final int viewFlags = mViewFlags;
15507        boolean changed = false;
15508
15509        // Common case is there are no scroll bars.
15510        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15511            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15512                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15513                        ? 0 : getVerticalScrollbarWidth();
15514                switch (mVerticalScrollbarPosition) {
15515                    case SCROLLBAR_POSITION_DEFAULT:
15516                        if (isLayoutRtl()) {
15517                            left += offset;
15518                        } else {
15519                            right += offset;
15520                        }
15521                        break;
15522                    case SCROLLBAR_POSITION_RIGHT:
15523                        right += offset;
15524                        break;
15525                    case SCROLLBAR_POSITION_LEFT:
15526                        left += offset;
15527                        break;
15528                }
15529            }
15530            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15531                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15532                        ? 0 : getHorizontalScrollbarHeight();
15533            }
15534        }
15535
15536        if (mPaddingLeft != left) {
15537            changed = true;
15538            mPaddingLeft = left;
15539        }
15540        if (mPaddingTop != top) {
15541            changed = true;
15542            mPaddingTop = top;
15543        }
15544        if (mPaddingRight != right) {
15545            changed = true;
15546            mPaddingRight = right;
15547        }
15548        if (mPaddingBottom != bottom) {
15549            changed = true;
15550            mPaddingBottom = bottom;
15551        }
15552
15553        if (changed) {
15554            requestLayout();
15555        }
15556    }
15557
15558    /**
15559     * Sets the relative padding. The view may add on the space required to display
15560     * the scrollbars, depending on the style and visibility of the scrollbars.
15561     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15562     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15563     * from the values set in this call.
15564     *
15565     * @attr ref android.R.styleable#View_padding
15566     * @attr ref android.R.styleable#View_paddingBottom
15567     * @attr ref android.R.styleable#View_paddingStart
15568     * @attr ref android.R.styleable#View_paddingEnd
15569     * @attr ref android.R.styleable#View_paddingTop
15570     * @param start the start padding in pixels
15571     * @param top the top padding in pixels
15572     * @param end the end padding in pixels
15573     * @param bottom the bottom padding in pixels
15574     */
15575    public void setPaddingRelative(int start, int top, int end, int bottom) {
15576        resetResolvedPadding();
15577
15578        mUserPaddingStart = start;
15579        mUserPaddingEnd = end;
15580
15581        switch(getLayoutDirection()) {
15582            case LAYOUT_DIRECTION_RTL:
15583                mUserPaddingLeftInitial = end;
15584                mUserPaddingRightInitial = start;
15585                internalSetPadding(end, top, start, bottom);
15586                break;
15587            case LAYOUT_DIRECTION_LTR:
15588            default:
15589                mUserPaddingLeftInitial = start;
15590                mUserPaddingRightInitial = end;
15591                internalSetPadding(start, top, end, bottom);
15592        }
15593    }
15594
15595    /**
15596     * Returns the top padding of this view.
15597     *
15598     * @return the top padding in pixels
15599     */
15600    public int getPaddingTop() {
15601        return mPaddingTop;
15602    }
15603
15604    /**
15605     * Returns the bottom padding of this view. If there are inset and enabled
15606     * scrollbars, this value may include the space required to display the
15607     * scrollbars as well.
15608     *
15609     * @return the bottom padding in pixels
15610     */
15611    public int getPaddingBottom() {
15612        return mPaddingBottom;
15613    }
15614
15615    /**
15616     * Returns the left padding of this view. If there are inset and enabled
15617     * scrollbars, this value may include the space required to display the
15618     * scrollbars as well.
15619     *
15620     * @return the left padding in pixels
15621     */
15622    public int getPaddingLeft() {
15623        if (!isPaddingResolved()) {
15624            resolvePadding();
15625        }
15626        return mPaddingLeft;
15627    }
15628
15629    /**
15630     * Returns the start padding of this view depending on its resolved layout direction.
15631     * If there are inset and enabled scrollbars, this value may include the space
15632     * required to display the scrollbars as well.
15633     *
15634     * @return the start padding in pixels
15635     */
15636    public int getPaddingStart() {
15637        if (!isPaddingResolved()) {
15638            resolvePadding();
15639        }
15640        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15641                mPaddingRight : mPaddingLeft;
15642    }
15643
15644    /**
15645     * Returns the right padding of this view. If there are inset and enabled
15646     * scrollbars, this value may include the space required to display the
15647     * scrollbars as well.
15648     *
15649     * @return the right padding in pixels
15650     */
15651    public int getPaddingRight() {
15652        if (!isPaddingResolved()) {
15653            resolvePadding();
15654        }
15655        return mPaddingRight;
15656    }
15657
15658    /**
15659     * Returns the end padding of this view depending on its resolved layout direction.
15660     * If there are inset and enabled scrollbars, this value may include the space
15661     * required to display the scrollbars as well.
15662     *
15663     * @return the end padding in pixels
15664     */
15665    public int getPaddingEnd() {
15666        if (!isPaddingResolved()) {
15667            resolvePadding();
15668        }
15669        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15670                mPaddingLeft : mPaddingRight;
15671    }
15672
15673    /**
15674     * Return if the padding as been set thru relative values
15675     * {@link #setPaddingRelative(int, int, int, int)} or thru
15676     * @attr ref android.R.styleable#View_paddingStart or
15677     * @attr ref android.R.styleable#View_paddingEnd
15678     *
15679     * @return true if the padding is relative or false if it is not.
15680     */
15681    public boolean isPaddingRelative() {
15682        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15683    }
15684
15685    Insets computeOpticalInsets() {
15686        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15687    }
15688
15689    /**
15690     * @hide
15691     */
15692    public void resetPaddingToInitialValues() {
15693        if (isRtlCompatibilityMode()) {
15694            mPaddingLeft = mUserPaddingLeftInitial;
15695            mPaddingRight = mUserPaddingRightInitial;
15696            return;
15697        }
15698        if (isLayoutRtl()) {
15699            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15700            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15701        } else {
15702            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15703            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15704        }
15705    }
15706
15707    /**
15708     * @hide
15709     */
15710    public Insets getOpticalInsets() {
15711        if (mLayoutInsets == null) {
15712            mLayoutInsets = computeOpticalInsets();
15713        }
15714        return mLayoutInsets;
15715    }
15716
15717    /**
15718     * Changes the selection state of this view. A view can be selected or not.
15719     * Note that selection is not the same as focus. Views are typically
15720     * selected in the context of an AdapterView like ListView or GridView;
15721     * the selected view is the view that is highlighted.
15722     *
15723     * @param selected true if the view must be selected, false otherwise
15724     */
15725    public void setSelected(boolean selected) {
15726        //noinspection DoubleNegation
15727        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15728            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15729            if (!selected) resetPressedState();
15730            invalidate(true);
15731            refreshDrawableState();
15732            dispatchSetSelected(selected);
15733            notifyViewAccessibilityStateChangedIfNeeded(
15734                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
15735        }
15736    }
15737
15738    /**
15739     * Dispatch setSelected to all of this View's children.
15740     *
15741     * @see #setSelected(boolean)
15742     *
15743     * @param selected The new selected state
15744     */
15745    protected void dispatchSetSelected(boolean selected) {
15746    }
15747
15748    /**
15749     * Indicates the selection state of this view.
15750     *
15751     * @return true if the view is selected, false otherwise
15752     */
15753    @ViewDebug.ExportedProperty
15754    public boolean isSelected() {
15755        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15756    }
15757
15758    /**
15759     * Changes the activated state of this view. A view can be activated or not.
15760     * Note that activation is not the same as selection.  Selection is
15761     * a transient property, representing the view (hierarchy) the user is
15762     * currently interacting with.  Activation is a longer-term state that the
15763     * user can move views in and out of.  For example, in a list view with
15764     * single or multiple selection enabled, the views in the current selection
15765     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15766     * here.)  The activated state is propagated down to children of the view it
15767     * is set on.
15768     *
15769     * @param activated true if the view must be activated, false otherwise
15770     */
15771    public void setActivated(boolean activated) {
15772        //noinspection DoubleNegation
15773        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15774            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15775            invalidate(true);
15776            refreshDrawableState();
15777            dispatchSetActivated(activated);
15778        }
15779    }
15780
15781    /**
15782     * Dispatch setActivated to all of this View's children.
15783     *
15784     * @see #setActivated(boolean)
15785     *
15786     * @param activated The new activated state
15787     */
15788    protected void dispatchSetActivated(boolean activated) {
15789    }
15790
15791    /**
15792     * Indicates the activation state of this view.
15793     *
15794     * @return true if the view is activated, false otherwise
15795     */
15796    @ViewDebug.ExportedProperty
15797    public boolean isActivated() {
15798        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15799    }
15800
15801    /**
15802     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15803     * observer can be used to get notifications when global events, like
15804     * layout, happen.
15805     *
15806     * The returned ViewTreeObserver observer is not guaranteed to remain
15807     * valid for the lifetime of this View. If the caller of this method keeps
15808     * a long-lived reference to ViewTreeObserver, it should always check for
15809     * the return value of {@link ViewTreeObserver#isAlive()}.
15810     *
15811     * @return The ViewTreeObserver for this view's hierarchy.
15812     */
15813    public ViewTreeObserver getViewTreeObserver() {
15814        if (mAttachInfo != null) {
15815            return mAttachInfo.mTreeObserver;
15816        }
15817        if (mFloatingTreeObserver == null) {
15818            mFloatingTreeObserver = new ViewTreeObserver();
15819        }
15820        return mFloatingTreeObserver;
15821    }
15822
15823    /**
15824     * <p>Finds the topmost view in the current view hierarchy.</p>
15825     *
15826     * @return the topmost view containing this view
15827     */
15828    public View getRootView() {
15829        if (mAttachInfo != null) {
15830            final View v = mAttachInfo.mRootView;
15831            if (v != null) {
15832                return v;
15833            }
15834        }
15835
15836        View parent = this;
15837
15838        while (parent.mParent != null && parent.mParent instanceof View) {
15839            parent = (View) parent.mParent;
15840        }
15841
15842        return parent;
15843    }
15844
15845    /**
15846     * Transforms a motion event from view-local coordinates to on-screen
15847     * coordinates.
15848     *
15849     * @param ev the view-local motion event
15850     * @return false if the transformation could not be applied
15851     * @hide
15852     */
15853    public boolean toGlobalMotionEvent(MotionEvent ev) {
15854        final AttachInfo info = mAttachInfo;
15855        if (info == null) {
15856            return false;
15857        }
15858
15859        transformMotionEventToGlobal(ev);
15860        ev.offsetLocation(info.mWindowLeft, info.mWindowTop);
15861        return true;
15862    }
15863
15864    /**
15865     * Transforms a motion event from on-screen coordinates to view-local
15866     * coordinates.
15867     *
15868     * @param ev the on-screen motion event
15869     * @return false if the transformation could not be applied
15870     * @hide
15871     */
15872    public boolean toLocalMotionEvent(MotionEvent ev) {
15873        final AttachInfo info = mAttachInfo;
15874        if (info == null) {
15875            return false;
15876        }
15877
15878        ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop);
15879        transformMotionEventToLocal(ev);
15880        return true;
15881    }
15882
15883    /**
15884     * Recursive helper method that applies transformations in post-order.
15885     *
15886     * @param ev the on-screen motion event
15887     */
15888    private void transformMotionEventToLocal(MotionEvent ev) {
15889        final ViewParent parent = mParent;
15890        if (parent instanceof View) {
15891            final View vp = (View) parent;
15892            vp.transformMotionEventToLocal(ev);
15893            ev.offsetLocation(vp.mScrollX, vp.mScrollY);
15894        } else if (parent instanceof ViewRootImpl) {
15895            final ViewRootImpl vr = (ViewRootImpl) parent;
15896            ev.offsetLocation(0, vr.mCurScrollY);
15897        }
15898
15899        ev.offsetLocation(-mLeft, -mTop);
15900
15901        if (!hasIdentityMatrix()) {
15902            ev.transform(getInverseMatrix());
15903        }
15904    }
15905
15906    /**
15907     * Recursive helper method that applies transformations in pre-order.
15908     *
15909     * @param ev the on-screen motion event
15910     */
15911    private void transformMotionEventToGlobal(MotionEvent ev) {
15912        if (!hasIdentityMatrix()) {
15913            ev.transform(getMatrix());
15914        }
15915
15916        ev.offsetLocation(mLeft, mTop);
15917
15918        final ViewParent parent = mParent;
15919        if (parent instanceof View) {
15920            final View vp = (View) parent;
15921            ev.offsetLocation(-vp.mScrollX, -vp.mScrollY);
15922            vp.transformMotionEventToGlobal(ev);
15923        } else if (parent instanceof ViewRootImpl) {
15924            final ViewRootImpl vr = (ViewRootImpl) parent;
15925            ev.offsetLocation(0, -vr.mCurScrollY);
15926        }
15927    }
15928
15929    /**
15930     * <p>Computes the coordinates of this view on the screen. The argument
15931     * must be an array of two integers. After the method returns, the array
15932     * contains the x and y location in that order.</p>
15933     *
15934     * @param location an array of two integers in which to hold the coordinates
15935     */
15936    public void getLocationOnScreen(int[] location) {
15937        getLocationInWindow(location);
15938
15939        final AttachInfo info = mAttachInfo;
15940        if (info != null) {
15941            location[0] += info.mWindowLeft;
15942            location[1] += info.mWindowTop;
15943        }
15944    }
15945
15946    /**
15947     * <p>Computes the coordinates of this view in its window. The argument
15948     * must be an array of two integers. After the method returns, the array
15949     * contains the x and y location in that order.</p>
15950     *
15951     * @param location an array of two integers in which to hold the coordinates
15952     */
15953    public void getLocationInWindow(int[] location) {
15954        if (location == null || location.length < 2) {
15955            throw new IllegalArgumentException("location must be an array of two integers");
15956        }
15957
15958        if (mAttachInfo == null) {
15959            // When the view is not attached to a window, this method does not make sense
15960            location[0] = location[1] = 0;
15961            return;
15962        }
15963
15964        float[] position = mAttachInfo.mTmpTransformLocation;
15965        position[0] = position[1] = 0.0f;
15966
15967        if (!hasIdentityMatrix()) {
15968            getMatrix().mapPoints(position);
15969        }
15970
15971        position[0] += mLeft;
15972        position[1] += mTop;
15973
15974        ViewParent viewParent = mParent;
15975        while (viewParent instanceof View) {
15976            final View view = (View) viewParent;
15977
15978            position[0] -= view.mScrollX;
15979            position[1] -= view.mScrollY;
15980
15981            if (!view.hasIdentityMatrix()) {
15982                view.getMatrix().mapPoints(position);
15983            }
15984
15985            position[0] += view.mLeft;
15986            position[1] += view.mTop;
15987
15988            viewParent = view.mParent;
15989         }
15990
15991        if (viewParent instanceof ViewRootImpl) {
15992            // *cough*
15993            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15994            position[1] -= vr.mCurScrollY;
15995        }
15996
15997        location[0] = (int) (position[0] + 0.5f);
15998        location[1] = (int) (position[1] + 0.5f);
15999    }
16000
16001    /**
16002     * {@hide}
16003     * @param id the id of the view to be found
16004     * @return the view of the specified id, null if cannot be found
16005     */
16006    protected View findViewTraversal(int id) {
16007        if (id == mID) {
16008            return this;
16009        }
16010        return null;
16011    }
16012
16013    /**
16014     * {@hide}
16015     * @param tag the tag of the view to be found
16016     * @return the view of specified tag, null if cannot be found
16017     */
16018    protected View findViewWithTagTraversal(Object tag) {
16019        if (tag != null && tag.equals(mTag)) {
16020            return this;
16021        }
16022        return null;
16023    }
16024
16025    /**
16026     * {@hide}
16027     * @param predicate The predicate to evaluate.
16028     * @param childToSkip If not null, ignores this child during the recursive traversal.
16029     * @return The first view that matches the predicate or null.
16030     */
16031    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16032        if (predicate.apply(this)) {
16033            return this;
16034        }
16035        return null;
16036    }
16037
16038    /**
16039     * Look for a child view with the given id.  If this view has the given
16040     * id, return this view.
16041     *
16042     * @param id The id to search for.
16043     * @return The view that has the given id in the hierarchy or null
16044     */
16045    public final View findViewById(int id) {
16046        if (id < 0) {
16047            return null;
16048        }
16049        return findViewTraversal(id);
16050    }
16051
16052    /**
16053     * Finds a view by its unuque and stable accessibility id.
16054     *
16055     * @param accessibilityId The searched accessibility id.
16056     * @return The found view.
16057     */
16058    final View findViewByAccessibilityId(int accessibilityId) {
16059        if (accessibilityId < 0) {
16060            return null;
16061        }
16062        return findViewByAccessibilityIdTraversal(accessibilityId);
16063    }
16064
16065    /**
16066     * Performs the traversal to find a view by its unuque and stable accessibility id.
16067     *
16068     * <strong>Note:</strong>This method does not stop at the root namespace
16069     * boundary since the user can touch the screen at an arbitrary location
16070     * potentially crossing the root namespace bounday which will send an
16071     * accessibility event to accessibility services and they should be able
16072     * to obtain the event source. Also accessibility ids are guaranteed to be
16073     * unique in the window.
16074     *
16075     * @param accessibilityId The accessibility id.
16076     * @return The found view.
16077     *
16078     * @hide
16079     */
16080    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16081        if (getAccessibilityViewId() == accessibilityId) {
16082            return this;
16083        }
16084        return null;
16085    }
16086
16087    /**
16088     * Look for a child view with the given tag.  If this view has the given
16089     * tag, return this view.
16090     *
16091     * @param tag The tag to search for, using "tag.equals(getTag())".
16092     * @return The View that has the given tag in the hierarchy or null
16093     */
16094    public final View findViewWithTag(Object tag) {
16095        if (tag == null) {
16096            return null;
16097        }
16098        return findViewWithTagTraversal(tag);
16099    }
16100
16101    /**
16102     * {@hide}
16103     * Look for a child view that matches the specified predicate.
16104     * If this view matches the predicate, return this view.
16105     *
16106     * @param predicate The predicate to evaluate.
16107     * @return The first view that matches the predicate or null.
16108     */
16109    public final View findViewByPredicate(Predicate<View> predicate) {
16110        return findViewByPredicateTraversal(predicate, null);
16111    }
16112
16113    /**
16114     * {@hide}
16115     * Look for a child view that matches the specified predicate,
16116     * starting with the specified view and its descendents and then
16117     * recusively searching the ancestors and siblings of that view
16118     * until this view is reached.
16119     *
16120     * This method is useful in cases where the predicate does not match
16121     * a single unique view (perhaps multiple views use the same id)
16122     * and we are trying to find the view that is "closest" in scope to the
16123     * starting view.
16124     *
16125     * @param start The view to start from.
16126     * @param predicate The predicate to evaluate.
16127     * @return The first view that matches the predicate or null.
16128     */
16129    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16130        View childToSkip = null;
16131        for (;;) {
16132            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16133            if (view != null || start == this) {
16134                return view;
16135            }
16136
16137            ViewParent parent = start.getParent();
16138            if (parent == null || !(parent instanceof View)) {
16139                return null;
16140            }
16141
16142            childToSkip = start;
16143            start = (View) parent;
16144        }
16145    }
16146
16147    /**
16148     * Sets the identifier for this view. The identifier does not have to be
16149     * unique in this view's hierarchy. The identifier should be a positive
16150     * number.
16151     *
16152     * @see #NO_ID
16153     * @see #getId()
16154     * @see #findViewById(int)
16155     *
16156     * @param id a number used to identify the view
16157     *
16158     * @attr ref android.R.styleable#View_id
16159     */
16160    public void setId(int id) {
16161        mID = id;
16162        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16163            mID = generateViewId();
16164        }
16165    }
16166
16167    /**
16168     * {@hide}
16169     *
16170     * @param isRoot true if the view belongs to the root namespace, false
16171     *        otherwise
16172     */
16173    public void setIsRootNamespace(boolean isRoot) {
16174        if (isRoot) {
16175            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16176        } else {
16177            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16178        }
16179    }
16180
16181    /**
16182     * {@hide}
16183     *
16184     * @return true if the view belongs to the root namespace, false otherwise
16185     */
16186    public boolean isRootNamespace() {
16187        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16188    }
16189
16190    /**
16191     * Returns this view's identifier.
16192     *
16193     * @return a positive integer used to identify the view or {@link #NO_ID}
16194     *         if the view has no ID
16195     *
16196     * @see #setId(int)
16197     * @see #findViewById(int)
16198     * @attr ref android.R.styleable#View_id
16199     */
16200    @ViewDebug.CapturedViewProperty
16201    public int getId() {
16202        return mID;
16203    }
16204
16205    /**
16206     * Returns this view's tag.
16207     *
16208     * @return the Object stored in this view as a tag
16209     *
16210     * @see #setTag(Object)
16211     * @see #getTag(int)
16212     */
16213    @ViewDebug.ExportedProperty
16214    public Object getTag() {
16215        return mTag;
16216    }
16217
16218    /**
16219     * Sets the tag associated with this view. A tag can be used to mark
16220     * a view in its hierarchy and does not have to be unique within the
16221     * hierarchy. Tags can also be used to store data within a view without
16222     * resorting to another data structure.
16223     *
16224     * @param tag an Object to tag the view with
16225     *
16226     * @see #getTag()
16227     * @see #setTag(int, Object)
16228     */
16229    public void setTag(final Object tag) {
16230        mTag = tag;
16231    }
16232
16233    /**
16234     * Returns the tag associated with this view and the specified key.
16235     *
16236     * @param key The key identifying the tag
16237     *
16238     * @return the Object stored in this view as a tag
16239     *
16240     * @see #setTag(int, Object)
16241     * @see #getTag()
16242     */
16243    public Object getTag(int key) {
16244        if (mKeyedTags != null) return mKeyedTags.get(key);
16245        return null;
16246    }
16247
16248    /**
16249     * Sets a tag associated with this view and a key. A tag can be used
16250     * to mark a view in its hierarchy and does not have to be unique within
16251     * the hierarchy. Tags can also be used to store data within a view
16252     * without resorting to another data structure.
16253     *
16254     * The specified key should be an id declared in the resources of the
16255     * application to ensure it is unique (see the <a
16256     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16257     * Keys identified as belonging to
16258     * the Android framework or not associated with any package will cause
16259     * an {@link IllegalArgumentException} to be thrown.
16260     *
16261     * @param key The key identifying the tag
16262     * @param tag An Object to tag the view with
16263     *
16264     * @throws IllegalArgumentException If they specified key is not valid
16265     *
16266     * @see #setTag(Object)
16267     * @see #getTag(int)
16268     */
16269    public void setTag(int key, final Object tag) {
16270        // If the package id is 0x00 or 0x01, it's either an undefined package
16271        // or a framework id
16272        if ((key >>> 24) < 2) {
16273            throw new IllegalArgumentException("The key must be an application-specific "
16274                    + "resource id.");
16275        }
16276
16277        setKeyedTag(key, tag);
16278    }
16279
16280    /**
16281     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16282     * framework id.
16283     *
16284     * @hide
16285     */
16286    public void setTagInternal(int key, Object tag) {
16287        if ((key >>> 24) != 0x1) {
16288            throw new IllegalArgumentException("The key must be a framework-specific "
16289                    + "resource id.");
16290        }
16291
16292        setKeyedTag(key, tag);
16293    }
16294
16295    private void setKeyedTag(int key, Object tag) {
16296        if (mKeyedTags == null) {
16297            mKeyedTags = new SparseArray<Object>(2);
16298        }
16299
16300        mKeyedTags.put(key, tag);
16301    }
16302
16303    /**
16304     * Prints information about this view in the log output, with the tag
16305     * {@link #VIEW_LOG_TAG}.
16306     *
16307     * @hide
16308     */
16309    public void debug() {
16310        debug(0);
16311    }
16312
16313    /**
16314     * Prints information about this view in the log output, with the tag
16315     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16316     * indentation defined by the <code>depth</code>.
16317     *
16318     * @param depth the indentation level
16319     *
16320     * @hide
16321     */
16322    protected void debug(int depth) {
16323        String output = debugIndent(depth - 1);
16324
16325        output += "+ " + this;
16326        int id = getId();
16327        if (id != -1) {
16328            output += " (id=" + id + ")";
16329        }
16330        Object tag = getTag();
16331        if (tag != null) {
16332            output += " (tag=" + tag + ")";
16333        }
16334        Log.d(VIEW_LOG_TAG, output);
16335
16336        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16337            output = debugIndent(depth) + " FOCUSED";
16338            Log.d(VIEW_LOG_TAG, output);
16339        }
16340
16341        output = debugIndent(depth);
16342        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16343                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16344                + "} ";
16345        Log.d(VIEW_LOG_TAG, output);
16346
16347        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16348                || mPaddingBottom != 0) {
16349            output = debugIndent(depth);
16350            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16351                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16352            Log.d(VIEW_LOG_TAG, output);
16353        }
16354
16355        output = debugIndent(depth);
16356        output += "mMeasureWidth=" + mMeasuredWidth +
16357                " mMeasureHeight=" + mMeasuredHeight;
16358        Log.d(VIEW_LOG_TAG, output);
16359
16360        output = debugIndent(depth);
16361        if (mLayoutParams == null) {
16362            output += "BAD! no layout params";
16363        } else {
16364            output = mLayoutParams.debug(output);
16365        }
16366        Log.d(VIEW_LOG_TAG, output);
16367
16368        output = debugIndent(depth);
16369        output += "flags={";
16370        output += View.printFlags(mViewFlags);
16371        output += "}";
16372        Log.d(VIEW_LOG_TAG, output);
16373
16374        output = debugIndent(depth);
16375        output += "privateFlags={";
16376        output += View.printPrivateFlags(mPrivateFlags);
16377        output += "}";
16378        Log.d(VIEW_LOG_TAG, output);
16379    }
16380
16381    /**
16382     * Creates a string of whitespaces used for indentation.
16383     *
16384     * @param depth the indentation level
16385     * @return a String containing (depth * 2 + 3) * 2 white spaces
16386     *
16387     * @hide
16388     */
16389    protected static String debugIndent(int depth) {
16390        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16391        for (int i = 0; i < (depth * 2) + 3; i++) {
16392            spaces.append(' ').append(' ');
16393        }
16394        return spaces.toString();
16395    }
16396
16397    /**
16398     * <p>Return the offset of the widget's text baseline from the widget's top
16399     * boundary. If this widget does not support baseline alignment, this
16400     * method returns -1. </p>
16401     *
16402     * @return the offset of the baseline within the widget's bounds or -1
16403     *         if baseline alignment is not supported
16404     */
16405    @ViewDebug.ExportedProperty(category = "layout")
16406    public int getBaseline() {
16407        return -1;
16408    }
16409
16410    /**
16411     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16412     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16413     * a layout pass.
16414     *
16415     * @return whether the view hierarchy is currently undergoing a layout pass
16416     */
16417    public boolean isInLayout() {
16418        ViewRootImpl viewRoot = getViewRootImpl();
16419        return (viewRoot != null && viewRoot.isInLayout());
16420    }
16421
16422    /**
16423     * Call this when something has changed which has invalidated the
16424     * layout of this view. This will schedule a layout pass of the view
16425     * tree. This should not be called while the view hierarchy is currently in a layout
16426     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16427     * end of the current layout pass (and then layout will run again) or after the current
16428     * frame is drawn and the next layout occurs.
16429     *
16430     * <p>Subclasses which override this method should call the superclass method to
16431     * handle possible request-during-layout errors correctly.</p>
16432     */
16433    public void requestLayout() {
16434        if (mMeasureCache != null) mMeasureCache.clear();
16435
16436        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16437            // Only trigger request-during-layout logic if this is the view requesting it,
16438            // not the views in its parent hierarchy
16439            ViewRootImpl viewRoot = getViewRootImpl();
16440            if (viewRoot != null && viewRoot.isInLayout()) {
16441                if (!viewRoot.requestLayoutDuringLayout(this)) {
16442                    return;
16443                }
16444            }
16445            mAttachInfo.mViewRequestingLayout = this;
16446        }
16447
16448        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16449        mPrivateFlags |= PFLAG_INVALIDATED;
16450
16451        if (mParent != null && !mParent.isLayoutRequested()) {
16452            mParent.requestLayout();
16453        }
16454        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16455            mAttachInfo.mViewRequestingLayout = null;
16456        }
16457    }
16458
16459    /**
16460     * Forces this view to be laid out during the next layout pass.
16461     * This method does not call requestLayout() or forceLayout()
16462     * on the parent.
16463     */
16464    public void forceLayout() {
16465        if (mMeasureCache != null) mMeasureCache.clear();
16466
16467        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16468        mPrivateFlags |= PFLAG_INVALIDATED;
16469    }
16470
16471    /**
16472     * <p>
16473     * This is called to find out how big a view should be. The parent
16474     * supplies constraint information in the width and height parameters.
16475     * </p>
16476     *
16477     * <p>
16478     * The actual measurement work of a view is performed in
16479     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16480     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16481     * </p>
16482     *
16483     *
16484     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16485     *        parent
16486     * @param heightMeasureSpec Vertical space requirements as imposed by the
16487     *        parent
16488     *
16489     * @see #onMeasure(int, int)
16490     */
16491    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16492        boolean optical = isLayoutModeOptical(this);
16493        if (optical != isLayoutModeOptical(mParent)) {
16494            Insets insets = getOpticalInsets();
16495            int oWidth  = insets.left + insets.right;
16496            int oHeight = insets.top  + insets.bottom;
16497            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16498            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16499        }
16500
16501        // Suppress sign extension for the low bytes
16502        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16503        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16504
16505        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16506                widthMeasureSpec != mOldWidthMeasureSpec ||
16507                heightMeasureSpec != mOldHeightMeasureSpec) {
16508
16509            // first clears the measured dimension flag
16510            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16511
16512            resolveRtlPropertiesIfNeeded();
16513
16514            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16515                    mMeasureCache.indexOfKey(key);
16516            if (cacheIndex < 0) {
16517                // measure ourselves, this should set the measured dimension flag back
16518                onMeasure(widthMeasureSpec, heightMeasureSpec);
16519                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16520            } else {
16521                long value = mMeasureCache.valueAt(cacheIndex);
16522                // Casting a long to int drops the high 32 bits, no mask needed
16523                setMeasuredDimension((int) (value >> 32), (int) value);
16524                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16525            }
16526
16527            // flag not set, setMeasuredDimension() was not invoked, we raise
16528            // an exception to warn the developer
16529            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16530                throw new IllegalStateException("onMeasure() did not set the"
16531                        + " measured dimension by calling"
16532                        + " setMeasuredDimension()");
16533            }
16534
16535            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16536        }
16537
16538        mOldWidthMeasureSpec = widthMeasureSpec;
16539        mOldHeightMeasureSpec = heightMeasureSpec;
16540
16541        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16542                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16543    }
16544
16545    /**
16546     * <p>
16547     * Measure the view and its content to determine the measured width and the
16548     * measured height. This method is invoked by {@link #measure(int, int)} and
16549     * should be overriden by subclasses to provide accurate and efficient
16550     * measurement of their contents.
16551     * </p>
16552     *
16553     * <p>
16554     * <strong>CONTRACT:</strong> When overriding this method, you
16555     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16556     * measured width and height of this view. Failure to do so will trigger an
16557     * <code>IllegalStateException</code>, thrown by
16558     * {@link #measure(int, int)}. Calling the superclass'
16559     * {@link #onMeasure(int, int)} is a valid use.
16560     * </p>
16561     *
16562     * <p>
16563     * The base class implementation of measure defaults to the background size,
16564     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16565     * override {@link #onMeasure(int, int)} to provide better measurements of
16566     * their content.
16567     * </p>
16568     *
16569     * <p>
16570     * If this method is overridden, it is the subclass's responsibility to make
16571     * sure the measured height and width are at least the view's minimum height
16572     * and width ({@link #getSuggestedMinimumHeight()} and
16573     * {@link #getSuggestedMinimumWidth()}).
16574     * </p>
16575     *
16576     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16577     *                         The requirements are encoded with
16578     *                         {@link android.view.View.MeasureSpec}.
16579     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16580     *                         The requirements are encoded with
16581     *                         {@link android.view.View.MeasureSpec}.
16582     *
16583     * @see #getMeasuredWidth()
16584     * @see #getMeasuredHeight()
16585     * @see #setMeasuredDimension(int, int)
16586     * @see #getSuggestedMinimumHeight()
16587     * @see #getSuggestedMinimumWidth()
16588     * @see android.view.View.MeasureSpec#getMode(int)
16589     * @see android.view.View.MeasureSpec#getSize(int)
16590     */
16591    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16592        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16593                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16594    }
16595
16596    /**
16597     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16598     * measured width and measured height. Failing to do so will trigger an
16599     * exception at measurement time.</p>
16600     *
16601     * @param measuredWidth The measured width of this view.  May be a complex
16602     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16603     * {@link #MEASURED_STATE_TOO_SMALL}.
16604     * @param measuredHeight The measured height of this view.  May be a complex
16605     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16606     * {@link #MEASURED_STATE_TOO_SMALL}.
16607     */
16608    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16609        boolean optical = isLayoutModeOptical(this);
16610        if (optical != isLayoutModeOptical(mParent)) {
16611            Insets insets = getOpticalInsets();
16612            int opticalWidth  = insets.left + insets.right;
16613            int opticalHeight = insets.top  + insets.bottom;
16614
16615            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16616            measuredHeight += optical ? opticalHeight : -opticalHeight;
16617        }
16618        mMeasuredWidth = measuredWidth;
16619        mMeasuredHeight = measuredHeight;
16620
16621        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16622    }
16623
16624    /**
16625     * Merge two states as returned by {@link #getMeasuredState()}.
16626     * @param curState The current state as returned from a view or the result
16627     * of combining multiple views.
16628     * @param newState The new view state to combine.
16629     * @return Returns a new integer reflecting the combination of the two
16630     * states.
16631     */
16632    public static int combineMeasuredStates(int curState, int newState) {
16633        return curState | newState;
16634    }
16635
16636    /**
16637     * Version of {@link #resolveSizeAndState(int, int, int)}
16638     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16639     */
16640    public static int resolveSize(int size, int measureSpec) {
16641        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16642    }
16643
16644    /**
16645     * Utility to reconcile a desired size and state, with constraints imposed
16646     * by a MeasureSpec.  Will take the desired size, unless a different size
16647     * is imposed by the constraints.  The returned value is a compound integer,
16648     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16649     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16650     * size is smaller than the size the view wants to be.
16651     *
16652     * @param size How big the view wants to be
16653     * @param measureSpec Constraints imposed by the parent
16654     * @return Size information bit mask as defined by
16655     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16656     */
16657    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16658        int result = size;
16659        int specMode = MeasureSpec.getMode(measureSpec);
16660        int specSize =  MeasureSpec.getSize(measureSpec);
16661        switch (specMode) {
16662        case MeasureSpec.UNSPECIFIED:
16663            result = size;
16664            break;
16665        case MeasureSpec.AT_MOST:
16666            if (specSize < size) {
16667                result = specSize | MEASURED_STATE_TOO_SMALL;
16668            } else {
16669                result = size;
16670            }
16671            break;
16672        case MeasureSpec.EXACTLY:
16673            result = specSize;
16674            break;
16675        }
16676        return result | (childMeasuredState&MEASURED_STATE_MASK);
16677    }
16678
16679    /**
16680     * Utility to return a default size. Uses the supplied size if the
16681     * MeasureSpec imposed no constraints. Will get larger if allowed
16682     * by the MeasureSpec.
16683     *
16684     * @param size Default size for this view
16685     * @param measureSpec Constraints imposed by the parent
16686     * @return The size this view should be.
16687     */
16688    public static int getDefaultSize(int size, int measureSpec) {
16689        int result = size;
16690        int specMode = MeasureSpec.getMode(measureSpec);
16691        int specSize = MeasureSpec.getSize(measureSpec);
16692
16693        switch (specMode) {
16694        case MeasureSpec.UNSPECIFIED:
16695            result = size;
16696            break;
16697        case MeasureSpec.AT_MOST:
16698        case MeasureSpec.EXACTLY:
16699            result = specSize;
16700            break;
16701        }
16702        return result;
16703    }
16704
16705    /**
16706     * Returns the suggested minimum height that the view should use. This
16707     * returns the maximum of the view's minimum height
16708     * and the background's minimum height
16709     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16710     * <p>
16711     * When being used in {@link #onMeasure(int, int)}, the caller should still
16712     * ensure the returned height is within the requirements of the parent.
16713     *
16714     * @return The suggested minimum height of the view.
16715     */
16716    protected int getSuggestedMinimumHeight() {
16717        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16718
16719    }
16720
16721    /**
16722     * Returns the suggested minimum width that the view should use. This
16723     * returns the maximum of the view's minimum width)
16724     * and the background's minimum width
16725     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16726     * <p>
16727     * When being used in {@link #onMeasure(int, int)}, the caller should still
16728     * ensure the returned width is within the requirements of the parent.
16729     *
16730     * @return The suggested minimum width of the view.
16731     */
16732    protected int getSuggestedMinimumWidth() {
16733        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16734    }
16735
16736    /**
16737     * Returns the minimum height of the view.
16738     *
16739     * @return the minimum height the view will try to be.
16740     *
16741     * @see #setMinimumHeight(int)
16742     *
16743     * @attr ref android.R.styleable#View_minHeight
16744     */
16745    public int getMinimumHeight() {
16746        return mMinHeight;
16747    }
16748
16749    /**
16750     * Sets the minimum height of the view. It is not guaranteed the view will
16751     * be able to achieve this minimum height (for example, if its parent layout
16752     * constrains it with less available height).
16753     *
16754     * @param minHeight The minimum height the view will try to be.
16755     *
16756     * @see #getMinimumHeight()
16757     *
16758     * @attr ref android.R.styleable#View_minHeight
16759     */
16760    public void setMinimumHeight(int minHeight) {
16761        mMinHeight = minHeight;
16762        requestLayout();
16763    }
16764
16765    /**
16766     * Returns the minimum width of the view.
16767     *
16768     * @return the minimum width the view will try to be.
16769     *
16770     * @see #setMinimumWidth(int)
16771     *
16772     * @attr ref android.R.styleable#View_minWidth
16773     */
16774    public int getMinimumWidth() {
16775        return mMinWidth;
16776    }
16777
16778    /**
16779     * Sets the minimum width of the view. It is not guaranteed the view will
16780     * be able to achieve this minimum width (for example, if its parent layout
16781     * constrains it with less available width).
16782     *
16783     * @param minWidth The minimum width the view will try to be.
16784     *
16785     * @see #getMinimumWidth()
16786     *
16787     * @attr ref android.R.styleable#View_minWidth
16788     */
16789    public void setMinimumWidth(int minWidth) {
16790        mMinWidth = minWidth;
16791        requestLayout();
16792
16793    }
16794
16795    /**
16796     * Get the animation currently associated with this view.
16797     *
16798     * @return The animation that is currently playing or
16799     *         scheduled to play for this view.
16800     */
16801    public Animation getAnimation() {
16802        return mCurrentAnimation;
16803    }
16804
16805    /**
16806     * Start the specified animation now.
16807     *
16808     * @param animation the animation to start now
16809     */
16810    public void startAnimation(Animation animation) {
16811        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16812        setAnimation(animation);
16813        invalidateParentCaches();
16814        invalidate(true);
16815    }
16816
16817    /**
16818     * Cancels any animations for this view.
16819     */
16820    public void clearAnimation() {
16821        if (mCurrentAnimation != null) {
16822            mCurrentAnimation.detach();
16823        }
16824        mCurrentAnimation = null;
16825        invalidateParentIfNeeded();
16826    }
16827
16828    /**
16829     * Sets the next animation to play for this view.
16830     * If you want the animation to play immediately, use
16831     * {@link #startAnimation(android.view.animation.Animation)} instead.
16832     * This method provides allows fine-grained
16833     * control over the start time and invalidation, but you
16834     * must make sure that 1) the animation has a start time set, and
16835     * 2) the view's parent (which controls animations on its children)
16836     * will be invalidated when the animation is supposed to
16837     * start.
16838     *
16839     * @param animation The next animation, or null.
16840     */
16841    public void setAnimation(Animation animation) {
16842        mCurrentAnimation = animation;
16843
16844        if (animation != null) {
16845            // If the screen is off assume the animation start time is now instead of
16846            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16847            // would cause the animation to start when the screen turns back on
16848            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16849                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16850                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16851            }
16852            animation.reset();
16853        }
16854    }
16855
16856    /**
16857     * Invoked by a parent ViewGroup to notify the start of the animation
16858     * currently associated with this view. If you override this method,
16859     * always call super.onAnimationStart();
16860     *
16861     * @see #setAnimation(android.view.animation.Animation)
16862     * @see #getAnimation()
16863     */
16864    protected void onAnimationStart() {
16865        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16866    }
16867
16868    /**
16869     * Invoked by a parent ViewGroup to notify the end of the animation
16870     * currently associated with this view. If you override this method,
16871     * always call super.onAnimationEnd();
16872     *
16873     * @see #setAnimation(android.view.animation.Animation)
16874     * @see #getAnimation()
16875     */
16876    protected void onAnimationEnd() {
16877        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16878    }
16879
16880    /**
16881     * Invoked if there is a Transform that involves alpha. Subclass that can
16882     * draw themselves with the specified alpha should return true, and then
16883     * respect that alpha when their onDraw() is called. If this returns false
16884     * then the view may be redirected to draw into an offscreen buffer to
16885     * fulfill the request, which will look fine, but may be slower than if the
16886     * subclass handles it internally. The default implementation returns false.
16887     *
16888     * @param alpha The alpha (0..255) to apply to the view's drawing
16889     * @return true if the view can draw with the specified alpha.
16890     */
16891    protected boolean onSetAlpha(int alpha) {
16892        return false;
16893    }
16894
16895    /**
16896     * This is used by the RootView to perform an optimization when
16897     * the view hierarchy contains one or several SurfaceView.
16898     * SurfaceView is always considered transparent, but its children are not,
16899     * therefore all View objects remove themselves from the global transparent
16900     * region (passed as a parameter to this function).
16901     *
16902     * @param region The transparent region for this ViewAncestor (window).
16903     *
16904     * @return Returns true if the effective visibility of the view at this
16905     * point is opaque, regardless of the transparent region; returns false
16906     * if it is possible for underlying windows to be seen behind the view.
16907     *
16908     * {@hide}
16909     */
16910    public boolean gatherTransparentRegion(Region region) {
16911        final AttachInfo attachInfo = mAttachInfo;
16912        if (region != null && attachInfo != null) {
16913            final int pflags = mPrivateFlags;
16914            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16915                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16916                // remove it from the transparent region.
16917                final int[] location = attachInfo.mTransparentLocation;
16918                getLocationInWindow(location);
16919                region.op(location[0], location[1], location[0] + mRight - mLeft,
16920                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16921            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16922                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16923                // exists, so we remove the background drawable's non-transparent
16924                // parts from this transparent region.
16925                applyDrawableToTransparentRegion(mBackground, region);
16926            }
16927        }
16928        return true;
16929    }
16930
16931    /**
16932     * Play a sound effect for this view.
16933     *
16934     * <p>The framework will play sound effects for some built in actions, such as
16935     * clicking, but you may wish to play these effects in your widget,
16936     * for instance, for internal navigation.
16937     *
16938     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16939     * {@link #isSoundEffectsEnabled()} is true.
16940     *
16941     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16942     */
16943    public void playSoundEffect(int soundConstant) {
16944        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16945            return;
16946        }
16947        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16948    }
16949
16950    /**
16951     * BZZZTT!!1!
16952     *
16953     * <p>Provide haptic feedback to the user for this view.
16954     *
16955     * <p>The framework will provide haptic feedback for some built in actions,
16956     * such as long presses, but you may wish to provide feedback for your
16957     * own widget.
16958     *
16959     * <p>The feedback will only be performed if
16960     * {@link #isHapticFeedbackEnabled()} is true.
16961     *
16962     * @param feedbackConstant One of the constants defined in
16963     * {@link HapticFeedbackConstants}
16964     */
16965    public boolean performHapticFeedback(int feedbackConstant) {
16966        return performHapticFeedback(feedbackConstant, 0);
16967    }
16968
16969    /**
16970     * BZZZTT!!1!
16971     *
16972     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16973     *
16974     * @param feedbackConstant One of the constants defined in
16975     * {@link HapticFeedbackConstants}
16976     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16977     */
16978    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16979        if (mAttachInfo == null) {
16980            return false;
16981        }
16982        //noinspection SimplifiableIfStatement
16983        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16984                && !isHapticFeedbackEnabled()) {
16985            return false;
16986        }
16987        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16988                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16989    }
16990
16991    /**
16992     * Request that the visibility of the status bar or other screen/window
16993     * decorations be changed.
16994     *
16995     * <p>This method is used to put the over device UI into temporary modes
16996     * where the user's attention is focused more on the application content,
16997     * by dimming or hiding surrounding system affordances.  This is typically
16998     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16999     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17000     * to be placed behind the action bar (and with these flags other system
17001     * affordances) so that smooth transitions between hiding and showing them
17002     * can be done.
17003     *
17004     * <p>Two representative examples of the use of system UI visibility is
17005     * implementing a content browsing application (like a magazine reader)
17006     * and a video playing application.
17007     *
17008     * <p>The first code shows a typical implementation of a View in a content
17009     * browsing application.  In this implementation, the application goes
17010     * into a content-oriented mode by hiding the status bar and action bar,
17011     * and putting the navigation elements into lights out mode.  The user can
17012     * then interact with content while in this mode.  Such an application should
17013     * provide an easy way for the user to toggle out of the mode (such as to
17014     * check information in the status bar or access notifications).  In the
17015     * implementation here, this is done simply by tapping on the content.
17016     *
17017     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17018     *      content}
17019     *
17020     * <p>This second code sample shows a typical implementation of a View
17021     * in a video playing application.  In this situation, while the video is
17022     * playing the application would like to go into a complete full-screen mode,
17023     * to use as much of the display as possible for the video.  When in this state
17024     * the user can not interact with the application; the system intercepts
17025     * touching on the screen to pop the UI out of full screen mode.  See
17026     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17027     *
17028     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17029     *      content}
17030     *
17031     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17032     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17033     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17034     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17035     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
17036     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
17037     */
17038    public void setSystemUiVisibility(int visibility) {
17039        if (visibility != mSystemUiVisibility) {
17040            mSystemUiVisibility = visibility;
17041            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17042                mParent.recomputeViewAttributes(this);
17043            }
17044        }
17045    }
17046
17047    /**
17048     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17049     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17050     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17051     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17052     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17053     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
17054     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
17055     */
17056    public int getSystemUiVisibility() {
17057        return mSystemUiVisibility;
17058    }
17059
17060    /**
17061     * Returns the current system UI visibility that is currently set for
17062     * the entire window.  This is the combination of the
17063     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17064     * views in the window.
17065     */
17066    public int getWindowSystemUiVisibility() {
17067        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17068    }
17069
17070    /**
17071     * Override to find out when the window's requested system UI visibility
17072     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17073     * This is different from the callbacks received through
17074     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17075     * in that this is only telling you about the local request of the window,
17076     * not the actual values applied by the system.
17077     */
17078    public void onWindowSystemUiVisibilityChanged(int visible) {
17079    }
17080
17081    /**
17082     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17083     * the view hierarchy.
17084     */
17085    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17086        onWindowSystemUiVisibilityChanged(visible);
17087    }
17088
17089    /**
17090     * Set a listener to receive callbacks when the visibility of the system bar changes.
17091     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17092     */
17093    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17094        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17095        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17096            mParent.recomputeViewAttributes(this);
17097        }
17098    }
17099
17100    /**
17101     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17102     * the view hierarchy.
17103     */
17104    public void dispatchSystemUiVisibilityChanged(int visibility) {
17105        ListenerInfo li = mListenerInfo;
17106        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17107            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17108                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17109        }
17110    }
17111
17112    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17113        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17114        if (val != mSystemUiVisibility) {
17115            setSystemUiVisibility(val);
17116            return true;
17117        }
17118        return false;
17119    }
17120
17121    /** @hide */
17122    public void setDisabledSystemUiVisibility(int flags) {
17123        if (mAttachInfo != null) {
17124            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17125                mAttachInfo.mDisabledSystemUiVisibility = flags;
17126                if (mParent != null) {
17127                    mParent.recomputeViewAttributes(this);
17128                }
17129            }
17130        }
17131    }
17132
17133    /**
17134     * Creates an image that the system displays during the drag and drop
17135     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17136     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17137     * appearance as the given View. The default also positions the center of the drag shadow
17138     * directly under the touch point. If no View is provided (the constructor with no parameters
17139     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17140     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17141     * default is an invisible drag shadow.
17142     * <p>
17143     * You are not required to use the View you provide to the constructor as the basis of the
17144     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17145     * anything you want as the drag shadow.
17146     * </p>
17147     * <p>
17148     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17149     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17150     *  size and position of the drag shadow. It uses this data to construct a
17151     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17152     *  so that your application can draw the shadow image in the Canvas.
17153     * </p>
17154     *
17155     * <div class="special reference">
17156     * <h3>Developer Guides</h3>
17157     * <p>For a guide to implementing drag and drop features, read the
17158     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17159     * </div>
17160     */
17161    public static class DragShadowBuilder {
17162        private final WeakReference<View> mView;
17163
17164        /**
17165         * Constructs a shadow image builder based on a View. By default, the resulting drag
17166         * shadow will have the same appearance and dimensions as the View, with the touch point
17167         * over the center of the View.
17168         * @param view A View. Any View in scope can be used.
17169         */
17170        public DragShadowBuilder(View view) {
17171            mView = new WeakReference<View>(view);
17172        }
17173
17174        /**
17175         * Construct a shadow builder object with no associated View.  This
17176         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17177         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17178         * to supply the drag shadow's dimensions and appearance without
17179         * reference to any View object. If they are not overridden, then the result is an
17180         * invisible drag shadow.
17181         */
17182        public DragShadowBuilder() {
17183            mView = new WeakReference<View>(null);
17184        }
17185
17186        /**
17187         * Returns the View object that had been passed to the
17188         * {@link #View.DragShadowBuilder(View)}
17189         * constructor.  If that View parameter was {@code null} or if the
17190         * {@link #View.DragShadowBuilder()}
17191         * constructor was used to instantiate the builder object, this method will return
17192         * null.
17193         *
17194         * @return The View object associate with this builder object.
17195         */
17196        @SuppressWarnings({"JavadocReference"})
17197        final public View getView() {
17198            return mView.get();
17199        }
17200
17201        /**
17202         * Provides the metrics for the shadow image. These include the dimensions of
17203         * the shadow image, and the point within that shadow that should
17204         * be centered under the touch location while dragging.
17205         * <p>
17206         * The default implementation sets the dimensions of the shadow to be the
17207         * same as the dimensions of the View itself and centers the shadow under
17208         * the touch point.
17209         * </p>
17210         *
17211         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17212         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17213         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17214         * image.
17215         *
17216         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17217         * shadow image that should be underneath the touch point during the drag and drop
17218         * operation. Your application must set {@link android.graphics.Point#x} to the
17219         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17220         */
17221        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17222            final View view = mView.get();
17223            if (view != null) {
17224                shadowSize.set(view.getWidth(), view.getHeight());
17225                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17226            } else {
17227                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17228            }
17229        }
17230
17231        /**
17232         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17233         * based on the dimensions it received from the
17234         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17235         *
17236         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17237         */
17238        public void onDrawShadow(Canvas canvas) {
17239            final View view = mView.get();
17240            if (view != null) {
17241                view.draw(canvas);
17242            } else {
17243                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17244            }
17245        }
17246    }
17247
17248    /**
17249     * Starts a drag and drop operation. When your application calls this method, it passes a
17250     * {@link android.view.View.DragShadowBuilder} object to the system. The
17251     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17252     * to get metrics for the drag shadow, and then calls the object's
17253     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17254     * <p>
17255     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17256     *  drag events to all the View objects in your application that are currently visible. It does
17257     *  this either by calling the View object's drag listener (an implementation of
17258     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17259     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17260     *  Both are passed a {@link android.view.DragEvent} object that has a
17261     *  {@link android.view.DragEvent#getAction()} value of
17262     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17263     * </p>
17264     * <p>
17265     * Your application can invoke startDrag() on any attached View object. The View object does not
17266     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17267     * be related to the View the user selected for dragging.
17268     * </p>
17269     * @param data A {@link android.content.ClipData} object pointing to the data to be
17270     * transferred by the drag and drop operation.
17271     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17272     * drag shadow.
17273     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17274     * drop operation. This Object is put into every DragEvent object sent by the system during the
17275     * current drag.
17276     * <p>
17277     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17278     * to the target Views. For example, it can contain flags that differentiate between a
17279     * a copy operation and a move operation.
17280     * </p>
17281     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17282     * so the parameter should be set to 0.
17283     * @return {@code true} if the method completes successfully, or
17284     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17285     * do a drag, and so no drag operation is in progress.
17286     */
17287    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17288            Object myLocalState, int flags) {
17289        if (ViewDebug.DEBUG_DRAG) {
17290            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17291        }
17292        boolean okay = false;
17293
17294        Point shadowSize = new Point();
17295        Point shadowTouchPoint = new Point();
17296        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17297
17298        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17299                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17300            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17301        }
17302
17303        if (ViewDebug.DEBUG_DRAG) {
17304            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17305                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17306        }
17307        Surface surface = new Surface();
17308        try {
17309            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17310                    flags, shadowSize.x, shadowSize.y, surface);
17311            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17312                    + " surface=" + surface);
17313            if (token != null) {
17314                Canvas canvas = surface.lockCanvas(null);
17315                try {
17316                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17317                    shadowBuilder.onDrawShadow(canvas);
17318                } finally {
17319                    surface.unlockCanvasAndPost(canvas);
17320                }
17321
17322                final ViewRootImpl root = getViewRootImpl();
17323
17324                // Cache the local state object for delivery with DragEvents
17325                root.setLocalDragState(myLocalState);
17326
17327                // repurpose 'shadowSize' for the last touch point
17328                root.getLastTouchPoint(shadowSize);
17329
17330                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17331                        shadowSize.x, shadowSize.y,
17332                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17333                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17334
17335                // Off and running!  Release our local surface instance; the drag
17336                // shadow surface is now managed by the system process.
17337                surface.release();
17338            }
17339        } catch (Exception e) {
17340            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17341            surface.destroy();
17342        }
17343
17344        return okay;
17345    }
17346
17347    /**
17348     * Handles drag events sent by the system following a call to
17349     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17350     *<p>
17351     * When the system calls this method, it passes a
17352     * {@link android.view.DragEvent} object. A call to
17353     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17354     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17355     * operation.
17356     * @param event The {@link android.view.DragEvent} sent by the system.
17357     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17358     * in DragEvent, indicating the type of drag event represented by this object.
17359     * @return {@code true} if the method was successful, otherwise {@code false}.
17360     * <p>
17361     *  The method should return {@code true} in response to an action type of
17362     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17363     *  operation.
17364     * </p>
17365     * <p>
17366     *  The method should also return {@code true} in response to an action type of
17367     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17368     *  {@code false} if it didn't.
17369     * </p>
17370     */
17371    public boolean onDragEvent(DragEvent event) {
17372        return false;
17373    }
17374
17375    /**
17376     * Detects if this View is enabled and has a drag event listener.
17377     * If both are true, then it calls the drag event listener with the
17378     * {@link android.view.DragEvent} it received. If the drag event listener returns
17379     * {@code true}, then dispatchDragEvent() returns {@code true}.
17380     * <p>
17381     * For all other cases, the method calls the
17382     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17383     * method and returns its result.
17384     * </p>
17385     * <p>
17386     * This ensures that a drag event is always consumed, even if the View does not have a drag
17387     * event listener. However, if the View has a listener and the listener returns true, then
17388     * onDragEvent() is not called.
17389     * </p>
17390     */
17391    public boolean dispatchDragEvent(DragEvent event) {
17392        ListenerInfo li = mListenerInfo;
17393        //noinspection SimplifiableIfStatement
17394        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17395                && li.mOnDragListener.onDrag(this, event)) {
17396            return true;
17397        }
17398        return onDragEvent(event);
17399    }
17400
17401    boolean canAcceptDrag() {
17402        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17403    }
17404
17405    /**
17406     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17407     * it is ever exposed at all.
17408     * @hide
17409     */
17410    public void onCloseSystemDialogs(String reason) {
17411    }
17412
17413    /**
17414     * Given a Drawable whose bounds have been set to draw into this view,
17415     * update a Region being computed for
17416     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17417     * that any non-transparent parts of the Drawable are removed from the
17418     * given transparent region.
17419     *
17420     * @param dr The Drawable whose transparency is to be applied to the region.
17421     * @param region A Region holding the current transparency information,
17422     * where any parts of the region that are set are considered to be
17423     * transparent.  On return, this region will be modified to have the
17424     * transparency information reduced by the corresponding parts of the
17425     * Drawable that are not transparent.
17426     * {@hide}
17427     */
17428    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17429        if (DBG) {
17430            Log.i("View", "Getting transparent region for: " + this);
17431        }
17432        final Region r = dr.getTransparentRegion();
17433        final Rect db = dr.getBounds();
17434        final AttachInfo attachInfo = mAttachInfo;
17435        if (r != null && attachInfo != null) {
17436            final int w = getRight()-getLeft();
17437            final int h = getBottom()-getTop();
17438            if (db.left > 0) {
17439                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17440                r.op(0, 0, db.left, h, Region.Op.UNION);
17441            }
17442            if (db.right < w) {
17443                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17444                r.op(db.right, 0, w, h, Region.Op.UNION);
17445            }
17446            if (db.top > 0) {
17447                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17448                r.op(0, 0, w, db.top, Region.Op.UNION);
17449            }
17450            if (db.bottom < h) {
17451                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17452                r.op(0, db.bottom, w, h, Region.Op.UNION);
17453            }
17454            final int[] location = attachInfo.mTransparentLocation;
17455            getLocationInWindow(location);
17456            r.translate(location[0], location[1]);
17457            region.op(r, Region.Op.INTERSECT);
17458        } else {
17459            region.op(db, Region.Op.DIFFERENCE);
17460        }
17461    }
17462
17463    private void checkForLongClick(int delayOffset) {
17464        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17465            mHasPerformedLongPress = false;
17466
17467            if (mPendingCheckForLongPress == null) {
17468                mPendingCheckForLongPress = new CheckForLongPress();
17469            }
17470            mPendingCheckForLongPress.rememberWindowAttachCount();
17471            postDelayed(mPendingCheckForLongPress,
17472                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17473        }
17474    }
17475
17476    /**
17477     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17478     * LayoutInflater} class, which provides a full range of options for view inflation.
17479     *
17480     * @param context The Context object for your activity or application.
17481     * @param resource The resource ID to inflate
17482     * @param root A view group that will be the parent.  Used to properly inflate the
17483     * layout_* parameters.
17484     * @see LayoutInflater
17485     */
17486    public static View inflate(Context context, int resource, ViewGroup root) {
17487        LayoutInflater factory = LayoutInflater.from(context);
17488        return factory.inflate(resource, root);
17489    }
17490
17491    /**
17492     * Scroll the view with standard behavior for scrolling beyond the normal
17493     * content boundaries. Views that call this method should override
17494     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17495     * results of an over-scroll operation.
17496     *
17497     * Views can use this method to handle any touch or fling-based scrolling.
17498     *
17499     * @param deltaX Change in X in pixels
17500     * @param deltaY Change in Y in pixels
17501     * @param scrollX Current X scroll value in pixels before applying deltaX
17502     * @param scrollY Current Y scroll value in pixels before applying deltaY
17503     * @param scrollRangeX Maximum content scroll range along the X axis
17504     * @param scrollRangeY Maximum content scroll range along the Y axis
17505     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17506     *          along the X axis.
17507     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17508     *          along the Y axis.
17509     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17510     * @return true if scrolling was clamped to an over-scroll boundary along either
17511     *          axis, false otherwise.
17512     */
17513    @SuppressWarnings({"UnusedParameters"})
17514    protected boolean overScrollBy(int deltaX, int deltaY,
17515            int scrollX, int scrollY,
17516            int scrollRangeX, int scrollRangeY,
17517            int maxOverScrollX, int maxOverScrollY,
17518            boolean isTouchEvent) {
17519        final int overScrollMode = mOverScrollMode;
17520        final boolean canScrollHorizontal =
17521                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17522        final boolean canScrollVertical =
17523                computeVerticalScrollRange() > computeVerticalScrollExtent();
17524        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17525                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17526        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17527                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17528
17529        int newScrollX = scrollX + deltaX;
17530        if (!overScrollHorizontal) {
17531            maxOverScrollX = 0;
17532        }
17533
17534        int newScrollY = scrollY + deltaY;
17535        if (!overScrollVertical) {
17536            maxOverScrollY = 0;
17537        }
17538
17539        // Clamp values if at the limits and record
17540        final int left = -maxOverScrollX;
17541        final int right = maxOverScrollX + scrollRangeX;
17542        final int top = -maxOverScrollY;
17543        final int bottom = maxOverScrollY + scrollRangeY;
17544
17545        boolean clampedX = false;
17546        if (newScrollX > right) {
17547            newScrollX = right;
17548            clampedX = true;
17549        } else if (newScrollX < left) {
17550            newScrollX = left;
17551            clampedX = true;
17552        }
17553
17554        boolean clampedY = false;
17555        if (newScrollY > bottom) {
17556            newScrollY = bottom;
17557            clampedY = true;
17558        } else if (newScrollY < top) {
17559            newScrollY = top;
17560            clampedY = true;
17561        }
17562
17563        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17564
17565        return clampedX || clampedY;
17566    }
17567
17568    /**
17569     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17570     * respond to the results of an over-scroll operation.
17571     *
17572     * @param scrollX New X scroll value in pixels
17573     * @param scrollY New Y scroll value in pixels
17574     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17575     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17576     */
17577    protected void onOverScrolled(int scrollX, int scrollY,
17578            boolean clampedX, boolean clampedY) {
17579        // Intentionally empty.
17580    }
17581
17582    /**
17583     * Returns the over-scroll mode for this view. The result will be
17584     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17585     * (allow over-scrolling only if the view content is larger than the container),
17586     * or {@link #OVER_SCROLL_NEVER}.
17587     *
17588     * @return This view's over-scroll mode.
17589     */
17590    public int getOverScrollMode() {
17591        return mOverScrollMode;
17592    }
17593
17594    /**
17595     * Set the over-scroll mode for this view. Valid over-scroll modes are
17596     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17597     * (allow over-scrolling only if the view content is larger than the container),
17598     * or {@link #OVER_SCROLL_NEVER}.
17599     *
17600     * Setting the over-scroll mode of a view will have an effect only if the
17601     * view is capable of scrolling.
17602     *
17603     * @param overScrollMode The new over-scroll mode for this view.
17604     */
17605    public void setOverScrollMode(int overScrollMode) {
17606        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17607                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17608                overScrollMode != OVER_SCROLL_NEVER) {
17609            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17610        }
17611        mOverScrollMode = overScrollMode;
17612    }
17613
17614    /**
17615     * Gets a scale factor that determines the distance the view should scroll
17616     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17617     * @return The vertical scroll scale factor.
17618     * @hide
17619     */
17620    protected float getVerticalScrollFactor() {
17621        if (mVerticalScrollFactor == 0) {
17622            TypedValue outValue = new TypedValue();
17623            if (!mContext.getTheme().resolveAttribute(
17624                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17625                throw new IllegalStateException(
17626                        "Expected theme to define listPreferredItemHeight.");
17627            }
17628            mVerticalScrollFactor = outValue.getDimension(
17629                    mContext.getResources().getDisplayMetrics());
17630        }
17631        return mVerticalScrollFactor;
17632    }
17633
17634    /**
17635     * Gets a scale factor that determines the distance the view should scroll
17636     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17637     * @return The horizontal scroll scale factor.
17638     * @hide
17639     */
17640    protected float getHorizontalScrollFactor() {
17641        // TODO: Should use something else.
17642        return getVerticalScrollFactor();
17643    }
17644
17645    /**
17646     * Return the value specifying the text direction or policy that was set with
17647     * {@link #setTextDirection(int)}.
17648     *
17649     * @return the defined text direction. It can be one of:
17650     *
17651     * {@link #TEXT_DIRECTION_INHERIT},
17652     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17653     * {@link #TEXT_DIRECTION_ANY_RTL},
17654     * {@link #TEXT_DIRECTION_LTR},
17655     * {@link #TEXT_DIRECTION_RTL},
17656     * {@link #TEXT_DIRECTION_LOCALE}
17657     *
17658     * @attr ref android.R.styleable#View_textDirection
17659     *
17660     * @hide
17661     */
17662    @ViewDebug.ExportedProperty(category = "text", mapping = {
17663            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17664            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17665            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17666            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17667            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17668            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17669    })
17670    public int getRawTextDirection() {
17671        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17672    }
17673
17674    /**
17675     * Set the text direction.
17676     *
17677     * @param textDirection the direction to set. Should be one of:
17678     *
17679     * {@link #TEXT_DIRECTION_INHERIT},
17680     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17681     * {@link #TEXT_DIRECTION_ANY_RTL},
17682     * {@link #TEXT_DIRECTION_LTR},
17683     * {@link #TEXT_DIRECTION_RTL},
17684     * {@link #TEXT_DIRECTION_LOCALE}
17685     *
17686     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17687     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17688     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17689     *
17690     * @attr ref android.R.styleable#View_textDirection
17691     */
17692    public void setTextDirection(int textDirection) {
17693        if (getRawTextDirection() != textDirection) {
17694            // Reset the current text direction and the resolved one
17695            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17696            resetResolvedTextDirection();
17697            // Set the new text direction
17698            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17699            // Do resolution
17700            resolveTextDirection();
17701            // Notify change
17702            onRtlPropertiesChanged(getLayoutDirection());
17703            // Refresh
17704            requestLayout();
17705            invalidate(true);
17706        }
17707    }
17708
17709    /**
17710     * Return the resolved text direction.
17711     *
17712     * @return the resolved text direction. Returns one of:
17713     *
17714     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17715     * {@link #TEXT_DIRECTION_ANY_RTL},
17716     * {@link #TEXT_DIRECTION_LTR},
17717     * {@link #TEXT_DIRECTION_RTL},
17718     * {@link #TEXT_DIRECTION_LOCALE}
17719     *
17720     * @attr ref android.R.styleable#View_textDirection
17721     */
17722    @ViewDebug.ExportedProperty(category = "text", mapping = {
17723            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17724            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17725            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17726            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17727            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17728            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17729    })
17730    public int getTextDirection() {
17731        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17732    }
17733
17734    /**
17735     * Resolve the text direction.
17736     *
17737     * @return true if resolution has been done, false otherwise.
17738     *
17739     * @hide
17740     */
17741    public boolean resolveTextDirection() {
17742        // Reset any previous text direction resolution
17743        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17744
17745        if (hasRtlSupport()) {
17746            // Set resolved text direction flag depending on text direction flag
17747            final int textDirection = getRawTextDirection();
17748            switch(textDirection) {
17749                case TEXT_DIRECTION_INHERIT:
17750                    if (!canResolveTextDirection()) {
17751                        // We cannot do the resolution if there is no parent, so use the default one
17752                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17753                        // Resolution will need to happen again later
17754                        return false;
17755                    }
17756
17757                    // Parent has not yet resolved, so we still return the default
17758                    try {
17759                        if (!mParent.isTextDirectionResolved()) {
17760                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17761                            // Resolution will need to happen again later
17762                            return false;
17763                        }
17764                    } catch (AbstractMethodError e) {
17765                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17766                                " does not fully implement ViewParent", e);
17767                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17768                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17769                        return true;
17770                    }
17771
17772                    // Set current resolved direction to the same value as the parent's one
17773                    int parentResolvedDirection;
17774                    try {
17775                        parentResolvedDirection = mParent.getTextDirection();
17776                    } catch (AbstractMethodError e) {
17777                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17778                                " does not fully implement ViewParent", e);
17779                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17780                    }
17781                    switch (parentResolvedDirection) {
17782                        case TEXT_DIRECTION_FIRST_STRONG:
17783                        case TEXT_DIRECTION_ANY_RTL:
17784                        case TEXT_DIRECTION_LTR:
17785                        case TEXT_DIRECTION_RTL:
17786                        case TEXT_DIRECTION_LOCALE:
17787                            mPrivateFlags2 |=
17788                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17789                            break;
17790                        default:
17791                            // Default resolved direction is "first strong" heuristic
17792                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17793                    }
17794                    break;
17795                case TEXT_DIRECTION_FIRST_STRONG:
17796                case TEXT_DIRECTION_ANY_RTL:
17797                case TEXT_DIRECTION_LTR:
17798                case TEXT_DIRECTION_RTL:
17799                case TEXT_DIRECTION_LOCALE:
17800                    // Resolved direction is the same as text direction
17801                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17802                    break;
17803                default:
17804                    // Default resolved direction is "first strong" heuristic
17805                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17806            }
17807        } else {
17808            // Default resolved direction is "first strong" heuristic
17809            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17810        }
17811
17812        // Set to resolved
17813        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17814        return true;
17815    }
17816
17817    /**
17818     * Check if text direction resolution can be done.
17819     *
17820     * @return true if text direction resolution can be done otherwise return false.
17821     */
17822    public boolean canResolveTextDirection() {
17823        switch (getRawTextDirection()) {
17824            case TEXT_DIRECTION_INHERIT:
17825                if (mParent != null) {
17826                    try {
17827                        return mParent.canResolveTextDirection();
17828                    } catch (AbstractMethodError e) {
17829                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17830                                " does not fully implement ViewParent", e);
17831                    }
17832                }
17833                return false;
17834
17835            default:
17836                return true;
17837        }
17838    }
17839
17840    /**
17841     * Reset resolved text direction. Text direction will be resolved during a call to
17842     * {@link #onMeasure(int, int)}.
17843     *
17844     * @hide
17845     */
17846    public void resetResolvedTextDirection() {
17847        // Reset any previous text direction resolution
17848        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17849        // Set to default value
17850        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17851    }
17852
17853    /**
17854     * @return true if text direction is inherited.
17855     *
17856     * @hide
17857     */
17858    public boolean isTextDirectionInherited() {
17859        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17860    }
17861
17862    /**
17863     * @return true if text direction is resolved.
17864     */
17865    public boolean isTextDirectionResolved() {
17866        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17867    }
17868
17869    /**
17870     * Return the value specifying the text alignment or policy that was set with
17871     * {@link #setTextAlignment(int)}.
17872     *
17873     * @return the defined text alignment. It can be one of:
17874     *
17875     * {@link #TEXT_ALIGNMENT_INHERIT},
17876     * {@link #TEXT_ALIGNMENT_GRAVITY},
17877     * {@link #TEXT_ALIGNMENT_CENTER},
17878     * {@link #TEXT_ALIGNMENT_TEXT_START},
17879     * {@link #TEXT_ALIGNMENT_TEXT_END},
17880     * {@link #TEXT_ALIGNMENT_VIEW_START},
17881     * {@link #TEXT_ALIGNMENT_VIEW_END}
17882     *
17883     * @attr ref android.R.styleable#View_textAlignment
17884     *
17885     * @hide
17886     */
17887    @ViewDebug.ExportedProperty(category = "text", mapping = {
17888            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17889            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17890            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17891            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17892            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17893            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17894            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17895    })
17896    @TextAlignment
17897    public int getRawTextAlignment() {
17898        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17899    }
17900
17901    /**
17902     * Set the text alignment.
17903     *
17904     * @param textAlignment The text alignment to set. Should be one of
17905     *
17906     * {@link #TEXT_ALIGNMENT_INHERIT},
17907     * {@link #TEXT_ALIGNMENT_GRAVITY},
17908     * {@link #TEXT_ALIGNMENT_CENTER},
17909     * {@link #TEXT_ALIGNMENT_TEXT_START},
17910     * {@link #TEXT_ALIGNMENT_TEXT_END},
17911     * {@link #TEXT_ALIGNMENT_VIEW_START},
17912     * {@link #TEXT_ALIGNMENT_VIEW_END}
17913     *
17914     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17915     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17916     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17917     *
17918     * @attr ref android.R.styleable#View_textAlignment
17919     */
17920    public void setTextAlignment(@TextAlignment int textAlignment) {
17921        if (textAlignment != getRawTextAlignment()) {
17922            // Reset the current and resolved text alignment
17923            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17924            resetResolvedTextAlignment();
17925            // Set the new text alignment
17926            mPrivateFlags2 |=
17927                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17928            // Do resolution
17929            resolveTextAlignment();
17930            // Notify change
17931            onRtlPropertiesChanged(getLayoutDirection());
17932            // Refresh
17933            requestLayout();
17934            invalidate(true);
17935        }
17936    }
17937
17938    /**
17939     * Return the resolved text alignment.
17940     *
17941     * @return the resolved text alignment. Returns one of:
17942     *
17943     * {@link #TEXT_ALIGNMENT_GRAVITY},
17944     * {@link #TEXT_ALIGNMENT_CENTER},
17945     * {@link #TEXT_ALIGNMENT_TEXT_START},
17946     * {@link #TEXT_ALIGNMENT_TEXT_END},
17947     * {@link #TEXT_ALIGNMENT_VIEW_START},
17948     * {@link #TEXT_ALIGNMENT_VIEW_END}
17949     *
17950     * @attr ref android.R.styleable#View_textAlignment
17951     */
17952    @ViewDebug.ExportedProperty(category = "text", mapping = {
17953            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17954            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17955            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17956            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17957            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17958            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17959            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17960    })
17961    @TextAlignment
17962    public int getTextAlignment() {
17963        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17964                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17965    }
17966
17967    /**
17968     * Resolve the text alignment.
17969     *
17970     * @return true if resolution has been done, false otherwise.
17971     *
17972     * @hide
17973     */
17974    public boolean resolveTextAlignment() {
17975        // Reset any previous text alignment resolution
17976        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17977
17978        if (hasRtlSupport()) {
17979            // Set resolved text alignment flag depending on text alignment flag
17980            final int textAlignment = getRawTextAlignment();
17981            switch (textAlignment) {
17982                case TEXT_ALIGNMENT_INHERIT:
17983                    // Check if we can resolve the text alignment
17984                    if (!canResolveTextAlignment()) {
17985                        // We cannot do the resolution if there is no parent so use the default
17986                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17987                        // Resolution will need to happen again later
17988                        return false;
17989                    }
17990
17991                    // Parent has not yet resolved, so we still return the default
17992                    try {
17993                        if (!mParent.isTextAlignmentResolved()) {
17994                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17995                            // Resolution will need to happen again later
17996                            return false;
17997                        }
17998                    } catch (AbstractMethodError e) {
17999                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18000                                " does not fully implement ViewParent", e);
18001                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18002                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18003                        return true;
18004                    }
18005
18006                    int parentResolvedTextAlignment;
18007                    try {
18008                        parentResolvedTextAlignment = mParent.getTextAlignment();
18009                    } catch (AbstractMethodError e) {
18010                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18011                                " does not fully implement ViewParent", e);
18012                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18013                    }
18014                    switch (parentResolvedTextAlignment) {
18015                        case TEXT_ALIGNMENT_GRAVITY:
18016                        case TEXT_ALIGNMENT_TEXT_START:
18017                        case TEXT_ALIGNMENT_TEXT_END:
18018                        case TEXT_ALIGNMENT_CENTER:
18019                        case TEXT_ALIGNMENT_VIEW_START:
18020                        case TEXT_ALIGNMENT_VIEW_END:
18021                            // Resolved text alignment is the same as the parent resolved
18022                            // text alignment
18023                            mPrivateFlags2 |=
18024                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18025                            break;
18026                        default:
18027                            // Use default resolved text alignment
18028                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18029                    }
18030                    break;
18031                case TEXT_ALIGNMENT_GRAVITY:
18032                case TEXT_ALIGNMENT_TEXT_START:
18033                case TEXT_ALIGNMENT_TEXT_END:
18034                case TEXT_ALIGNMENT_CENTER:
18035                case TEXT_ALIGNMENT_VIEW_START:
18036                case TEXT_ALIGNMENT_VIEW_END:
18037                    // Resolved text alignment is the same as text alignment
18038                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18039                    break;
18040                default:
18041                    // Use default resolved text alignment
18042                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18043            }
18044        } else {
18045            // Use default resolved text alignment
18046            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18047        }
18048
18049        // Set the resolved
18050        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18051        return true;
18052    }
18053
18054    /**
18055     * Check if text alignment resolution can be done.
18056     *
18057     * @return true if text alignment resolution can be done otherwise return false.
18058     */
18059    public boolean canResolveTextAlignment() {
18060        switch (getRawTextAlignment()) {
18061            case TEXT_DIRECTION_INHERIT:
18062                if (mParent != null) {
18063                    try {
18064                        return mParent.canResolveTextAlignment();
18065                    } catch (AbstractMethodError e) {
18066                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18067                                " does not fully implement ViewParent", e);
18068                    }
18069                }
18070                return false;
18071
18072            default:
18073                return true;
18074        }
18075    }
18076
18077    /**
18078     * Reset resolved text alignment. Text alignment will be resolved during a call to
18079     * {@link #onMeasure(int, int)}.
18080     *
18081     * @hide
18082     */
18083    public void resetResolvedTextAlignment() {
18084        // Reset any previous text alignment resolution
18085        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18086        // Set to default
18087        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18088    }
18089
18090    /**
18091     * @return true if text alignment is inherited.
18092     *
18093     * @hide
18094     */
18095    public boolean isTextAlignmentInherited() {
18096        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18097    }
18098
18099    /**
18100     * @return true if text alignment is resolved.
18101     */
18102    public boolean isTextAlignmentResolved() {
18103        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18104    }
18105
18106    /**
18107     * Generate a value suitable for use in {@link #setId(int)}.
18108     * This value will not collide with ID values generated at build time by aapt for R.id.
18109     *
18110     * @return a generated ID value
18111     */
18112    public static int generateViewId() {
18113        for (;;) {
18114            final int result = sNextGeneratedId.get();
18115            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18116            int newValue = result + 1;
18117            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18118            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18119                return result;
18120            }
18121        }
18122    }
18123
18124    //
18125    // Properties
18126    //
18127    /**
18128     * A Property wrapper around the <code>alpha</code> functionality handled by the
18129     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18130     */
18131    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18132        @Override
18133        public void setValue(View object, float value) {
18134            object.setAlpha(value);
18135        }
18136
18137        @Override
18138        public Float get(View object) {
18139            return object.getAlpha();
18140        }
18141    };
18142
18143    /**
18144     * A Property wrapper around the <code>translationX</code> functionality handled by the
18145     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18146     */
18147    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18148        @Override
18149        public void setValue(View object, float value) {
18150            object.setTranslationX(value);
18151        }
18152
18153                @Override
18154        public Float get(View object) {
18155            return object.getTranslationX();
18156        }
18157    };
18158
18159    /**
18160     * A Property wrapper around the <code>translationY</code> functionality handled by the
18161     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18162     */
18163    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18164        @Override
18165        public void setValue(View object, float value) {
18166            object.setTranslationY(value);
18167        }
18168
18169        @Override
18170        public Float get(View object) {
18171            return object.getTranslationY();
18172        }
18173    };
18174
18175    /**
18176     * A Property wrapper around the <code>x</code> functionality handled by the
18177     * {@link View#setX(float)} and {@link View#getX()} methods.
18178     */
18179    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18180        @Override
18181        public void setValue(View object, float value) {
18182            object.setX(value);
18183        }
18184
18185        @Override
18186        public Float get(View object) {
18187            return object.getX();
18188        }
18189    };
18190
18191    /**
18192     * A Property wrapper around the <code>y</code> functionality handled by the
18193     * {@link View#setY(float)} and {@link View#getY()} methods.
18194     */
18195    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18196        @Override
18197        public void setValue(View object, float value) {
18198            object.setY(value);
18199        }
18200
18201        @Override
18202        public Float get(View object) {
18203            return object.getY();
18204        }
18205    };
18206
18207    /**
18208     * A Property wrapper around the <code>rotation</code> functionality handled by the
18209     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18210     */
18211    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18212        @Override
18213        public void setValue(View object, float value) {
18214            object.setRotation(value);
18215        }
18216
18217        @Override
18218        public Float get(View object) {
18219            return object.getRotation();
18220        }
18221    };
18222
18223    /**
18224     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18225     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18226     */
18227    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18228        @Override
18229        public void setValue(View object, float value) {
18230            object.setRotationX(value);
18231        }
18232
18233        @Override
18234        public Float get(View object) {
18235            return object.getRotationX();
18236        }
18237    };
18238
18239    /**
18240     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18241     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18242     */
18243    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18244        @Override
18245        public void setValue(View object, float value) {
18246            object.setRotationY(value);
18247        }
18248
18249        @Override
18250        public Float get(View object) {
18251            return object.getRotationY();
18252        }
18253    };
18254
18255    /**
18256     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18257     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18258     */
18259    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18260        @Override
18261        public void setValue(View object, float value) {
18262            object.setScaleX(value);
18263        }
18264
18265        @Override
18266        public Float get(View object) {
18267            return object.getScaleX();
18268        }
18269    };
18270
18271    /**
18272     * A Property wrapper around the <code>scaleY</code> functionality handled by the
18273     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
18274     */
18275    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
18276        @Override
18277        public void setValue(View object, float value) {
18278            object.setScaleY(value);
18279        }
18280
18281        @Override
18282        public Float get(View object) {
18283            return object.getScaleY();
18284        }
18285    };
18286
18287    /**
18288     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
18289     * Each MeasureSpec represents a requirement for either the width or the height.
18290     * A MeasureSpec is comprised of a size and a mode. There are three possible
18291     * modes:
18292     * <dl>
18293     * <dt>UNSPECIFIED</dt>
18294     * <dd>
18295     * The parent has not imposed any constraint on the child. It can be whatever size
18296     * it wants.
18297     * </dd>
18298     *
18299     * <dt>EXACTLY</dt>
18300     * <dd>
18301     * The parent has determined an exact size for the child. The child is going to be
18302     * given those bounds regardless of how big it wants to be.
18303     * </dd>
18304     *
18305     * <dt>AT_MOST</dt>
18306     * <dd>
18307     * The child can be as large as it wants up to the specified size.
18308     * </dd>
18309     * </dl>
18310     *
18311     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18312     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18313     */
18314    public static class MeasureSpec {
18315        private static final int MODE_SHIFT = 30;
18316        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18317
18318        /**
18319         * Measure specification mode: The parent has not imposed any constraint
18320         * on the child. It can be whatever size it wants.
18321         */
18322        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
18323
18324        /**
18325         * Measure specification mode: The parent has determined an exact size
18326         * for the child. The child is going to be given those bounds regardless
18327         * of how big it wants to be.
18328         */
18329        public static final int EXACTLY     = 1 << MODE_SHIFT;
18330
18331        /**
18332         * Measure specification mode: The child can be as large as it wants up
18333         * to the specified size.
18334         */
18335        public static final int AT_MOST     = 2 << MODE_SHIFT;
18336
18337        /**
18338         * Creates a measure specification based on the supplied size and mode.
18339         *
18340         * The mode must always be one of the following:
18341         * <ul>
18342         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
18343         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
18344         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
18345         * </ul>
18346         *
18347         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
18348         * implementation was such that the order of arguments did not matter
18349         * and overflow in either value could impact the resulting MeasureSpec.
18350         * {@link android.widget.RelativeLayout} was affected by this bug.
18351         * Apps targeting API levels greater than 17 will get the fixed, more strict
18352         * behavior.</p>
18353         *
18354         * @param size the size of the measure specification
18355         * @param mode the mode of the measure specification
18356         * @return the measure specification based on size and mode
18357         */
18358        public static int makeMeasureSpec(int size, int mode) {
18359            if (sUseBrokenMakeMeasureSpec) {
18360                return size + mode;
18361            } else {
18362                return (size & ~MODE_MASK) | (mode & MODE_MASK);
18363            }
18364        }
18365
18366        /**
18367         * Extracts the mode from the supplied measure specification.
18368         *
18369         * @param measureSpec the measure specification to extract the mode from
18370         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
18371         *         {@link android.view.View.MeasureSpec#AT_MOST} or
18372         *         {@link android.view.View.MeasureSpec#EXACTLY}
18373         */
18374        public static int getMode(int measureSpec) {
18375            return (measureSpec & MODE_MASK);
18376        }
18377
18378        /**
18379         * Extracts the size from the supplied measure specification.
18380         *
18381         * @param measureSpec the measure specification to extract the size from
18382         * @return the size in pixels defined in the supplied measure specification
18383         */
18384        public static int getSize(int measureSpec) {
18385            return (measureSpec & ~MODE_MASK);
18386        }
18387
18388        static int adjust(int measureSpec, int delta) {
18389            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
18390        }
18391
18392        /**
18393         * Returns a String representation of the specified measure
18394         * specification.
18395         *
18396         * @param measureSpec the measure specification to convert to a String
18397         * @return a String with the following format: "MeasureSpec: MODE SIZE"
18398         */
18399        public static String toString(int measureSpec) {
18400            int mode = getMode(measureSpec);
18401            int size = getSize(measureSpec);
18402
18403            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18404
18405            if (mode == UNSPECIFIED)
18406                sb.append("UNSPECIFIED ");
18407            else if (mode == EXACTLY)
18408                sb.append("EXACTLY ");
18409            else if (mode == AT_MOST)
18410                sb.append("AT_MOST ");
18411            else
18412                sb.append(mode).append(" ");
18413
18414            sb.append(size);
18415            return sb.toString();
18416        }
18417    }
18418
18419    class CheckForLongPress implements Runnable {
18420
18421        private int mOriginalWindowAttachCount;
18422
18423        public void run() {
18424            if (isPressed() && (mParent != null)
18425                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18426                if (performLongClick()) {
18427                    mHasPerformedLongPress = true;
18428                }
18429            }
18430        }
18431
18432        public void rememberWindowAttachCount() {
18433            mOriginalWindowAttachCount = mWindowAttachCount;
18434        }
18435    }
18436
18437    private final class CheckForTap implements Runnable {
18438        public void run() {
18439            mPrivateFlags &= ~PFLAG_PREPRESSED;
18440            setPressed(true);
18441            checkForLongClick(ViewConfiguration.getTapTimeout());
18442        }
18443    }
18444
18445    private final class PerformClick implements Runnable {
18446        public void run() {
18447            performClick();
18448        }
18449    }
18450
18451    /** @hide */
18452    public void hackTurnOffWindowResizeAnim(boolean off) {
18453        mAttachInfo.mTurnOffWindowResizeAnim = off;
18454    }
18455
18456    /**
18457     * This method returns a ViewPropertyAnimator object, which can be used to animate
18458     * specific properties on this View.
18459     *
18460     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
18461     */
18462    public ViewPropertyAnimator animate() {
18463        if (mAnimator == null) {
18464            mAnimator = new ViewPropertyAnimator(this);
18465        }
18466        return mAnimator;
18467    }
18468
18469    /**
18470     * Interface definition for a callback to be invoked when a hardware key event is
18471     * dispatched to this view. The callback will be invoked before the key event is
18472     * given to the view. This is only useful for hardware keyboards; a software input
18473     * method has no obligation to trigger this listener.
18474     */
18475    public interface OnKeyListener {
18476        /**
18477         * Called when a hardware key is dispatched to a view. This allows listeners to
18478         * get a chance to respond before the target view.
18479         * <p>Key presses in software keyboards will generally NOT trigger this method,
18480         * although some may elect to do so in some situations. Do not assume a
18481         * software input method has to be key-based; even if it is, it may use key presses
18482         * in a different way than you expect, so there is no way to reliably catch soft
18483         * input key presses.
18484         *
18485         * @param v The view the key has been dispatched to.
18486         * @param keyCode The code for the physical key that was pressed
18487         * @param event The KeyEvent object containing full information about
18488         *        the event.
18489         * @return True if the listener has consumed the event, false otherwise.
18490         */
18491        boolean onKey(View v, int keyCode, KeyEvent event);
18492    }
18493
18494    /**
18495     * Interface definition for a callback to be invoked when a touch event is
18496     * dispatched to this view. The callback will be invoked before the touch
18497     * event is given to the view.
18498     */
18499    public interface OnTouchListener {
18500        /**
18501         * Called when a touch event is dispatched to a view. This allows listeners to
18502         * get a chance to respond before the target view.
18503         *
18504         * @param v The view the touch event has been dispatched to.
18505         * @param event The MotionEvent object containing full information about
18506         *        the event.
18507         * @return True if the listener has consumed the event, false otherwise.
18508         */
18509        boolean onTouch(View v, MotionEvent event);
18510    }
18511
18512    /**
18513     * Interface definition for a callback to be invoked when a hover event is
18514     * dispatched to this view. The callback will be invoked before the hover
18515     * event is given to the view.
18516     */
18517    public interface OnHoverListener {
18518        /**
18519         * Called when a hover event is dispatched to a view. This allows listeners to
18520         * get a chance to respond before the target view.
18521         *
18522         * @param v The view the hover event has been dispatched to.
18523         * @param event The MotionEvent object containing full information about
18524         *        the event.
18525         * @return True if the listener has consumed the event, false otherwise.
18526         */
18527        boolean onHover(View v, MotionEvent event);
18528    }
18529
18530    /**
18531     * Interface definition for a callback to be invoked when a generic motion event is
18532     * dispatched to this view. The callback will be invoked before the generic motion
18533     * event is given to the view.
18534     */
18535    public interface OnGenericMotionListener {
18536        /**
18537         * Called when a generic motion event is dispatched to a view. This allows listeners to
18538         * get a chance to respond before the target view.
18539         *
18540         * @param v The view the generic motion event has been dispatched to.
18541         * @param event The MotionEvent object containing full information about
18542         *        the event.
18543         * @return True if the listener has consumed the event, false otherwise.
18544         */
18545        boolean onGenericMotion(View v, MotionEvent event);
18546    }
18547
18548    /**
18549     * Interface definition for a callback to be invoked when a view has been clicked and held.
18550     */
18551    public interface OnLongClickListener {
18552        /**
18553         * Called when a view has been clicked and held.
18554         *
18555         * @param v The view that was clicked and held.
18556         *
18557         * @return true if the callback consumed the long click, false otherwise.
18558         */
18559        boolean onLongClick(View v);
18560    }
18561
18562    /**
18563     * Interface definition for a callback to be invoked when a drag is being dispatched
18564     * to this view.  The callback will be invoked before the hosting view's own
18565     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18566     * onDrag(event) behavior, it should return 'false' from this callback.
18567     *
18568     * <div class="special reference">
18569     * <h3>Developer Guides</h3>
18570     * <p>For a guide to implementing drag and drop features, read the
18571     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18572     * </div>
18573     */
18574    public interface OnDragListener {
18575        /**
18576         * Called when a drag event is dispatched to a view. This allows listeners
18577         * to get a chance to override base View behavior.
18578         *
18579         * @param v The View that received the drag event.
18580         * @param event The {@link android.view.DragEvent} object for the drag event.
18581         * @return {@code true} if the drag event was handled successfully, or {@code false}
18582         * if the drag event was not handled. Note that {@code false} will trigger the View
18583         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18584         */
18585        boolean onDrag(View v, DragEvent event);
18586    }
18587
18588    /**
18589     * Interface definition for a callback to be invoked when the focus state of
18590     * a view changed.
18591     */
18592    public interface OnFocusChangeListener {
18593        /**
18594         * Called when the focus state of a view has changed.
18595         *
18596         * @param v The view whose state has changed.
18597         * @param hasFocus The new focus state of v.
18598         */
18599        void onFocusChange(View v, boolean hasFocus);
18600    }
18601
18602    /**
18603     * Interface definition for a callback to be invoked when a view is clicked.
18604     */
18605    public interface OnClickListener {
18606        /**
18607         * Called when a view has been clicked.
18608         *
18609         * @param v The view that was clicked.
18610         */
18611        void onClick(View v);
18612    }
18613
18614    /**
18615     * Interface definition for a callback to be invoked when the context menu
18616     * for this view is being built.
18617     */
18618    public interface OnCreateContextMenuListener {
18619        /**
18620         * Called when the context menu for this view is being built. It is not
18621         * safe to hold onto the menu after this method returns.
18622         *
18623         * @param menu The context menu that is being built
18624         * @param v The view for which the context menu is being built
18625         * @param menuInfo Extra information about the item for which the
18626         *            context menu should be shown. This information will vary
18627         *            depending on the class of v.
18628         */
18629        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18630    }
18631
18632    /**
18633     * Interface definition for a callback to be invoked when the status bar changes
18634     * visibility.  This reports <strong>global</strong> changes to the system UI
18635     * state, not what the application is requesting.
18636     *
18637     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18638     */
18639    public interface OnSystemUiVisibilityChangeListener {
18640        /**
18641         * Called when the status bar changes visibility because of a call to
18642         * {@link View#setSystemUiVisibility(int)}.
18643         *
18644         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18645         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18646         * This tells you the <strong>global</strong> state of these UI visibility
18647         * flags, not what your app is currently applying.
18648         */
18649        public void onSystemUiVisibilityChange(int visibility);
18650    }
18651
18652    /**
18653     * Interface definition for a callback to be invoked when this view is attached
18654     * or detached from its window.
18655     */
18656    public interface OnAttachStateChangeListener {
18657        /**
18658         * Called when the view is attached to a window.
18659         * @param v The view that was attached
18660         */
18661        public void onViewAttachedToWindow(View v);
18662        /**
18663         * Called when the view is detached from a window.
18664         * @param v The view that was detached
18665         */
18666        public void onViewDetachedFromWindow(View v);
18667    }
18668
18669    private final class UnsetPressedState implements Runnable {
18670        public void run() {
18671            setPressed(false);
18672        }
18673    }
18674
18675    /**
18676     * Base class for derived classes that want to save and restore their own
18677     * state in {@link android.view.View#onSaveInstanceState()}.
18678     */
18679    public static class BaseSavedState extends AbsSavedState {
18680        /**
18681         * Constructor used when reading from a parcel. Reads the state of the superclass.
18682         *
18683         * @param source
18684         */
18685        public BaseSavedState(Parcel source) {
18686            super(source);
18687        }
18688
18689        /**
18690         * Constructor called by derived classes when creating their SavedState objects
18691         *
18692         * @param superState The state of the superclass of this view
18693         */
18694        public BaseSavedState(Parcelable superState) {
18695            super(superState);
18696        }
18697
18698        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18699                new Parcelable.Creator<BaseSavedState>() {
18700            public BaseSavedState createFromParcel(Parcel in) {
18701                return new BaseSavedState(in);
18702            }
18703
18704            public BaseSavedState[] newArray(int size) {
18705                return new BaseSavedState[size];
18706            }
18707        };
18708    }
18709
18710    /**
18711     * A set of information given to a view when it is attached to its parent
18712     * window.
18713     */
18714    static class AttachInfo {
18715        interface Callbacks {
18716            void playSoundEffect(int effectId);
18717            boolean performHapticFeedback(int effectId, boolean always);
18718        }
18719
18720        /**
18721         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18722         * to a Handler. This class contains the target (View) to invalidate and
18723         * the coordinates of the dirty rectangle.
18724         *
18725         * For performance purposes, this class also implements a pool of up to
18726         * POOL_LIMIT objects that get reused. This reduces memory allocations
18727         * whenever possible.
18728         */
18729        static class InvalidateInfo {
18730            private static final int POOL_LIMIT = 10;
18731
18732            private static final SynchronizedPool<InvalidateInfo> sPool =
18733                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18734
18735            View target;
18736
18737            int left;
18738            int top;
18739            int right;
18740            int bottom;
18741
18742            public static InvalidateInfo obtain() {
18743                InvalidateInfo instance = sPool.acquire();
18744                return (instance != null) ? instance : new InvalidateInfo();
18745            }
18746
18747            public void recycle() {
18748                target = null;
18749                sPool.release(this);
18750            }
18751        }
18752
18753        final IWindowSession mSession;
18754
18755        final IWindow mWindow;
18756
18757        final IBinder mWindowToken;
18758
18759        final Display mDisplay;
18760
18761        final Callbacks mRootCallbacks;
18762
18763        HardwareCanvas mHardwareCanvas;
18764
18765        IWindowId mIWindowId;
18766        WindowId mWindowId;
18767
18768        /**
18769         * The top view of the hierarchy.
18770         */
18771        View mRootView;
18772
18773        IBinder mPanelParentWindowToken;
18774        Surface mSurface;
18775
18776        boolean mHardwareAccelerated;
18777        boolean mHardwareAccelerationRequested;
18778        HardwareRenderer mHardwareRenderer;
18779
18780        boolean mScreenOn;
18781
18782        /**
18783         * Scale factor used by the compatibility mode
18784         */
18785        float mApplicationScale;
18786
18787        /**
18788         * Indicates whether the application is in compatibility mode
18789         */
18790        boolean mScalingRequired;
18791
18792        /**
18793         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18794         */
18795        boolean mTurnOffWindowResizeAnim;
18796
18797        /**
18798         * Left position of this view's window
18799         */
18800        int mWindowLeft;
18801
18802        /**
18803         * Top position of this view's window
18804         */
18805        int mWindowTop;
18806
18807        /**
18808         * Indicates whether views need to use 32-bit drawing caches
18809         */
18810        boolean mUse32BitDrawingCache;
18811
18812        /**
18813         * For windows that are full-screen but using insets to layout inside
18814         * of the screen areas, these are the current insets to appear inside
18815         * the overscan area of the display.
18816         */
18817        final Rect mOverscanInsets = new Rect();
18818
18819        /**
18820         * For windows that are full-screen but using insets to layout inside
18821         * of the screen decorations, these are the current insets for the
18822         * content of the window.
18823         */
18824        final Rect mContentInsets = new Rect();
18825
18826        /**
18827         * For windows that are full-screen but using insets to layout inside
18828         * of the screen decorations, these are the current insets for the
18829         * actual visible parts of the window.
18830         */
18831        final Rect mVisibleInsets = new Rect();
18832
18833        /**
18834         * The internal insets given by this window.  This value is
18835         * supplied by the client (through
18836         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18837         * be given to the window manager when changed to be used in laying
18838         * out windows behind it.
18839         */
18840        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18841                = new ViewTreeObserver.InternalInsetsInfo();
18842
18843        /**
18844         * All views in the window's hierarchy that serve as scroll containers,
18845         * used to determine if the window can be resized or must be panned
18846         * to adjust for a soft input area.
18847         */
18848        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18849
18850        final KeyEvent.DispatcherState mKeyDispatchState
18851                = new KeyEvent.DispatcherState();
18852
18853        /**
18854         * Indicates whether the view's window currently has the focus.
18855         */
18856        boolean mHasWindowFocus;
18857
18858        /**
18859         * The current visibility of the window.
18860         */
18861        int mWindowVisibility;
18862
18863        /**
18864         * Indicates the time at which drawing started to occur.
18865         */
18866        long mDrawingTime;
18867
18868        /**
18869         * Indicates whether or not ignoring the DIRTY_MASK flags.
18870         */
18871        boolean mIgnoreDirtyState;
18872
18873        /**
18874         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18875         * to avoid clearing that flag prematurely.
18876         */
18877        boolean mSetIgnoreDirtyState = false;
18878
18879        /**
18880         * Indicates whether the view's window is currently in touch mode.
18881         */
18882        boolean mInTouchMode;
18883
18884        /**
18885         * Indicates that ViewAncestor should trigger a global layout change
18886         * the next time it performs a traversal
18887         */
18888        boolean mRecomputeGlobalAttributes;
18889
18890        /**
18891         * Always report new attributes at next traversal.
18892         */
18893        boolean mForceReportNewAttributes;
18894
18895        /**
18896         * Set during a traveral if any views want to keep the screen on.
18897         */
18898        boolean mKeepScreenOn;
18899
18900        /**
18901         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18902         */
18903        int mSystemUiVisibility;
18904
18905        /**
18906         * Hack to force certain system UI visibility flags to be cleared.
18907         */
18908        int mDisabledSystemUiVisibility;
18909
18910        /**
18911         * Last global system UI visibility reported by the window manager.
18912         */
18913        int mGlobalSystemUiVisibility;
18914
18915        /**
18916         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18917         * attached.
18918         */
18919        boolean mHasSystemUiListeners;
18920
18921        /**
18922         * Set if the window has requested to extend into the overscan region
18923         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18924         */
18925        boolean mOverscanRequested;
18926
18927        /**
18928         * Set if the visibility of any views has changed.
18929         */
18930        boolean mViewVisibilityChanged;
18931
18932        /**
18933         * Set to true if a view has been scrolled.
18934         */
18935        boolean mViewScrollChanged;
18936
18937        /**
18938         * Global to the view hierarchy used as a temporary for dealing with
18939         * x/y points in the transparent region computations.
18940         */
18941        final int[] mTransparentLocation = new int[2];
18942
18943        /**
18944         * Global to the view hierarchy used as a temporary for dealing with
18945         * x/y points in the ViewGroup.invalidateChild implementation.
18946         */
18947        final int[] mInvalidateChildLocation = new int[2];
18948
18949
18950        /**
18951         * Global to the view hierarchy used as a temporary for dealing with
18952         * x/y location when view is transformed.
18953         */
18954        final float[] mTmpTransformLocation = new float[2];
18955
18956        /**
18957         * The view tree observer used to dispatch global events like
18958         * layout, pre-draw, touch mode change, etc.
18959         */
18960        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18961
18962        /**
18963         * A Canvas used by the view hierarchy to perform bitmap caching.
18964         */
18965        Canvas mCanvas;
18966
18967        /**
18968         * The view root impl.
18969         */
18970        final ViewRootImpl mViewRootImpl;
18971
18972        /**
18973         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18974         * handler can be used to pump events in the UI events queue.
18975         */
18976        final Handler mHandler;
18977
18978        /**
18979         * Temporary for use in computing invalidate rectangles while
18980         * calling up the hierarchy.
18981         */
18982        final Rect mTmpInvalRect = new Rect();
18983
18984        /**
18985         * Temporary for use in computing hit areas with transformed views
18986         */
18987        final RectF mTmpTransformRect = new RectF();
18988
18989        /**
18990         * Temporary for use in transforming invalidation rect
18991         */
18992        final Matrix mTmpMatrix = new Matrix();
18993
18994        /**
18995         * Temporary for use in transforming invalidation rect
18996         */
18997        final Transformation mTmpTransformation = new Transformation();
18998
18999        /**
19000         * Temporary list for use in collecting focusable descendents of a view.
19001         */
19002        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19003
19004        /**
19005         * The id of the window for accessibility purposes.
19006         */
19007        int mAccessibilityWindowId = View.NO_ID;
19008
19009        /**
19010         * Flags related to accessibility processing.
19011         *
19012         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19013         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19014         */
19015        int mAccessibilityFetchFlags;
19016
19017        /**
19018         * The drawable for highlighting accessibility focus.
19019         */
19020        Drawable mAccessibilityFocusDrawable;
19021
19022        /**
19023         * Show where the margins, bounds and layout bounds are for each view.
19024         */
19025        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19026
19027        /**
19028         * Point used to compute visible regions.
19029         */
19030        final Point mPoint = new Point();
19031
19032        /**
19033         * Used to track which View originated a requestLayout() call, used when
19034         * requestLayout() is called during layout.
19035         */
19036        View mViewRequestingLayout;
19037
19038        /**
19039         * Creates a new set of attachment information with the specified
19040         * events handler and thread.
19041         *
19042         * @param handler the events handler the view must use
19043         */
19044        AttachInfo(IWindowSession session, IWindow window, Display display,
19045                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19046            mSession = session;
19047            mWindow = window;
19048            mWindowToken = window.asBinder();
19049            mDisplay = display;
19050            mViewRootImpl = viewRootImpl;
19051            mHandler = handler;
19052            mRootCallbacks = effectPlayer;
19053        }
19054    }
19055
19056    /**
19057     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19058     * is supported. This avoids keeping too many unused fields in most
19059     * instances of View.</p>
19060     */
19061    private static class ScrollabilityCache implements Runnable {
19062
19063        /**
19064         * Scrollbars are not visible
19065         */
19066        public static final int OFF = 0;
19067
19068        /**
19069         * Scrollbars are visible
19070         */
19071        public static final int ON = 1;
19072
19073        /**
19074         * Scrollbars are fading away
19075         */
19076        public static final int FADING = 2;
19077
19078        public boolean fadeScrollBars;
19079
19080        public int fadingEdgeLength;
19081        public int scrollBarDefaultDelayBeforeFade;
19082        public int scrollBarFadeDuration;
19083
19084        public int scrollBarSize;
19085        public ScrollBarDrawable scrollBar;
19086        public float[] interpolatorValues;
19087        public View host;
19088
19089        public final Paint paint;
19090        public final Matrix matrix;
19091        public Shader shader;
19092
19093        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19094
19095        private static final float[] OPAQUE = { 255 };
19096        private static final float[] TRANSPARENT = { 0.0f };
19097
19098        /**
19099         * When fading should start. This time moves into the future every time
19100         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19101         */
19102        public long fadeStartTime;
19103
19104
19105        /**
19106         * The current state of the scrollbars: ON, OFF, or FADING
19107         */
19108        public int state = OFF;
19109
19110        private int mLastColor;
19111
19112        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19113            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19114            scrollBarSize = configuration.getScaledScrollBarSize();
19115            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19116            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19117
19118            paint = new Paint();
19119            matrix = new Matrix();
19120            // use use a height of 1, and then wack the matrix each time we
19121            // actually use it.
19122            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19123            paint.setShader(shader);
19124            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19125
19126            this.host = host;
19127        }
19128
19129        public void setFadeColor(int color) {
19130            if (color != mLastColor) {
19131                mLastColor = color;
19132
19133                if (color != 0) {
19134                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19135                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19136                    paint.setShader(shader);
19137                    // Restore the default transfer mode (src_over)
19138                    paint.setXfermode(null);
19139                } else {
19140                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19141                    paint.setShader(shader);
19142                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19143                }
19144            }
19145        }
19146
19147        public void run() {
19148            long now = AnimationUtils.currentAnimationTimeMillis();
19149            if (now >= fadeStartTime) {
19150
19151                // the animation fades the scrollbars out by changing
19152                // the opacity (alpha) from fully opaque to fully
19153                // transparent
19154                int nextFrame = (int) now;
19155                int framesCount = 0;
19156
19157                Interpolator interpolator = scrollBarInterpolator;
19158
19159                // Start opaque
19160                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19161
19162                // End transparent
19163                nextFrame += scrollBarFadeDuration;
19164                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19165
19166                state = FADING;
19167
19168                // Kick off the fade animation
19169                host.invalidate(true);
19170            }
19171        }
19172    }
19173
19174    /**
19175     * Resuable callback for sending
19176     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19177     */
19178    private class SendViewScrolledAccessibilityEvent implements Runnable {
19179        public volatile boolean mIsPending;
19180
19181        public void run() {
19182            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19183            mIsPending = false;
19184        }
19185    }
19186
19187    /**
19188     * <p>
19189     * This class represents a delegate that can be registered in a {@link View}
19190     * to enhance accessibility support via composition rather via inheritance.
19191     * It is specifically targeted to widget developers that extend basic View
19192     * classes i.e. classes in package android.view, that would like their
19193     * applications to be backwards compatible.
19194     * </p>
19195     * <div class="special reference">
19196     * <h3>Developer Guides</h3>
19197     * <p>For more information about making applications accessible, read the
19198     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19199     * developer guide.</p>
19200     * </div>
19201     * <p>
19202     * A scenario in which a developer would like to use an accessibility delegate
19203     * is overriding a method introduced in a later API version then the minimal API
19204     * version supported by the application. For example, the method
19205     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19206     * in API version 4 when the accessibility APIs were first introduced. If a
19207     * developer would like his application to run on API version 4 devices (assuming
19208     * all other APIs used by the application are version 4 or lower) and take advantage
19209     * of this method, instead of overriding the method which would break the application's
19210     * backwards compatibility, he can override the corresponding method in this
19211     * delegate and register the delegate in the target View if the API version of
19212     * the system is high enough i.e. the API version is same or higher to the API
19213     * version that introduced
19214     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
19215     * </p>
19216     * <p>
19217     * Here is an example implementation:
19218     * </p>
19219     * <code><pre><p>
19220     * if (Build.VERSION.SDK_INT >= 14) {
19221     *     // If the API version is equal of higher than the version in
19222     *     // which onInitializeAccessibilityNodeInfo was introduced we
19223     *     // register a delegate with a customized implementation.
19224     *     View view = findViewById(R.id.view_id);
19225     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
19226     *         public void onInitializeAccessibilityNodeInfo(View host,
19227     *                 AccessibilityNodeInfo info) {
19228     *             // Let the default implementation populate the info.
19229     *             super.onInitializeAccessibilityNodeInfo(host, info);
19230     *             // Set some other information.
19231     *             info.setEnabled(host.isEnabled());
19232     *         }
19233     *     });
19234     * }
19235     * </code></pre></p>
19236     * <p>
19237     * This delegate contains methods that correspond to the accessibility methods
19238     * in View. If a delegate has been specified the implementation in View hands
19239     * off handling to the corresponding method in this delegate. The default
19240     * implementation the delegate methods behaves exactly as the corresponding
19241     * method in View for the case of no accessibility delegate been set. Hence,
19242     * to customize the behavior of a View method, clients can override only the
19243     * corresponding delegate method without altering the behavior of the rest
19244     * accessibility related methods of the host view.
19245     * </p>
19246     */
19247    public static class AccessibilityDelegate {
19248
19249        /**
19250         * Sends an accessibility event of the given type. If accessibility is not
19251         * enabled this method has no effect.
19252         * <p>
19253         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
19254         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
19255         * been set.
19256         * </p>
19257         *
19258         * @param host The View hosting the delegate.
19259         * @param eventType The type of the event to send.
19260         *
19261         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
19262         */
19263        public void sendAccessibilityEvent(View host, int eventType) {
19264            host.sendAccessibilityEventInternal(eventType);
19265        }
19266
19267        /**
19268         * Performs the specified accessibility action on the view. For
19269         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
19270         * <p>
19271         * The default implementation behaves as
19272         * {@link View#performAccessibilityAction(int, Bundle)
19273         *  View#performAccessibilityAction(int, Bundle)} for the case of
19274         *  no accessibility delegate been set.
19275         * </p>
19276         *
19277         * @param action The action to perform.
19278         * @return Whether the action was performed.
19279         *
19280         * @see View#performAccessibilityAction(int, Bundle)
19281         *      View#performAccessibilityAction(int, Bundle)
19282         */
19283        public boolean performAccessibilityAction(View host, int action, Bundle args) {
19284            return host.performAccessibilityActionInternal(action, args);
19285        }
19286
19287        /**
19288         * Sends an accessibility event. This method behaves exactly as
19289         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
19290         * empty {@link AccessibilityEvent} and does not perform a check whether
19291         * accessibility is enabled.
19292         * <p>
19293         * The default implementation behaves as
19294         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19295         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
19296         * the case of no accessibility delegate been set.
19297         * </p>
19298         *
19299         * @param host The View hosting the delegate.
19300         * @param event The event to send.
19301         *
19302         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19303         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19304         */
19305        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
19306            host.sendAccessibilityEventUncheckedInternal(event);
19307        }
19308
19309        /**
19310         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
19311         * to its children for adding their text content to the event.
19312         * <p>
19313         * The default implementation behaves as
19314         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19315         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
19316         * the case of no accessibility delegate been set.
19317         * </p>
19318         *
19319         * @param host The View hosting the delegate.
19320         * @param event The event.
19321         * @return True if the event population was completed.
19322         *
19323         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19324         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19325         */
19326        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19327            return host.dispatchPopulateAccessibilityEventInternal(event);
19328        }
19329
19330        /**
19331         * Gives a chance to the host View to populate the accessibility event with its
19332         * text content.
19333         * <p>
19334         * The default implementation behaves as
19335         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
19336         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
19337         * the case of no accessibility delegate been set.
19338         * </p>
19339         *
19340         * @param host The View hosting the delegate.
19341         * @param event The accessibility event which to populate.
19342         *
19343         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
19344         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
19345         */
19346        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19347            host.onPopulateAccessibilityEventInternal(event);
19348        }
19349
19350        /**
19351         * Initializes an {@link AccessibilityEvent} with information about the
19352         * the host View which is the event source.
19353         * <p>
19354         * The default implementation behaves as
19355         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
19356         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
19357         * the case of no accessibility delegate been set.
19358         * </p>
19359         *
19360         * @param host The View hosting the delegate.
19361         * @param event The event to initialize.
19362         *
19363         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
19364         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
19365         */
19366        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
19367            host.onInitializeAccessibilityEventInternal(event);
19368        }
19369
19370        /**
19371         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
19372         * <p>
19373         * The default implementation behaves as
19374         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19375         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19376         * the case of no accessibility delegate been set.
19377         * </p>
19378         *
19379         * @param host The View hosting the delegate.
19380         * @param info The instance to initialize.
19381         *
19382         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19383         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19384         */
19385        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19386            host.onInitializeAccessibilityNodeInfoInternal(info);
19387        }
19388
19389        /**
19390         * Called when a child of the host View has requested sending an
19391         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19392         * to augment the event.
19393         * <p>
19394         * The default implementation behaves as
19395         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19396         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19397         * the case of no accessibility delegate been set.
19398         * </p>
19399         *
19400         * @param host The View hosting the delegate.
19401         * @param child The child which requests sending the event.
19402         * @param event The event to be sent.
19403         * @return True if the event should be sent
19404         *
19405         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19406         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19407         */
19408        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
19409                AccessibilityEvent event) {
19410            return host.onRequestSendAccessibilityEventInternal(child, event);
19411        }
19412
19413        /**
19414         * Gets the provider for managing a virtual view hierarchy rooted at this View
19415         * and reported to {@link android.accessibilityservice.AccessibilityService}s
19416         * that explore the window content.
19417         * <p>
19418         * The default implementation behaves as
19419         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
19420         * the case of no accessibility delegate been set.
19421         * </p>
19422         *
19423         * @return The provider.
19424         *
19425         * @see AccessibilityNodeProvider
19426         */
19427        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
19428            return null;
19429        }
19430
19431        /**
19432         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
19433         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
19434         * This method is responsible for obtaining an accessibility node info from a
19435         * pool of reusable instances and calling
19436         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
19437         * view to initialize the former.
19438         * <p>
19439         * <strong>Note:</strong> The client is responsible for recycling the obtained
19440         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
19441         * creation.
19442         * </p>
19443         * <p>
19444         * The default implementation behaves as
19445         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
19446         * the case of no accessibility delegate been set.
19447         * </p>
19448         * @return A populated {@link AccessibilityNodeInfo}.
19449         *
19450         * @see AccessibilityNodeInfo
19451         *
19452         * @hide
19453         */
19454        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
19455            return host.createAccessibilityNodeInfoInternal();
19456        }
19457    }
19458
19459    private class MatchIdPredicate implements Predicate<View> {
19460        public int mId;
19461
19462        @Override
19463        public boolean apply(View view) {
19464            return (view.mID == mId);
19465        }
19466    }
19467
19468    private class MatchLabelForPredicate implements Predicate<View> {
19469        private int mLabeledId;
19470
19471        @Override
19472        public boolean apply(View view) {
19473            return (view.mLabelForId == mLabeledId);
19474        }
19475    }
19476
19477    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19478        private int mChangeTypes = 0;
19479        private boolean mPosted;
19480        private boolean mPostedWithDelay;
19481        private long mLastEventTimeMillis;
19482
19483        @Override
19484        public void run() {
19485            mPosted = false;
19486            mPostedWithDelay = false;
19487            mLastEventTimeMillis = SystemClock.uptimeMillis();
19488            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19489                final AccessibilityEvent event = AccessibilityEvent.obtain();
19490                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19491                event.setContentChangeTypes(mChangeTypes);
19492                sendAccessibilityEventUnchecked(event);
19493            }
19494            mChangeTypes = 0;
19495        }
19496
19497        public void runOrPost(int changeType) {
19498            mChangeTypes |= changeType;
19499
19500            // If this is a live region or the child of a live region, collect
19501            // all events from this frame and send them on the next frame.
19502            if (inLiveRegion()) {
19503                // If we're already posted with a delay, remove that.
19504                if (mPostedWithDelay) {
19505                    removeCallbacks(this);
19506                    mPostedWithDelay = false;
19507                }
19508                // Only post if we're not already posted.
19509                if (!mPosted) {
19510                    post(this);
19511                    mPosted = true;
19512                }
19513                return;
19514            }
19515
19516            if (mPosted) {
19517                return;
19518            }
19519            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19520            final long minEventIntevalMillis =
19521                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19522            if (timeSinceLastMillis >= minEventIntevalMillis) {
19523                removeCallbacks(this);
19524                run();
19525            } else {
19526                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19527                mPosted = true;
19528                mPostedWithDelay = true;
19529            }
19530        }
19531    }
19532
19533    private boolean inLiveRegion() {
19534        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19535            return true;
19536        }
19537
19538        ViewParent parent = getParent();
19539        while (parent instanceof View) {
19540            if (((View) parent).getAccessibilityLiveRegion()
19541                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19542                return true;
19543            }
19544            parent = parent.getParent();
19545        }
19546
19547        return false;
19548    }
19549
19550    /**
19551     * Dump all private flags in readable format, useful for documentation and
19552     * sanity checking.
19553     */
19554    private static void dumpFlags() {
19555        final HashMap<String, String> found = Maps.newHashMap();
19556        try {
19557            for (Field field : View.class.getDeclaredFields()) {
19558                final int modifiers = field.getModifiers();
19559                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19560                    if (field.getType().equals(int.class)) {
19561                        final int value = field.getInt(null);
19562                        dumpFlag(found, field.getName(), value);
19563                    } else if (field.getType().equals(int[].class)) {
19564                        final int[] values = (int[]) field.get(null);
19565                        for (int i = 0; i < values.length; i++) {
19566                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19567                        }
19568                    }
19569                }
19570            }
19571        } catch (IllegalAccessException e) {
19572            throw new RuntimeException(e);
19573        }
19574
19575        final ArrayList<String> keys = Lists.newArrayList();
19576        keys.addAll(found.keySet());
19577        Collections.sort(keys);
19578        for (String key : keys) {
19579            Log.d(VIEW_LOG_TAG, found.get(key));
19580        }
19581    }
19582
19583    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19584        // Sort flags by prefix, then by bits, always keeping unique keys
19585        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19586        final int prefix = name.indexOf('_');
19587        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19588        final String output = bits + " " + name;
19589        found.put(key, output);
19590    }
19591}
19592