View.java revision 9a67d191ab9e3f7c5ac1c1f1cce1cb87e1ebd547
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.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.Path;
39import android.graphics.PathMeasure;
40import android.graphics.PixelFormat;
41import android.graphics.Point;
42import android.graphics.PorterDuff;
43import android.graphics.PorterDuffXfermode;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region;
47import android.graphics.Shader;
48import android.graphics.drawable.ColorDrawable;
49import android.graphics.drawable.Drawable;
50import android.hardware.display.DisplayManagerGlobal;
51import android.os.Bundle;
52import android.os.Handler;
53import android.os.IBinder;
54import android.os.Parcel;
55import android.os.Parcelable;
56import android.os.RemoteException;
57import android.os.SystemClock;
58import android.os.SystemProperties;
59import android.os.Trace;
60import android.text.TextUtils;
61import android.util.AttributeSet;
62import android.util.FloatProperty;
63import android.util.LayoutDirection;
64import android.util.Log;
65import android.util.LongSparseLongArray;
66import android.util.Pools.SynchronizedPool;
67import android.util.Property;
68import android.util.SparseArray;
69import android.util.StateSet;
70import android.util.SuperNotCalledException;
71import android.util.TypedValue;
72import android.view.ContextMenu.ContextMenuInfo;
73import android.view.AccessibilityIterators.TextSegmentIterator;
74import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
75import android.view.AccessibilityIterators.WordTextSegmentIterator;
76import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
77import android.view.accessibility.AccessibilityEvent;
78import android.view.accessibility.AccessibilityEventSource;
79import android.view.accessibility.AccessibilityManager;
80import android.view.accessibility.AccessibilityNodeInfo;
81import android.view.accessibility.AccessibilityNodeProvider;
82import android.view.animation.Animation;
83import android.view.animation.AnimationUtils;
84import android.view.animation.Transformation;
85import android.view.inputmethod.EditorInfo;
86import android.view.inputmethod.InputConnection;
87import android.view.inputmethod.InputMethodManager;
88import android.widget.ScrollBarDrawable;
89
90import static android.os.Build.VERSION_CODES.*;
91import static java.lang.Math.max;
92
93import com.android.internal.R;
94import com.android.internal.util.Predicate;
95import com.android.internal.view.menu.MenuBuilder;
96import com.google.android.collect.Lists;
97import com.google.android.collect.Maps;
98
99import java.lang.annotation.Retention;
100import java.lang.annotation.RetentionPolicy;
101import java.lang.ref.WeakReference;
102import java.lang.reflect.Field;
103import java.lang.reflect.InvocationTargetException;
104import java.lang.reflect.Method;
105import java.lang.reflect.Modifier;
106import java.util.ArrayList;
107import java.util.Arrays;
108import java.util.Collections;
109import java.util.HashMap;
110import java.util.List;
111import java.util.Locale;
112import java.util.Map;
113import java.util.concurrent.CopyOnWriteArrayList;
114import java.util.concurrent.atomic.AtomicInteger;
115
116/**
117 * <p>
118 * This class represents the basic building block for user interface components. A View
119 * occupies a rectangular area on the screen and is responsible for drawing and
120 * event handling. View is the base class for <em>widgets</em>, which are
121 * used to create interactive UI components (buttons, text fields, etc.). The
122 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
123 * are invisible containers that hold other Views (or other ViewGroups) and define
124 * their layout properties.
125 * </p>
126 *
127 * <div class="special reference">
128 * <h3>Developer Guides</h3>
129 * <p>For information about using this class to develop your application's user interface,
130 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
131 * </div>
132 *
133 * <a name="Using"></a>
134 * <h3>Using Views</h3>
135 * <p>
136 * All of the views in a window are arranged in a single tree. You can add views
137 * either from code or by specifying a tree of views in one or more XML layout
138 * files. There are many specialized subclasses of views that act as controls or
139 * are capable of displaying text, images, or other content.
140 * </p>
141 * <p>
142 * Once you have created a tree of views, there are typically a few types of
143 * common operations you may wish to perform:
144 * <ul>
145 * <li><strong>Set properties:</strong> for example setting the text of a
146 * {@link android.widget.TextView}. The available properties and the methods
147 * that set them will vary among the different subclasses of views. Note that
148 * properties that are known at build time can be set in the XML layout
149 * files.</li>
150 * <li><strong>Set focus:</strong> The framework will handled moving focus in
151 * response to user input. To force focus to a specific view, call
152 * {@link #requestFocus}.</li>
153 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
154 * that will be notified when something interesting happens to the view. For
155 * example, all views will let you set a listener to be notified when the view
156 * gains or loses focus. You can register such a listener using
157 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
158 * Other view subclasses offer more specialized listeners. For example, a Button
159 * exposes a listener to notify clients when the button is clicked.</li>
160 * <li><strong>Set visibility:</strong> You can hide or show views using
161 * {@link #setVisibility(int)}.</li>
162 * </ul>
163 * </p>
164 * <p><em>
165 * Note: The Android framework is responsible for measuring, laying out and
166 * drawing views. You should not call methods that perform these actions on
167 * views yourself unless you are actually implementing a
168 * {@link android.view.ViewGroup}.
169 * </em></p>
170 *
171 * <a name="Lifecycle"></a>
172 * <h3>Implementing a Custom View</h3>
173 *
174 * <p>
175 * To implement a custom view, you will usually begin by providing overrides for
176 * some of the standard methods that the framework calls on all views. You do
177 * not need to override all of these methods. In fact, you can start by just
178 * overriding {@link #onDraw(android.graphics.Canvas)}.
179 * <table border="2" width="85%" align="center" cellpadding="5">
180 *     <thead>
181 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
182 *     </thead>
183 *
184 *     <tbody>
185 *     <tr>
186 *         <td rowspan="2">Creation</td>
187 *         <td>Constructors</td>
188 *         <td>There is a form of the constructor that are called when the view
189 *         is created from code and a form that is called when the view is
190 *         inflated from a layout file. The second form should parse and apply
191 *         any attributes defined in the layout file.
192 *         </td>
193 *     </tr>
194 *     <tr>
195 *         <td><code>{@link #onFinishInflate()}</code></td>
196 *         <td>Called after a view and all of its children has been inflated
197 *         from XML.</td>
198 *     </tr>
199 *
200 *     <tr>
201 *         <td rowspan="3">Layout</td>
202 *         <td><code>{@link #onMeasure(int, int)}</code></td>
203 *         <td>Called to determine the size requirements for this view and all
204 *         of its children.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
209 *         <td>Called when this view should assign a size and position to all
210 *         of its children.
211 *         </td>
212 *     </tr>
213 *     <tr>
214 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
215 *         <td>Called when the size of this view has changed.
216 *         </td>
217 *     </tr>
218 *
219 *     <tr>
220 *         <td>Drawing</td>
221 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
222 *         <td>Called when the view should render its content.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="4">Event processing</td>
228 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
229 *         <td>Called when a new hardware key event occurs.
230 *         </td>
231 *     </tr>
232 *     <tr>
233 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
234 *         <td>Called when a hardware key up event occurs.
235 *         </td>
236 *     </tr>
237 *     <tr>
238 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
239 *         <td>Called when a trackball motion event occurs.
240 *         </td>
241 *     </tr>
242 *     <tr>
243 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
244 *         <td>Called when a touch screen motion event occurs.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td rowspan="2">Focus</td>
250 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
251 *         <td>Called when the view gains or loses focus.
252 *         </td>
253 *     </tr>
254 *
255 *     <tr>
256 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
257 *         <td>Called when the window containing the view gains or loses focus.
258 *         </td>
259 *     </tr>
260 *
261 *     <tr>
262 *         <td rowspan="3">Attaching</td>
263 *         <td><code>{@link #onAttachedToWindow()}</code></td>
264 *         <td>Called when the view is attached to a window.
265 *         </td>
266 *     </tr>
267 *
268 *     <tr>
269 *         <td><code>{@link #onDetachedFromWindow}</code></td>
270 *         <td>Called when the view is detached from its window.
271 *         </td>
272 *     </tr>
273 *
274 *     <tr>
275 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
276 *         <td>Called when the visibility of the window containing the view
277 *         has changed.
278 *         </td>
279 *     </tr>
280 *     </tbody>
281 *
282 * </table>
283 * </p>
284 *
285 * <a name="IDs"></a>
286 * <h3>IDs</h3>
287 * Views may have an integer id associated with them. These ids are typically
288 * assigned in the layout XML files, and are used to find specific views within
289 * the view tree. A common pattern is to:
290 * <ul>
291 * <li>Define a Button in the layout file and assign it a unique ID.
292 * <pre>
293 * &lt;Button
294 *     android:id="@+id/my_button"
295 *     android:layout_width="wrap_content"
296 *     android:layout_height="wrap_content"
297 *     android:text="@string/my_button_text"/&gt;
298 * </pre></li>
299 * <li>From the onCreate method of an Activity, find the Button
300 * <pre class="prettyprint">
301 *      Button myButton = (Button) findViewById(R.id.my_button);
302 * </pre></li>
303 * </ul>
304 * <p>
305 * View IDs need not be unique throughout the tree, but it is good practice to
306 * ensure that they are at least unique within the part of the tree you are
307 * searching.
308 * </p>
309 *
310 * <a name="Position"></a>
311 * <h3>Position</h3>
312 * <p>
313 * The geometry of a view is that of a rectangle. A view has a location,
314 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
315 * two dimensions, expressed as a width and a height. The unit for location
316 * and dimensions is the pixel.
317 * </p>
318 *
319 * <p>
320 * It is possible to retrieve the location of a view by invoking the methods
321 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
322 * coordinate of the rectangle representing the view. The latter returns the
323 * top, or Y, coordinate of the rectangle representing the view. These methods
324 * both return the location of the view relative to its parent. For instance,
325 * when getLeft() returns 20, that means the view is located 20 pixels to the
326 * right of the left edge of its direct parent.
327 * </p>
328 *
329 * <p>
330 * In addition, several convenience methods are offered to avoid unnecessary
331 * computations, namely {@link #getRight()} and {@link #getBottom()}.
332 * These methods return the coordinates of the right and bottom edges of the
333 * rectangle representing the view. For instance, calling {@link #getRight()}
334 * is similar to the following computation: <code>getLeft() + getWidth()</code>
335 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
336 * </p>
337 *
338 * <a name="SizePaddingMargins"></a>
339 * <h3>Size, padding and margins</h3>
340 * <p>
341 * The size of a view is expressed with a width and a height. A view actually
342 * possess two pairs of width and height values.
343 * </p>
344 *
345 * <p>
346 * The first pair is known as <em>measured width</em> and
347 * <em>measured height</em>. These dimensions define how big a view wants to be
348 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
349 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
350 * and {@link #getMeasuredHeight()}.
351 * </p>
352 *
353 * <p>
354 * The second pair is simply known as <em>width</em> and <em>height</em>, or
355 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
356 * dimensions define the actual size of the view on screen, at drawing time and
357 * after layout. These values may, but do not have to, be different from the
358 * measured width and height. The width and height can be obtained by calling
359 * {@link #getWidth()} and {@link #getHeight()}.
360 * </p>
361 *
362 * <p>
363 * To measure its dimensions, a view takes into account its padding. The padding
364 * is expressed in pixels for the left, top, right and bottom parts of the view.
365 * Padding can be used to offset the content of the view by a specific amount of
366 * pixels. For instance, a left padding of 2 will push the view's content by
367 * 2 pixels to the right of the left edge. Padding can be set using the
368 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
369 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
370 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
371 * {@link #getPaddingEnd()}.
372 * </p>
373 *
374 * <p>
375 * Even though a view can define a padding, it does not provide any support for
376 * margins. However, view groups provide such a support. Refer to
377 * {@link android.view.ViewGroup} and
378 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
379 * </p>
380 *
381 * <a name="Layout"></a>
382 * <h3>Layout</h3>
383 * <p>
384 * Layout is a two pass process: a measure pass and a layout pass. The measuring
385 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
386 * of the view tree. Each view pushes dimension specifications down the tree
387 * during the recursion. At the end of the measure pass, every view has stored
388 * its measurements. The second pass happens in
389 * {@link #layout(int,int,int,int)} and is also top-down. During
390 * this pass each parent is responsible for positioning all of its children
391 * using the sizes computed in the measure pass.
392 * </p>
393 *
394 * <p>
395 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
396 * {@link #getMeasuredHeight()} values must be set, along with those for all of
397 * that view's descendants. A view's measured width and measured height values
398 * must respect the constraints imposed by the view's parents. This guarantees
399 * that at the end of the measure pass, all parents accept all of their
400 * children's measurements. A parent view may call measure() more than once on
401 * its children. For example, the parent may measure each child once with
402 * unspecified dimensions to find out how big they want to be, then call
403 * measure() on them again with actual numbers if the sum of all the children's
404 * unconstrained sizes is too big or too small.
405 * </p>
406 *
407 * <p>
408 * The measure pass uses two classes to communicate dimensions. The
409 * {@link MeasureSpec} class is used by views to tell their parents how they
410 * want to be measured and positioned. The base LayoutParams class just
411 * describes how big the view wants to be for both width and height. For each
412 * dimension, it can specify one of:
413 * <ul>
414 * <li> an exact number
415 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
416 * (minus padding)
417 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
418 * enclose its content (plus padding).
419 * </ul>
420 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
421 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
422 * an X and Y value.
423 * </p>
424 *
425 * <p>
426 * MeasureSpecs are used to push requirements down the tree from parent to
427 * child. A MeasureSpec can be in one of three modes:
428 * <ul>
429 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
430 * of a child view. For example, a LinearLayout may call measure() on its child
431 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
432 * tall the child view wants to be given a width of 240 pixels.
433 * <li>EXACTLY: This is used by the parent to impose an exact size on the
434 * child. The child must use this size, and guarantee that all of its
435 * descendants will fit within this size.
436 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
437 * child. The child must guarantee that it and all of its descendants will fit
438 * within this size.
439 * </ul>
440 * </p>
441 *
442 * <p>
443 * To initiate a layout, call {@link #requestLayout}. This method is typically
444 * called by a view on itself when it believes that is can no longer fit within
445 * its current bounds.
446 * </p>
447 *
448 * <a name="Drawing"></a>
449 * <h3>Drawing</h3>
450 * <p>
451 * Drawing is handled by walking the tree and recording the drawing commands of
452 * any View that needs to update. After this, the drawing commands of the
453 * entire tree are issued to screen, clipped to the newly damaged area.
454 * </p>
455 *
456 * <p>
457 * The tree is largely recorded and drawn in order, with parents drawn before
458 * (i.e., behind) their children, with siblings drawn in the order they appear
459 * in the tree. If you set a background drawable for a View, then the View will
460 * draw it before calling back to its <code>onDraw()</code> method. The child
461 * drawing order can be overridden with
462 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
463 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
464 * </p>
465 *
466 * <p>
467 * To force a view to draw, call {@link #invalidate()}.
468 * </p>
469 *
470 * <a name="EventHandlingThreading"></a>
471 * <h3>Event Handling and Threading</h3>
472 * <p>
473 * The basic cycle of a view is as follows:
474 * <ol>
475 * <li>An event comes in and is dispatched to the appropriate view. The view
476 * handles the event and notifies any listeners.</li>
477 * <li>If in the course of processing the event, the view's bounds may need
478 * to be changed, the view will call {@link #requestLayout()}.</li>
479 * <li>Similarly, if in the course of processing the event the view's appearance
480 * may need to be changed, the view will call {@link #invalidate()}.</li>
481 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
482 * the framework will take care of measuring, laying out, and drawing the tree
483 * as appropriate.</li>
484 * </ol>
485 * </p>
486 *
487 * <p><em>Note: The entire view tree is single threaded. You must always be on
488 * the UI thread when calling any method on any view.</em>
489 * If you are doing work on other threads and want to update the state of a view
490 * from that thread, you should use a {@link Handler}.
491 * </p>
492 *
493 * <a name="FocusHandling"></a>
494 * <h3>Focus Handling</h3>
495 * <p>
496 * The framework will handle routine focus movement in response to user input.
497 * This includes changing the focus as views are removed or hidden, or as new
498 * views become available. Views indicate their willingness to take focus
499 * through the {@link #isFocusable} method. To change whether a view can take
500 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
501 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
502 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
503 * </p>
504 * <p>
505 * Focus movement is based on an algorithm which finds the nearest neighbor in a
506 * given direction. In rare cases, the default algorithm may not match the
507 * intended behavior of the developer. In these situations, you can provide
508 * explicit overrides by using these XML attributes in the layout file:
509 * <pre>
510 * nextFocusDown
511 * nextFocusLeft
512 * nextFocusRight
513 * nextFocusUp
514 * </pre>
515 * </p>
516 *
517 *
518 * <p>
519 * To get a particular view to take focus, call {@link #requestFocus()}.
520 * </p>
521 *
522 * <a name="TouchMode"></a>
523 * <h3>Touch Mode</h3>
524 * <p>
525 * When a user is navigating a user interface via directional keys such as a D-pad, it is
526 * necessary to give focus to actionable items such as buttons so the user can see
527 * what will take input.  If the device has touch capabilities, however, and the user
528 * begins interacting with the interface by touching it, it is no longer necessary to
529 * always highlight, or give focus to, a particular view.  This motivates a mode
530 * for interaction named 'touch mode'.
531 * </p>
532 * <p>
533 * For a touch capable device, once the user touches the screen, the device
534 * will enter touch mode.  From this point onward, only views for which
535 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
536 * Other views that are touchable, like buttons, will not take focus when touched; they will
537 * only fire the on click listeners.
538 * </p>
539 * <p>
540 * Any time a user hits a directional key, such as a D-pad direction, the view device will
541 * exit touch mode, and find a view to take focus, so that the user may resume interacting
542 * with the user interface without touching the screen again.
543 * </p>
544 * <p>
545 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
546 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
547 * </p>
548 *
549 * <a name="Scrolling"></a>
550 * <h3>Scrolling</h3>
551 * <p>
552 * The framework provides basic support for views that wish to internally
553 * scroll their content. This includes keeping track of the X and Y scroll
554 * offset as well as mechanisms for drawing scrollbars. See
555 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
556 * {@link #awakenScrollBars()} for more details.
557 * </p>
558 *
559 * <a name="Tags"></a>
560 * <h3>Tags</h3>
561 * <p>
562 * Unlike IDs, tags are not used to identify views. Tags are essentially an
563 * extra piece of information that can be associated with a view. They are most
564 * often used as a convenience to store data related to views in the views
565 * themselves rather than by putting them in a separate structure.
566 * </p>
567 *
568 * <a name="Properties"></a>
569 * <h3>Properties</h3>
570 * <p>
571 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
572 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
573 * available both in the {@link Property} form as well as in similarly-named setter/getter
574 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
575 * be used to set persistent state associated with these rendering-related properties on the view.
576 * The properties and methods can also be used in conjunction with
577 * {@link android.animation.Animator Animator}-based animations, described more in the
578 * <a href="#Animation">Animation</a> section.
579 * </p>
580 *
581 * <a name="Animation"></a>
582 * <h3>Animation</h3>
583 * <p>
584 * Starting with Android 3.0, the preferred way of animating views is to use the
585 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
586 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
587 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
588 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
589 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
590 * makes animating these View properties particularly easy and efficient.
591 * </p>
592 * <p>
593 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
594 * You can attach an {@link Animation} object to a view using
595 * {@link #setAnimation(Animation)} or
596 * {@link #startAnimation(Animation)}. The animation can alter the scale,
597 * rotation, translation and alpha of a view over time. If the animation is
598 * attached to a view that has children, the animation will affect the entire
599 * subtree rooted by that node. When an animation is started, the framework will
600 * take care of redrawing the appropriate views until the animation completes.
601 * </p>
602 *
603 * <a name="Security"></a>
604 * <h3>Security</h3>
605 * <p>
606 * Sometimes it is essential that an application be able to verify that an action
607 * is being performed with the full knowledge and consent of the user, such as
608 * granting a permission request, making a purchase or clicking on an advertisement.
609 * Unfortunately, a malicious application could try to spoof the user into
610 * performing these actions, unaware, by concealing the intended purpose of the view.
611 * As a remedy, the framework offers a touch filtering mechanism that can be used to
612 * improve the security of views that provide access to sensitive functionality.
613 * </p><p>
614 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
615 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
616 * will discard touches that are received whenever the view's window is obscured by
617 * another visible window.  As a result, the view will not receive touches whenever a
618 * toast, dialog or other window appears above the view's window.
619 * </p><p>
620 * For more fine-grained control over security, consider overriding the
621 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
622 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
623 * </p>
624 *
625 * @attr ref android.R.styleable#View_alpha
626 * @attr ref android.R.styleable#View_background
627 * @attr ref android.R.styleable#View_clickable
628 * @attr ref android.R.styleable#View_contentDescription
629 * @attr ref android.R.styleable#View_drawingCacheQuality
630 * @attr ref android.R.styleable#View_duplicateParentState
631 * @attr ref android.R.styleable#View_id
632 * @attr ref android.R.styleable#View_requiresFadingEdge
633 * @attr ref android.R.styleable#View_fadeScrollbars
634 * @attr ref android.R.styleable#View_fadingEdgeLength
635 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
636 * @attr ref android.R.styleable#View_fitsSystemWindows
637 * @attr ref android.R.styleable#View_isScrollContainer
638 * @attr ref android.R.styleable#View_focusable
639 * @attr ref android.R.styleable#View_focusableInTouchMode
640 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
641 * @attr ref android.R.styleable#View_keepScreenOn
642 * @attr ref android.R.styleable#View_layerType
643 * @attr ref android.R.styleable#View_layoutDirection
644 * @attr ref android.R.styleable#View_longClickable
645 * @attr ref android.R.styleable#View_minHeight
646 * @attr ref android.R.styleable#View_minWidth
647 * @attr ref android.R.styleable#View_nextFocusDown
648 * @attr ref android.R.styleable#View_nextFocusLeft
649 * @attr ref android.R.styleable#View_nextFocusRight
650 * @attr ref android.R.styleable#View_nextFocusUp
651 * @attr ref android.R.styleable#View_onClick
652 * @attr ref android.R.styleable#View_padding
653 * @attr ref android.R.styleable#View_paddingBottom
654 * @attr ref android.R.styleable#View_paddingLeft
655 * @attr ref android.R.styleable#View_paddingRight
656 * @attr ref android.R.styleable#View_paddingTop
657 * @attr ref android.R.styleable#View_paddingStart
658 * @attr ref android.R.styleable#View_paddingEnd
659 * @attr ref android.R.styleable#View_saveEnabled
660 * @attr ref android.R.styleable#View_rotation
661 * @attr ref android.R.styleable#View_rotationX
662 * @attr ref android.R.styleable#View_rotationY
663 * @attr ref android.R.styleable#View_scaleX
664 * @attr ref android.R.styleable#View_scaleY
665 * @attr ref android.R.styleable#View_scrollX
666 * @attr ref android.R.styleable#View_scrollY
667 * @attr ref android.R.styleable#View_scrollbarSize
668 * @attr ref android.R.styleable#View_scrollbarStyle
669 * @attr ref android.R.styleable#View_scrollbars
670 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
671 * @attr ref android.R.styleable#View_scrollbarFadeDuration
672 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
673 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
674 * @attr ref android.R.styleable#View_scrollbarThumbVertical
675 * @attr ref android.R.styleable#View_scrollbarTrackVertical
676 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
677 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
678 * @attr ref android.R.styleable#View_stateListAnimator
679 * @attr ref android.R.styleable#View_transitionName
680 * @attr ref android.R.styleable#View_soundEffectsEnabled
681 * @attr ref android.R.styleable#View_tag
682 * @attr ref android.R.styleable#View_textAlignment
683 * @attr ref android.R.styleable#View_textDirection
684 * @attr ref android.R.styleable#View_transformPivotX
685 * @attr ref android.R.styleable#View_transformPivotY
686 * @attr ref android.R.styleable#View_translationX
687 * @attr ref android.R.styleable#View_translationY
688 * @attr ref android.R.styleable#View_translationZ
689 * @attr ref android.R.styleable#View_visibility
690 *
691 * @see android.view.ViewGroup
692 */
693public class View implements Drawable.Callback, KeyEvent.Callback,
694        AccessibilityEventSource {
695    private static final boolean DBG = false;
696
697    /**
698     * The logging tag used by this class with android.util.Log.
699     */
700    protected static final String VIEW_LOG_TAG = "View";
701
702    /**
703     * When set to true, apps will draw debugging information about their layouts.
704     *
705     * @hide
706     */
707    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
708
709    /**
710     * When set to true, this view will save its attribute data.
711     *
712     * @hide
713     */
714    public static boolean mDebugViewAttributes = false;
715
716    /**
717     * Used to mark a View that has no ID.
718     */
719    public static final int NO_ID = -1;
720
721    /**
722     * Signals that compatibility booleans have been initialized according to
723     * target SDK versions.
724     */
725    private static boolean sCompatibilityDone = false;
726
727    /**
728     * Use the old (broken) way of building MeasureSpecs.
729     */
730    private static boolean sUseBrokenMakeMeasureSpec = false;
731
732    /**
733     * Ignore any optimizations using the measure cache.
734     */
735    private static boolean sIgnoreMeasureCache = false;
736
737    /**
738     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
739     * calling setFlags.
740     */
741    private static final int NOT_FOCUSABLE = 0x00000000;
742
743    /**
744     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
745     * setFlags.
746     */
747    private static final int FOCUSABLE = 0x00000001;
748
749    /**
750     * Mask for use with setFlags indicating bits used for focus.
751     */
752    private static final int FOCUSABLE_MASK = 0x00000001;
753
754    /**
755     * This view will adjust its padding to fit sytem windows (e.g. status bar)
756     */
757    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
758
759    /** @hide */
760    @IntDef({VISIBLE, INVISIBLE, GONE})
761    @Retention(RetentionPolicy.SOURCE)
762    public @interface Visibility {}
763
764    /**
765     * This view is visible.
766     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
767     * android:visibility}.
768     */
769    public static final int VISIBLE = 0x00000000;
770
771    /**
772     * This view is invisible, but it still takes up space for layout purposes.
773     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
774     * android:visibility}.
775     */
776    public static final int INVISIBLE = 0x00000004;
777
778    /**
779     * This view is invisible, and it doesn't take any space for layout
780     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
781     * android:visibility}.
782     */
783    public static final int GONE = 0x00000008;
784
785    /**
786     * Mask for use with setFlags indicating bits used for visibility.
787     * {@hide}
788     */
789    static final int VISIBILITY_MASK = 0x0000000C;
790
791    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
792
793    /**
794     * This view is enabled. Interpretation varies by subclass.
795     * Use with ENABLED_MASK when calling setFlags.
796     * {@hide}
797     */
798    static final int ENABLED = 0x00000000;
799
800    /**
801     * This view is disabled. Interpretation varies by subclass.
802     * Use with ENABLED_MASK when calling setFlags.
803     * {@hide}
804     */
805    static final int DISABLED = 0x00000020;
806
807   /**
808    * Mask for use with setFlags indicating bits used for indicating whether
809    * this view is enabled
810    * {@hide}
811    */
812    static final int ENABLED_MASK = 0x00000020;
813
814    /**
815     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
816     * called and further optimizations will be performed. It is okay to have
817     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
818     * {@hide}
819     */
820    static final int WILL_NOT_DRAW = 0x00000080;
821
822    /**
823     * Mask for use with setFlags indicating bits used for indicating whether
824     * this view is will draw
825     * {@hide}
826     */
827    static final int DRAW_MASK = 0x00000080;
828
829    /**
830     * <p>This view doesn't show scrollbars.</p>
831     * {@hide}
832     */
833    static final int SCROLLBARS_NONE = 0x00000000;
834
835    /**
836     * <p>This view shows horizontal scrollbars.</p>
837     * {@hide}
838     */
839    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
840
841    /**
842     * <p>This view shows vertical scrollbars.</p>
843     * {@hide}
844     */
845    static final int SCROLLBARS_VERTICAL = 0x00000200;
846
847    /**
848     * <p>Mask for use with setFlags indicating bits used for indicating which
849     * scrollbars are enabled.</p>
850     * {@hide}
851     */
852    static final int SCROLLBARS_MASK = 0x00000300;
853
854    /**
855     * Indicates that the view should filter touches when its window is obscured.
856     * Refer to the class comments for more information about this security feature.
857     * {@hide}
858     */
859    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
860
861    /**
862     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
863     * that they are optional and should be skipped if the window has
864     * requested system UI flags that ignore those insets for layout.
865     */
866    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
867
868    /**
869     * <p>This view doesn't show fading edges.</p>
870     * {@hide}
871     */
872    static final int FADING_EDGE_NONE = 0x00000000;
873
874    /**
875     * <p>This view shows horizontal fading edges.</p>
876     * {@hide}
877     */
878    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
879
880    /**
881     * <p>This view shows vertical fading edges.</p>
882     * {@hide}
883     */
884    static final int FADING_EDGE_VERTICAL = 0x00002000;
885
886    /**
887     * <p>Mask for use with setFlags indicating bits used for indicating which
888     * fading edges are enabled.</p>
889     * {@hide}
890     */
891    static final int FADING_EDGE_MASK = 0x00003000;
892
893    /**
894     * <p>Indicates this view can be clicked. When clickable, a View reacts
895     * to clicks by notifying the OnClickListener.<p>
896     * {@hide}
897     */
898    static final int CLICKABLE = 0x00004000;
899
900    /**
901     * <p>Indicates this view is caching its drawing into a bitmap.</p>
902     * {@hide}
903     */
904    static final int DRAWING_CACHE_ENABLED = 0x00008000;
905
906    /**
907     * <p>Indicates that no icicle should be saved for this view.<p>
908     * {@hide}
909     */
910    static final int SAVE_DISABLED = 0x000010000;
911
912    /**
913     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
914     * property.</p>
915     * {@hide}
916     */
917    static final int SAVE_DISABLED_MASK = 0x000010000;
918
919    /**
920     * <p>Indicates that no drawing cache should ever be created for this view.<p>
921     * {@hide}
922     */
923    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
924
925    /**
926     * <p>Indicates this view can take / keep focus when int touch mode.</p>
927     * {@hide}
928     */
929    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
930
931    /** @hide */
932    @Retention(RetentionPolicy.SOURCE)
933    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
934    public @interface DrawingCacheQuality {}
935
936    /**
937     * <p>Enables low quality mode for the drawing cache.</p>
938     */
939    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
940
941    /**
942     * <p>Enables high quality mode for the drawing cache.</p>
943     */
944    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
945
946    /**
947     * <p>Enables automatic quality mode for the drawing cache.</p>
948     */
949    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
950
951    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
952            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
953    };
954
955    /**
956     * <p>Mask for use with setFlags indicating bits used for the cache
957     * quality property.</p>
958     * {@hide}
959     */
960    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
961
962    /**
963     * <p>
964     * Indicates this view can be long clicked. When long clickable, a View
965     * reacts to long clicks by notifying the OnLongClickListener or showing a
966     * context menu.
967     * </p>
968     * {@hide}
969     */
970    static final int LONG_CLICKABLE = 0x00200000;
971
972    /**
973     * <p>Indicates that this view gets its drawable states from its direct parent
974     * and ignores its original internal states.</p>
975     *
976     * @hide
977     */
978    static final int DUPLICATE_PARENT_STATE = 0x00400000;
979
980    /** @hide */
981    @IntDef({
982        SCROLLBARS_INSIDE_OVERLAY,
983        SCROLLBARS_INSIDE_INSET,
984        SCROLLBARS_OUTSIDE_OVERLAY,
985        SCROLLBARS_OUTSIDE_INSET
986    })
987    @Retention(RetentionPolicy.SOURCE)
988    public @interface ScrollBarStyle {}
989
990    /**
991     * The scrollbar style to display the scrollbars inside the content area,
992     * without increasing the padding. The scrollbars will be overlaid with
993     * translucency on the view's content.
994     */
995    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
996
997    /**
998     * The scrollbar style to display the scrollbars inside the padded area,
999     * increasing the padding of the view. The scrollbars will not overlap the
1000     * content area of the view.
1001     */
1002    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1003
1004    /**
1005     * The scrollbar style to display the scrollbars at the edge of the view,
1006     * without increasing the padding. The scrollbars will be overlaid with
1007     * translucency.
1008     */
1009    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1010
1011    /**
1012     * The scrollbar style to display the scrollbars at the edge of the view,
1013     * increasing the padding of the view. The scrollbars will only overlap the
1014     * background, if any.
1015     */
1016    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1017
1018    /**
1019     * Mask to check if the scrollbar style is overlay or inset.
1020     * {@hide}
1021     */
1022    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1023
1024    /**
1025     * Mask to check if the scrollbar style is inside or outside.
1026     * {@hide}
1027     */
1028    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1029
1030    /**
1031     * Mask for scrollbar style.
1032     * {@hide}
1033     */
1034    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1035
1036    /**
1037     * View flag indicating that the screen should remain on while the
1038     * window containing this view is visible to the user.  This effectively
1039     * takes care of automatically setting the WindowManager's
1040     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1041     */
1042    public static final int KEEP_SCREEN_ON = 0x04000000;
1043
1044    /**
1045     * View flag indicating whether this view should have sound effects enabled
1046     * for events such as clicking and touching.
1047     */
1048    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1049
1050    /**
1051     * View flag indicating whether this view should have haptic feedback
1052     * enabled for events such as long presses.
1053     */
1054    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1055
1056    /**
1057     * <p>Indicates that the view hierarchy should stop saving state when
1058     * it reaches this view.  If state saving is initiated immediately at
1059     * the view, it will be allowed.
1060     * {@hide}
1061     */
1062    static final int PARENT_SAVE_DISABLED = 0x20000000;
1063
1064    /**
1065     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1066     * {@hide}
1067     */
1068    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1069
1070    /** @hide */
1071    @IntDef(flag = true,
1072            value = {
1073                FOCUSABLES_ALL,
1074                FOCUSABLES_TOUCH_MODE
1075            })
1076    @Retention(RetentionPolicy.SOURCE)
1077    public @interface FocusableMode {}
1078
1079    /**
1080     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1081     * should add all focusable Views regardless if they are focusable in touch mode.
1082     */
1083    public static final int FOCUSABLES_ALL = 0x00000000;
1084
1085    /**
1086     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1087     * should add only Views focusable in touch mode.
1088     */
1089    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1090
1091    /** @hide */
1092    @IntDef({
1093            FOCUS_BACKWARD,
1094            FOCUS_FORWARD,
1095            FOCUS_LEFT,
1096            FOCUS_UP,
1097            FOCUS_RIGHT,
1098            FOCUS_DOWN
1099    })
1100    @Retention(RetentionPolicy.SOURCE)
1101    public @interface FocusDirection {}
1102
1103    /** @hide */
1104    @IntDef({
1105            FOCUS_LEFT,
1106            FOCUS_UP,
1107            FOCUS_RIGHT,
1108            FOCUS_DOWN
1109    })
1110    @Retention(RetentionPolicy.SOURCE)
1111    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1112
1113    /**
1114     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1115     * item.
1116     */
1117    public static final int FOCUS_BACKWARD = 0x00000001;
1118
1119    /**
1120     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1121     * item.
1122     */
1123    public static final int FOCUS_FORWARD = 0x00000002;
1124
1125    /**
1126     * Use with {@link #focusSearch(int)}. Move focus to the left.
1127     */
1128    public static final int FOCUS_LEFT = 0x00000011;
1129
1130    /**
1131     * Use with {@link #focusSearch(int)}. Move focus up.
1132     */
1133    public static final int FOCUS_UP = 0x00000021;
1134
1135    /**
1136     * Use with {@link #focusSearch(int)}. Move focus to the right.
1137     */
1138    public static final int FOCUS_RIGHT = 0x00000042;
1139
1140    /**
1141     * Use with {@link #focusSearch(int)}. Move focus down.
1142     */
1143    public static final int FOCUS_DOWN = 0x00000082;
1144
1145    /**
1146     * Bits of {@link #getMeasuredWidthAndState()} and
1147     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1148     */
1149    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1150
1151    /**
1152     * Bits of {@link #getMeasuredWidthAndState()} and
1153     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1154     */
1155    public static final int MEASURED_STATE_MASK = 0xff000000;
1156
1157    /**
1158     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1159     * for functions that combine both width and height into a single int,
1160     * such as {@link #getMeasuredState()} and the childState argument of
1161     * {@link #resolveSizeAndState(int, int, int)}.
1162     */
1163    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1164
1165    /**
1166     * Bit of {@link #getMeasuredWidthAndState()} and
1167     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1168     * is smaller that the space the view would like to have.
1169     */
1170    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1171
1172    /**
1173     * Base View state sets
1174     */
1175    // Singles
1176    /**
1177     * Indicates the view has no states set. 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[] EMPTY_STATE_SET;
1185    /**
1186     * Indicates the view is enabled. 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[] ENABLED_STATE_SET;
1194    /**
1195     * Indicates the view is focused. States are used with
1196     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1197     * view depending on its state.
1198     *
1199     * @see android.graphics.drawable.Drawable
1200     * @see #getDrawableState()
1201     */
1202    protected static final int[] FOCUSED_STATE_SET;
1203    /**
1204     * Indicates the view is selected. States are used with
1205     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1206     * view depending on its state.
1207     *
1208     * @see android.graphics.drawable.Drawable
1209     * @see #getDrawableState()
1210     */
1211    protected static final int[] SELECTED_STATE_SET;
1212    /**
1213     * Indicates the view is pressed. States are used with
1214     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1215     * view depending on its state.
1216     *
1217     * @see android.graphics.drawable.Drawable
1218     * @see #getDrawableState()
1219     */
1220    protected static final int[] PRESSED_STATE_SET;
1221    /**
1222     * Indicates the view's window has focus. States are used with
1223     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1224     * view depending on its state.
1225     *
1226     * @see android.graphics.drawable.Drawable
1227     * @see #getDrawableState()
1228     */
1229    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1230    // Doubles
1231    /**
1232     * Indicates the view is enabled and has the focus.
1233     *
1234     * @see #ENABLED_STATE_SET
1235     * @see #FOCUSED_STATE_SET
1236     */
1237    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1238    /**
1239     * Indicates the view is enabled and selected.
1240     *
1241     * @see #ENABLED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     */
1244    protected static final int[] ENABLED_SELECTED_STATE_SET;
1245    /**
1246     * Indicates the view is enabled and that its window has focus.
1247     *
1248     * @see #ENABLED_STATE_SET
1249     * @see #WINDOW_FOCUSED_STATE_SET
1250     */
1251    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1252    /**
1253     * Indicates the view is focused and selected.
1254     *
1255     * @see #FOCUSED_STATE_SET
1256     * @see #SELECTED_STATE_SET
1257     */
1258    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1259    /**
1260     * Indicates the view has the focus and that its window has the focus.
1261     *
1262     * @see #FOCUSED_STATE_SET
1263     * @see #WINDOW_FOCUSED_STATE_SET
1264     */
1265    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1266    /**
1267     * Indicates the view is selected and that its window has the focus.
1268     *
1269     * @see #SELECTED_STATE_SET
1270     * @see #WINDOW_FOCUSED_STATE_SET
1271     */
1272    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1273    // Triples
1274    /**
1275     * Indicates the view is enabled, focused and selected.
1276     *
1277     * @see #ENABLED_STATE_SET
1278     * @see #FOCUSED_STATE_SET
1279     * @see #SELECTED_STATE_SET
1280     */
1281    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1282    /**
1283     * Indicates the view is enabled, focused and its window has the focus.
1284     *
1285     * @see #ENABLED_STATE_SET
1286     * @see #FOCUSED_STATE_SET
1287     * @see #WINDOW_FOCUSED_STATE_SET
1288     */
1289    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1290    /**
1291     * Indicates the view is enabled, selected and its window has the focus.
1292     *
1293     * @see #ENABLED_STATE_SET
1294     * @see #SELECTED_STATE_SET
1295     * @see #WINDOW_FOCUSED_STATE_SET
1296     */
1297    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1298    /**
1299     * Indicates the view is focused, selected and its window has the focus.
1300     *
1301     * @see #FOCUSED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is enabled, focused, selected and its window
1308     * has the focus.
1309     *
1310     * @see #ENABLED_STATE_SET
1311     * @see #FOCUSED_STATE_SET
1312     * @see #SELECTED_STATE_SET
1313     * @see #WINDOW_FOCUSED_STATE_SET
1314     */
1315    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed and its window has the focus.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #WINDOW_FOCUSED_STATE_SET
1321     */
1322    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1323    /**
1324     * Indicates the view is pressed and selected.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #SELECTED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_SELECTED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed, selected and its window has the focus.
1332     *
1333     * @see #PRESSED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #WINDOW_FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed and focused.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #FOCUSED_STATE_SET
1343     */
1344    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1345    /**
1346     * Indicates the view is pressed, focused and its window has the focus.
1347     *
1348     * @see #PRESSED_STATE_SET
1349     * @see #FOCUSED_STATE_SET
1350     * @see #WINDOW_FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed, focused and selected.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #SELECTED_STATE_SET
1358     * @see #FOCUSED_STATE_SET
1359     */
1360    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1361    /**
1362     * Indicates the view is pressed, focused, selected and its window has the focus.
1363     *
1364     * @see #PRESSED_STATE_SET
1365     * @see #FOCUSED_STATE_SET
1366     * @see #SELECTED_STATE_SET
1367     * @see #WINDOW_FOCUSED_STATE_SET
1368     */
1369    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1370    /**
1371     * Indicates the view is pressed and enabled.
1372     *
1373     * @see #PRESSED_STATE_SET
1374     * @see #ENABLED_STATE_SET
1375     */
1376    protected static final int[] PRESSED_ENABLED_STATE_SET;
1377    /**
1378     * Indicates the view is pressed, enabled and its window has the focus.
1379     *
1380     * @see #PRESSED_STATE_SET
1381     * @see #ENABLED_STATE_SET
1382     * @see #WINDOW_FOCUSED_STATE_SET
1383     */
1384    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1385    /**
1386     * Indicates the view is pressed, enabled and selected.
1387     *
1388     * @see #PRESSED_STATE_SET
1389     * @see #ENABLED_STATE_SET
1390     * @see #SELECTED_STATE_SET
1391     */
1392    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1393    /**
1394     * Indicates the view is pressed, enabled, selected and its window has the
1395     * focus.
1396     *
1397     * @see #PRESSED_STATE_SET
1398     * @see #ENABLED_STATE_SET
1399     * @see #SELECTED_STATE_SET
1400     * @see #WINDOW_FOCUSED_STATE_SET
1401     */
1402    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1403    /**
1404     * Indicates the view is pressed, enabled and focused.
1405     *
1406     * @see #PRESSED_STATE_SET
1407     * @see #ENABLED_STATE_SET
1408     * @see #FOCUSED_STATE_SET
1409     */
1410    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1411    /**
1412     * Indicates the view is pressed, enabled, focused and its window has the
1413     * focus.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #ENABLED_STATE_SET
1417     * @see #FOCUSED_STATE_SET
1418     * @see #WINDOW_FOCUSED_STATE_SET
1419     */
1420    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1421    /**
1422     * Indicates the view is pressed, enabled, focused and selected.
1423     *
1424     * @see #PRESSED_STATE_SET
1425     * @see #ENABLED_STATE_SET
1426     * @see #SELECTED_STATE_SET
1427     * @see #FOCUSED_STATE_SET
1428     */
1429    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1430    /**
1431     * Indicates the view is pressed, enabled, focused, selected and its window
1432     * has the focus.
1433     *
1434     * @see #PRESSED_STATE_SET
1435     * @see #ENABLED_STATE_SET
1436     * @see #SELECTED_STATE_SET
1437     * @see #FOCUSED_STATE_SET
1438     * @see #WINDOW_FOCUSED_STATE_SET
1439     */
1440    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1441
1442    static {
1443        EMPTY_STATE_SET = StateSet.get(0);
1444
1445        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1446
1447        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1448        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1449                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1450
1451        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1452        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1453                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1454        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1455                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1456        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1457                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1458                        | StateSet.VIEW_STATE_FOCUSED);
1459
1460        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1461        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1462                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1463        ENABLED_SELECTED_STATE_SET = StateSet.get(
1464                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1465        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1466                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1467                        | StateSet.VIEW_STATE_ENABLED);
1468        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1469                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1470        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1471                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1472                        | StateSet.VIEW_STATE_ENABLED);
1473        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1474                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1475                        | StateSet.VIEW_STATE_ENABLED);
1476        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1477                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1478                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1479
1480        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1481        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1482                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1483        PRESSED_SELECTED_STATE_SET = StateSet.get(
1484                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1485        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1486                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1487                        | StateSet.VIEW_STATE_PRESSED);
1488        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1489                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1490        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1491                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1492                        | StateSet.VIEW_STATE_PRESSED);
1493        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1494                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1495                        | StateSet.VIEW_STATE_PRESSED);
1496        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1497                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1498                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1499        PRESSED_ENABLED_STATE_SET = StateSet.get(
1500                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1501        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1502                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1503                        | StateSet.VIEW_STATE_PRESSED);
1504        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1505                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1506                        | StateSet.VIEW_STATE_PRESSED);
1507        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1508                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1509                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1510        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1511                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1512                        | StateSet.VIEW_STATE_PRESSED);
1513        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1514                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1515                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1516        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1517                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1518                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1519        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1520                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1521                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1522                        | StateSet.VIEW_STATE_PRESSED);
1523    }
1524
1525    /**
1526     * Accessibility event types that are dispatched for text population.
1527     */
1528    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1529            AccessibilityEvent.TYPE_VIEW_CLICKED
1530            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1531            | AccessibilityEvent.TYPE_VIEW_SELECTED
1532            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1533            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1534            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1535            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1536            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1537            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1538            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1539            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1540
1541    /**
1542     * Temporary Rect currently for use in setBackground().  This will probably
1543     * be extended in the future to hold our own class with more than just
1544     * a Rect. :)
1545     */
1546    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1547
1548    /**
1549     * Map used to store views' tags.
1550     */
1551    private SparseArray<Object> mKeyedTags;
1552
1553    /**
1554     * The next available accessibility id.
1555     */
1556    private static int sNextAccessibilityViewId;
1557
1558    /**
1559     * The animation currently associated with this view.
1560     * @hide
1561     */
1562    protected Animation mCurrentAnimation = null;
1563
1564    /**
1565     * Width as measured during measure pass.
1566     * {@hide}
1567     */
1568    @ViewDebug.ExportedProperty(category = "measurement")
1569    int mMeasuredWidth;
1570
1571    /**
1572     * Height as measured during measure pass.
1573     * {@hide}
1574     */
1575    @ViewDebug.ExportedProperty(category = "measurement")
1576    int mMeasuredHeight;
1577
1578    /**
1579     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1580     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1581     * its display list. This flag, used only when hw accelerated, allows us to clear the
1582     * flag while retaining this information until it's needed (at getDisplayList() time and
1583     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1584     *
1585     * {@hide}
1586     */
1587    boolean mRecreateDisplayList = false;
1588
1589    /**
1590     * The view's identifier.
1591     * {@hide}
1592     *
1593     * @see #setId(int)
1594     * @see #getId()
1595     */
1596    @ViewDebug.ExportedProperty(resolveId = true)
1597    int mID = NO_ID;
1598
1599    /**
1600     * The stable ID of this view for accessibility purposes.
1601     */
1602    int mAccessibilityViewId = NO_ID;
1603
1604    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1605
1606    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1607
1608    /**
1609     * The view's tag.
1610     * {@hide}
1611     *
1612     * @see #setTag(Object)
1613     * @see #getTag()
1614     */
1615    protected Object mTag = null;
1616
1617    // for mPrivateFlags:
1618    /** {@hide} */
1619    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1620    /** {@hide} */
1621    static final int PFLAG_FOCUSED                     = 0x00000002;
1622    /** {@hide} */
1623    static final int PFLAG_SELECTED                    = 0x00000004;
1624    /** {@hide} */
1625    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1626    /** {@hide} */
1627    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1628    /** {@hide} */
1629    static final int PFLAG_DRAWN                       = 0x00000020;
1630    /**
1631     * When this flag is set, this view is running an animation on behalf of its
1632     * children and should therefore not cancel invalidate requests, even if they
1633     * lie outside of this view's bounds.
1634     *
1635     * {@hide}
1636     */
1637    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1638    /** {@hide} */
1639    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1640    /** {@hide} */
1641    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1642    /** {@hide} */
1643    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1644    /** {@hide} */
1645    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1646    /** {@hide} */
1647    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1648    /** {@hide} */
1649    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1650    /** {@hide} */
1651    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1652
1653    private static final int PFLAG_PRESSED             = 0x00004000;
1654
1655    /** {@hide} */
1656    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1657    /**
1658     * Flag used to indicate that this view should be drawn once more (and only once
1659     * more) after its animation has completed.
1660     * {@hide}
1661     */
1662    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1663
1664    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1665
1666    /**
1667     * Indicates that the View returned true when onSetAlpha() was called and that
1668     * the alpha must be restored.
1669     * {@hide}
1670     */
1671    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1672
1673    /**
1674     * Set by {@link #setScrollContainer(boolean)}.
1675     */
1676    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1677
1678    /**
1679     * Set by {@link #setScrollContainer(boolean)}.
1680     */
1681    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1682
1683    /**
1684     * View flag indicating whether this view was invalidated (fully or partially.)
1685     *
1686     * @hide
1687     */
1688    static final int PFLAG_DIRTY                       = 0x00200000;
1689
1690    /**
1691     * View flag indicating whether this view was invalidated by an opaque
1692     * invalidate request.
1693     *
1694     * @hide
1695     */
1696    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1697
1698    /**
1699     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1700     *
1701     * @hide
1702     */
1703    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1704
1705    /**
1706     * Indicates whether the background is opaque.
1707     *
1708     * @hide
1709     */
1710    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1711
1712    /**
1713     * Indicates whether the scrollbars are opaque.
1714     *
1715     * @hide
1716     */
1717    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1718
1719    /**
1720     * Indicates whether the view is opaque.
1721     *
1722     * @hide
1723     */
1724    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1725
1726    /**
1727     * Indicates a prepressed state;
1728     * the short time between ACTION_DOWN and recognizing
1729     * a 'real' press. Prepressed is used to recognize quick taps
1730     * even when they are shorter than ViewConfiguration.getTapTimeout().
1731     *
1732     * @hide
1733     */
1734    private static final int PFLAG_PREPRESSED          = 0x02000000;
1735
1736    /**
1737     * Indicates whether the view is temporarily detached.
1738     *
1739     * @hide
1740     */
1741    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1742
1743    /**
1744     * Indicates that we should awaken scroll bars once attached
1745     *
1746     * @hide
1747     */
1748    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1749
1750    /**
1751     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1752     * @hide
1753     */
1754    private static final int PFLAG_HOVERED             = 0x10000000;
1755
1756    /**
1757     * no longer needed, should be reused
1758     */
1759    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1760
1761    /** {@hide} */
1762    static final int PFLAG_ACTIVATED                   = 0x40000000;
1763
1764    /**
1765     * Indicates that this view was specifically invalidated, not just dirtied because some
1766     * child view was invalidated. The flag is used to determine when we need to recreate
1767     * a view's display list (as opposed to just returning a reference to its existing
1768     * display list).
1769     *
1770     * @hide
1771     */
1772    static final int PFLAG_INVALIDATED                 = 0x80000000;
1773
1774    /**
1775     * Masks for mPrivateFlags2, as generated by dumpFlags():
1776     *
1777     * |-------|-------|-------|-------|
1778     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1779     *                                1  PFLAG2_DRAG_HOVERED
1780     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1781     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1782     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1783     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1784     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1785     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1786     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1787     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1788     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1789     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1790     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1791     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1792     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1793     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1794     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1795     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1796     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1797     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1798     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1799     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1800     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1801     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1802     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1803     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1804     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1805     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1806     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1807     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1808     *    1                              PFLAG2_PADDING_RESOLVED
1809     *   1                               PFLAG2_DRAWABLE_RESOLVED
1810     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1811     * |-------|-------|-------|-------|
1812     */
1813
1814    /**
1815     * Indicates that this view has reported that it can accept the current drag's content.
1816     * Cleared when the drag operation concludes.
1817     * @hide
1818     */
1819    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1820
1821    /**
1822     * Indicates that this view is currently directly under the drag location in a
1823     * drag-and-drop operation involving content that it can accept.  Cleared when
1824     * the drag exits the view, or when the drag operation concludes.
1825     * @hide
1826     */
1827    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1828
1829    /** @hide */
1830    @IntDef({
1831        LAYOUT_DIRECTION_LTR,
1832        LAYOUT_DIRECTION_RTL,
1833        LAYOUT_DIRECTION_INHERIT,
1834        LAYOUT_DIRECTION_LOCALE
1835    })
1836    @Retention(RetentionPolicy.SOURCE)
1837    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1838    public @interface LayoutDir {}
1839
1840    /** @hide */
1841    @IntDef({
1842        LAYOUT_DIRECTION_LTR,
1843        LAYOUT_DIRECTION_RTL
1844    })
1845    @Retention(RetentionPolicy.SOURCE)
1846    public @interface ResolvedLayoutDir {}
1847
1848    /**
1849     * Horizontal layout direction of this view is from Left to Right.
1850     * Use with {@link #setLayoutDirection}.
1851     */
1852    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1853
1854    /**
1855     * Horizontal layout direction of this view is from Right to Left.
1856     * Use with {@link #setLayoutDirection}.
1857     */
1858    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1859
1860    /**
1861     * Horizontal layout direction of this view is inherited from its parent.
1862     * Use with {@link #setLayoutDirection}.
1863     */
1864    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1865
1866    /**
1867     * Horizontal layout direction of this view is from deduced from the default language
1868     * script for the locale. Use with {@link #setLayoutDirection}.
1869     */
1870    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1871
1872    /**
1873     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1874     * @hide
1875     */
1876    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1877
1878    /**
1879     * Mask for use with private flags indicating bits used for horizontal layout direction.
1880     * @hide
1881     */
1882    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1883
1884    /**
1885     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1886     * right-to-left direction.
1887     * @hide
1888     */
1889    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1890
1891    /**
1892     * Indicates whether the view horizontal layout direction has been resolved.
1893     * @hide
1894     */
1895    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1896
1897    /**
1898     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1899     * @hide
1900     */
1901    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1902            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1903
1904    /*
1905     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1906     * flag value.
1907     * @hide
1908     */
1909    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1910            LAYOUT_DIRECTION_LTR,
1911            LAYOUT_DIRECTION_RTL,
1912            LAYOUT_DIRECTION_INHERIT,
1913            LAYOUT_DIRECTION_LOCALE
1914    };
1915
1916    /**
1917     * Default horizontal layout direction.
1918     */
1919    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1920
1921    /**
1922     * Default horizontal layout direction.
1923     * @hide
1924     */
1925    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1926
1927    /**
1928     * Text direction is inherited through {@link ViewGroup}
1929     */
1930    public static final int TEXT_DIRECTION_INHERIT = 0;
1931
1932    /**
1933     * Text direction is using "first strong algorithm". The first strong directional character
1934     * determines the paragraph direction. If there is no strong directional character, the
1935     * paragraph direction is the view's resolved layout direction.
1936     */
1937    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1938
1939    /**
1940     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1941     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1942     * If there are neither, the paragraph direction is the view's resolved layout direction.
1943     */
1944    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1945
1946    /**
1947     * Text direction is forced to LTR.
1948     */
1949    public static final int TEXT_DIRECTION_LTR = 3;
1950
1951    /**
1952     * Text direction is forced to RTL.
1953     */
1954    public static final int TEXT_DIRECTION_RTL = 4;
1955
1956    /**
1957     * Text direction is coming from the system Locale.
1958     */
1959    public static final int TEXT_DIRECTION_LOCALE = 5;
1960
1961    /**
1962     * Default text direction is inherited
1963     */
1964    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1965
1966    /**
1967     * Default resolved text direction
1968     * @hide
1969     */
1970    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1971
1972    /**
1973     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1974     * @hide
1975     */
1976    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1977
1978    /**
1979     * Mask for use with private flags indicating bits used for text direction.
1980     * @hide
1981     */
1982    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1983            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1984
1985    /**
1986     * Array of text direction flags for mapping attribute "textDirection" to correct
1987     * flag value.
1988     * @hide
1989     */
1990    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1991            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1992            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1993            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1994            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1995            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1996            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1997    };
1998
1999    /**
2000     * Indicates whether the view text direction has been resolved.
2001     * @hide
2002     */
2003    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2004            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2005
2006    /**
2007     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2008     * @hide
2009     */
2010    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2011
2012    /**
2013     * Mask for use with private flags indicating bits used for resolved text direction.
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2017            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2018
2019    /**
2020     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2021     * @hide
2022     */
2023    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2024            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2025
2026    /** @hide */
2027    @IntDef({
2028        TEXT_ALIGNMENT_INHERIT,
2029        TEXT_ALIGNMENT_GRAVITY,
2030        TEXT_ALIGNMENT_CENTER,
2031        TEXT_ALIGNMENT_TEXT_START,
2032        TEXT_ALIGNMENT_TEXT_END,
2033        TEXT_ALIGNMENT_VIEW_START,
2034        TEXT_ALIGNMENT_VIEW_END
2035    })
2036    @Retention(RetentionPolicy.SOURCE)
2037    public @interface TextAlignment {}
2038
2039    /**
2040     * Default text alignment. The text alignment of this View is inherited from its parent.
2041     * Use with {@link #setTextAlignment(int)}
2042     */
2043    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2044
2045    /**
2046     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2047     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2048     *
2049     * Use with {@link #setTextAlignment(int)}
2050     */
2051    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2052
2053    /**
2054     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2055     *
2056     * Use with {@link #setTextAlignment(int)}
2057     */
2058    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2059
2060    /**
2061     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2062     *
2063     * Use with {@link #setTextAlignment(int)}
2064     */
2065    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2066
2067    /**
2068     * Center the paragraph, e.g. ALIGN_CENTER.
2069     *
2070     * Use with {@link #setTextAlignment(int)}
2071     */
2072    public static final int TEXT_ALIGNMENT_CENTER = 4;
2073
2074    /**
2075     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2076     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2077     *
2078     * Use with {@link #setTextAlignment(int)}
2079     */
2080    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2081
2082    /**
2083     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2084     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2085     *
2086     * Use with {@link #setTextAlignment(int)}
2087     */
2088    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2089
2090    /**
2091     * Default text alignment is inherited
2092     */
2093    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2094
2095    /**
2096     * Default resolved text alignment
2097     * @hide
2098     */
2099    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2100
2101    /**
2102      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2103      * @hide
2104      */
2105    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2106
2107    /**
2108      * Mask for use with private flags indicating bits used for text alignment.
2109      * @hide
2110      */
2111    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2112
2113    /**
2114     * Array of text direction flags for mapping attribute "textAlignment" to correct
2115     * flag value.
2116     * @hide
2117     */
2118    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2119            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2120            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2121            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2122            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2123            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2124            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2125            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2126    };
2127
2128    /**
2129     * Indicates whether the view text alignment has been resolved.
2130     * @hide
2131     */
2132    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2133
2134    /**
2135     * Bit shift to get the resolved text alignment.
2136     * @hide
2137     */
2138    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2139
2140    /**
2141     * Mask for use with private flags indicating bits used for text alignment.
2142     * @hide
2143     */
2144    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2145            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2146
2147    /**
2148     * Indicates whether if the view text alignment has been resolved to gravity
2149     */
2150    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2151            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2152
2153    // Accessiblity constants for mPrivateFlags2
2154
2155    /**
2156     * Shift for the bits in {@link #mPrivateFlags2} related to the
2157     * "importantForAccessibility" attribute.
2158     */
2159    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2160
2161    /**
2162     * Automatically determine whether a view is important for accessibility.
2163     */
2164    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2165
2166    /**
2167     * The view is important for accessibility.
2168     */
2169    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2170
2171    /**
2172     * The view is not important for accessibility.
2173     */
2174    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2175
2176    /**
2177     * The view is not important for accessibility, nor are any of its
2178     * descendant views.
2179     */
2180    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2181
2182    /**
2183     * The default whether the view is important for accessibility.
2184     */
2185    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2186
2187    /**
2188     * Mask for obtainig the bits which specify how to determine
2189     * whether a view is important for accessibility.
2190     */
2191    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2192        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2193        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2194        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2195
2196    /**
2197     * Shift for the bits in {@link #mPrivateFlags2} related to the
2198     * "accessibilityLiveRegion" attribute.
2199     */
2200    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2201
2202    /**
2203     * Live region mode specifying that accessibility services should not
2204     * automatically announce changes to this view. This is the default live
2205     * region mode for most views.
2206     * <p>
2207     * Use with {@link #setAccessibilityLiveRegion(int)}.
2208     */
2209    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2210
2211    /**
2212     * Live region mode specifying that accessibility services should announce
2213     * changes to this view.
2214     * <p>
2215     * Use with {@link #setAccessibilityLiveRegion(int)}.
2216     */
2217    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2218
2219    /**
2220     * Live region mode specifying that accessibility services should interrupt
2221     * ongoing speech to immediately announce changes to this view.
2222     * <p>
2223     * Use with {@link #setAccessibilityLiveRegion(int)}.
2224     */
2225    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2226
2227    /**
2228     * The default whether the view is important for accessibility.
2229     */
2230    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2231
2232    /**
2233     * Mask for obtaining the bits which specify a view's accessibility live
2234     * region mode.
2235     */
2236    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2237            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2238            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2239
2240    /**
2241     * Flag indicating whether a view has accessibility focus.
2242     */
2243    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2244
2245    /**
2246     * Flag whether the accessibility state of the subtree rooted at this view changed.
2247     */
2248    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2249
2250    /**
2251     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2252     * is used to check whether later changes to the view's transform should invalidate the
2253     * view to force the quickReject test to run again.
2254     */
2255    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2256
2257    /**
2258     * Flag indicating that start/end padding has been resolved into left/right padding
2259     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2260     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2261     * during measurement. In some special cases this is required such as when an adapter-based
2262     * view measures prospective children without attaching them to a window.
2263     */
2264    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2265
2266    /**
2267     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2268     */
2269    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2270
2271    /**
2272     * Indicates that the view is tracking some sort of transient state
2273     * that the app should not need to be aware of, but that the framework
2274     * should take special care to preserve.
2275     */
2276    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2277
2278    /**
2279     * Group of bits indicating that RTL properties resolution is done.
2280     */
2281    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2282            PFLAG2_TEXT_DIRECTION_RESOLVED |
2283            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2284            PFLAG2_PADDING_RESOLVED |
2285            PFLAG2_DRAWABLE_RESOLVED;
2286
2287    // There are a couple of flags left in mPrivateFlags2
2288
2289    /* End of masks for mPrivateFlags2 */
2290
2291    /**
2292     * Masks for mPrivateFlags3, as generated by dumpFlags():
2293     *
2294     * |-------|-------|-------|-------|
2295     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2296     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2297     *                               1   PFLAG3_IS_LAID_OUT
2298     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2299     *                             1     PFLAG3_CALLED_SUPER
2300     * |-------|-------|-------|-------|
2301     */
2302
2303    /**
2304     * Flag indicating that view has a transform animation set on it. This is used to track whether
2305     * an animation is cleared between successive frames, in order to tell the associated
2306     * DisplayList to clear its animation matrix.
2307     */
2308    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2309
2310    /**
2311     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2312     * animation is cleared between successive frames, in order to tell the associated
2313     * DisplayList to restore its alpha value.
2314     */
2315    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2316
2317    /**
2318     * Flag indicating that the view has been through at least one layout since it
2319     * was last attached to a window.
2320     */
2321    static final int PFLAG3_IS_LAID_OUT = 0x4;
2322
2323    /**
2324     * Flag indicating that a call to measure() was skipped and should be done
2325     * instead when layout() is invoked.
2326     */
2327    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2328
2329    /**
2330     * Flag indicating that an overridden method correctly called down to
2331     * the superclass implementation as required by the API spec.
2332     */
2333    static final int PFLAG3_CALLED_SUPER = 0x10;
2334
2335    /**
2336     * Flag indicating that we're in the process of applying window insets.
2337     */
2338    static final int PFLAG3_APPLYING_INSETS = 0x20;
2339
2340    /**
2341     * Flag indicating that we're in the process of fitting system windows using the old method.
2342     */
2343    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2344
2345    /**
2346     * Flag indicating that nested scrolling is enabled for this view.
2347     * The view will optionally cooperate with views up its parent chain to allow for
2348     * integrated nested scrolling along the same axis.
2349     */
2350    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2351
2352    /* End of masks for mPrivateFlags3 */
2353
2354    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2355
2356    /**
2357     * Always allow a user to over-scroll this view, provided it is a
2358     * view that can scroll.
2359     *
2360     * @see #getOverScrollMode()
2361     * @see #setOverScrollMode(int)
2362     */
2363    public static final int OVER_SCROLL_ALWAYS = 0;
2364
2365    /**
2366     * Allow a user to over-scroll this view only if the content is large
2367     * enough to meaningfully scroll, provided it is a view that can scroll.
2368     *
2369     * @see #getOverScrollMode()
2370     * @see #setOverScrollMode(int)
2371     */
2372    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2373
2374    /**
2375     * Never allow a user to over-scroll this view.
2376     *
2377     * @see #getOverScrollMode()
2378     * @see #setOverScrollMode(int)
2379     */
2380    public static final int OVER_SCROLL_NEVER = 2;
2381
2382    /**
2383     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2384     * requested the system UI (status bar) to be visible (the default).
2385     *
2386     * @see #setSystemUiVisibility(int)
2387     */
2388    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2389
2390    /**
2391     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2392     * system UI to enter an unobtrusive "low profile" mode.
2393     *
2394     * <p>This is for use in games, book readers, video players, or any other
2395     * "immersive" application where the usual system chrome is deemed too distracting.
2396     *
2397     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2398     *
2399     * @see #setSystemUiVisibility(int)
2400     */
2401    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2402
2403    /**
2404     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2405     * system navigation be temporarily hidden.
2406     *
2407     * <p>This is an even less obtrusive state than that called for by
2408     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2409     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2410     * those to disappear. This is useful (in conjunction with the
2411     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2412     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2413     * window flags) for displaying content using every last pixel on the display.
2414     *
2415     * <p>There is a limitation: because navigation controls are so important, the least user
2416     * interaction will cause them to reappear immediately.  When this happens, both
2417     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2418     * so that both elements reappear at the same time.
2419     *
2420     * @see #setSystemUiVisibility(int)
2421     */
2422    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2423
2424    /**
2425     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2426     * into the normal fullscreen mode so that its content can take over the screen
2427     * while still allowing the user to interact with the application.
2428     *
2429     * <p>This has the same visual effect as
2430     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2431     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2432     * meaning that non-critical screen decorations (such as the status bar) will be
2433     * hidden while the user is in the View's window, focusing the experience on
2434     * that content.  Unlike the window flag, if you are using ActionBar in
2435     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2436     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2437     * hide the action bar.
2438     *
2439     * <p>This approach to going fullscreen is best used over the window flag when
2440     * it is a transient state -- that is, the application does this at certain
2441     * points in its user interaction where it wants to allow the user to focus
2442     * on content, but not as a continuous state.  For situations where the application
2443     * would like to simply stay full screen the entire time (such as a game that
2444     * wants to take over the screen), the
2445     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2446     * is usually a better approach.  The state set here will be removed by the system
2447     * in various situations (such as the user moving to another application) like
2448     * the other system UI states.
2449     *
2450     * <p>When using this flag, the application should provide some easy facility
2451     * for the user to go out of it.  A common example would be in an e-book
2452     * reader, where tapping on the screen brings back whatever screen and UI
2453     * decorations that had been hidden while the user was immersed in reading
2454     * the book.
2455     *
2456     * @see #setSystemUiVisibility(int)
2457     */
2458    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2459
2460    /**
2461     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2462     * flags, we would like a stable view of the content insets given to
2463     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2464     * will always represent the worst case that the application can expect
2465     * as a continuous state.  In the stock Android UI this is the space for
2466     * the system bar, nav bar, and status bar, but not more transient elements
2467     * such as an input method.
2468     *
2469     * The stable layout your UI sees is based on the system UI modes you can
2470     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2471     * then you will get a stable layout for changes of the
2472     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2473     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2474     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2475     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2476     * with a stable layout.  (Note that you should avoid using
2477     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2478     *
2479     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2480     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2481     * then a hidden status bar will be considered a "stable" state for purposes
2482     * here.  This allows your UI to continually hide the status bar, while still
2483     * using the system UI flags to hide the action bar while still retaining
2484     * a stable layout.  Note that changing the window fullscreen flag will never
2485     * provide a stable layout for a clean transition.
2486     *
2487     * <p>If you are using ActionBar in
2488     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2489     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2490     * insets it adds to those given to the application.
2491     */
2492    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2493
2494    /**
2495     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2496     * to be laid out as if it has requested
2497     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2498     * allows it to avoid artifacts when switching in and out of that mode, at
2499     * the expense that some of its user interface may be covered by screen
2500     * decorations when they are shown.  You can perform layout of your inner
2501     * UI elements to account for the navigation system UI through the
2502     * {@link #fitSystemWindows(Rect)} method.
2503     */
2504    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2505
2506    /**
2507     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2508     * to be laid out as if it has requested
2509     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2510     * allows it to avoid artifacts when switching in and out of that mode, at
2511     * the expense that some of its user interface may be covered by screen
2512     * decorations when they are shown.  You can perform layout of your inner
2513     * UI elements to account for non-fullscreen system UI through the
2514     * {@link #fitSystemWindows(Rect)} method.
2515     */
2516    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2517
2518    /**
2519     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2520     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2521     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2522     * user interaction.
2523     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2524     * has an effect when used in combination with that flag.</p>
2525     */
2526    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2527
2528    /**
2529     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2530     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2531     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2532     * experience while also hiding the system bars.  If this flag is not set,
2533     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2534     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2535     * if the user swipes from the top of the screen.
2536     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2537     * system gestures, such as swiping from the top of the screen.  These transient system bars
2538     * will overlay app’s content, may have some degree of transparency, and will automatically
2539     * hide after a short timeout.
2540     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2541     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2542     * with one or both of those flags.</p>
2543     */
2544    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2545
2546    /**
2547     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2548     */
2549    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2550
2551    /**
2552     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2553     */
2554    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2555
2556    /**
2557     * @hide
2558     *
2559     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2560     * out of the public fields to keep the undefined bits out of the developer's way.
2561     *
2562     * Flag to make the status bar not expandable.  Unless you also
2563     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2564     */
2565    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2566
2567    /**
2568     * @hide
2569     *
2570     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2571     * out of the public fields to keep the undefined bits out of the developer's way.
2572     *
2573     * Flag to hide notification icons and scrolling ticker text.
2574     */
2575    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2576
2577    /**
2578     * @hide
2579     *
2580     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2581     * out of the public fields to keep the undefined bits out of the developer's way.
2582     *
2583     * Flag to disable incoming notification alerts.  This will not block
2584     * icons, but it will block sound, vibrating and other visual or aural notifications.
2585     */
2586    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2587
2588    /**
2589     * @hide
2590     *
2591     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2592     * out of the public fields to keep the undefined bits out of the developer's way.
2593     *
2594     * Flag to hide only the scrolling ticker.  Note that
2595     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2596     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2597     */
2598    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2599
2600    /**
2601     * @hide
2602     *
2603     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2604     * out of the public fields to keep the undefined bits out of the developer's way.
2605     *
2606     * Flag to hide the center system info area.
2607     */
2608    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2609
2610    /**
2611     * @hide
2612     *
2613     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2614     * out of the public fields to keep the undefined bits out of the developer's way.
2615     *
2616     * Flag to hide only the home button.  Don't use this
2617     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2618     */
2619    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2620
2621    /**
2622     * @hide
2623     *
2624     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2625     * out of the public fields to keep the undefined bits out of the developer's way.
2626     *
2627     * Flag to hide only the back button. Don't use this
2628     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2629     */
2630    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2631
2632    /**
2633     * @hide
2634     *
2635     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2636     * out of the public fields to keep the undefined bits out of the developer's way.
2637     *
2638     * Flag to hide only the clock.  You might use this if your activity has
2639     * its own clock making the status bar's clock redundant.
2640     */
2641    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2642
2643    /**
2644     * @hide
2645     *
2646     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2647     * out of the public fields to keep the undefined bits out of the developer's way.
2648     *
2649     * Flag to hide only the recent apps button. Don't use this
2650     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2651     */
2652    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2653
2654    /**
2655     * @hide
2656     *
2657     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2658     * out of the public fields to keep the undefined bits out of the developer's way.
2659     *
2660     * Flag to disable the global search gesture. Don't use this
2661     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2662     */
2663    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2664
2665    /**
2666     * @hide
2667     *
2668     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2669     * out of the public fields to keep the undefined bits out of the developer's way.
2670     *
2671     * Flag to specify that the status bar is displayed in transient mode.
2672     */
2673    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2674
2675    /**
2676     * @hide
2677     *
2678     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2679     * out of the public fields to keep the undefined bits out of the developer's way.
2680     *
2681     * Flag to specify that the navigation bar is displayed in transient mode.
2682     */
2683    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2684
2685    /**
2686     * @hide
2687     *
2688     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2689     * out of the public fields to keep the undefined bits out of the developer's way.
2690     *
2691     * Flag to specify that the hidden status bar would like to be shown.
2692     */
2693    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2694
2695    /**
2696     * @hide
2697     *
2698     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2699     * out of the public fields to keep the undefined bits out of the developer's way.
2700     *
2701     * Flag to specify that the hidden navigation bar would like to be shown.
2702     */
2703    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2704
2705    /**
2706     * @hide
2707     *
2708     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2709     * out of the public fields to keep the undefined bits out of the developer's way.
2710     *
2711     * Flag to specify that the status bar is displayed in translucent mode.
2712     */
2713    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2714
2715    /**
2716     * @hide
2717     *
2718     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2719     * out of the public fields to keep the undefined bits out of the developer's way.
2720     *
2721     * Flag to specify that the navigation bar is displayed in translucent mode.
2722     */
2723    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2724
2725    /**
2726     * @hide
2727     *
2728     * Whether Recents is visible or not.
2729     */
2730    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2731
2732    /**
2733     * @hide
2734     *
2735     * Makes system ui transparent.
2736     */
2737    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2738
2739    /**
2740     * @hide
2741     */
2742    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2743
2744    /**
2745     * These are the system UI flags that can be cleared by events outside
2746     * of an application.  Currently this is just the ability to tap on the
2747     * screen while hiding the navigation bar to have it return.
2748     * @hide
2749     */
2750    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2751            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2752            | SYSTEM_UI_FLAG_FULLSCREEN;
2753
2754    /**
2755     * Flags that can impact the layout in relation to system UI.
2756     */
2757    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2758            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2759            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2760
2761    /** @hide */
2762    @IntDef(flag = true,
2763            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2764    @Retention(RetentionPolicy.SOURCE)
2765    public @interface FindViewFlags {}
2766
2767    /**
2768     * Find views that render the specified text.
2769     *
2770     * @see #findViewsWithText(ArrayList, CharSequence, int)
2771     */
2772    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2773
2774    /**
2775     * Find find views that contain the specified content description.
2776     *
2777     * @see #findViewsWithText(ArrayList, CharSequence, int)
2778     */
2779    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2780
2781    /**
2782     * Find views that contain {@link AccessibilityNodeProvider}. Such
2783     * a View is a root of virtual view hierarchy and may contain the searched
2784     * text. If this flag is set Views with providers are automatically
2785     * added and it is a responsibility of the client to call the APIs of
2786     * the provider to determine whether the virtual tree rooted at this View
2787     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2788     * representing the virtual views with this text.
2789     *
2790     * @see #findViewsWithText(ArrayList, CharSequence, int)
2791     *
2792     * @hide
2793     */
2794    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2795
2796    /**
2797     * The undefined cursor position.
2798     *
2799     * @hide
2800     */
2801    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2802
2803    /**
2804     * Indicates that the screen has changed state and is now off.
2805     *
2806     * @see #onScreenStateChanged(int)
2807     */
2808    public static final int SCREEN_STATE_OFF = 0x0;
2809
2810    /**
2811     * Indicates that the screen has changed state and is now on.
2812     *
2813     * @see #onScreenStateChanged(int)
2814     */
2815    public static final int SCREEN_STATE_ON = 0x1;
2816
2817    /**
2818     * Indicates no axis of view scrolling.
2819     */
2820    public static final int SCROLL_AXIS_NONE = 0;
2821
2822    /**
2823     * Indicates scrolling along the horizontal axis.
2824     */
2825    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2826
2827    /**
2828     * Indicates scrolling along the vertical axis.
2829     */
2830    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2831
2832    /**
2833     * Controls the over-scroll mode for this view.
2834     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2835     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2836     * and {@link #OVER_SCROLL_NEVER}.
2837     */
2838    private int mOverScrollMode;
2839
2840    /**
2841     * The parent this view is attached to.
2842     * {@hide}
2843     *
2844     * @see #getParent()
2845     */
2846    protected ViewParent mParent;
2847
2848    /**
2849     * {@hide}
2850     */
2851    AttachInfo mAttachInfo;
2852
2853    /**
2854     * {@hide}
2855     */
2856    @ViewDebug.ExportedProperty(flagMapping = {
2857        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2858                name = "FORCE_LAYOUT"),
2859        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2860                name = "LAYOUT_REQUIRED"),
2861        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2862            name = "DRAWING_CACHE_INVALID", outputIf = false),
2863        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2864        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2865        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2866        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2867    }, formatToHexString = true)
2868    int mPrivateFlags;
2869    int mPrivateFlags2;
2870    int mPrivateFlags3;
2871
2872    /**
2873     * This view's request for the visibility of the status bar.
2874     * @hide
2875     */
2876    @ViewDebug.ExportedProperty(flagMapping = {
2877        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2878                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2879                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2880        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2881                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2882                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2883        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2884                                equals = SYSTEM_UI_FLAG_VISIBLE,
2885                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2886    }, formatToHexString = true)
2887    int mSystemUiVisibility;
2888
2889    /**
2890     * Reference count for transient state.
2891     * @see #setHasTransientState(boolean)
2892     */
2893    int mTransientStateCount = 0;
2894
2895    /**
2896     * Count of how many windows this view has been attached to.
2897     */
2898    int mWindowAttachCount;
2899
2900    /**
2901     * The layout parameters associated with this view and used by the parent
2902     * {@link android.view.ViewGroup} to determine how this view should be
2903     * laid out.
2904     * {@hide}
2905     */
2906    protected ViewGroup.LayoutParams mLayoutParams;
2907
2908    /**
2909     * The view flags hold various views states.
2910     * {@hide}
2911     */
2912    @ViewDebug.ExportedProperty(formatToHexString = true)
2913    int mViewFlags;
2914
2915    static class TransformationInfo {
2916        /**
2917         * The transform matrix for the View. This transform is calculated internally
2918         * based on the translation, rotation, and scale properties.
2919         *
2920         * Do *not* use this variable directly; instead call getMatrix(), which will
2921         * load the value from the View's RenderNode.
2922         */
2923        private final Matrix mMatrix = new Matrix();
2924
2925        /**
2926         * The inverse transform matrix for the View. This transform is calculated
2927         * internally based on the translation, rotation, and scale properties.
2928         *
2929         * Do *not* use this variable directly; instead call getInverseMatrix(),
2930         * which will load the value from the View's RenderNode.
2931         */
2932        private Matrix mInverseMatrix;
2933
2934        /**
2935         * The opacity of the View. This is a value from 0 to 1, where 0 means
2936         * completely transparent and 1 means completely opaque.
2937         */
2938        @ViewDebug.ExportedProperty
2939        float mAlpha = 1f;
2940
2941        /**
2942         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2943         * property only used by transitions, which is composited with the other alpha
2944         * values to calculate the final visual alpha value.
2945         */
2946        float mTransitionAlpha = 1f;
2947    }
2948
2949    TransformationInfo mTransformationInfo;
2950
2951    /**
2952     * Current clip bounds. to which all drawing of this view are constrained.
2953     */
2954    Rect mClipBounds = null;
2955
2956    private boolean mLastIsOpaque;
2957
2958    /**
2959     * The distance in pixels from the left edge of this view's parent
2960     * to the left edge of this view.
2961     * {@hide}
2962     */
2963    @ViewDebug.ExportedProperty(category = "layout")
2964    protected int mLeft;
2965    /**
2966     * The distance in pixels from the left edge of this view's parent
2967     * to the right edge of this view.
2968     * {@hide}
2969     */
2970    @ViewDebug.ExportedProperty(category = "layout")
2971    protected int mRight;
2972    /**
2973     * The distance in pixels from the top edge of this view's parent
2974     * to the top edge of this view.
2975     * {@hide}
2976     */
2977    @ViewDebug.ExportedProperty(category = "layout")
2978    protected int mTop;
2979    /**
2980     * The distance in pixels from the top edge of this view's parent
2981     * to the bottom edge of this view.
2982     * {@hide}
2983     */
2984    @ViewDebug.ExportedProperty(category = "layout")
2985    protected int mBottom;
2986
2987    /**
2988     * The offset, in pixels, by which the content of this view is scrolled
2989     * horizontally.
2990     * {@hide}
2991     */
2992    @ViewDebug.ExportedProperty(category = "scrolling")
2993    protected int mScrollX;
2994    /**
2995     * The offset, in pixels, by which the content of this view is scrolled
2996     * vertically.
2997     * {@hide}
2998     */
2999    @ViewDebug.ExportedProperty(category = "scrolling")
3000    protected int mScrollY;
3001
3002    /**
3003     * The left padding in pixels, that is the distance in pixels between the
3004     * left edge of this view and the left edge of its content.
3005     * {@hide}
3006     */
3007    @ViewDebug.ExportedProperty(category = "padding")
3008    protected int mPaddingLeft = 0;
3009    /**
3010     * The right padding in pixels, that is the distance in pixels between the
3011     * right edge of this view and the right edge of its content.
3012     * {@hide}
3013     */
3014    @ViewDebug.ExportedProperty(category = "padding")
3015    protected int mPaddingRight = 0;
3016    /**
3017     * The top padding in pixels, that is the distance in pixels between the
3018     * top edge of this view and the top edge of its content.
3019     * {@hide}
3020     */
3021    @ViewDebug.ExportedProperty(category = "padding")
3022    protected int mPaddingTop;
3023    /**
3024     * The bottom padding in pixels, that is the distance in pixels between the
3025     * bottom edge of this view and the bottom edge of its content.
3026     * {@hide}
3027     */
3028    @ViewDebug.ExportedProperty(category = "padding")
3029    protected int mPaddingBottom;
3030
3031    /**
3032     * The layout insets in pixels, that is the distance in pixels between the
3033     * visible edges of this view its bounds.
3034     */
3035    private Insets mLayoutInsets;
3036
3037    /**
3038     * Briefly describes the view and is primarily used for accessibility support.
3039     */
3040    private CharSequence mContentDescription;
3041
3042    /**
3043     * Specifies the id of a view for which this view serves as a label for
3044     * accessibility purposes.
3045     */
3046    private int mLabelForId = View.NO_ID;
3047
3048    /**
3049     * Predicate for matching labeled view id with its label for
3050     * accessibility purposes.
3051     */
3052    private MatchLabelForPredicate mMatchLabelForPredicate;
3053
3054    /**
3055     * Specifies a view before which this one is visited in accessibility traversal.
3056     */
3057    private int mAccessibilityTraversalBeforeId = NO_ID;
3058
3059    /**
3060     * Specifies a view after which this one is visited in accessibility traversal.
3061     */
3062    private int mAccessibilityTraversalAfterId = NO_ID;
3063
3064    /**
3065     * Predicate for matching a view by its id.
3066     */
3067    private MatchIdPredicate mMatchIdPredicate;
3068
3069    /**
3070     * Cache the paddingRight set by the user to append to the scrollbar's size.
3071     *
3072     * @hide
3073     */
3074    @ViewDebug.ExportedProperty(category = "padding")
3075    protected int mUserPaddingRight;
3076
3077    /**
3078     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3079     *
3080     * @hide
3081     */
3082    @ViewDebug.ExportedProperty(category = "padding")
3083    protected int mUserPaddingBottom;
3084
3085    /**
3086     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3087     *
3088     * @hide
3089     */
3090    @ViewDebug.ExportedProperty(category = "padding")
3091    protected int mUserPaddingLeft;
3092
3093    /**
3094     * Cache the paddingStart set by the user to append to the scrollbar's size.
3095     *
3096     */
3097    @ViewDebug.ExportedProperty(category = "padding")
3098    int mUserPaddingStart;
3099
3100    /**
3101     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3102     *
3103     */
3104    @ViewDebug.ExportedProperty(category = "padding")
3105    int mUserPaddingEnd;
3106
3107    /**
3108     * Cache initial left padding.
3109     *
3110     * @hide
3111     */
3112    int mUserPaddingLeftInitial;
3113
3114    /**
3115     * Cache initial right padding.
3116     *
3117     * @hide
3118     */
3119    int mUserPaddingRightInitial;
3120
3121    /**
3122     * Default undefined padding
3123     */
3124    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3125
3126    /**
3127     * Cache if a left padding has been defined
3128     */
3129    private boolean mLeftPaddingDefined = false;
3130
3131    /**
3132     * Cache if a right padding has been defined
3133     */
3134    private boolean mRightPaddingDefined = false;
3135
3136    /**
3137     * @hide
3138     */
3139    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3140    /**
3141     * @hide
3142     */
3143    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3144
3145    private LongSparseLongArray mMeasureCache;
3146
3147    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3148    private Drawable mBackground;
3149    private TintInfo mBackgroundTint;
3150
3151    /**
3152     * RenderNode used for backgrounds.
3153     * <p>
3154     * When non-null and valid, this is expected to contain an up-to-date copy
3155     * of the background drawable. It is cleared on temporary detach, and reset
3156     * on cleanup.
3157     */
3158    private RenderNode mBackgroundRenderNode;
3159
3160    private int mBackgroundResource;
3161    private boolean mBackgroundSizeChanged;
3162
3163    private String mTransitionName;
3164
3165    private static class TintInfo {
3166        ColorStateList mTintList;
3167        PorterDuff.Mode mTintMode;
3168        boolean mHasTintMode;
3169        boolean mHasTintList;
3170    }
3171
3172    static class ListenerInfo {
3173        /**
3174         * Listener used to dispatch focus change events.
3175         * This field should be made private, so it is hidden from the SDK.
3176         * {@hide}
3177         */
3178        protected OnFocusChangeListener mOnFocusChangeListener;
3179
3180        /**
3181         * Listeners for layout change events.
3182         */
3183        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3184
3185        protected OnScrollChangeListener mOnScrollChangeListener;
3186
3187        /**
3188         * Listeners for attach events.
3189         */
3190        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3191
3192        /**
3193         * Listener used to dispatch click events.
3194         * This field should be made private, so it is hidden from the SDK.
3195         * {@hide}
3196         */
3197        public OnClickListener mOnClickListener;
3198
3199        /**
3200         * Listener used to dispatch long click events.
3201         * This field should be made private, so it is hidden from the SDK.
3202         * {@hide}
3203         */
3204        protected OnLongClickListener mOnLongClickListener;
3205
3206        /**
3207         * Listener used to build the context menu.
3208         * This field should be made private, so it is hidden from the SDK.
3209         * {@hide}
3210         */
3211        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3212
3213        private OnKeyListener mOnKeyListener;
3214
3215        private OnTouchListener mOnTouchListener;
3216
3217        private OnHoverListener mOnHoverListener;
3218
3219        private OnGenericMotionListener mOnGenericMotionListener;
3220
3221        private OnDragListener mOnDragListener;
3222
3223        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3224
3225        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3226    }
3227
3228    ListenerInfo mListenerInfo;
3229
3230    /**
3231     * The application environment this view lives in.
3232     * This field should be made private, so it is hidden from the SDK.
3233     * {@hide}
3234     */
3235    @ViewDebug.ExportedProperty(deepExport = true)
3236    protected Context mContext;
3237
3238    private final Resources mResources;
3239
3240    private ScrollabilityCache mScrollCache;
3241
3242    private int[] mDrawableState = null;
3243
3244    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3245
3246    /**
3247     * Animator that automatically runs based on state changes.
3248     */
3249    private StateListAnimator mStateListAnimator;
3250
3251    /**
3252     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3253     * the user may specify which view to go to next.
3254     */
3255    private int mNextFocusLeftId = View.NO_ID;
3256
3257    /**
3258     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3259     * the user may specify which view to go to next.
3260     */
3261    private int mNextFocusRightId = View.NO_ID;
3262
3263    /**
3264     * When this view has focus and the next focus is {@link #FOCUS_UP},
3265     * the user may specify which view to go to next.
3266     */
3267    private int mNextFocusUpId = View.NO_ID;
3268
3269    /**
3270     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3271     * the user may specify which view to go to next.
3272     */
3273    private int mNextFocusDownId = View.NO_ID;
3274
3275    /**
3276     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3277     * the user may specify which view to go to next.
3278     */
3279    int mNextFocusForwardId = View.NO_ID;
3280
3281    private CheckForLongPress mPendingCheckForLongPress;
3282    private CheckForTap mPendingCheckForTap = null;
3283    private PerformClick mPerformClick;
3284    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3285
3286    private UnsetPressedState mUnsetPressedState;
3287
3288    /**
3289     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3290     * up event while a long press is invoked as soon as the long press duration is reached, so
3291     * a long press could be performed before the tap is checked, in which case the tap's action
3292     * should not be invoked.
3293     */
3294    private boolean mHasPerformedLongPress;
3295
3296    /**
3297     * The minimum height of the view. We'll try our best to have the height
3298     * of this view to at least this amount.
3299     */
3300    @ViewDebug.ExportedProperty(category = "measurement")
3301    private int mMinHeight;
3302
3303    /**
3304     * The minimum width of the view. We'll try our best to have the width
3305     * of this view to at least this amount.
3306     */
3307    @ViewDebug.ExportedProperty(category = "measurement")
3308    private int mMinWidth;
3309
3310    /**
3311     * The delegate to handle touch events that are physically in this view
3312     * but should be handled by another view.
3313     */
3314    private TouchDelegate mTouchDelegate = null;
3315
3316    /**
3317     * Solid color to use as a background when creating the drawing cache. Enables
3318     * the cache to use 16 bit bitmaps instead of 32 bit.
3319     */
3320    private int mDrawingCacheBackgroundColor = 0;
3321
3322    /**
3323     * Special tree observer used when mAttachInfo is null.
3324     */
3325    private ViewTreeObserver mFloatingTreeObserver;
3326
3327    /**
3328     * Cache the touch slop from the context that created the view.
3329     */
3330    private int mTouchSlop;
3331
3332    /**
3333     * Object that handles automatic animation of view properties.
3334     */
3335    private ViewPropertyAnimator mAnimator = null;
3336
3337    /**
3338     * Flag indicating that a drag can cross window boundaries.  When
3339     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3340     * with this flag set, all visible applications will be able to participate
3341     * in the drag operation and receive the dragged content.
3342     *
3343     * @hide
3344     */
3345    public static final int DRAG_FLAG_GLOBAL = 1;
3346
3347    /**
3348     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3349     */
3350    private float mVerticalScrollFactor;
3351
3352    /**
3353     * Position of the vertical scroll bar.
3354     */
3355    private int mVerticalScrollbarPosition;
3356
3357    /**
3358     * Position the scroll bar at the default position as determined by the system.
3359     */
3360    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3361
3362    /**
3363     * Position the scroll bar along the left edge.
3364     */
3365    public static final int SCROLLBAR_POSITION_LEFT = 1;
3366
3367    /**
3368     * Position the scroll bar along the right edge.
3369     */
3370    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3371
3372    /**
3373     * Indicates that the view does not have a layer.
3374     *
3375     * @see #getLayerType()
3376     * @see #setLayerType(int, android.graphics.Paint)
3377     * @see #LAYER_TYPE_SOFTWARE
3378     * @see #LAYER_TYPE_HARDWARE
3379     */
3380    public static final int LAYER_TYPE_NONE = 0;
3381
3382    /**
3383     * <p>Indicates that the view has a software layer. A software layer is backed
3384     * by a bitmap and causes the view to be rendered using Android's software
3385     * rendering pipeline, even if hardware acceleration is enabled.</p>
3386     *
3387     * <p>Software layers have various usages:</p>
3388     * <p>When the application is not using hardware acceleration, a software layer
3389     * is useful to apply a specific color filter and/or blending mode and/or
3390     * translucency to a view and all its children.</p>
3391     * <p>When the application is using hardware acceleration, a software layer
3392     * is useful to render drawing primitives not supported by the hardware
3393     * accelerated pipeline. It can also be used to cache a complex view tree
3394     * into a texture and reduce the complexity of drawing operations. For instance,
3395     * when animating a complex view tree with a translation, a software layer can
3396     * be used to render the view tree only once.</p>
3397     * <p>Software layers should be avoided when the affected view tree updates
3398     * often. Every update will require to re-render the software layer, which can
3399     * potentially be slow (particularly when hardware acceleration is turned on
3400     * since the layer will have to be uploaded into a hardware texture after every
3401     * update.)</p>
3402     *
3403     * @see #getLayerType()
3404     * @see #setLayerType(int, android.graphics.Paint)
3405     * @see #LAYER_TYPE_NONE
3406     * @see #LAYER_TYPE_HARDWARE
3407     */
3408    public static final int LAYER_TYPE_SOFTWARE = 1;
3409
3410    /**
3411     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3412     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3413     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3414     * rendering pipeline, but only if hardware acceleration is turned on for the
3415     * view hierarchy. When hardware acceleration is turned off, hardware layers
3416     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3417     *
3418     * <p>A hardware layer is useful to apply a specific color filter and/or
3419     * blending mode and/or translucency to a view and all its children.</p>
3420     * <p>A hardware layer can be used to cache a complex view tree into a
3421     * texture and reduce the complexity of drawing operations. For instance,
3422     * when animating a complex view tree with a translation, a hardware layer can
3423     * be used to render the view tree only once.</p>
3424     * <p>A hardware layer can also be used to increase the rendering quality when
3425     * rotation transformations are applied on a view. It can also be used to
3426     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3427     *
3428     * @see #getLayerType()
3429     * @see #setLayerType(int, android.graphics.Paint)
3430     * @see #LAYER_TYPE_NONE
3431     * @see #LAYER_TYPE_SOFTWARE
3432     */
3433    public static final int LAYER_TYPE_HARDWARE = 2;
3434
3435    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3436            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3437            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3438            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3439    })
3440    int mLayerType = LAYER_TYPE_NONE;
3441    Paint mLayerPaint;
3442
3443    /**
3444     * Set to true when drawing cache is enabled and cannot be created.
3445     *
3446     * @hide
3447     */
3448    public boolean mCachingFailed;
3449    private Bitmap mDrawingCache;
3450    private Bitmap mUnscaledDrawingCache;
3451
3452    /**
3453     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3454     * <p>
3455     * When non-null and valid, this is expected to contain an up-to-date copy
3456     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3457     * cleanup.
3458     */
3459    final RenderNode mRenderNode;
3460
3461    /**
3462     * Set to true when the view is sending hover accessibility events because it
3463     * is the innermost hovered view.
3464     */
3465    private boolean mSendingHoverAccessibilityEvents;
3466
3467    /**
3468     * Delegate for injecting accessibility functionality.
3469     */
3470    AccessibilityDelegate mAccessibilityDelegate;
3471
3472    /**
3473     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3474     * and add/remove objects to/from the overlay directly through the Overlay methods.
3475     */
3476    ViewOverlay mOverlay;
3477
3478    /**
3479     * The currently active parent view for receiving delegated nested scrolling events.
3480     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3481     * by {@link #stopNestedScroll()} at the same point where we clear
3482     * requestDisallowInterceptTouchEvent.
3483     */
3484    private ViewParent mNestedScrollingParent;
3485
3486    /**
3487     * Consistency verifier for debugging purposes.
3488     * @hide
3489     */
3490    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3491            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3492                    new InputEventConsistencyVerifier(this, 0) : null;
3493
3494    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3495
3496    private int[] mTempNestedScrollConsumed;
3497
3498    /**
3499     * An overlay is going to draw this View instead of being drawn as part of this
3500     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3501     * when this view is invalidated.
3502     */
3503    GhostView mGhostView;
3504
3505    /**
3506     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3507     * @hide
3508     */
3509    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3510    public String[] mAttributes;
3511
3512    /**
3513     * Maps a Resource id to its name.
3514     */
3515    private static SparseArray<String> mAttributeMap;
3516
3517    /**
3518     * Simple constructor to use when creating a view from code.
3519     *
3520     * @param context The Context the view is running in, through which it can
3521     *        access the current theme, resources, etc.
3522     */
3523    public View(Context context) {
3524        mContext = context;
3525        mResources = context != null ? context.getResources() : null;
3526        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3527        // Set some flags defaults
3528        mPrivateFlags2 =
3529                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3530                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3531                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3532                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3533                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3534                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3535        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3536        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3537        mUserPaddingStart = UNDEFINED_PADDING;
3538        mUserPaddingEnd = UNDEFINED_PADDING;
3539        mRenderNode = RenderNode.create(getClass().getName(), this);
3540
3541        if (!sCompatibilityDone && context != null) {
3542            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3543
3544            // Older apps may need this compatibility hack for measurement.
3545            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3546
3547            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3548            // of whether a layout was requested on that View.
3549            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3550
3551            sCompatibilityDone = true;
3552        }
3553    }
3554
3555    /**
3556     * Constructor that is called when inflating a view from XML. This is called
3557     * when a view is being constructed from an XML file, supplying attributes
3558     * that were specified in the XML file. This version uses a default style of
3559     * 0, so the only attribute values applied are those in the Context's Theme
3560     * and the given AttributeSet.
3561     *
3562     * <p>
3563     * The method onFinishInflate() will be called after all children have been
3564     * added.
3565     *
3566     * @param context The Context the view is running in, through which it can
3567     *        access the current theme, resources, etc.
3568     * @param attrs The attributes of the XML tag that is inflating the view.
3569     * @see #View(Context, AttributeSet, int)
3570     */
3571    public View(Context context, AttributeSet attrs) {
3572        this(context, attrs, 0);
3573    }
3574
3575    /**
3576     * Perform inflation from XML and apply a class-specific base style from a
3577     * theme attribute. This constructor of View allows subclasses to use their
3578     * own base style when they are inflating. For example, a Button class's
3579     * constructor would call this version of the super class constructor and
3580     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3581     * allows the theme's button style to modify all of the base view attributes
3582     * (in particular its background) as well as the Button class's attributes.
3583     *
3584     * @param context The Context the view is running in, through which it can
3585     *        access the current theme, resources, etc.
3586     * @param attrs The attributes of the XML tag that is inflating the view.
3587     * @param defStyleAttr An attribute in the current theme that contains a
3588     *        reference to a style resource that supplies default values for
3589     *        the view. Can be 0 to not look for defaults.
3590     * @see #View(Context, AttributeSet)
3591     */
3592    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3593        this(context, attrs, defStyleAttr, 0);
3594    }
3595
3596    /**
3597     * Perform inflation from XML and apply a class-specific base style from a
3598     * theme attribute or style resource. This constructor of View allows
3599     * subclasses to use their own base style when they are inflating.
3600     * <p>
3601     * When determining the final value of a particular attribute, there are
3602     * four inputs that come into play:
3603     * <ol>
3604     * <li>Any attribute values in the given AttributeSet.
3605     * <li>The style resource specified in the AttributeSet (named "style").
3606     * <li>The default style specified by <var>defStyleAttr</var>.
3607     * <li>The default style specified by <var>defStyleRes</var>.
3608     * <li>The base values in this theme.
3609     * </ol>
3610     * <p>
3611     * Each of these inputs is considered in-order, with the first listed taking
3612     * precedence over the following ones. In other words, if in the
3613     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3614     * , then the button's text will <em>always</em> be black, regardless of
3615     * what is specified in any of the styles.
3616     *
3617     * @param context The Context the view is running in, through which it can
3618     *        access the current theme, resources, etc.
3619     * @param attrs The attributes of the XML tag that is inflating the view.
3620     * @param defStyleAttr An attribute in the current theme that contains a
3621     *        reference to a style resource that supplies default values for
3622     *        the view. Can be 0 to not look for defaults.
3623     * @param defStyleRes A resource identifier of a style resource that
3624     *        supplies default values for the view, used only if
3625     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3626     *        to not look for defaults.
3627     * @see #View(Context, AttributeSet, int)
3628     */
3629    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3630        this(context);
3631
3632        final TypedArray a = context.obtainStyledAttributes(
3633                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3634
3635        if (mDebugViewAttributes) {
3636            saveAttributeData(attrs, a);
3637        }
3638
3639        Drawable background = null;
3640
3641        int leftPadding = -1;
3642        int topPadding = -1;
3643        int rightPadding = -1;
3644        int bottomPadding = -1;
3645        int startPadding = UNDEFINED_PADDING;
3646        int endPadding = UNDEFINED_PADDING;
3647
3648        int padding = -1;
3649
3650        int viewFlagValues = 0;
3651        int viewFlagMasks = 0;
3652
3653        boolean setScrollContainer = false;
3654
3655        int x = 0;
3656        int y = 0;
3657
3658        float tx = 0;
3659        float ty = 0;
3660        float tz = 0;
3661        float elevation = 0;
3662        float rotation = 0;
3663        float rotationX = 0;
3664        float rotationY = 0;
3665        float sx = 1f;
3666        float sy = 1f;
3667        boolean transformSet = false;
3668
3669        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3670        int overScrollMode = mOverScrollMode;
3671        boolean initializeScrollbars = false;
3672
3673        boolean startPaddingDefined = false;
3674        boolean endPaddingDefined = false;
3675        boolean leftPaddingDefined = false;
3676        boolean rightPaddingDefined = false;
3677
3678        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3679
3680        final int N = a.getIndexCount();
3681        for (int i = 0; i < N; i++) {
3682            int attr = a.getIndex(i);
3683            switch (attr) {
3684                case com.android.internal.R.styleable.View_background:
3685                    background = a.getDrawable(attr);
3686                    break;
3687                case com.android.internal.R.styleable.View_padding:
3688                    padding = a.getDimensionPixelSize(attr, -1);
3689                    mUserPaddingLeftInitial = padding;
3690                    mUserPaddingRightInitial = padding;
3691                    leftPaddingDefined = true;
3692                    rightPaddingDefined = true;
3693                    break;
3694                 case com.android.internal.R.styleable.View_paddingLeft:
3695                    leftPadding = a.getDimensionPixelSize(attr, -1);
3696                    mUserPaddingLeftInitial = leftPadding;
3697                    leftPaddingDefined = true;
3698                    break;
3699                case com.android.internal.R.styleable.View_paddingTop:
3700                    topPadding = a.getDimensionPixelSize(attr, -1);
3701                    break;
3702                case com.android.internal.R.styleable.View_paddingRight:
3703                    rightPadding = a.getDimensionPixelSize(attr, -1);
3704                    mUserPaddingRightInitial = rightPadding;
3705                    rightPaddingDefined = true;
3706                    break;
3707                case com.android.internal.R.styleable.View_paddingBottom:
3708                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3709                    break;
3710                case com.android.internal.R.styleable.View_paddingStart:
3711                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3712                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3713                    break;
3714                case com.android.internal.R.styleable.View_paddingEnd:
3715                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3716                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3717                    break;
3718                case com.android.internal.R.styleable.View_scrollX:
3719                    x = a.getDimensionPixelOffset(attr, 0);
3720                    break;
3721                case com.android.internal.R.styleable.View_scrollY:
3722                    y = a.getDimensionPixelOffset(attr, 0);
3723                    break;
3724                case com.android.internal.R.styleable.View_alpha:
3725                    setAlpha(a.getFloat(attr, 1f));
3726                    break;
3727                case com.android.internal.R.styleable.View_transformPivotX:
3728                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3729                    break;
3730                case com.android.internal.R.styleable.View_transformPivotY:
3731                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3732                    break;
3733                case com.android.internal.R.styleable.View_translationX:
3734                    tx = a.getDimensionPixelOffset(attr, 0);
3735                    transformSet = true;
3736                    break;
3737                case com.android.internal.R.styleable.View_translationY:
3738                    ty = a.getDimensionPixelOffset(attr, 0);
3739                    transformSet = true;
3740                    break;
3741                case com.android.internal.R.styleable.View_translationZ:
3742                    tz = a.getDimensionPixelOffset(attr, 0);
3743                    transformSet = true;
3744                    break;
3745                case com.android.internal.R.styleable.View_elevation:
3746                    elevation = a.getDimensionPixelOffset(attr, 0);
3747                    transformSet = true;
3748                    break;
3749                case com.android.internal.R.styleable.View_rotation:
3750                    rotation = a.getFloat(attr, 0);
3751                    transformSet = true;
3752                    break;
3753                case com.android.internal.R.styleable.View_rotationX:
3754                    rotationX = a.getFloat(attr, 0);
3755                    transformSet = true;
3756                    break;
3757                case com.android.internal.R.styleable.View_rotationY:
3758                    rotationY = a.getFloat(attr, 0);
3759                    transformSet = true;
3760                    break;
3761                case com.android.internal.R.styleable.View_scaleX:
3762                    sx = a.getFloat(attr, 1f);
3763                    transformSet = true;
3764                    break;
3765                case com.android.internal.R.styleable.View_scaleY:
3766                    sy = a.getFloat(attr, 1f);
3767                    transformSet = true;
3768                    break;
3769                case com.android.internal.R.styleable.View_id:
3770                    mID = a.getResourceId(attr, NO_ID);
3771                    break;
3772                case com.android.internal.R.styleable.View_tag:
3773                    mTag = a.getText(attr);
3774                    break;
3775                case com.android.internal.R.styleable.View_fitsSystemWindows:
3776                    if (a.getBoolean(attr, false)) {
3777                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3778                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3779                    }
3780                    break;
3781                case com.android.internal.R.styleable.View_focusable:
3782                    if (a.getBoolean(attr, false)) {
3783                        viewFlagValues |= FOCUSABLE;
3784                        viewFlagMasks |= FOCUSABLE_MASK;
3785                    }
3786                    break;
3787                case com.android.internal.R.styleable.View_focusableInTouchMode:
3788                    if (a.getBoolean(attr, false)) {
3789                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3790                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3791                    }
3792                    break;
3793                case com.android.internal.R.styleable.View_clickable:
3794                    if (a.getBoolean(attr, false)) {
3795                        viewFlagValues |= CLICKABLE;
3796                        viewFlagMasks |= CLICKABLE;
3797                    }
3798                    break;
3799                case com.android.internal.R.styleable.View_longClickable:
3800                    if (a.getBoolean(attr, false)) {
3801                        viewFlagValues |= LONG_CLICKABLE;
3802                        viewFlagMasks |= LONG_CLICKABLE;
3803                    }
3804                    break;
3805                case com.android.internal.R.styleable.View_saveEnabled:
3806                    if (!a.getBoolean(attr, true)) {
3807                        viewFlagValues |= SAVE_DISABLED;
3808                        viewFlagMasks |= SAVE_DISABLED_MASK;
3809                    }
3810                    break;
3811                case com.android.internal.R.styleable.View_duplicateParentState:
3812                    if (a.getBoolean(attr, false)) {
3813                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3814                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3815                    }
3816                    break;
3817                case com.android.internal.R.styleable.View_visibility:
3818                    final int visibility = a.getInt(attr, 0);
3819                    if (visibility != 0) {
3820                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3821                        viewFlagMasks |= VISIBILITY_MASK;
3822                    }
3823                    break;
3824                case com.android.internal.R.styleable.View_layoutDirection:
3825                    // Clear any layout direction flags (included resolved bits) already set
3826                    mPrivateFlags2 &=
3827                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3828                    // Set the layout direction flags depending on the value of the attribute
3829                    final int layoutDirection = a.getInt(attr, -1);
3830                    final int value = (layoutDirection != -1) ?
3831                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3832                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3833                    break;
3834                case com.android.internal.R.styleable.View_drawingCacheQuality:
3835                    final int cacheQuality = a.getInt(attr, 0);
3836                    if (cacheQuality != 0) {
3837                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3838                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3839                    }
3840                    break;
3841                case com.android.internal.R.styleable.View_contentDescription:
3842                    setContentDescription(a.getString(attr));
3843                    break;
3844                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3845                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3846                    break;
3847                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3848                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3849                    break;
3850                case com.android.internal.R.styleable.View_labelFor:
3851                    setLabelFor(a.getResourceId(attr, NO_ID));
3852                    break;
3853                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3854                    if (!a.getBoolean(attr, true)) {
3855                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3856                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3857                    }
3858                    break;
3859                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3860                    if (!a.getBoolean(attr, true)) {
3861                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3862                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3863                    }
3864                    break;
3865                case R.styleable.View_scrollbars:
3866                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3867                    if (scrollbars != SCROLLBARS_NONE) {
3868                        viewFlagValues |= scrollbars;
3869                        viewFlagMasks |= SCROLLBARS_MASK;
3870                        initializeScrollbars = true;
3871                    }
3872                    break;
3873                //noinspection deprecation
3874                case R.styleable.View_fadingEdge:
3875                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3876                        // Ignore the attribute starting with ICS
3877                        break;
3878                    }
3879                    // With builds < ICS, fall through and apply fading edges
3880                case R.styleable.View_requiresFadingEdge:
3881                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3882                    if (fadingEdge != FADING_EDGE_NONE) {
3883                        viewFlagValues |= fadingEdge;
3884                        viewFlagMasks |= FADING_EDGE_MASK;
3885                        initializeFadingEdgeInternal(a);
3886                    }
3887                    break;
3888                case R.styleable.View_scrollbarStyle:
3889                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3890                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3891                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3892                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3893                    }
3894                    break;
3895                case R.styleable.View_isScrollContainer:
3896                    setScrollContainer = true;
3897                    if (a.getBoolean(attr, false)) {
3898                        setScrollContainer(true);
3899                    }
3900                    break;
3901                case com.android.internal.R.styleable.View_keepScreenOn:
3902                    if (a.getBoolean(attr, false)) {
3903                        viewFlagValues |= KEEP_SCREEN_ON;
3904                        viewFlagMasks |= KEEP_SCREEN_ON;
3905                    }
3906                    break;
3907                case R.styleable.View_filterTouchesWhenObscured:
3908                    if (a.getBoolean(attr, false)) {
3909                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3910                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3911                    }
3912                    break;
3913                case R.styleable.View_nextFocusLeft:
3914                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3915                    break;
3916                case R.styleable.View_nextFocusRight:
3917                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3918                    break;
3919                case R.styleable.View_nextFocusUp:
3920                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3921                    break;
3922                case R.styleable.View_nextFocusDown:
3923                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3924                    break;
3925                case R.styleable.View_nextFocusForward:
3926                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3927                    break;
3928                case R.styleable.View_minWidth:
3929                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3930                    break;
3931                case R.styleable.View_minHeight:
3932                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3933                    break;
3934                case R.styleable.View_onClick:
3935                    if (context.isRestricted()) {
3936                        throw new IllegalStateException("The android:onClick attribute cannot "
3937                                + "be used within a restricted context");
3938                    }
3939
3940                    final String handlerName = a.getString(attr);
3941                    if (handlerName != null) {
3942                        setOnClickListener(new OnClickListener() {
3943                            private Method mHandler;
3944
3945                            public void onClick(View v) {
3946                                if (mHandler == null) {
3947                                    try {
3948                                        mHandler = getContext().getClass().getMethod(handlerName,
3949                                                View.class);
3950                                    } catch (NoSuchMethodException e) {
3951                                        int id = getId();
3952                                        String idText = id == NO_ID ? "" : " with id '"
3953                                                + getContext().getResources().getResourceEntryName(
3954                                                    id) + "'";
3955                                        throw new IllegalStateException("Could not find a method " +
3956                                                handlerName + "(View) in the activity "
3957                                                + getContext().getClass() + " for onClick handler"
3958                                                + " on view " + View.this.getClass() + idText, e);
3959                                    }
3960                                }
3961
3962                                try {
3963                                    mHandler.invoke(getContext(), View.this);
3964                                } catch (IllegalAccessException e) {
3965                                    throw new IllegalStateException("Could not execute non "
3966                                            + "public method of the activity", e);
3967                                } catch (InvocationTargetException e) {
3968                                    throw new IllegalStateException("Could not execute "
3969                                            + "method of the activity", e);
3970                                }
3971                            }
3972                        });
3973                    }
3974                    break;
3975                case R.styleable.View_overScrollMode:
3976                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3977                    break;
3978                case R.styleable.View_verticalScrollbarPosition:
3979                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3980                    break;
3981                case R.styleable.View_layerType:
3982                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3983                    break;
3984                case R.styleable.View_textDirection:
3985                    // Clear any text direction flag already set
3986                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3987                    // Set the text direction flags depending on the value of the attribute
3988                    final int textDirection = a.getInt(attr, -1);
3989                    if (textDirection != -1) {
3990                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3991                    }
3992                    break;
3993                case R.styleable.View_textAlignment:
3994                    // Clear any text alignment flag already set
3995                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3996                    // Set the text alignment flag depending on the value of the attribute
3997                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3998                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3999                    break;
4000                case R.styleable.View_importantForAccessibility:
4001                    setImportantForAccessibility(a.getInt(attr,
4002                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4003                    break;
4004                case R.styleable.View_accessibilityLiveRegion:
4005                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4006                    break;
4007                case R.styleable.View_transitionName:
4008                    setTransitionName(a.getString(attr));
4009                    break;
4010                case R.styleable.View_nestedScrollingEnabled:
4011                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4012                    break;
4013                case R.styleable.View_stateListAnimator:
4014                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4015                            a.getResourceId(attr, 0)));
4016                    break;
4017                case R.styleable.View_backgroundTint:
4018                    // This will get applied later during setBackground().
4019                    if (mBackgroundTint == null) {
4020                        mBackgroundTint = new TintInfo();
4021                    }
4022                    mBackgroundTint.mTintList = a.getColorStateList(
4023                            R.styleable.View_backgroundTint);
4024                    mBackgroundTint.mHasTintList = true;
4025                    break;
4026                case R.styleable.View_backgroundTintMode:
4027                    // This will get applied later during setBackground().
4028                    if (mBackgroundTint == null) {
4029                        mBackgroundTint = new TintInfo();
4030                    }
4031                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4032                            R.styleable.View_backgroundTintMode, -1), null);
4033                    mBackgroundTint.mHasTintMode = true;
4034                    break;
4035                case R.styleable.View_outlineProvider:
4036                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4037                            PROVIDER_BACKGROUND));
4038                    break;
4039            }
4040        }
4041
4042        setOverScrollMode(overScrollMode);
4043
4044        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4045        // the resolved layout direction). Those cached values will be used later during padding
4046        // resolution.
4047        mUserPaddingStart = startPadding;
4048        mUserPaddingEnd = endPadding;
4049
4050        if (background != null) {
4051            setBackground(background);
4052        }
4053
4054        // setBackground above will record that padding is currently provided by the background.
4055        // If we have padding specified via xml, record that here instead and use it.
4056        mLeftPaddingDefined = leftPaddingDefined;
4057        mRightPaddingDefined = rightPaddingDefined;
4058
4059        if (padding >= 0) {
4060            leftPadding = padding;
4061            topPadding = padding;
4062            rightPadding = padding;
4063            bottomPadding = padding;
4064            mUserPaddingLeftInitial = padding;
4065            mUserPaddingRightInitial = padding;
4066        }
4067
4068        if (isRtlCompatibilityMode()) {
4069            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4070            // left / right padding are used if defined (meaning here nothing to do). If they are not
4071            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4072            // start / end and resolve them as left / right (layout direction is not taken into account).
4073            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4074            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4075            // defined.
4076            if (!mLeftPaddingDefined && startPaddingDefined) {
4077                leftPadding = startPadding;
4078            }
4079            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4080            if (!mRightPaddingDefined && endPaddingDefined) {
4081                rightPadding = endPadding;
4082            }
4083            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4084        } else {
4085            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4086            // values defined. Otherwise, left /right values are used.
4087            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4088            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4089            // defined.
4090            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4091
4092            if (mLeftPaddingDefined && !hasRelativePadding) {
4093                mUserPaddingLeftInitial = leftPadding;
4094            }
4095            if (mRightPaddingDefined && !hasRelativePadding) {
4096                mUserPaddingRightInitial = rightPadding;
4097            }
4098        }
4099
4100        internalSetPadding(
4101                mUserPaddingLeftInitial,
4102                topPadding >= 0 ? topPadding : mPaddingTop,
4103                mUserPaddingRightInitial,
4104                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4105
4106        if (viewFlagMasks != 0) {
4107            setFlags(viewFlagValues, viewFlagMasks);
4108        }
4109
4110        if (initializeScrollbars) {
4111            initializeScrollbarsInternal(a);
4112        }
4113
4114        a.recycle();
4115
4116        // Needs to be called after mViewFlags is set
4117        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4118            recomputePadding();
4119        }
4120
4121        if (x != 0 || y != 0) {
4122            scrollTo(x, y);
4123        }
4124
4125        if (transformSet) {
4126            setTranslationX(tx);
4127            setTranslationY(ty);
4128            setTranslationZ(tz);
4129            setElevation(elevation);
4130            setRotation(rotation);
4131            setRotationX(rotationX);
4132            setRotationY(rotationY);
4133            setScaleX(sx);
4134            setScaleY(sy);
4135        }
4136
4137        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4138            setScrollContainer(true);
4139        }
4140
4141        computeOpaqueFlags();
4142    }
4143
4144    /**
4145     * Non-public constructor for use in testing
4146     */
4147    View() {
4148        mResources = null;
4149        mRenderNode = RenderNode.create(getClass().getName(), this);
4150    }
4151
4152    private static SparseArray<String> getAttributeMap() {
4153        if (mAttributeMap == null) {
4154            mAttributeMap = new SparseArray<String>();
4155        }
4156        return mAttributeMap;
4157    }
4158
4159    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4160        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4161        mAttributes = new String[length];
4162
4163        int i = 0;
4164        if (attrs != null) {
4165            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4166                mAttributes[i] = attrs.getAttributeName(i);
4167                mAttributes[i + 1] = attrs.getAttributeValue(i);
4168            }
4169
4170        }
4171
4172        SparseArray<String> attributeMap = getAttributeMap();
4173        for (int j = 0; j < a.length(); ++j) {
4174            if (a.hasValue(j)) {
4175                try {
4176                    int resourceId = a.getResourceId(j, 0);
4177                    if (resourceId == 0) {
4178                        continue;
4179                    }
4180
4181                    String resourceName = attributeMap.get(resourceId);
4182                    if (resourceName == null) {
4183                        resourceName = a.getResources().getResourceName(resourceId);
4184                        attributeMap.put(resourceId, resourceName);
4185                    }
4186
4187                    mAttributes[i] = resourceName;
4188                    mAttributes[i + 1] = a.getText(j).toString();
4189                    i += 2;
4190                } catch (Resources.NotFoundException e) {
4191                    // if we can't get the resource name, we just ignore it
4192                }
4193            }
4194        }
4195    }
4196
4197    public String toString() {
4198        StringBuilder out = new StringBuilder(128);
4199        out.append(getClass().getName());
4200        out.append('{');
4201        out.append(Integer.toHexString(System.identityHashCode(this)));
4202        out.append(' ');
4203        switch (mViewFlags&VISIBILITY_MASK) {
4204            case VISIBLE: out.append('V'); break;
4205            case INVISIBLE: out.append('I'); break;
4206            case GONE: out.append('G'); break;
4207            default: out.append('.'); break;
4208        }
4209        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4210        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4211        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4212        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4213        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4214        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4215        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4216        out.append(' ');
4217        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4218        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4219        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4220        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4221            out.append('p');
4222        } else {
4223            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4224        }
4225        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4226        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4227        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4228        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4229        out.append(' ');
4230        out.append(mLeft);
4231        out.append(',');
4232        out.append(mTop);
4233        out.append('-');
4234        out.append(mRight);
4235        out.append(',');
4236        out.append(mBottom);
4237        final int id = getId();
4238        if (id != NO_ID) {
4239            out.append(" #");
4240            out.append(Integer.toHexString(id));
4241            final Resources r = mResources;
4242            if (Resources.resourceHasPackage(id) && r != null) {
4243                try {
4244                    String pkgname;
4245                    switch (id&0xff000000) {
4246                        case 0x7f000000:
4247                            pkgname="app";
4248                            break;
4249                        case 0x01000000:
4250                            pkgname="android";
4251                            break;
4252                        default:
4253                            pkgname = r.getResourcePackageName(id);
4254                            break;
4255                    }
4256                    String typename = r.getResourceTypeName(id);
4257                    String entryname = r.getResourceEntryName(id);
4258                    out.append(" ");
4259                    out.append(pkgname);
4260                    out.append(":");
4261                    out.append(typename);
4262                    out.append("/");
4263                    out.append(entryname);
4264                } catch (Resources.NotFoundException e) {
4265                }
4266            }
4267        }
4268        out.append("}");
4269        return out.toString();
4270    }
4271
4272    /**
4273     * <p>
4274     * Initializes the fading edges from a given set of styled attributes. This
4275     * method should be called by subclasses that need fading edges and when an
4276     * instance of these subclasses is created programmatically rather than
4277     * being inflated from XML. This method is automatically called when the XML
4278     * is inflated.
4279     * </p>
4280     *
4281     * @param a the styled attributes set to initialize the fading edges from
4282     *
4283     * @removed
4284     */
4285    protected void initializeFadingEdge(TypedArray a) {
4286        // This method probably shouldn't have been included in the SDK to begin with.
4287        // It relies on 'a' having been initialized using an attribute filter array that is
4288        // not publicly available to the SDK. The old method has been renamed
4289        // to initializeFadingEdgeInternal and hidden for framework use only;
4290        // this one initializes using defaults to make it safe to call for apps.
4291
4292        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4293
4294        initializeFadingEdgeInternal(arr);
4295
4296        arr.recycle();
4297    }
4298
4299    /**
4300     * <p>
4301     * Initializes the fading edges from a given set of styled attributes. This
4302     * method should be called by subclasses that need fading edges and when an
4303     * instance of these subclasses is created programmatically rather than
4304     * being inflated from XML. This method is automatically called when the XML
4305     * is inflated.
4306     * </p>
4307     *
4308     * @param a the styled attributes set to initialize the fading edges from
4309     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4310     */
4311    protected void initializeFadingEdgeInternal(TypedArray a) {
4312        initScrollCache();
4313
4314        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4315                R.styleable.View_fadingEdgeLength,
4316                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4317    }
4318
4319    /**
4320     * Returns the size of the vertical faded edges used to indicate that more
4321     * content in this view is visible.
4322     *
4323     * @return The size in pixels of the vertical faded edge or 0 if vertical
4324     *         faded edges are not enabled for this view.
4325     * @attr ref android.R.styleable#View_fadingEdgeLength
4326     */
4327    public int getVerticalFadingEdgeLength() {
4328        if (isVerticalFadingEdgeEnabled()) {
4329            ScrollabilityCache cache = mScrollCache;
4330            if (cache != null) {
4331                return cache.fadingEdgeLength;
4332            }
4333        }
4334        return 0;
4335    }
4336
4337    /**
4338     * Set the size of the faded edge used to indicate that more content in this
4339     * view is available.  Will not change whether the fading edge is enabled; use
4340     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4341     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4342     * for the vertical or horizontal fading edges.
4343     *
4344     * @param length The size in pixels of the faded edge used to indicate that more
4345     *        content in this view is visible.
4346     */
4347    public void setFadingEdgeLength(int length) {
4348        initScrollCache();
4349        mScrollCache.fadingEdgeLength = length;
4350    }
4351
4352    /**
4353     * Returns the size of the horizontal faded edges used to indicate that more
4354     * content in this view is visible.
4355     *
4356     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4357     *         faded edges are not enabled for this view.
4358     * @attr ref android.R.styleable#View_fadingEdgeLength
4359     */
4360    public int getHorizontalFadingEdgeLength() {
4361        if (isHorizontalFadingEdgeEnabled()) {
4362            ScrollabilityCache cache = mScrollCache;
4363            if (cache != null) {
4364                return cache.fadingEdgeLength;
4365            }
4366        }
4367        return 0;
4368    }
4369
4370    /**
4371     * Returns the width of the vertical scrollbar.
4372     *
4373     * @return The width in pixels of the vertical scrollbar or 0 if there
4374     *         is no vertical scrollbar.
4375     */
4376    public int getVerticalScrollbarWidth() {
4377        ScrollabilityCache cache = mScrollCache;
4378        if (cache != null) {
4379            ScrollBarDrawable scrollBar = cache.scrollBar;
4380            if (scrollBar != null) {
4381                int size = scrollBar.getSize(true);
4382                if (size <= 0) {
4383                    size = cache.scrollBarSize;
4384                }
4385                return size;
4386            }
4387            return 0;
4388        }
4389        return 0;
4390    }
4391
4392    /**
4393     * Returns the height of the horizontal scrollbar.
4394     *
4395     * @return The height in pixels of the horizontal scrollbar or 0 if
4396     *         there is no horizontal scrollbar.
4397     */
4398    protected int getHorizontalScrollbarHeight() {
4399        ScrollabilityCache cache = mScrollCache;
4400        if (cache != null) {
4401            ScrollBarDrawable scrollBar = cache.scrollBar;
4402            if (scrollBar != null) {
4403                int size = scrollBar.getSize(false);
4404                if (size <= 0) {
4405                    size = cache.scrollBarSize;
4406                }
4407                return size;
4408            }
4409            return 0;
4410        }
4411        return 0;
4412    }
4413
4414    /**
4415     * <p>
4416     * Initializes the scrollbars from a given set of styled attributes. This
4417     * method should be called by subclasses that need scrollbars and when an
4418     * instance of these subclasses is created programmatically rather than
4419     * being inflated from XML. This method is automatically called when the XML
4420     * is inflated.
4421     * </p>
4422     *
4423     * @param a the styled attributes set to initialize the scrollbars from
4424     *
4425     * @removed
4426     */
4427    protected void initializeScrollbars(TypedArray a) {
4428        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4429        // using the View filter array which is not available to the SDK. As such, internal
4430        // framework usage now uses initializeScrollbarsInternal and we grab a default
4431        // TypedArray with the right filter instead here.
4432        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4433
4434        initializeScrollbarsInternal(arr);
4435
4436        // We ignored the method parameter. Recycle the one we actually did use.
4437        arr.recycle();
4438    }
4439
4440    /**
4441     * <p>
4442     * Initializes the scrollbars from a given set of styled attributes. This
4443     * method should be called by subclasses that need scrollbars and when an
4444     * instance of these subclasses is created programmatically rather than
4445     * being inflated from XML. This method is automatically called when the XML
4446     * is inflated.
4447     * </p>
4448     *
4449     * @param a the styled attributes set to initialize the scrollbars from
4450     * @hide
4451     */
4452    protected void initializeScrollbarsInternal(TypedArray a) {
4453        initScrollCache();
4454
4455        final ScrollabilityCache scrollabilityCache = mScrollCache;
4456
4457        if (scrollabilityCache.scrollBar == null) {
4458            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4459        }
4460
4461        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4462
4463        if (!fadeScrollbars) {
4464            scrollabilityCache.state = ScrollabilityCache.ON;
4465        }
4466        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4467
4468
4469        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4470                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4471                        .getScrollBarFadeDuration());
4472        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4473                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4474                ViewConfiguration.getScrollDefaultDelay());
4475
4476
4477        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4478                com.android.internal.R.styleable.View_scrollbarSize,
4479                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4480
4481        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4482        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4483
4484        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4485        if (thumb != null) {
4486            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4487        }
4488
4489        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4490                false);
4491        if (alwaysDraw) {
4492            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4493        }
4494
4495        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4496        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4497
4498        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4499        if (thumb != null) {
4500            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4501        }
4502
4503        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4504                false);
4505        if (alwaysDraw) {
4506            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4507        }
4508
4509        // Apply layout direction to the new Drawables if needed
4510        final int layoutDirection = getLayoutDirection();
4511        if (track != null) {
4512            track.setLayoutDirection(layoutDirection);
4513        }
4514        if (thumb != null) {
4515            thumb.setLayoutDirection(layoutDirection);
4516        }
4517
4518        // Re-apply user/background padding so that scrollbar(s) get added
4519        resolvePadding();
4520    }
4521
4522    /**
4523     * <p>
4524     * Initalizes the scrollability cache if necessary.
4525     * </p>
4526     */
4527    private void initScrollCache() {
4528        if (mScrollCache == null) {
4529            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4530        }
4531    }
4532
4533    private ScrollabilityCache getScrollCache() {
4534        initScrollCache();
4535        return mScrollCache;
4536    }
4537
4538    /**
4539     * Set the position of the vertical scroll bar. Should be one of
4540     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4541     * {@link #SCROLLBAR_POSITION_RIGHT}.
4542     *
4543     * @param position Where the vertical scroll bar should be positioned.
4544     */
4545    public void setVerticalScrollbarPosition(int position) {
4546        if (mVerticalScrollbarPosition != position) {
4547            mVerticalScrollbarPosition = position;
4548            computeOpaqueFlags();
4549            resolvePadding();
4550        }
4551    }
4552
4553    /**
4554     * @return The position where the vertical scroll bar will show, if applicable.
4555     * @see #setVerticalScrollbarPosition(int)
4556     */
4557    public int getVerticalScrollbarPosition() {
4558        return mVerticalScrollbarPosition;
4559    }
4560
4561    ListenerInfo getListenerInfo() {
4562        if (mListenerInfo != null) {
4563            return mListenerInfo;
4564        }
4565        mListenerInfo = new ListenerInfo();
4566        return mListenerInfo;
4567    }
4568
4569    /**
4570     * Register a callback to be invoked when the scroll position of this view
4571     * changed.
4572     *
4573     * @param l The callback that will run.
4574     * @hide Only used internally.
4575     */
4576    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4577        getListenerInfo().mOnScrollChangeListener = l;
4578    }
4579
4580    /**
4581     * Register a callback to be invoked when focus of this view changed.
4582     *
4583     * @param l The callback that will run.
4584     */
4585    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4586        getListenerInfo().mOnFocusChangeListener = l;
4587    }
4588
4589    /**
4590     * Add a listener that will be called when the bounds of the view change due to
4591     * layout processing.
4592     *
4593     * @param listener The listener that will be called when layout bounds change.
4594     */
4595    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4596        ListenerInfo li = getListenerInfo();
4597        if (li.mOnLayoutChangeListeners == null) {
4598            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4599        }
4600        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4601            li.mOnLayoutChangeListeners.add(listener);
4602        }
4603    }
4604
4605    /**
4606     * Remove a listener for layout changes.
4607     *
4608     * @param listener The listener for layout bounds change.
4609     */
4610    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4611        ListenerInfo li = mListenerInfo;
4612        if (li == null || li.mOnLayoutChangeListeners == null) {
4613            return;
4614        }
4615        li.mOnLayoutChangeListeners.remove(listener);
4616    }
4617
4618    /**
4619     * Add a listener for attach state changes.
4620     *
4621     * This listener will be called whenever this view is attached or detached
4622     * from a window. Remove the listener using
4623     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4624     *
4625     * @param listener Listener to attach
4626     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4627     */
4628    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4629        ListenerInfo li = getListenerInfo();
4630        if (li.mOnAttachStateChangeListeners == null) {
4631            li.mOnAttachStateChangeListeners
4632                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4633        }
4634        li.mOnAttachStateChangeListeners.add(listener);
4635    }
4636
4637    /**
4638     * Remove a listener for attach state changes. The listener will receive no further
4639     * notification of window attach/detach events.
4640     *
4641     * @param listener Listener to remove
4642     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4643     */
4644    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4645        ListenerInfo li = mListenerInfo;
4646        if (li == null || li.mOnAttachStateChangeListeners == null) {
4647            return;
4648        }
4649        li.mOnAttachStateChangeListeners.remove(listener);
4650    }
4651
4652    /**
4653     * Returns the focus-change callback registered for this view.
4654     *
4655     * @return The callback, or null if one is not registered.
4656     */
4657    public OnFocusChangeListener getOnFocusChangeListener() {
4658        ListenerInfo li = mListenerInfo;
4659        return li != null ? li.mOnFocusChangeListener : null;
4660    }
4661
4662    /**
4663     * Register a callback to be invoked when this view is clicked. If this view is not
4664     * clickable, it becomes clickable.
4665     *
4666     * @param l The callback that will run
4667     *
4668     * @see #setClickable(boolean)
4669     */
4670    public void setOnClickListener(OnClickListener l) {
4671        if (!isClickable()) {
4672            setClickable(true);
4673        }
4674        getListenerInfo().mOnClickListener = l;
4675    }
4676
4677    /**
4678     * Return whether this view has an attached OnClickListener.  Returns
4679     * true if there is a listener, false if there is none.
4680     */
4681    public boolean hasOnClickListeners() {
4682        ListenerInfo li = mListenerInfo;
4683        return (li != null && li.mOnClickListener != null);
4684    }
4685
4686    /**
4687     * Register a callback to be invoked when this view is clicked and held. If this view is not
4688     * long clickable, it becomes long clickable.
4689     *
4690     * @param l The callback that will run
4691     *
4692     * @see #setLongClickable(boolean)
4693     */
4694    public void setOnLongClickListener(OnLongClickListener l) {
4695        if (!isLongClickable()) {
4696            setLongClickable(true);
4697        }
4698        getListenerInfo().mOnLongClickListener = l;
4699    }
4700
4701    /**
4702     * Register a callback to be invoked when the context menu for this view is
4703     * being built. If this view is not long clickable, it becomes long clickable.
4704     *
4705     * @param l The callback that will run
4706     *
4707     */
4708    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4709        if (!isLongClickable()) {
4710            setLongClickable(true);
4711        }
4712        getListenerInfo().mOnCreateContextMenuListener = l;
4713    }
4714
4715    /**
4716     * Call this view's OnClickListener, if it is defined.  Performs all normal
4717     * actions associated with clicking: reporting accessibility event, playing
4718     * a sound, etc.
4719     *
4720     * @return True there was an assigned OnClickListener that was called, false
4721     *         otherwise is returned.
4722     */
4723    public boolean performClick() {
4724        final boolean result;
4725        final ListenerInfo li = mListenerInfo;
4726        if (li != null && li.mOnClickListener != null) {
4727            playSoundEffect(SoundEffectConstants.CLICK);
4728            li.mOnClickListener.onClick(this);
4729            result = true;
4730        } else {
4731            result = false;
4732        }
4733
4734        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4735        return result;
4736    }
4737
4738    /**
4739     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4740     * this only calls the listener, and does not do any associated clicking
4741     * actions like reporting an accessibility event.
4742     *
4743     * @return True there was an assigned OnClickListener that was called, false
4744     *         otherwise is returned.
4745     */
4746    public boolean callOnClick() {
4747        ListenerInfo li = mListenerInfo;
4748        if (li != null && li.mOnClickListener != null) {
4749            li.mOnClickListener.onClick(this);
4750            return true;
4751        }
4752        return false;
4753    }
4754
4755    /**
4756     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4757     * OnLongClickListener did not consume the event.
4758     *
4759     * @return True if one of the above receivers consumed the event, false otherwise.
4760     */
4761    public boolean performLongClick() {
4762        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4763
4764        boolean handled = false;
4765        ListenerInfo li = mListenerInfo;
4766        if (li != null && li.mOnLongClickListener != null) {
4767            handled = li.mOnLongClickListener.onLongClick(View.this);
4768        }
4769        if (!handled) {
4770            handled = showContextMenu();
4771        }
4772        if (handled) {
4773            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4774        }
4775        return handled;
4776    }
4777
4778    /**
4779     * Performs button-related actions during a touch down event.
4780     *
4781     * @param event The event.
4782     * @return True if the down was consumed.
4783     *
4784     * @hide
4785     */
4786    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4787        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4788            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4789                return true;
4790            }
4791        }
4792        return false;
4793    }
4794
4795    /**
4796     * Bring up the context menu for this view.
4797     *
4798     * @return Whether a context menu was displayed.
4799     */
4800    public boolean showContextMenu() {
4801        return getParent().showContextMenuForChild(this);
4802    }
4803
4804    /**
4805     * Bring up the context menu for this view, referring to the item under the specified point.
4806     *
4807     * @param x The referenced x coordinate.
4808     * @param y The referenced y coordinate.
4809     * @param metaState The keyboard modifiers that were pressed.
4810     * @return Whether a context menu was displayed.
4811     *
4812     * @hide
4813     */
4814    public boolean showContextMenu(float x, float y, int metaState) {
4815        return showContextMenu();
4816    }
4817
4818    /**
4819     * Start an action mode.
4820     *
4821     * @param callback Callback that will control the lifecycle of the action mode
4822     * @return The new action mode if it is started, null otherwise
4823     *
4824     * @see ActionMode
4825     */
4826    public ActionMode startActionMode(ActionMode.Callback callback) {
4827        ViewParent parent = getParent();
4828        if (parent == null) return null;
4829        return parent.startActionModeForChild(this, callback);
4830    }
4831
4832    /**
4833     * Register a callback to be invoked when a hardware key is pressed in this view.
4834     * Key presses in software input methods will generally not trigger the methods of
4835     * this listener.
4836     * @param l the key listener to attach to this view
4837     */
4838    public void setOnKeyListener(OnKeyListener l) {
4839        getListenerInfo().mOnKeyListener = l;
4840    }
4841
4842    /**
4843     * Register a callback to be invoked when a touch event is sent to this view.
4844     * @param l the touch listener to attach to this view
4845     */
4846    public void setOnTouchListener(OnTouchListener l) {
4847        getListenerInfo().mOnTouchListener = l;
4848    }
4849
4850    /**
4851     * Register a callback to be invoked when a generic motion event is sent to this view.
4852     * @param l the generic motion listener to attach to this view
4853     */
4854    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4855        getListenerInfo().mOnGenericMotionListener = l;
4856    }
4857
4858    /**
4859     * Register a callback to be invoked when a hover event is sent to this view.
4860     * @param l the hover listener to attach to this view
4861     */
4862    public void setOnHoverListener(OnHoverListener l) {
4863        getListenerInfo().mOnHoverListener = l;
4864    }
4865
4866    /**
4867     * Register a drag event listener callback object for this View. The parameter is
4868     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4869     * View, the system calls the
4870     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4871     * @param l An implementation of {@link android.view.View.OnDragListener}.
4872     */
4873    public void setOnDragListener(OnDragListener l) {
4874        getListenerInfo().mOnDragListener = l;
4875    }
4876
4877    /**
4878     * Give this view focus. This will cause
4879     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4880     *
4881     * Note: this does not check whether this {@link View} should get focus, it just
4882     * gives it focus no matter what.  It should only be called internally by framework
4883     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4884     *
4885     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4886     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4887     *        focus moved when requestFocus() is called. It may not always
4888     *        apply, in which case use the default View.FOCUS_DOWN.
4889     * @param previouslyFocusedRect The rectangle of the view that had focus
4890     *        prior in this View's coordinate system.
4891     */
4892    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4893        if (DBG) {
4894            System.out.println(this + " requestFocus()");
4895        }
4896
4897        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4898            mPrivateFlags |= PFLAG_FOCUSED;
4899
4900            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4901
4902            if (mParent != null) {
4903                mParent.requestChildFocus(this, this);
4904            }
4905
4906            if (mAttachInfo != null) {
4907                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4908            }
4909
4910            onFocusChanged(true, direction, previouslyFocusedRect);
4911            refreshDrawableState();
4912        }
4913    }
4914
4915    /**
4916     * Populates <code>outRect</code> with the hotspot bounds. By default,
4917     * the hotspot bounds are identical to the screen bounds.
4918     *
4919     * @param outRect rect to populate with hotspot bounds
4920     * @hide Only for internal use by views and widgets.
4921     */
4922    public void getHotspotBounds(Rect outRect) {
4923        final Drawable background = getBackground();
4924        if (background != null) {
4925            background.getHotspotBounds(outRect);
4926        } else {
4927            getBoundsOnScreen(outRect);
4928        }
4929    }
4930
4931    /**
4932     * Request that a rectangle of this view be visible on the screen,
4933     * scrolling if necessary just enough.
4934     *
4935     * <p>A View should call this if it maintains some notion of which part
4936     * of its content is interesting.  For example, a text editing view
4937     * should call this when its cursor moves.
4938     *
4939     * @param rectangle The rectangle.
4940     * @return Whether any parent scrolled.
4941     */
4942    public boolean requestRectangleOnScreen(Rect rectangle) {
4943        return requestRectangleOnScreen(rectangle, false);
4944    }
4945
4946    /**
4947     * Request that a rectangle of this view be visible on the screen,
4948     * scrolling if necessary just enough.
4949     *
4950     * <p>A View should call this if it maintains some notion of which part
4951     * of its content is interesting.  For example, a text editing view
4952     * should call this when its cursor moves.
4953     *
4954     * <p>When <code>immediate</code> is set to true, scrolling will not be
4955     * animated.
4956     *
4957     * @param rectangle The rectangle.
4958     * @param immediate True to forbid animated scrolling, false otherwise
4959     * @return Whether any parent scrolled.
4960     */
4961    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4962        if (mParent == null) {
4963            return false;
4964        }
4965
4966        View child = this;
4967
4968        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4969        position.set(rectangle);
4970
4971        ViewParent parent = mParent;
4972        boolean scrolled = false;
4973        while (parent != null) {
4974            rectangle.set((int) position.left, (int) position.top,
4975                    (int) position.right, (int) position.bottom);
4976
4977            scrolled |= parent.requestChildRectangleOnScreen(child,
4978                    rectangle, immediate);
4979
4980            if (!child.hasIdentityMatrix()) {
4981                child.getMatrix().mapRect(position);
4982            }
4983
4984            position.offset(child.mLeft, child.mTop);
4985
4986            if (!(parent instanceof View)) {
4987                break;
4988            }
4989
4990            View parentView = (View) parent;
4991
4992            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4993
4994            child = parentView;
4995            parent = child.getParent();
4996        }
4997
4998        return scrolled;
4999    }
5000
5001    /**
5002     * Called when this view wants to give up focus. If focus is cleared
5003     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5004     * <p>
5005     * <strong>Note:</strong> When a View clears focus the framework is trying
5006     * to give focus to the first focusable View from the top. Hence, if this
5007     * View is the first from the top that can take focus, then all callbacks
5008     * related to clearing focus will be invoked after which the framework will
5009     * give focus to this view.
5010     * </p>
5011     */
5012    public void clearFocus() {
5013        if (DBG) {
5014            System.out.println(this + " clearFocus()");
5015        }
5016
5017        clearFocusInternal(null, true, true);
5018    }
5019
5020    /**
5021     * Clears focus from the view, optionally propagating the change up through
5022     * the parent hierarchy and requesting that the root view place new focus.
5023     *
5024     * @param propagate whether to propagate the change up through the parent
5025     *            hierarchy
5026     * @param refocus when propagate is true, specifies whether to request the
5027     *            root view place new focus
5028     */
5029    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5030        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5031            mPrivateFlags &= ~PFLAG_FOCUSED;
5032
5033            if (propagate && mParent != null) {
5034                mParent.clearChildFocus(this);
5035            }
5036
5037            onFocusChanged(false, 0, null);
5038            refreshDrawableState();
5039
5040            if (propagate && (!refocus || !rootViewRequestFocus())) {
5041                notifyGlobalFocusCleared(this);
5042            }
5043        }
5044    }
5045
5046    void notifyGlobalFocusCleared(View oldFocus) {
5047        if (oldFocus != null && mAttachInfo != null) {
5048            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5049        }
5050    }
5051
5052    boolean rootViewRequestFocus() {
5053        final View root = getRootView();
5054        return root != null && root.requestFocus();
5055    }
5056
5057    /**
5058     * Called internally by the view system when a new view is getting focus.
5059     * This is what clears the old focus.
5060     * <p>
5061     * <b>NOTE:</b> The parent view's focused child must be updated manually
5062     * after calling this method. Otherwise, the view hierarchy may be left in
5063     * an inconstent state.
5064     */
5065    void unFocus(View focused) {
5066        if (DBG) {
5067            System.out.println(this + " unFocus()");
5068        }
5069
5070        clearFocusInternal(focused, false, false);
5071    }
5072
5073    /**
5074     * Returns true if this view has focus itself, or is the ancestor of the
5075     * view that has focus.
5076     *
5077     * @return True if this view has or contains focus, false otherwise.
5078     */
5079    @ViewDebug.ExportedProperty(category = "focus")
5080    public boolean hasFocus() {
5081        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5082    }
5083
5084    /**
5085     * Returns true if this view is focusable or if it contains a reachable View
5086     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5087     * is a View whose parents do not block descendants focus.
5088     *
5089     * Only {@link #VISIBLE} views are considered focusable.
5090     *
5091     * @return True if the view is focusable or if the view contains a focusable
5092     *         View, false otherwise.
5093     *
5094     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5095     * @see ViewGroup#getTouchscreenBlocksFocus()
5096     */
5097    public boolean hasFocusable() {
5098        if (!isFocusableInTouchMode()) {
5099            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5100                final ViewGroup g = (ViewGroup) p;
5101                if (g.shouldBlockFocusForTouchscreen()) {
5102                    return false;
5103                }
5104            }
5105        }
5106        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5107    }
5108
5109    /**
5110     * Called by the view system when the focus state of this view changes.
5111     * When the focus change event is caused by directional navigation, direction
5112     * and previouslyFocusedRect provide insight into where the focus is coming from.
5113     * When overriding, be sure to call up through to the super class so that
5114     * the standard focus handling will occur.
5115     *
5116     * @param gainFocus True if the View has focus; false otherwise.
5117     * @param direction The direction focus has moved when requestFocus()
5118     *                  is called to give this view focus. Values are
5119     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5120     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5121     *                  It may not always apply, in which case use the default.
5122     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5123     *        system, of the previously focused view.  If applicable, this will be
5124     *        passed in as finer grained information about where the focus is coming
5125     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5126     */
5127    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5128            @Nullable Rect previouslyFocusedRect) {
5129        if (gainFocus) {
5130            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5131        } else {
5132            notifyViewAccessibilityStateChangedIfNeeded(
5133                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5134        }
5135
5136        InputMethodManager imm = InputMethodManager.peekInstance();
5137        if (!gainFocus) {
5138            if (isPressed()) {
5139                setPressed(false);
5140            }
5141            if (imm != null && mAttachInfo != null
5142                    && mAttachInfo.mHasWindowFocus) {
5143                imm.focusOut(this);
5144            }
5145            onFocusLost();
5146        } else if (imm != null && mAttachInfo != null
5147                && mAttachInfo.mHasWindowFocus) {
5148            imm.focusIn(this);
5149        }
5150
5151        invalidate(true);
5152        ListenerInfo li = mListenerInfo;
5153        if (li != null && li.mOnFocusChangeListener != null) {
5154            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5155        }
5156
5157        if (mAttachInfo != null) {
5158            mAttachInfo.mKeyDispatchState.reset(this);
5159        }
5160    }
5161
5162    /**
5163     * Sends an accessibility event of the given type. If accessibility is
5164     * not enabled this method has no effect. The default implementation calls
5165     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5166     * to populate information about the event source (this View), then calls
5167     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5168     * populate the text content of the event source including its descendants,
5169     * and last calls
5170     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5171     * on its parent to request sending of the event to interested parties.
5172     * <p>
5173     * If an {@link AccessibilityDelegate} has been specified via calling
5174     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5175     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5176     * responsible for handling this call.
5177     * </p>
5178     *
5179     * @param eventType The type of the event to send, as defined by several types from
5180     * {@link android.view.accessibility.AccessibilityEvent}, such as
5181     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5182     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5183     *
5184     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5185     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5186     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5187     * @see AccessibilityDelegate
5188     */
5189    public void sendAccessibilityEvent(int eventType) {
5190        if (mAccessibilityDelegate != null) {
5191            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5192        } else {
5193            sendAccessibilityEventInternal(eventType);
5194        }
5195    }
5196
5197    /**
5198     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5199     * {@link AccessibilityEvent} to make an announcement which is related to some
5200     * sort of a context change for which none of the events representing UI transitions
5201     * is a good fit. For example, announcing a new page in a book. If accessibility
5202     * is not enabled this method does nothing.
5203     *
5204     * @param text The announcement text.
5205     */
5206    public void announceForAccessibility(CharSequence text) {
5207        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5208            AccessibilityEvent event = AccessibilityEvent.obtain(
5209                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5210            onInitializeAccessibilityEvent(event);
5211            event.getText().add(text);
5212            event.setContentDescription(null);
5213            mParent.requestSendAccessibilityEvent(this, event);
5214        }
5215    }
5216
5217    /**
5218     * @see #sendAccessibilityEvent(int)
5219     *
5220     * Note: Called from the default {@link AccessibilityDelegate}.
5221     *
5222     * @hide
5223     */
5224    public void sendAccessibilityEventInternal(int eventType) {
5225        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5226            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5227        }
5228    }
5229
5230    /**
5231     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5232     * takes as an argument an empty {@link AccessibilityEvent} and does not
5233     * perform a check whether accessibility is enabled.
5234     * <p>
5235     * If an {@link AccessibilityDelegate} has been specified via calling
5236     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5237     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5238     * is responsible for handling this call.
5239     * </p>
5240     *
5241     * @param event The event to send.
5242     *
5243     * @see #sendAccessibilityEvent(int)
5244     */
5245    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5246        if (mAccessibilityDelegate != null) {
5247            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5248        } else {
5249            sendAccessibilityEventUncheckedInternal(event);
5250        }
5251    }
5252
5253    /**
5254     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5255     *
5256     * Note: Called from the default {@link AccessibilityDelegate}.
5257     *
5258     * @hide
5259     */
5260    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5261        if (!isShown()) {
5262            return;
5263        }
5264        onInitializeAccessibilityEvent(event);
5265        // Only a subset of accessibility events populates text content.
5266        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5267            dispatchPopulateAccessibilityEvent(event);
5268        }
5269        // In the beginning we called #isShown(), so we know that getParent() is not null.
5270        getParent().requestSendAccessibilityEvent(this, event);
5271    }
5272
5273    /**
5274     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5275     * to its children for adding their text content to the event. Note that the
5276     * event text is populated in a separate dispatch path since we add to the
5277     * event not only the text of the source but also the text of all its descendants.
5278     * A typical implementation will call
5279     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5280     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5281     * on each child. Override this method if custom population of the event text
5282     * content is required.
5283     * <p>
5284     * If an {@link AccessibilityDelegate} has been specified via calling
5285     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5286     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5287     * is responsible for handling this call.
5288     * </p>
5289     * <p>
5290     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5291     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5292     * </p>
5293     *
5294     * @param event The event.
5295     *
5296     * @return True if the event population was completed.
5297     */
5298    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5299        if (mAccessibilityDelegate != null) {
5300            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5301        } else {
5302            return dispatchPopulateAccessibilityEventInternal(event);
5303        }
5304    }
5305
5306    /**
5307     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5308     *
5309     * Note: Called from the default {@link AccessibilityDelegate}.
5310     *
5311     * @hide
5312     */
5313    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5314        onPopulateAccessibilityEvent(event);
5315        return false;
5316    }
5317
5318    /**
5319     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5320     * giving a chance to this View to populate the accessibility event with its
5321     * text content. While this method is free to modify event
5322     * attributes other than text content, doing so should normally be performed in
5323     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5324     * <p>
5325     * Example: Adding formatted date string to an accessibility event in addition
5326     *          to the text added by the super implementation:
5327     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5328     *     super.onPopulateAccessibilityEvent(event);
5329     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5330     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5331     *         mCurrentDate.getTimeInMillis(), flags);
5332     *     event.getText().add(selectedDateUtterance);
5333     * }</pre>
5334     * <p>
5335     * If an {@link AccessibilityDelegate} has been specified via calling
5336     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5337     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5338     * is responsible for handling this call.
5339     * </p>
5340     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5341     * information to the event, in case the default implementation has basic information to add.
5342     * </p>
5343     *
5344     * @param event The accessibility event which to populate.
5345     *
5346     * @see #sendAccessibilityEvent(int)
5347     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5348     */
5349    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5350        if (mAccessibilityDelegate != null) {
5351            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5352        } else {
5353            onPopulateAccessibilityEventInternal(event);
5354        }
5355    }
5356
5357    /**
5358     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5359     *
5360     * Note: Called from the default {@link AccessibilityDelegate}.
5361     *
5362     * @hide
5363     */
5364    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5365    }
5366
5367    /**
5368     * Initializes an {@link AccessibilityEvent} with information about
5369     * this View which is the event source. In other words, the source of
5370     * an accessibility event is the view whose state change triggered firing
5371     * the event.
5372     * <p>
5373     * Example: Setting the password property of an event in addition
5374     *          to properties set by the super implementation:
5375     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5376     *     super.onInitializeAccessibilityEvent(event);
5377     *     event.setPassword(true);
5378     * }</pre>
5379     * <p>
5380     * If an {@link AccessibilityDelegate} has been specified via calling
5381     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5382     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5383     * is responsible for handling this call.
5384     * </p>
5385     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5386     * information to the event, in case the default implementation has basic information to add.
5387     * </p>
5388     * @param event The event to initialize.
5389     *
5390     * @see #sendAccessibilityEvent(int)
5391     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5392     */
5393    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5394        if (mAccessibilityDelegate != null) {
5395            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5396        } else {
5397            onInitializeAccessibilityEventInternal(event);
5398        }
5399    }
5400
5401    /**
5402     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5403     *
5404     * Note: Called from the default {@link AccessibilityDelegate}.
5405     *
5406     * @hide
5407     */
5408    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5409        event.setSource(this);
5410        event.setClassName(View.class.getName());
5411        event.setPackageName(getContext().getPackageName());
5412        event.setEnabled(isEnabled());
5413        event.setContentDescription(mContentDescription);
5414
5415        switch (event.getEventType()) {
5416            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5417                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5418                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5419                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5420                event.setItemCount(focusablesTempList.size());
5421                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5422                if (mAttachInfo != null) {
5423                    focusablesTempList.clear();
5424                }
5425            } break;
5426            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5427                CharSequence text = getIterableTextForAccessibility();
5428                if (text != null && text.length() > 0) {
5429                    event.setFromIndex(getAccessibilitySelectionStart());
5430                    event.setToIndex(getAccessibilitySelectionEnd());
5431                    event.setItemCount(text.length());
5432                }
5433            } break;
5434        }
5435    }
5436
5437    /**
5438     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5439     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5440     * This method is responsible for obtaining an accessibility node info from a
5441     * pool of reusable instances and calling
5442     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5443     * initialize the former.
5444     * <p>
5445     * Note: The client is responsible for recycling the obtained instance by calling
5446     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5447     * </p>
5448     *
5449     * @return A populated {@link AccessibilityNodeInfo}.
5450     *
5451     * @see AccessibilityNodeInfo
5452     */
5453    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5454        if (mAccessibilityDelegate != null) {
5455            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5456        } else {
5457            return createAccessibilityNodeInfoInternal();
5458        }
5459    }
5460
5461    /**
5462     * @see #createAccessibilityNodeInfo()
5463     *
5464     * @hide
5465     */
5466    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5467        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5468        if (provider != null) {
5469            return provider.createAccessibilityNodeInfo(View.NO_ID);
5470        } else {
5471            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5472            onInitializeAccessibilityNodeInfo(info);
5473            return info;
5474        }
5475    }
5476
5477    /**
5478     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5479     * The base implementation sets:
5480     * <ul>
5481     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5482     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5483     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5484     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5485     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5486     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5487     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5488     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5489     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5490     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5491     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5492     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5493     * </ul>
5494     * <p>
5495     * Subclasses should override this method, call the super implementation,
5496     * and set additional attributes.
5497     * </p>
5498     * <p>
5499     * If an {@link AccessibilityDelegate} has been specified via calling
5500     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5501     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5502     * is responsible for handling this call.
5503     * </p>
5504     *
5505     * @param info The instance to initialize.
5506     */
5507    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5508        if (mAccessibilityDelegate != null) {
5509            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5510        } else {
5511            onInitializeAccessibilityNodeInfoInternal(info);
5512        }
5513    }
5514
5515    /**
5516     * Gets the location of this view in screen coordintates.
5517     *
5518     * @param outRect The output location
5519     * @hide
5520     */
5521    public void getBoundsOnScreen(Rect outRect) {
5522        if (mAttachInfo == null) {
5523            return;
5524        }
5525
5526        RectF position = mAttachInfo.mTmpTransformRect;
5527        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5528
5529        if (!hasIdentityMatrix()) {
5530            getMatrix().mapRect(position);
5531        }
5532
5533        position.offset(mLeft, mTop);
5534
5535        ViewParent parent = mParent;
5536        while (parent instanceof View) {
5537            View parentView = (View) parent;
5538
5539            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5540
5541            if (!parentView.hasIdentityMatrix()) {
5542                parentView.getMatrix().mapRect(position);
5543            }
5544
5545            position.offset(parentView.mLeft, parentView.mTop);
5546
5547            parent = parentView.mParent;
5548        }
5549
5550        if (parent instanceof ViewRootImpl) {
5551            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5552            position.offset(0, -viewRootImpl.mCurScrollY);
5553        }
5554
5555        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5556
5557        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5558                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5559    }
5560
5561    /**
5562     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5563     *
5564     * Note: Called from the default {@link AccessibilityDelegate}.
5565     *
5566     * @hide
5567     */
5568    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5569        Rect bounds = mAttachInfo.mTmpInvalRect;
5570
5571        getDrawingRect(bounds);
5572        info.setBoundsInParent(bounds);
5573
5574        getBoundsOnScreen(bounds);
5575        info.setBoundsInScreen(bounds);
5576
5577        ViewParent parent = getParentForAccessibility();
5578        if (parent instanceof View) {
5579            info.setParent((View) parent);
5580        }
5581
5582        if (mID != View.NO_ID) {
5583            View rootView = getRootView();
5584            if (rootView == null) {
5585                rootView = this;
5586            }
5587
5588            View label = rootView.findLabelForView(this, mID);
5589            if (label != null) {
5590                info.setLabeledBy(label);
5591            }
5592
5593            if ((mAttachInfo.mAccessibilityFetchFlags
5594                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5595                    && Resources.resourceHasPackage(mID)) {
5596                try {
5597                    String viewId = getResources().getResourceName(mID);
5598                    info.setViewIdResourceName(viewId);
5599                } catch (Resources.NotFoundException nfe) {
5600                    /* ignore */
5601                }
5602            }
5603        }
5604
5605        if (mLabelForId != View.NO_ID) {
5606            View rootView = getRootView();
5607            if (rootView == null) {
5608                rootView = this;
5609            }
5610            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5611            if (labeled != null) {
5612                info.setLabelFor(labeled);
5613            }
5614        }
5615
5616        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
5617            View rootView = getRootView();
5618            if (rootView == null) {
5619                rootView = this;
5620            }
5621            View next = rootView.findViewInsideOutShouldExist(this,
5622                    mAccessibilityTraversalBeforeId);
5623            if (next != null) {
5624                info.setTraversalBefore(next);
5625            }
5626        }
5627
5628        if (mAccessibilityTraversalAfterId != View.NO_ID) {
5629            View rootView = getRootView();
5630            if (rootView == null) {
5631                rootView = this;
5632            }
5633            View next = rootView.findViewInsideOutShouldExist(this,
5634                    mAccessibilityTraversalAfterId);
5635            if (next != null) {
5636                info.setTraversalAfter(next);
5637            }
5638        }
5639
5640        info.setVisibleToUser(isVisibleToUser());
5641
5642        info.setPackageName(mContext.getPackageName());
5643        info.setClassName(View.class.getName());
5644        info.setContentDescription(getContentDescription());
5645
5646        info.setEnabled(isEnabled());
5647        info.setClickable(isClickable());
5648        info.setFocusable(isFocusable());
5649        info.setFocused(isFocused());
5650        info.setAccessibilityFocused(isAccessibilityFocused());
5651        info.setSelected(isSelected());
5652        info.setLongClickable(isLongClickable());
5653        info.setLiveRegion(getAccessibilityLiveRegion());
5654
5655        // TODO: These make sense only if we are in an AdapterView but all
5656        // views can be selected. Maybe from accessibility perspective
5657        // we should report as selectable view in an AdapterView.
5658        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5659        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5660
5661        if (isFocusable()) {
5662            if (isFocused()) {
5663                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5664            } else {
5665                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5666            }
5667        }
5668
5669        if (!isAccessibilityFocused()) {
5670            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5671        } else {
5672            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5673        }
5674
5675        if (isClickable() && isEnabled()) {
5676            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5677        }
5678
5679        if (isLongClickable() && isEnabled()) {
5680            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5681        }
5682
5683        CharSequence text = getIterableTextForAccessibility();
5684        if (text != null && text.length() > 0) {
5685            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5686
5687            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5688            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5689            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5690            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5691                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5692                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5693        }
5694    }
5695
5696    private View findLabelForView(View view, int labeledId) {
5697        if (mMatchLabelForPredicate == null) {
5698            mMatchLabelForPredicate = new MatchLabelForPredicate();
5699        }
5700        mMatchLabelForPredicate.mLabeledId = labeledId;
5701        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5702    }
5703
5704    /**
5705     * Computes whether this view is visible to the user. Such a view is
5706     * attached, visible, all its predecessors are visible, it is not clipped
5707     * entirely by its predecessors, and has an alpha greater than zero.
5708     *
5709     * @return Whether the view is visible on the screen.
5710     *
5711     * @hide
5712     */
5713    protected boolean isVisibleToUser() {
5714        return isVisibleToUser(null);
5715    }
5716
5717    /**
5718     * Computes whether the given portion of this view is visible to the user.
5719     * Such a view is attached, visible, all its predecessors are visible,
5720     * has an alpha greater than zero, and the specified portion is not
5721     * clipped entirely by its predecessors.
5722     *
5723     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5724     *                    <code>null</code>, and the entire view will be tested in this case.
5725     *                    When <code>true</code> is returned by the function, the actual visible
5726     *                    region will be stored in this parameter; that is, if boundInView is fully
5727     *                    contained within the view, no modification will be made, otherwise regions
5728     *                    outside of the visible area of the view will be clipped.
5729     *
5730     * @return Whether the specified portion of the view is visible on the screen.
5731     *
5732     * @hide
5733     */
5734    protected boolean isVisibleToUser(Rect boundInView) {
5735        if (mAttachInfo != null) {
5736            // Attached to invisible window means this view is not visible.
5737            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5738                return false;
5739            }
5740            // An invisible predecessor or one with alpha zero means
5741            // that this view is not visible to the user.
5742            Object current = this;
5743            while (current instanceof View) {
5744                View view = (View) current;
5745                // We have attach info so this view is attached and there is no
5746                // need to check whether we reach to ViewRootImpl on the way up.
5747                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5748                        view.getVisibility() != VISIBLE) {
5749                    return false;
5750                }
5751                current = view.mParent;
5752            }
5753            // Check if the view is entirely covered by its predecessors.
5754            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5755            Point offset = mAttachInfo.mPoint;
5756            if (!getGlobalVisibleRect(visibleRect, offset)) {
5757                return false;
5758            }
5759            // Check if the visible portion intersects the rectangle of interest.
5760            if (boundInView != null) {
5761                visibleRect.offset(-offset.x, -offset.y);
5762                return boundInView.intersect(visibleRect);
5763            }
5764            return true;
5765        }
5766        return false;
5767    }
5768
5769    /**
5770     * Computes a point on which a sequence of a down/up event can be sent to
5771     * trigger clicking this view. This method is for the exclusive use by the
5772     * accessibility layer to determine where to send a click event in explore
5773     * by touch mode.
5774     *
5775     * @param interactiveRegion The interactive portion of this window.
5776     * @param outPoint The point to populate.
5777     * @return True of such a point exists.
5778     */
5779    boolean computeClickPointInScreenForAccessibility(Region interactiveRegion,
5780            Point outPoint) {
5781        // Since the interactive portion of the view is a region but as a view
5782        // may have a transformation matrix which cannot be applied to a
5783        // region we compute the view bounds rectangle and all interactive
5784        // predecessor's and sibling's (siblings of predecessors included)
5785        // rectangles that intersect the view bounds. At the
5786        // end if the view was partially covered by another interactive
5787        // view we compute the view's interactive region and pick a point
5788        // on its boundary path as regions do not offer APIs to get inner
5789        // points. Note that the the code is optimized to fail early and
5790        // avoid unnecessary allocations plus computations.
5791
5792        // The current approach has edge cases that may produce false
5793        // positives or false negatives. For example, a portion of the
5794        // view may be covered by an interactive descendant of a
5795        // predecessor, which we do not compute. Also a view may be handling
5796        // raw touch events instead registering click listeners, which
5797        // we cannot compute. Despite these limitations this approach will
5798        // work most of the time and it is a huge improvement over just
5799        // blindly sending the down and up events in the center of the
5800        // view.
5801
5802        // Cannot click on an unattached view.
5803        if (mAttachInfo == null) {
5804            return false;
5805        }
5806
5807        // Attached to an invisible window means this view is not visible.
5808        if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5809            return false;
5810        }
5811
5812        RectF bounds = mAttachInfo.mTmpTransformRect;
5813        bounds.set(0, 0, getWidth(), getHeight());
5814        List<RectF> intersections = mAttachInfo.mTmpRectList;
5815        intersections.clear();
5816
5817        if (mParent instanceof ViewGroup) {
5818            ViewGroup parentGroup = (ViewGroup) mParent;
5819            if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates(
5820                    this, bounds, intersections)) {
5821                intersections.clear();
5822                return false;
5823            }
5824        }
5825
5826        // Take into account the window location.
5827        final int dx = mAttachInfo.mWindowLeft;
5828        final int dy = mAttachInfo.mWindowTop;
5829        bounds.offset(dx, dy);
5830        offsetRects(intersections, dx, dy);
5831
5832        if (intersections.isEmpty() && interactiveRegion == null) {
5833            outPoint.set((int) bounds.centerX(), (int) bounds.centerY());
5834        } else {
5835            // This view is partially covered by other views, then compute
5836            // the not covered region and pick a point on its boundary.
5837            Region region = new Region();
5838            region.set((int) bounds.left, (int) bounds.top,
5839                    (int) bounds.right, (int) bounds.bottom);
5840
5841            final int intersectionCount = intersections.size();
5842            for (int i = intersectionCount - 1; i >= 0; i--) {
5843                RectF intersection = intersections.remove(i);
5844                region.op((int) intersection.left, (int) intersection.top,
5845                        (int) intersection.right, (int) intersection.bottom,
5846                        Region.Op.DIFFERENCE);
5847            }
5848
5849            // If the view is completely covered, done.
5850            if (region.isEmpty()) {
5851                return false;
5852            }
5853
5854            // Take into account the interactive portion of the window
5855            // as the rest is covered by other windows. If no such a region
5856            // then the whole window is interactive.
5857            if (interactiveRegion != null) {
5858                region.op(interactiveRegion, Region.Op.INTERSECT);
5859            }
5860
5861            // Take into account the window bounds.
5862            final View root = getRootView();
5863            if (root != null) {
5864                region.op(dx, dy, root.getWidth() + dx, root.getHeight() + dy, Region.Op.INTERSECT);
5865            }
5866
5867            // If the view is completely covered, done.
5868            if (region.isEmpty()) {
5869                return false;
5870            }
5871
5872            // Try a shortcut here.
5873            if (region.isRect()) {
5874                Rect regionBounds = mAttachInfo.mTmpInvalRect;
5875                region.getBounds(regionBounds);
5876                outPoint.set(regionBounds.centerX(), regionBounds.centerY());
5877                return true;
5878            }
5879
5880            // Get the a point on the region boundary path.
5881            Path path = region.getBoundaryPath();
5882            PathMeasure pathMeasure = new PathMeasure(path, false);
5883            final float[] coordinates = mAttachInfo.mTmpTransformLocation;
5884
5885            // Without loss of generality pick a point.
5886            final float point = pathMeasure.getLength() * 0.01f;
5887            if (!pathMeasure.getPosTan(point, coordinates, null)) {
5888                return false;
5889            }
5890
5891            outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1]));
5892        }
5893
5894        return true;
5895    }
5896
5897    /**
5898     * Adds the clickable rectangles withing the bounds of this view. They
5899     * may overlap. This method is intended for use only by the accessibility
5900     * layer.
5901     *
5902     * @param outRects List to which to add clickable areas.
5903     *
5904     * @hide
5905     */
5906    public void addClickableRectsForAccessibility(List<RectF> outRects) {
5907        if (isClickable() || isLongClickable()) {
5908            RectF bounds = new RectF();
5909            bounds.set(0, 0, getWidth(), getHeight());
5910            outRects.add(bounds);
5911        }
5912    }
5913
5914    static void offsetRects(List<RectF> rects, float offsetX, float offsetY) {
5915        final int rectCount = rects.size();
5916        for (int i = 0; i < rectCount; i++) {
5917            RectF intersection = rects.get(i);
5918            intersection.offset(offsetX, offsetY);
5919        }
5920    }
5921
5922    /**
5923     * Returns the delegate for implementing accessibility support via
5924     * composition. For more details see {@link AccessibilityDelegate}.
5925     *
5926     * @return The delegate, or null if none set.
5927     *
5928     * @hide
5929     */
5930    public AccessibilityDelegate getAccessibilityDelegate() {
5931        return mAccessibilityDelegate;
5932    }
5933
5934    /**
5935     * Sets a delegate for implementing accessibility support via composition as
5936     * opposed to inheritance. The delegate's primary use is for implementing
5937     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5938     *
5939     * @param delegate The delegate instance.
5940     *
5941     * @see AccessibilityDelegate
5942     */
5943    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5944        mAccessibilityDelegate = delegate;
5945    }
5946
5947    /**
5948     * Gets the provider for managing a virtual view hierarchy rooted at this View
5949     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5950     * that explore the window content.
5951     * <p>
5952     * If this method returns an instance, this instance is responsible for managing
5953     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5954     * View including the one representing the View itself. Similarly the returned
5955     * instance is responsible for performing accessibility actions on any virtual
5956     * view or the root view itself.
5957     * </p>
5958     * <p>
5959     * If an {@link AccessibilityDelegate} has been specified via calling
5960     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5961     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5962     * is responsible for handling this call.
5963     * </p>
5964     *
5965     * @return The provider.
5966     *
5967     * @see AccessibilityNodeProvider
5968     */
5969    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5970        if (mAccessibilityDelegate != null) {
5971            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5972        } else {
5973            return null;
5974        }
5975    }
5976
5977    /**
5978     * Gets the unique identifier of this view on the screen for accessibility purposes.
5979     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5980     *
5981     * @return The view accessibility id.
5982     *
5983     * @hide
5984     */
5985    public int getAccessibilityViewId() {
5986        if (mAccessibilityViewId == NO_ID) {
5987            mAccessibilityViewId = sNextAccessibilityViewId++;
5988        }
5989        return mAccessibilityViewId;
5990    }
5991
5992    /**
5993     * Gets the unique identifier of the window in which this View reseides.
5994     *
5995     * @return The window accessibility id.
5996     *
5997     * @hide
5998     */
5999    public int getAccessibilityWindowId() {
6000        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6001                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6002    }
6003
6004    /**
6005     * Gets the {@link View} description. It briefly describes the view and is
6006     * primarily used for accessibility support. Set this property to enable
6007     * better accessibility support for your application. This is especially
6008     * true for views that do not have textual representation (For example,
6009     * ImageButton).
6010     *
6011     * @return The content description.
6012     *
6013     * @attr ref android.R.styleable#View_contentDescription
6014     */
6015    @ViewDebug.ExportedProperty(category = "accessibility")
6016    public CharSequence getContentDescription() {
6017        return mContentDescription;
6018    }
6019
6020    /**
6021     * Sets the {@link View} description. It briefly describes the view and is
6022     * primarily used for accessibility support. Set this property to enable
6023     * better accessibility support for your application. This is especially
6024     * true for views that do not have textual representation (For example,
6025     * ImageButton).
6026     *
6027     * @param contentDescription The content description.
6028     *
6029     * @attr ref android.R.styleable#View_contentDescription
6030     */
6031    @RemotableViewMethod
6032    public void setContentDescription(CharSequence contentDescription) {
6033        if (mContentDescription == null) {
6034            if (contentDescription == null) {
6035                return;
6036            }
6037        } else if (mContentDescription.equals(contentDescription)) {
6038            return;
6039        }
6040        mContentDescription = contentDescription;
6041        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6042        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6043            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6044            notifySubtreeAccessibilityStateChangedIfNeeded();
6045        } else {
6046            notifyViewAccessibilityStateChangedIfNeeded(
6047                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6048        }
6049    }
6050
6051    /**
6052     * Sets the id of a view before which this one is visited in accessibility traversal.
6053     * A screen-reader must visit the content of this view before the content of the one
6054     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6055     * will traverse the entire content of B before traversing the entire content of A,
6056     * regardles of what traversal strategy it is using.
6057     * <p>
6058     * Views that do not have specified before/after relationships are traversed in order
6059     * determined by the screen-reader.
6060     * </p>
6061     * <p>
6062     * Setting that this view is before a view that is not important for accessibility
6063     * or if this view is not important for accessibility will have no effect as the
6064     * screen-reader is not aware of unimportant views.
6065     * </p>
6066     *
6067     * @param beforeId The id of a view this one precedes in accessibility traversal.
6068     *
6069     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6070     *
6071     * @see #setImportantForAccessibility(int)
6072     */
6073    @RemotableViewMethod
6074    public void setAccessibilityTraversalBefore(int beforeId) {
6075        if (mAccessibilityTraversalBeforeId == beforeId) {
6076            return;
6077        }
6078        mAccessibilityTraversalBeforeId = beforeId;
6079        notifyViewAccessibilityStateChangedIfNeeded(
6080                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6081    }
6082
6083    /**
6084     * Gets the id of a view before which this one is visited in accessibility traversal.
6085     *
6086     * @return The id of a view this one precedes in accessibility traversal if
6087     *         specified, otherwise {@link #NO_ID}.
6088     *
6089     * @see #setAccessibilityTraversalBefore(int)
6090     */
6091    public int getAccessibilityTraversalBefore() {
6092        return mAccessibilityTraversalBeforeId;
6093    }
6094
6095    /**
6096     * Sets the id of a view after which this one is visited in accessibility traversal.
6097     * A screen-reader must visit the content of the other view before the content of this
6098     * one. For example, if view B is set to be after view A, then a screen-reader
6099     * will traverse the entire content of A before traversing the entire content of B,
6100     * regardles of what traversal strategy it is using.
6101     * <p>
6102     * Views that do not have specified before/after relationships are traversed in order
6103     * determined by the screen-reader.
6104     * </p>
6105     * <p>
6106     * Setting that this view is after a view that is not important for accessibility
6107     * or if this view is not important for accessibility will have no effect as the
6108     * screen-reader is not aware of unimportant views.
6109     * </p>
6110     *
6111     * @param afterId The id of a view this one succedees in accessibility traversal.
6112     *
6113     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6114     *
6115     * @see #setImportantForAccessibility(int)
6116     */
6117    @RemotableViewMethod
6118    public void setAccessibilityTraversalAfter(int afterId) {
6119        if (mAccessibilityTraversalAfterId == afterId) {
6120            return;
6121        }
6122        mAccessibilityTraversalAfterId = afterId;
6123        notifyViewAccessibilityStateChangedIfNeeded(
6124                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6125    }
6126
6127    /**
6128     * Gets the id of a view after which this one is visited in accessibility traversal.
6129     *
6130     * @return The id of a view this one succeedes in accessibility traversal if
6131     *         specified, otherwise {@link #NO_ID}.
6132     *
6133     * @see #setAccessibilityTraversalAfter(int)
6134     */
6135    public int getAccessibilityTraversalAfter() {
6136        return mAccessibilityTraversalAfterId;
6137    }
6138
6139    /**
6140     * Gets the id of a view for which this view serves as a label for
6141     * accessibility purposes.
6142     *
6143     * @return The labeled view id.
6144     */
6145    @ViewDebug.ExportedProperty(category = "accessibility")
6146    public int getLabelFor() {
6147        return mLabelForId;
6148    }
6149
6150    /**
6151     * Sets the id of a view for which this view serves as a label for
6152     * accessibility purposes.
6153     *
6154     * @param id The labeled view id.
6155     */
6156    @RemotableViewMethod
6157    public void setLabelFor(int id) {
6158        if (mLabelForId == id) {
6159            return;
6160        }
6161        mLabelForId = id;
6162        if (mLabelForId != View.NO_ID
6163                && mID == View.NO_ID) {
6164            mID = generateViewId();
6165        }
6166        notifyViewAccessibilityStateChangedIfNeeded(
6167                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6168    }
6169
6170    /**
6171     * Invoked whenever this view loses focus, either by losing window focus or by losing
6172     * focus within its window. This method can be used to clear any state tied to the
6173     * focus. For instance, if a button is held pressed with the trackball and the window
6174     * loses focus, this method can be used to cancel the press.
6175     *
6176     * Subclasses of View overriding this method should always call super.onFocusLost().
6177     *
6178     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6179     * @see #onWindowFocusChanged(boolean)
6180     *
6181     * @hide pending API council approval
6182     */
6183    protected void onFocusLost() {
6184        resetPressedState();
6185    }
6186
6187    private void resetPressedState() {
6188        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6189            return;
6190        }
6191
6192        if (isPressed()) {
6193            setPressed(false);
6194
6195            if (!mHasPerformedLongPress) {
6196                removeLongPressCallback();
6197            }
6198        }
6199    }
6200
6201    /**
6202     * Returns true if this view has focus
6203     *
6204     * @return True if this view has focus, false otherwise.
6205     */
6206    @ViewDebug.ExportedProperty(category = "focus")
6207    public boolean isFocused() {
6208        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6209    }
6210
6211    /**
6212     * Find the view in the hierarchy rooted at this view that currently has
6213     * focus.
6214     *
6215     * @return The view that currently has focus, or null if no focused view can
6216     *         be found.
6217     */
6218    public View findFocus() {
6219        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6220    }
6221
6222    /**
6223     * Indicates whether this view is one of the set of scrollable containers in
6224     * its window.
6225     *
6226     * @return whether this view is one of the set of scrollable containers in
6227     * its window
6228     *
6229     * @attr ref android.R.styleable#View_isScrollContainer
6230     */
6231    public boolean isScrollContainer() {
6232        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6233    }
6234
6235    /**
6236     * Change whether this view is one of the set of scrollable containers in
6237     * its window.  This will be used to determine whether the window can
6238     * resize or must pan when a soft input area is open -- scrollable
6239     * containers allow the window to use resize mode since the container
6240     * will appropriately shrink.
6241     *
6242     * @attr ref android.R.styleable#View_isScrollContainer
6243     */
6244    public void setScrollContainer(boolean isScrollContainer) {
6245        if (isScrollContainer) {
6246            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6247                mAttachInfo.mScrollContainers.add(this);
6248                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6249            }
6250            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6251        } else {
6252            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6253                mAttachInfo.mScrollContainers.remove(this);
6254            }
6255            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6256        }
6257    }
6258
6259    /**
6260     * Returns the quality of the drawing cache.
6261     *
6262     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6263     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6264     *
6265     * @see #setDrawingCacheQuality(int)
6266     * @see #setDrawingCacheEnabled(boolean)
6267     * @see #isDrawingCacheEnabled()
6268     *
6269     * @attr ref android.R.styleable#View_drawingCacheQuality
6270     */
6271    @DrawingCacheQuality
6272    public int getDrawingCacheQuality() {
6273        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6274    }
6275
6276    /**
6277     * Set the drawing cache quality of this view. This value is used only when the
6278     * drawing cache is enabled
6279     *
6280     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6281     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6282     *
6283     * @see #getDrawingCacheQuality()
6284     * @see #setDrawingCacheEnabled(boolean)
6285     * @see #isDrawingCacheEnabled()
6286     *
6287     * @attr ref android.R.styleable#View_drawingCacheQuality
6288     */
6289    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6290        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6291    }
6292
6293    /**
6294     * Returns whether the screen should remain on, corresponding to the current
6295     * value of {@link #KEEP_SCREEN_ON}.
6296     *
6297     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6298     *
6299     * @see #setKeepScreenOn(boolean)
6300     *
6301     * @attr ref android.R.styleable#View_keepScreenOn
6302     */
6303    public boolean getKeepScreenOn() {
6304        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6305    }
6306
6307    /**
6308     * Controls whether the screen should remain on, modifying the
6309     * value of {@link #KEEP_SCREEN_ON}.
6310     *
6311     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6312     *
6313     * @see #getKeepScreenOn()
6314     *
6315     * @attr ref android.R.styleable#View_keepScreenOn
6316     */
6317    public void setKeepScreenOn(boolean keepScreenOn) {
6318        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6319    }
6320
6321    /**
6322     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6323     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6324     *
6325     * @attr ref android.R.styleable#View_nextFocusLeft
6326     */
6327    public int getNextFocusLeftId() {
6328        return mNextFocusLeftId;
6329    }
6330
6331    /**
6332     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6333     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6334     * decide automatically.
6335     *
6336     * @attr ref android.R.styleable#View_nextFocusLeft
6337     */
6338    public void setNextFocusLeftId(int nextFocusLeftId) {
6339        mNextFocusLeftId = nextFocusLeftId;
6340    }
6341
6342    /**
6343     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6344     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6345     *
6346     * @attr ref android.R.styleable#View_nextFocusRight
6347     */
6348    public int getNextFocusRightId() {
6349        return mNextFocusRightId;
6350    }
6351
6352    /**
6353     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6354     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6355     * decide automatically.
6356     *
6357     * @attr ref android.R.styleable#View_nextFocusRight
6358     */
6359    public void setNextFocusRightId(int nextFocusRightId) {
6360        mNextFocusRightId = nextFocusRightId;
6361    }
6362
6363    /**
6364     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6365     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6366     *
6367     * @attr ref android.R.styleable#View_nextFocusUp
6368     */
6369    public int getNextFocusUpId() {
6370        return mNextFocusUpId;
6371    }
6372
6373    /**
6374     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6375     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6376     * decide automatically.
6377     *
6378     * @attr ref android.R.styleable#View_nextFocusUp
6379     */
6380    public void setNextFocusUpId(int nextFocusUpId) {
6381        mNextFocusUpId = nextFocusUpId;
6382    }
6383
6384    /**
6385     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6386     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6387     *
6388     * @attr ref android.R.styleable#View_nextFocusDown
6389     */
6390    public int getNextFocusDownId() {
6391        return mNextFocusDownId;
6392    }
6393
6394    /**
6395     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6396     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6397     * decide automatically.
6398     *
6399     * @attr ref android.R.styleable#View_nextFocusDown
6400     */
6401    public void setNextFocusDownId(int nextFocusDownId) {
6402        mNextFocusDownId = nextFocusDownId;
6403    }
6404
6405    /**
6406     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6407     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6408     *
6409     * @attr ref android.R.styleable#View_nextFocusForward
6410     */
6411    public int getNextFocusForwardId() {
6412        return mNextFocusForwardId;
6413    }
6414
6415    /**
6416     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6417     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6418     * decide automatically.
6419     *
6420     * @attr ref android.R.styleable#View_nextFocusForward
6421     */
6422    public void setNextFocusForwardId(int nextFocusForwardId) {
6423        mNextFocusForwardId = nextFocusForwardId;
6424    }
6425
6426    /**
6427     * Returns the visibility of this view and all of its ancestors
6428     *
6429     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6430     */
6431    public boolean isShown() {
6432        View current = this;
6433        //noinspection ConstantConditions
6434        do {
6435            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6436                return false;
6437            }
6438            ViewParent parent = current.mParent;
6439            if (parent == null) {
6440                return false; // We are not attached to the view root
6441            }
6442            if (!(parent instanceof View)) {
6443                return true;
6444            }
6445            current = (View) parent;
6446        } while (current != null);
6447
6448        return false;
6449    }
6450
6451    /**
6452     * Called by the view hierarchy when the content insets for a window have
6453     * changed, to allow it to adjust its content to fit within those windows.
6454     * The content insets tell you the space that the status bar, input method,
6455     * and other system windows infringe on the application's window.
6456     *
6457     * <p>You do not normally need to deal with this function, since the default
6458     * window decoration given to applications takes care of applying it to the
6459     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6460     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6461     * and your content can be placed under those system elements.  You can then
6462     * use this method within your view hierarchy if you have parts of your UI
6463     * which you would like to ensure are not being covered.
6464     *
6465     * <p>The default implementation of this method simply applies the content
6466     * insets to the view's padding, consuming that content (modifying the
6467     * insets to be 0), and returning true.  This behavior is off by default, but can
6468     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6469     *
6470     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6471     * insets object is propagated down the hierarchy, so any changes made to it will
6472     * be seen by all following views (including potentially ones above in
6473     * the hierarchy since this is a depth-first traversal).  The first view
6474     * that returns true will abort the entire traversal.
6475     *
6476     * <p>The default implementation works well for a situation where it is
6477     * used with a container that covers the entire window, allowing it to
6478     * apply the appropriate insets to its content on all edges.  If you need
6479     * a more complicated layout (such as two different views fitting system
6480     * windows, one on the top of the window, and one on the bottom),
6481     * you can override the method and handle the insets however you would like.
6482     * Note that the insets provided by the framework are always relative to the
6483     * far edges of the window, not accounting for the location of the called view
6484     * within that window.  (In fact when this method is called you do not yet know
6485     * where the layout will place the view, as it is done before layout happens.)
6486     *
6487     * <p>Note: unlike many View methods, there is no dispatch phase to this
6488     * call.  If you are overriding it in a ViewGroup and want to allow the
6489     * call to continue to your children, you must be sure to call the super
6490     * implementation.
6491     *
6492     * <p>Here is a sample layout that makes use of fitting system windows
6493     * to have controls for a video view placed inside of the window decorations
6494     * that it hides and shows.  This can be used with code like the second
6495     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6496     *
6497     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6498     *
6499     * @param insets Current content insets of the window.  Prior to
6500     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6501     * the insets or else you and Android will be unhappy.
6502     *
6503     * @return {@code true} if this view applied the insets and it should not
6504     * continue propagating further down the hierarchy, {@code false} otherwise.
6505     * @see #getFitsSystemWindows()
6506     * @see #setFitsSystemWindows(boolean)
6507     * @see #setSystemUiVisibility(int)
6508     *
6509     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6510     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6511     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6512     * to implement handling their own insets.
6513     */
6514    protected boolean fitSystemWindows(Rect insets) {
6515        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6516            if (insets == null) {
6517                // Null insets by definition have already been consumed.
6518                // This call cannot apply insets since there are none to apply,
6519                // so return false.
6520                return false;
6521            }
6522            // If we're not in the process of dispatching the newer apply insets call,
6523            // that means we're not in the compatibility path. Dispatch into the newer
6524            // apply insets path and take things from there.
6525            try {
6526                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6527                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6528            } finally {
6529                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6530            }
6531        } else {
6532            // We're being called from the newer apply insets path.
6533            // Perform the standard fallback behavior.
6534            return fitSystemWindowsInt(insets);
6535        }
6536    }
6537
6538    private boolean fitSystemWindowsInt(Rect insets) {
6539        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6540            mUserPaddingStart = UNDEFINED_PADDING;
6541            mUserPaddingEnd = UNDEFINED_PADDING;
6542            Rect localInsets = sThreadLocal.get();
6543            if (localInsets == null) {
6544                localInsets = new Rect();
6545                sThreadLocal.set(localInsets);
6546            }
6547            boolean res = computeFitSystemWindows(insets, localInsets);
6548            mUserPaddingLeftInitial = localInsets.left;
6549            mUserPaddingRightInitial = localInsets.right;
6550            internalSetPadding(localInsets.left, localInsets.top,
6551                    localInsets.right, localInsets.bottom);
6552            return res;
6553        }
6554        return false;
6555    }
6556
6557    /**
6558     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6559     *
6560     * <p>This method should be overridden by views that wish to apply a policy different from or
6561     * in addition to the default behavior. Clients that wish to force a view subtree
6562     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6563     *
6564     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6565     * it will be called during dispatch instead of this method. The listener may optionally
6566     * call this method from its own implementation if it wishes to apply the view's default
6567     * insets policy in addition to its own.</p>
6568     *
6569     * <p>Implementations of this method should either return the insets parameter unchanged
6570     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6571     * that this view applied itself. This allows new inset types added in future platform
6572     * versions to pass through existing implementations unchanged without being erroneously
6573     * consumed.</p>
6574     *
6575     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6576     * property is set then the view will consume the system window insets and apply them
6577     * as padding for the view.</p>
6578     *
6579     * @param insets Insets to apply
6580     * @return The supplied insets with any applied insets consumed
6581     */
6582    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6583        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6584            // We weren't called from within a direct call to fitSystemWindows,
6585            // call into it as a fallback in case we're in a class that overrides it
6586            // and has logic to perform.
6587            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6588                return insets.consumeSystemWindowInsets();
6589            }
6590        } else {
6591            // We were called from within a direct call to fitSystemWindows.
6592            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6593                return insets.consumeSystemWindowInsets();
6594            }
6595        }
6596        return insets;
6597    }
6598
6599    /**
6600     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6601     * window insets to this view. The listener's
6602     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6603     * method will be called instead of the view's
6604     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6605     *
6606     * @param listener Listener to set
6607     *
6608     * @see #onApplyWindowInsets(WindowInsets)
6609     */
6610    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6611        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6612    }
6613
6614    /**
6615     * Request to apply the given window insets to this view or another view in its subtree.
6616     *
6617     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6618     * obscured by window decorations or overlays. This can include the status and navigation bars,
6619     * action bars, input methods and more. New inset categories may be added in the future.
6620     * The method returns the insets provided minus any that were applied by this view or its
6621     * children.</p>
6622     *
6623     * <p>Clients wishing to provide custom behavior should override the
6624     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6625     * {@link OnApplyWindowInsetsListener} via the
6626     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6627     * method.</p>
6628     *
6629     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6630     * </p>
6631     *
6632     * @param insets Insets to apply
6633     * @return The provided insets minus the insets that were consumed
6634     */
6635    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6636        try {
6637            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6638            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6639                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6640            } else {
6641                return onApplyWindowInsets(insets);
6642            }
6643        } finally {
6644            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6645        }
6646    }
6647
6648    /**
6649     * @hide Compute the insets that should be consumed by this view and the ones
6650     * that should propagate to those under it.
6651     */
6652    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6653        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6654                || mAttachInfo == null
6655                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6656                        && !mAttachInfo.mOverscanRequested)) {
6657            outLocalInsets.set(inoutInsets);
6658            inoutInsets.set(0, 0, 0, 0);
6659            return true;
6660        } else {
6661            // The application wants to take care of fitting system window for
6662            // the content...  however we still need to take care of any overscan here.
6663            final Rect overscan = mAttachInfo.mOverscanInsets;
6664            outLocalInsets.set(overscan);
6665            inoutInsets.left -= overscan.left;
6666            inoutInsets.top -= overscan.top;
6667            inoutInsets.right -= overscan.right;
6668            inoutInsets.bottom -= overscan.bottom;
6669            return false;
6670        }
6671    }
6672
6673    /**
6674     * Compute insets that should be consumed by this view and the ones that should propagate
6675     * to those under it.
6676     *
6677     * @param in Insets currently being processed by this View, likely received as a parameter
6678     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6679     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6680     *                       by this view
6681     * @return Insets that should be passed along to views under this one
6682     */
6683    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6684        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6685                || mAttachInfo == null
6686                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6687            outLocalInsets.set(in.getSystemWindowInsets());
6688            return in.consumeSystemWindowInsets();
6689        } else {
6690            outLocalInsets.set(0, 0, 0, 0);
6691            return in;
6692        }
6693    }
6694
6695    /**
6696     * Sets whether or not this view should account for system screen decorations
6697     * such as the status bar and inset its content; that is, controlling whether
6698     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6699     * executed.  See that method for more details.
6700     *
6701     * <p>Note that if you are providing your own implementation of
6702     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6703     * flag to true -- your implementation will be overriding the default
6704     * implementation that checks this flag.
6705     *
6706     * @param fitSystemWindows If true, then the default implementation of
6707     * {@link #fitSystemWindows(Rect)} will be executed.
6708     *
6709     * @attr ref android.R.styleable#View_fitsSystemWindows
6710     * @see #getFitsSystemWindows()
6711     * @see #fitSystemWindows(Rect)
6712     * @see #setSystemUiVisibility(int)
6713     */
6714    public void setFitsSystemWindows(boolean fitSystemWindows) {
6715        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6716    }
6717
6718    /**
6719     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6720     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6721     * will be executed.
6722     *
6723     * @return {@code true} if the default implementation of
6724     * {@link #fitSystemWindows(Rect)} will be executed.
6725     *
6726     * @attr ref android.R.styleable#View_fitsSystemWindows
6727     * @see #setFitsSystemWindows(boolean)
6728     * @see #fitSystemWindows(Rect)
6729     * @see #setSystemUiVisibility(int)
6730     */
6731    @ViewDebug.ExportedProperty
6732    public boolean getFitsSystemWindows() {
6733        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6734    }
6735
6736    /** @hide */
6737    public boolean fitsSystemWindows() {
6738        return getFitsSystemWindows();
6739    }
6740
6741    /**
6742     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6743     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6744     */
6745    public void requestFitSystemWindows() {
6746        if (mParent != null) {
6747            mParent.requestFitSystemWindows();
6748        }
6749    }
6750
6751    /**
6752     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6753     */
6754    public void requestApplyInsets() {
6755        requestFitSystemWindows();
6756    }
6757
6758    /**
6759     * For use by PhoneWindow to make its own system window fitting optional.
6760     * @hide
6761     */
6762    public void makeOptionalFitsSystemWindows() {
6763        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6764    }
6765
6766    /**
6767     * Returns the visibility status for this view.
6768     *
6769     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6770     * @attr ref android.R.styleable#View_visibility
6771     */
6772    @ViewDebug.ExportedProperty(mapping = {
6773        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6774        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6775        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6776    })
6777    @Visibility
6778    public int getVisibility() {
6779        return mViewFlags & VISIBILITY_MASK;
6780    }
6781
6782    /**
6783     * Set the enabled state of this view.
6784     *
6785     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6786     * @attr ref android.R.styleable#View_visibility
6787     */
6788    @RemotableViewMethod
6789    public void setVisibility(@Visibility int visibility) {
6790        setFlags(visibility, VISIBILITY_MASK);
6791        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6792    }
6793
6794    /**
6795     * Returns the enabled status for this view. The interpretation of the
6796     * enabled state varies by subclass.
6797     *
6798     * @return True if this view is enabled, false otherwise.
6799     */
6800    @ViewDebug.ExportedProperty
6801    public boolean isEnabled() {
6802        return (mViewFlags & ENABLED_MASK) == ENABLED;
6803    }
6804
6805    /**
6806     * Set the enabled state of this view. The interpretation of the enabled
6807     * state varies by subclass.
6808     *
6809     * @param enabled True if this view is enabled, false otherwise.
6810     */
6811    @RemotableViewMethod
6812    public void setEnabled(boolean enabled) {
6813        if (enabled == isEnabled()) return;
6814
6815        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6816
6817        /*
6818         * The View most likely has to change its appearance, so refresh
6819         * the drawable state.
6820         */
6821        refreshDrawableState();
6822
6823        // Invalidate too, since the default behavior for views is to be
6824        // be drawn at 50% alpha rather than to change the drawable.
6825        invalidate(true);
6826
6827        if (!enabled) {
6828            cancelPendingInputEvents();
6829        }
6830    }
6831
6832    /**
6833     * Set whether this view can receive the focus.
6834     *
6835     * Setting this to false will also ensure that this view is not focusable
6836     * in touch mode.
6837     *
6838     * @param focusable If true, this view can receive the focus.
6839     *
6840     * @see #setFocusableInTouchMode(boolean)
6841     * @attr ref android.R.styleable#View_focusable
6842     */
6843    public void setFocusable(boolean focusable) {
6844        if (!focusable) {
6845            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6846        }
6847        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6848    }
6849
6850    /**
6851     * Set whether this view can receive focus while in touch mode.
6852     *
6853     * Setting this to true will also ensure that this view is focusable.
6854     *
6855     * @param focusableInTouchMode If true, this view can receive the focus while
6856     *   in touch mode.
6857     *
6858     * @see #setFocusable(boolean)
6859     * @attr ref android.R.styleable#View_focusableInTouchMode
6860     */
6861    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6862        // Focusable in touch mode should always be set before the focusable flag
6863        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6864        // which, in touch mode, will not successfully request focus on this view
6865        // because the focusable in touch mode flag is not set
6866        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6867        if (focusableInTouchMode) {
6868            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6869        }
6870    }
6871
6872    /**
6873     * Set whether this view should have sound effects enabled for events such as
6874     * clicking and touching.
6875     *
6876     * <p>You may wish to disable sound effects for a view if you already play sounds,
6877     * for instance, a dial key that plays dtmf tones.
6878     *
6879     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6880     * @see #isSoundEffectsEnabled()
6881     * @see #playSoundEffect(int)
6882     * @attr ref android.R.styleable#View_soundEffectsEnabled
6883     */
6884    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6885        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6886    }
6887
6888    /**
6889     * @return whether this view should have sound effects enabled for events such as
6890     *     clicking and touching.
6891     *
6892     * @see #setSoundEffectsEnabled(boolean)
6893     * @see #playSoundEffect(int)
6894     * @attr ref android.R.styleable#View_soundEffectsEnabled
6895     */
6896    @ViewDebug.ExportedProperty
6897    public boolean isSoundEffectsEnabled() {
6898        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6899    }
6900
6901    /**
6902     * Set whether this view should have haptic feedback for events such as
6903     * long presses.
6904     *
6905     * <p>You may wish to disable haptic feedback if your view already controls
6906     * its own haptic feedback.
6907     *
6908     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6909     * @see #isHapticFeedbackEnabled()
6910     * @see #performHapticFeedback(int)
6911     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6912     */
6913    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6914        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6915    }
6916
6917    /**
6918     * @return whether this view should have haptic feedback enabled for events
6919     * long presses.
6920     *
6921     * @see #setHapticFeedbackEnabled(boolean)
6922     * @see #performHapticFeedback(int)
6923     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6924     */
6925    @ViewDebug.ExportedProperty
6926    public boolean isHapticFeedbackEnabled() {
6927        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6928    }
6929
6930    /**
6931     * Returns the layout direction for this view.
6932     *
6933     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6934     *   {@link #LAYOUT_DIRECTION_RTL},
6935     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6936     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6937     *
6938     * @attr ref android.R.styleable#View_layoutDirection
6939     *
6940     * @hide
6941     */
6942    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6943        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6944        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6945        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6946        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6947    })
6948    @LayoutDir
6949    public int getRawLayoutDirection() {
6950        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6951    }
6952
6953    /**
6954     * Set the layout direction for this view. This will propagate a reset of layout direction
6955     * resolution to the view's children and resolve layout direction for this view.
6956     *
6957     * @param layoutDirection the layout direction to set. Should be one of:
6958     *
6959     * {@link #LAYOUT_DIRECTION_LTR},
6960     * {@link #LAYOUT_DIRECTION_RTL},
6961     * {@link #LAYOUT_DIRECTION_INHERIT},
6962     * {@link #LAYOUT_DIRECTION_LOCALE}.
6963     *
6964     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6965     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6966     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6967     *
6968     * @attr ref android.R.styleable#View_layoutDirection
6969     */
6970    @RemotableViewMethod
6971    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6972        if (getRawLayoutDirection() != layoutDirection) {
6973            // Reset the current layout direction and the resolved one
6974            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6975            resetRtlProperties();
6976            // Set the new layout direction (filtered)
6977            mPrivateFlags2 |=
6978                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6979            // We need to resolve all RTL properties as they all depend on layout direction
6980            resolveRtlPropertiesIfNeeded();
6981            requestLayout();
6982            invalidate(true);
6983        }
6984    }
6985
6986    /**
6987     * Returns the resolved layout direction for this view.
6988     *
6989     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6990     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6991     *
6992     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6993     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6994     *
6995     * @attr ref android.R.styleable#View_layoutDirection
6996     */
6997    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6998        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6999        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7000    })
7001    @ResolvedLayoutDir
7002    public int getLayoutDirection() {
7003        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7004        if (targetSdkVersion < JELLY_BEAN_MR1) {
7005            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7006            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7007        }
7008        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7009                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7010    }
7011
7012    /**
7013     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7014     * layout attribute and/or the inherited value from the parent
7015     *
7016     * @return true if the layout is right-to-left.
7017     *
7018     * @hide
7019     */
7020    @ViewDebug.ExportedProperty(category = "layout")
7021    public boolean isLayoutRtl() {
7022        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7023    }
7024
7025    /**
7026     * Indicates whether the view is currently tracking transient state that the
7027     * app should not need to concern itself with saving and restoring, but that
7028     * the framework should take special note to preserve when possible.
7029     *
7030     * <p>A view with transient state cannot be trivially rebound from an external
7031     * data source, such as an adapter binding item views in a list. This may be
7032     * because the view is performing an animation, tracking user selection
7033     * of content, or similar.</p>
7034     *
7035     * @return true if the view has transient state
7036     */
7037    @ViewDebug.ExportedProperty(category = "layout")
7038    public boolean hasTransientState() {
7039        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7040    }
7041
7042    /**
7043     * Set whether this view is currently tracking transient state that the
7044     * framework should attempt to preserve when possible. This flag is reference counted,
7045     * so every call to setHasTransientState(true) should be paired with a later call
7046     * to setHasTransientState(false).
7047     *
7048     * <p>A view with transient state cannot be trivially rebound from an external
7049     * data source, such as an adapter binding item views in a list. This may be
7050     * because the view is performing an animation, tracking user selection
7051     * of content, or similar.</p>
7052     *
7053     * @param hasTransientState true if this view has transient state
7054     */
7055    public void setHasTransientState(boolean hasTransientState) {
7056        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7057                mTransientStateCount - 1;
7058        if (mTransientStateCount < 0) {
7059            mTransientStateCount = 0;
7060            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7061                    "unmatched pair of setHasTransientState calls");
7062        } else if ((hasTransientState && mTransientStateCount == 1) ||
7063                (!hasTransientState && mTransientStateCount == 0)) {
7064            // update flag if we've just incremented up from 0 or decremented down to 0
7065            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7066                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7067            if (mParent != null) {
7068                try {
7069                    mParent.childHasTransientStateChanged(this, hasTransientState);
7070                } catch (AbstractMethodError e) {
7071                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7072                            " does not fully implement ViewParent", e);
7073                }
7074            }
7075        }
7076    }
7077
7078    /**
7079     * Returns true if this view is currently attached to a window.
7080     */
7081    public boolean isAttachedToWindow() {
7082        return mAttachInfo != null;
7083    }
7084
7085    /**
7086     * Returns true if this view has been through at least one layout since it
7087     * was last attached to or detached from a window.
7088     */
7089    public boolean isLaidOut() {
7090        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7091    }
7092
7093    /**
7094     * If this view doesn't do any drawing on its own, set this flag to
7095     * allow further optimizations. By default, this flag is not set on
7096     * View, but could be set on some View subclasses such as ViewGroup.
7097     *
7098     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7099     * you should clear this flag.
7100     *
7101     * @param willNotDraw whether or not this View draw on its own
7102     */
7103    public void setWillNotDraw(boolean willNotDraw) {
7104        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7105    }
7106
7107    /**
7108     * Returns whether or not this View draws on its own.
7109     *
7110     * @return true if this view has nothing to draw, false otherwise
7111     */
7112    @ViewDebug.ExportedProperty(category = "drawing")
7113    public boolean willNotDraw() {
7114        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7115    }
7116
7117    /**
7118     * When a View's drawing cache is enabled, drawing is redirected to an
7119     * offscreen bitmap. Some views, like an ImageView, must be able to
7120     * bypass this mechanism if they already draw a single bitmap, to avoid
7121     * unnecessary usage of the memory.
7122     *
7123     * @param willNotCacheDrawing true if this view does not cache its
7124     *        drawing, false otherwise
7125     */
7126    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7127        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7128    }
7129
7130    /**
7131     * Returns whether or not this View can cache its drawing or not.
7132     *
7133     * @return true if this view does not cache its drawing, false otherwise
7134     */
7135    @ViewDebug.ExportedProperty(category = "drawing")
7136    public boolean willNotCacheDrawing() {
7137        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7138    }
7139
7140    /**
7141     * Indicates whether this view reacts to click events or not.
7142     *
7143     * @return true if the view is clickable, false otherwise
7144     *
7145     * @see #setClickable(boolean)
7146     * @attr ref android.R.styleable#View_clickable
7147     */
7148    @ViewDebug.ExportedProperty
7149    public boolean isClickable() {
7150        return (mViewFlags & CLICKABLE) == CLICKABLE;
7151    }
7152
7153    /**
7154     * Enables or disables click events for this view. When a view
7155     * is clickable it will change its state to "pressed" on every click.
7156     * Subclasses should set the view clickable to visually react to
7157     * user's clicks.
7158     *
7159     * @param clickable true to make the view clickable, false otherwise
7160     *
7161     * @see #isClickable()
7162     * @attr ref android.R.styleable#View_clickable
7163     */
7164    public void setClickable(boolean clickable) {
7165        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7166    }
7167
7168    /**
7169     * Indicates whether this view reacts to long click events or not.
7170     *
7171     * @return true if the view is long clickable, false otherwise
7172     *
7173     * @see #setLongClickable(boolean)
7174     * @attr ref android.R.styleable#View_longClickable
7175     */
7176    public boolean isLongClickable() {
7177        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7178    }
7179
7180    /**
7181     * Enables or disables long click events for this view. When a view is long
7182     * clickable it reacts to the user holding down the button for a longer
7183     * duration than a tap. This event can either launch the listener or a
7184     * context menu.
7185     *
7186     * @param longClickable true to make the view long clickable, false otherwise
7187     * @see #isLongClickable()
7188     * @attr ref android.R.styleable#View_longClickable
7189     */
7190    public void setLongClickable(boolean longClickable) {
7191        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7192    }
7193
7194    /**
7195     * Sets the pressed state for this view and provides a touch coordinate for
7196     * animation hinting.
7197     *
7198     * @param pressed Pass true to set the View's internal state to "pressed",
7199     *            or false to reverts the View's internal state from a
7200     *            previously set "pressed" state.
7201     * @param x The x coordinate of the touch that caused the press
7202     * @param y The y coordinate of the touch that caused the press
7203     */
7204    private void setPressed(boolean pressed, float x, float y) {
7205        if (pressed) {
7206            drawableHotspotChanged(x, y);
7207        }
7208
7209        setPressed(pressed);
7210    }
7211
7212    /**
7213     * Sets the pressed state for this view.
7214     *
7215     * @see #isClickable()
7216     * @see #setClickable(boolean)
7217     *
7218     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7219     *        the View's internal state from a previously set "pressed" state.
7220     */
7221    public void setPressed(boolean pressed) {
7222        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7223
7224        if (pressed) {
7225            mPrivateFlags |= PFLAG_PRESSED;
7226        } else {
7227            mPrivateFlags &= ~PFLAG_PRESSED;
7228        }
7229
7230        if (needsRefresh) {
7231            refreshDrawableState();
7232        }
7233        dispatchSetPressed(pressed);
7234    }
7235
7236    /**
7237     * Dispatch setPressed to all of this View's children.
7238     *
7239     * @see #setPressed(boolean)
7240     *
7241     * @param pressed The new pressed state
7242     */
7243    protected void dispatchSetPressed(boolean pressed) {
7244    }
7245
7246    /**
7247     * Indicates whether the view is currently in pressed state. Unless
7248     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7249     * the pressed state.
7250     *
7251     * @see #setPressed(boolean)
7252     * @see #isClickable()
7253     * @see #setClickable(boolean)
7254     *
7255     * @return true if the view is currently pressed, false otherwise
7256     */
7257    @ViewDebug.ExportedProperty
7258    public boolean isPressed() {
7259        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7260    }
7261
7262    /**
7263     * Indicates whether this view will save its state (that is,
7264     * whether its {@link #onSaveInstanceState} method will be called).
7265     *
7266     * @return Returns true if the view state saving is enabled, else false.
7267     *
7268     * @see #setSaveEnabled(boolean)
7269     * @attr ref android.R.styleable#View_saveEnabled
7270     */
7271    public boolean isSaveEnabled() {
7272        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7273    }
7274
7275    /**
7276     * Controls whether the saving of this view's state is
7277     * enabled (that is, whether its {@link #onSaveInstanceState} method
7278     * will be called).  Note that even if freezing is enabled, the
7279     * view still must have an id assigned to it (via {@link #setId(int)})
7280     * for its state to be saved.  This flag can only disable the
7281     * saving of this view; any child views may still have their state saved.
7282     *
7283     * @param enabled Set to false to <em>disable</em> state saving, or true
7284     * (the default) to allow it.
7285     *
7286     * @see #isSaveEnabled()
7287     * @see #setId(int)
7288     * @see #onSaveInstanceState()
7289     * @attr ref android.R.styleable#View_saveEnabled
7290     */
7291    public void setSaveEnabled(boolean enabled) {
7292        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7293    }
7294
7295    /**
7296     * Gets whether the framework should discard touches when the view's
7297     * window is obscured by another visible window.
7298     * Refer to the {@link View} security documentation for more details.
7299     *
7300     * @return True if touch filtering is enabled.
7301     *
7302     * @see #setFilterTouchesWhenObscured(boolean)
7303     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7304     */
7305    @ViewDebug.ExportedProperty
7306    public boolean getFilterTouchesWhenObscured() {
7307        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7308    }
7309
7310    /**
7311     * Sets whether the framework should discard touches when the view's
7312     * window is obscured by another visible window.
7313     * Refer to the {@link View} security documentation for more details.
7314     *
7315     * @param enabled True if touch filtering should be enabled.
7316     *
7317     * @see #getFilterTouchesWhenObscured
7318     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7319     */
7320    public void setFilterTouchesWhenObscured(boolean enabled) {
7321        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7322                FILTER_TOUCHES_WHEN_OBSCURED);
7323    }
7324
7325    /**
7326     * Indicates whether the entire hierarchy under this view will save its
7327     * state when a state saving traversal occurs from its parent.  The default
7328     * is true; if false, these views will not be saved unless
7329     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7330     *
7331     * @return Returns true if the view state saving from parent is enabled, else false.
7332     *
7333     * @see #setSaveFromParentEnabled(boolean)
7334     */
7335    public boolean isSaveFromParentEnabled() {
7336        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7337    }
7338
7339    /**
7340     * Controls whether the entire hierarchy under this view will save its
7341     * state when a state saving traversal occurs from its parent.  The default
7342     * is true; if false, these views will not be saved unless
7343     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7344     *
7345     * @param enabled Set to false to <em>disable</em> state saving, or true
7346     * (the default) to allow it.
7347     *
7348     * @see #isSaveFromParentEnabled()
7349     * @see #setId(int)
7350     * @see #onSaveInstanceState()
7351     */
7352    public void setSaveFromParentEnabled(boolean enabled) {
7353        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7354    }
7355
7356
7357    /**
7358     * Returns whether this View is able to take focus.
7359     *
7360     * @return True if this view can take focus, or false otherwise.
7361     * @attr ref android.R.styleable#View_focusable
7362     */
7363    @ViewDebug.ExportedProperty(category = "focus")
7364    public final boolean isFocusable() {
7365        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7366    }
7367
7368    /**
7369     * When a view is focusable, it may not want to take focus when in touch mode.
7370     * For example, a button would like focus when the user is navigating via a D-pad
7371     * so that the user can click on it, but once the user starts touching the screen,
7372     * the button shouldn't take focus
7373     * @return Whether the view is focusable in touch mode.
7374     * @attr ref android.R.styleable#View_focusableInTouchMode
7375     */
7376    @ViewDebug.ExportedProperty
7377    public final boolean isFocusableInTouchMode() {
7378        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7379    }
7380
7381    /**
7382     * Find the nearest view in the specified direction that can take focus.
7383     * This does not actually give focus to that view.
7384     *
7385     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7386     *
7387     * @return The nearest focusable in the specified direction, or null if none
7388     *         can be found.
7389     */
7390    public View focusSearch(@FocusRealDirection int direction) {
7391        if (mParent != null) {
7392            return mParent.focusSearch(this, direction);
7393        } else {
7394            return null;
7395        }
7396    }
7397
7398    /**
7399     * This method is the last chance for the focused view and its ancestors to
7400     * respond to an arrow key. This is called when the focused view did not
7401     * consume the key internally, nor could the view system find a new view in
7402     * the requested direction to give focus to.
7403     *
7404     * @param focused The currently focused view.
7405     * @param direction The direction focus wants to move. One of FOCUS_UP,
7406     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7407     * @return True if the this view consumed this unhandled move.
7408     */
7409    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7410        return false;
7411    }
7412
7413    /**
7414     * If a user manually specified the next view id for a particular direction,
7415     * use the root to look up the view.
7416     * @param root The root view of the hierarchy containing this view.
7417     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7418     * or FOCUS_BACKWARD.
7419     * @return The user specified next view, or null if there is none.
7420     */
7421    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7422        switch (direction) {
7423            case FOCUS_LEFT:
7424                if (mNextFocusLeftId == View.NO_ID) return null;
7425                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7426            case FOCUS_RIGHT:
7427                if (mNextFocusRightId == View.NO_ID) return null;
7428                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7429            case FOCUS_UP:
7430                if (mNextFocusUpId == View.NO_ID) return null;
7431                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7432            case FOCUS_DOWN:
7433                if (mNextFocusDownId == View.NO_ID) return null;
7434                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7435            case FOCUS_FORWARD:
7436                if (mNextFocusForwardId == View.NO_ID) return null;
7437                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7438            case FOCUS_BACKWARD: {
7439                if (mID == View.NO_ID) return null;
7440                final int id = mID;
7441                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7442                    @Override
7443                    public boolean apply(View t) {
7444                        return t.mNextFocusForwardId == id;
7445                    }
7446                });
7447            }
7448        }
7449        return null;
7450    }
7451
7452    private View findViewInsideOutShouldExist(View root, int id) {
7453        if (mMatchIdPredicate == null) {
7454            mMatchIdPredicate = new MatchIdPredicate();
7455        }
7456        mMatchIdPredicate.mId = id;
7457        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7458        if (result == null) {
7459            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7460        }
7461        return result;
7462    }
7463
7464    /**
7465     * Find and return all focusable views that are descendants of this view,
7466     * possibly including this view if it is focusable itself.
7467     *
7468     * @param direction The direction of the focus
7469     * @return A list of focusable views
7470     */
7471    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7472        ArrayList<View> result = new ArrayList<View>(24);
7473        addFocusables(result, direction);
7474        return result;
7475    }
7476
7477    /**
7478     * Add any focusable views that are descendants of this view (possibly
7479     * including this view if it is focusable itself) to views.  If we are in touch mode,
7480     * only add views that are also focusable in touch mode.
7481     *
7482     * @param views Focusable views found so far
7483     * @param direction The direction of the focus
7484     */
7485    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7486        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7487    }
7488
7489    /**
7490     * Adds any focusable views that are descendants of this view (possibly
7491     * including this view if it is focusable itself) to views. This method
7492     * adds all focusable views regardless if we are in touch mode or
7493     * only views focusable in touch mode if we are in touch mode or
7494     * only views that can take accessibility focus if accessibility is enabled
7495     * depending on the focusable mode parameter.
7496     *
7497     * @param views Focusable views found so far or null if all we are interested is
7498     *        the number of focusables.
7499     * @param direction The direction of the focus.
7500     * @param focusableMode The type of focusables to be added.
7501     *
7502     * @see #FOCUSABLES_ALL
7503     * @see #FOCUSABLES_TOUCH_MODE
7504     */
7505    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7506            @FocusableMode int focusableMode) {
7507        if (views == null) {
7508            return;
7509        }
7510        if (!isFocusable()) {
7511            return;
7512        }
7513        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7514                && isInTouchMode() && !isFocusableInTouchMode()) {
7515            return;
7516        }
7517        views.add(this);
7518    }
7519
7520    /**
7521     * Finds the Views that contain given text. The containment is case insensitive.
7522     * The search is performed by either the text that the View renders or the content
7523     * description that describes the view for accessibility purposes and the view does
7524     * not render or both. Clients can specify how the search is to be performed via
7525     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7526     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7527     *
7528     * @param outViews The output list of matching Views.
7529     * @param searched The text to match against.
7530     *
7531     * @see #FIND_VIEWS_WITH_TEXT
7532     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7533     * @see #setContentDescription(CharSequence)
7534     */
7535    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7536            @FindViewFlags int flags) {
7537        if (getAccessibilityNodeProvider() != null) {
7538            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7539                outViews.add(this);
7540            }
7541        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7542                && (searched != null && searched.length() > 0)
7543                && (mContentDescription != null && mContentDescription.length() > 0)) {
7544            String searchedLowerCase = searched.toString().toLowerCase();
7545            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7546            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7547                outViews.add(this);
7548            }
7549        }
7550    }
7551
7552    /**
7553     * Find and return all touchable views that are descendants of this view,
7554     * possibly including this view if it is touchable itself.
7555     *
7556     * @return A list of touchable views
7557     */
7558    public ArrayList<View> getTouchables() {
7559        ArrayList<View> result = new ArrayList<View>();
7560        addTouchables(result);
7561        return result;
7562    }
7563
7564    /**
7565     * Add any touchable views that are descendants of this view (possibly
7566     * including this view if it is touchable itself) to views.
7567     *
7568     * @param views Touchable views found so far
7569     */
7570    public void addTouchables(ArrayList<View> views) {
7571        final int viewFlags = mViewFlags;
7572
7573        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7574                && (viewFlags & ENABLED_MASK) == ENABLED) {
7575            views.add(this);
7576        }
7577    }
7578
7579    /**
7580     * Returns whether this View is accessibility focused.
7581     *
7582     * @return True if this View is accessibility focused.
7583     */
7584    public boolean isAccessibilityFocused() {
7585        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7586    }
7587
7588    /**
7589     * Call this to try to give accessibility focus to this view.
7590     *
7591     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7592     * returns false or the view is no visible or the view already has accessibility
7593     * focus.
7594     *
7595     * See also {@link #focusSearch(int)}, which is what you call to say that you
7596     * have focus, and you want your parent to look for the next one.
7597     *
7598     * @return Whether this view actually took accessibility focus.
7599     *
7600     * @hide
7601     */
7602    public boolean requestAccessibilityFocus() {
7603        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7604        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7605            return false;
7606        }
7607        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7608            return false;
7609        }
7610        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7611            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7612            ViewRootImpl viewRootImpl = getViewRootImpl();
7613            if (viewRootImpl != null) {
7614                viewRootImpl.setAccessibilityFocus(this, null);
7615            }
7616            invalidate();
7617            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7618            return true;
7619        }
7620        return false;
7621    }
7622
7623    /**
7624     * Call this to try to clear accessibility focus of this view.
7625     *
7626     * See also {@link #focusSearch(int)}, which is what you call to say that you
7627     * have focus, and you want your parent to look for the next one.
7628     *
7629     * @hide
7630     */
7631    public void clearAccessibilityFocus() {
7632        clearAccessibilityFocusNoCallbacks();
7633        // Clear the global reference of accessibility focus if this
7634        // view or any of its descendants had accessibility focus.
7635        ViewRootImpl viewRootImpl = getViewRootImpl();
7636        if (viewRootImpl != null) {
7637            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7638            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7639                viewRootImpl.setAccessibilityFocus(null, null);
7640            }
7641        }
7642    }
7643
7644    private void sendAccessibilityHoverEvent(int eventType) {
7645        // Since we are not delivering to a client accessibility events from not
7646        // important views (unless the clinet request that) we need to fire the
7647        // event from the deepest view exposed to the client. As a consequence if
7648        // the user crosses a not exposed view the client will see enter and exit
7649        // of the exposed predecessor followed by and enter and exit of that same
7650        // predecessor when entering and exiting the not exposed descendant. This
7651        // is fine since the client has a clear idea which view is hovered at the
7652        // price of a couple more events being sent. This is a simple and
7653        // working solution.
7654        View source = this;
7655        while (true) {
7656            if (source.includeForAccessibility()) {
7657                source.sendAccessibilityEvent(eventType);
7658                return;
7659            }
7660            ViewParent parent = source.getParent();
7661            if (parent instanceof View) {
7662                source = (View) parent;
7663            } else {
7664                return;
7665            }
7666        }
7667    }
7668
7669    /**
7670     * Clears accessibility focus without calling any callback methods
7671     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7672     * is used for clearing accessibility focus when giving this focus to
7673     * another view.
7674     */
7675    void clearAccessibilityFocusNoCallbacks() {
7676        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7677            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7678            invalidate();
7679            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7680        }
7681    }
7682
7683    /**
7684     * Call this to try to give focus to a specific view or to one of its
7685     * descendants.
7686     *
7687     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7688     * false), or if it is focusable and it is not focusable in touch mode
7689     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7690     *
7691     * See also {@link #focusSearch(int)}, which is what you call to say that you
7692     * have focus, and you want your parent to look for the next one.
7693     *
7694     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7695     * {@link #FOCUS_DOWN} and <code>null</code>.
7696     *
7697     * @return Whether this view or one of its descendants actually took focus.
7698     */
7699    public final boolean requestFocus() {
7700        return requestFocus(View.FOCUS_DOWN);
7701    }
7702
7703    /**
7704     * Call this to try to give focus to a specific view or to one of its
7705     * descendants and give it a hint about what direction focus is heading.
7706     *
7707     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7708     * false), or if it is focusable and it is not focusable in touch mode
7709     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7710     *
7711     * See also {@link #focusSearch(int)}, which is what you call to say that you
7712     * have focus, and you want your parent to look for the next one.
7713     *
7714     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7715     * <code>null</code> set for the previously focused rectangle.
7716     *
7717     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7718     * @return Whether this view or one of its descendants actually took focus.
7719     */
7720    public final boolean requestFocus(int direction) {
7721        return requestFocus(direction, null);
7722    }
7723
7724    /**
7725     * Call this to try to give focus to a specific view or to one of its descendants
7726     * and give it hints about the direction and a specific rectangle that the focus
7727     * is coming from.  The rectangle can help give larger views a finer grained hint
7728     * about where focus is coming from, and therefore, where to show selection, or
7729     * forward focus change internally.
7730     *
7731     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7732     * false), or if it is focusable and it is not focusable in touch mode
7733     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7734     *
7735     * A View will not take focus if it is not visible.
7736     *
7737     * A View will not take focus if one of its parents has
7738     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7739     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7740     *
7741     * See also {@link #focusSearch(int)}, which is what you call to say that you
7742     * have focus, and you want your parent to look for the next one.
7743     *
7744     * You may wish to override this method if your custom {@link View} has an internal
7745     * {@link View} that it wishes to forward the request to.
7746     *
7747     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7748     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7749     *        to give a finer grained hint about where focus is coming from.  May be null
7750     *        if there is no hint.
7751     * @return Whether this view or one of its descendants actually took focus.
7752     */
7753    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7754        return requestFocusNoSearch(direction, previouslyFocusedRect);
7755    }
7756
7757    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7758        // need to be focusable
7759        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7760                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7761            return false;
7762        }
7763
7764        // need to be focusable in touch mode if in touch mode
7765        if (isInTouchMode() &&
7766            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7767               return false;
7768        }
7769
7770        // need to not have any parents blocking us
7771        if (hasAncestorThatBlocksDescendantFocus()) {
7772            return false;
7773        }
7774
7775        handleFocusGainInternal(direction, previouslyFocusedRect);
7776        return true;
7777    }
7778
7779    /**
7780     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7781     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
7782     * touch mode to request focus when they are touched.
7783     *
7784     * @return Whether this view or one of its descendants actually took focus.
7785     *
7786     * @see #isInTouchMode()
7787     *
7788     */
7789    public final boolean requestFocusFromTouch() {
7790        // Leave touch mode if we need to
7791        if (isInTouchMode()) {
7792            ViewRootImpl viewRoot = getViewRootImpl();
7793            if (viewRoot != null) {
7794                viewRoot.ensureTouchMode(false);
7795            }
7796        }
7797        return requestFocus(View.FOCUS_DOWN);
7798    }
7799
7800    /**
7801     * @return Whether any ancestor of this view blocks descendant focus.
7802     */
7803    private boolean hasAncestorThatBlocksDescendantFocus() {
7804        final boolean focusableInTouchMode = isFocusableInTouchMode();
7805        ViewParent ancestor = mParent;
7806        while (ancestor instanceof ViewGroup) {
7807            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7808            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7809                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7810                return true;
7811            } else {
7812                ancestor = vgAncestor.getParent();
7813            }
7814        }
7815        return false;
7816    }
7817
7818    /**
7819     * Gets the mode for determining whether this View is important for accessibility
7820     * which is if it fires accessibility events and if it is reported to
7821     * accessibility services that query the screen.
7822     *
7823     * @return The mode for determining whether a View is important for accessibility.
7824     *
7825     * @attr ref android.R.styleable#View_importantForAccessibility
7826     *
7827     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7828     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7829     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7830     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7831     */
7832    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7833            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7834            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7835            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7836            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7837                    to = "noHideDescendants")
7838        })
7839    public int getImportantForAccessibility() {
7840        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7841                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7842    }
7843
7844    /**
7845     * Sets the live region mode for this view. This indicates to accessibility
7846     * services whether they should automatically notify the user about changes
7847     * to the view's content description or text, or to the content descriptions
7848     * or text of the view's children (where applicable).
7849     * <p>
7850     * For example, in a login screen with a TextView that displays an "incorrect
7851     * password" notification, that view should be marked as a live region with
7852     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7853     * <p>
7854     * To disable change notifications for this view, use
7855     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7856     * mode for most views.
7857     * <p>
7858     * To indicate that the user should be notified of changes, use
7859     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7860     * <p>
7861     * If the view's changes should interrupt ongoing speech and notify the user
7862     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7863     *
7864     * @param mode The live region mode for this view, one of:
7865     *        <ul>
7866     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7867     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7868     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7869     *        </ul>
7870     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7871     */
7872    public void setAccessibilityLiveRegion(int mode) {
7873        if (mode != getAccessibilityLiveRegion()) {
7874            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7875            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7876                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7877            notifyViewAccessibilityStateChangedIfNeeded(
7878                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7879        }
7880    }
7881
7882    /**
7883     * Gets the live region mode for this View.
7884     *
7885     * @return The live region mode for the view.
7886     *
7887     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7888     *
7889     * @see #setAccessibilityLiveRegion(int)
7890     */
7891    public int getAccessibilityLiveRegion() {
7892        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7893                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7894    }
7895
7896    /**
7897     * Sets how to determine whether this view is important for accessibility
7898     * which is if it fires accessibility events and if it is reported to
7899     * accessibility services that query the screen.
7900     *
7901     * @param mode How to determine whether this view is important for accessibility.
7902     *
7903     * @attr ref android.R.styleable#View_importantForAccessibility
7904     *
7905     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7906     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7907     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7908     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7909     */
7910    public void setImportantForAccessibility(int mode) {
7911        final int oldMode = getImportantForAccessibility();
7912        if (mode != oldMode) {
7913            // If we're moving between AUTO and another state, we might not need
7914            // to send a subtree changed notification. We'll store the computed
7915            // importance, since we'll need to check it later to make sure.
7916            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7917                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7918            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7919            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7920            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7921                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7922            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7923                notifySubtreeAccessibilityStateChangedIfNeeded();
7924            } else {
7925                notifyViewAccessibilityStateChangedIfNeeded(
7926                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7927            }
7928        }
7929    }
7930
7931    /**
7932     * Computes whether this view should be exposed for accessibility. In
7933     * general, views that are interactive or provide information are exposed
7934     * while views that serve only as containers are hidden.
7935     * <p>
7936     * If an ancestor of this view has importance
7937     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7938     * returns <code>false</code>.
7939     * <p>
7940     * Otherwise, the value is computed according to the view's
7941     * {@link #getImportantForAccessibility()} value:
7942     * <ol>
7943     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7944     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7945     * </code>
7946     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7947     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7948     * view satisfies any of the following:
7949     * <ul>
7950     * <li>Is actionable, e.g. {@link #isClickable()},
7951     * {@link #isLongClickable()}, or {@link #isFocusable()}
7952     * <li>Has an {@link AccessibilityDelegate}
7953     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7954     * {@link OnKeyListener}, etc.
7955     * <li>Is an accessibility live region, e.g.
7956     * {@link #getAccessibilityLiveRegion()} is not
7957     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7958     * </ul>
7959     * </ol>
7960     *
7961     * @return Whether the view is exposed for accessibility.
7962     * @see #setImportantForAccessibility(int)
7963     * @see #getImportantForAccessibility()
7964     */
7965    public boolean isImportantForAccessibility() {
7966        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7967                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7968        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7969                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7970            return false;
7971        }
7972
7973        // Check parent mode to ensure we're not hidden.
7974        ViewParent parent = mParent;
7975        while (parent instanceof View) {
7976            if (((View) parent).getImportantForAccessibility()
7977                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7978                return false;
7979            }
7980            parent = parent.getParent();
7981        }
7982
7983        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7984                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7985                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7986    }
7987
7988    /**
7989     * Gets the parent for accessibility purposes. Note that the parent for
7990     * accessibility is not necessary the immediate parent. It is the first
7991     * predecessor that is important for accessibility.
7992     *
7993     * @return The parent for accessibility purposes.
7994     */
7995    public ViewParent getParentForAccessibility() {
7996        if (mParent instanceof View) {
7997            View parentView = (View) mParent;
7998            if (parentView.includeForAccessibility()) {
7999                return mParent;
8000            } else {
8001                return mParent.getParentForAccessibility();
8002            }
8003        }
8004        return null;
8005    }
8006
8007    /**
8008     * Adds the children of a given View for accessibility. Since some Views are
8009     * not important for accessibility the children for accessibility are not
8010     * necessarily direct children of the view, rather they are the first level of
8011     * descendants important for accessibility.
8012     *
8013     * @param children The list of children for accessibility.
8014     */
8015    public void addChildrenForAccessibility(ArrayList<View> children) {
8016
8017    }
8018
8019    /**
8020     * Whether to regard this view for accessibility. A view is regarded for
8021     * accessibility if it is important for accessibility or the querying
8022     * accessibility service has explicitly requested that view not
8023     * important for accessibility are regarded.
8024     *
8025     * @return Whether to regard the view for accessibility.
8026     *
8027     * @hide
8028     */
8029    public boolean includeForAccessibility() {
8030        if (mAttachInfo != null) {
8031            return (mAttachInfo.mAccessibilityFetchFlags
8032                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8033                    || isImportantForAccessibility();
8034        }
8035        return false;
8036    }
8037
8038    /**
8039     * Returns whether the View is considered actionable from
8040     * accessibility perspective. Such view are important for
8041     * accessibility.
8042     *
8043     * @return True if the view is actionable for accessibility.
8044     *
8045     * @hide
8046     */
8047    public boolean isActionableForAccessibility() {
8048        return (isClickable() || isLongClickable() || isFocusable());
8049    }
8050
8051    /**
8052     * Returns whether the View has registered callbacks which makes it
8053     * important for accessibility.
8054     *
8055     * @return True if the view is actionable for accessibility.
8056     */
8057    private boolean hasListenersForAccessibility() {
8058        ListenerInfo info = getListenerInfo();
8059        return mTouchDelegate != null || info.mOnKeyListener != null
8060                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8061                || info.mOnHoverListener != null || info.mOnDragListener != null;
8062    }
8063
8064    /**
8065     * Notifies that the accessibility state of this view changed. The change
8066     * is local to this view and does not represent structural changes such
8067     * as children and parent. For example, the view became focusable. The
8068     * notification is at at most once every
8069     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8070     * to avoid unnecessary load to the system. Also once a view has a pending
8071     * notification this method is a NOP until the notification has been sent.
8072     *
8073     * @hide
8074     */
8075    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8076        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8077            return;
8078        }
8079        if (mSendViewStateChangedAccessibilityEvent == null) {
8080            mSendViewStateChangedAccessibilityEvent =
8081                    new SendViewStateChangedAccessibilityEvent();
8082        }
8083        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8084    }
8085
8086    /**
8087     * Notifies that the accessibility state of this view changed. The change
8088     * is *not* local to this view and does represent structural changes such
8089     * as children and parent. For example, the view size changed. The
8090     * notification is at at most once every
8091     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8092     * to avoid unnecessary load to the system. Also once a view has a pending
8093     * notification this method is a NOP until the notification has been sent.
8094     *
8095     * @hide
8096     */
8097    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8098        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8099            return;
8100        }
8101        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8102            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8103            if (mParent != null) {
8104                try {
8105                    mParent.notifySubtreeAccessibilityStateChanged(
8106                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8107                } catch (AbstractMethodError e) {
8108                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8109                            " does not fully implement ViewParent", e);
8110                }
8111            }
8112        }
8113    }
8114
8115    /**
8116     * Reset the flag indicating the accessibility state of the subtree rooted
8117     * at this view changed.
8118     */
8119    void resetSubtreeAccessibilityStateChanged() {
8120        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8121    }
8122
8123    /**
8124     * Report an accessibility action to this view's parents for delegated processing.
8125     *
8126     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8127     * call this method to delegate an accessibility action to a supporting parent. If the parent
8128     * returns true from its
8129     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8130     * method this method will return true to signify that the action was consumed.</p>
8131     *
8132     * <p>This method is useful for implementing nested scrolling child views. If
8133     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8134     * a custom view implementation may invoke this method to allow a parent to consume the
8135     * scroll first. If this method returns true the custom view should skip its own scrolling
8136     * behavior.</p>
8137     *
8138     * @param action Accessibility action to delegate
8139     * @param arguments Optional action arguments
8140     * @return true if the action was consumed by a parent
8141     */
8142    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8143        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8144            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8145                return true;
8146            }
8147        }
8148        return false;
8149    }
8150
8151    /**
8152     * Performs the specified accessibility action on the view. For
8153     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8154     * <p>
8155     * If an {@link AccessibilityDelegate} has been specified via calling
8156     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8157     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8158     * is responsible for handling this call.
8159     * </p>
8160     *
8161     * <p>The default implementation will delegate
8162     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8163     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8164     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8165     *
8166     * @param action The action to perform.
8167     * @param arguments Optional action arguments.
8168     * @return Whether the action was performed.
8169     */
8170    public boolean performAccessibilityAction(int action, Bundle arguments) {
8171      if (mAccessibilityDelegate != null) {
8172          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8173      } else {
8174          return performAccessibilityActionInternal(action, arguments);
8175      }
8176    }
8177
8178   /**
8179    * @see #performAccessibilityAction(int, Bundle)
8180    *
8181    * Note: Called from the default {@link AccessibilityDelegate}.
8182    *
8183    * @hide
8184    */
8185    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8186        if (isNestedScrollingEnabled()
8187                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8188                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
8189            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8190                return true;
8191            }
8192        }
8193
8194        switch (action) {
8195            case AccessibilityNodeInfo.ACTION_CLICK: {
8196                if (isClickable()) {
8197                    performClick();
8198                    return true;
8199                }
8200            } break;
8201            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8202                if (isLongClickable()) {
8203                    performLongClick();
8204                    return true;
8205                }
8206            } break;
8207            case AccessibilityNodeInfo.ACTION_FOCUS: {
8208                if (!hasFocus()) {
8209                    // Get out of touch mode since accessibility
8210                    // wants to move focus around.
8211                    getViewRootImpl().ensureTouchMode(false);
8212                    return requestFocus();
8213                }
8214            } break;
8215            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8216                if (hasFocus()) {
8217                    clearFocus();
8218                    return !isFocused();
8219                }
8220            } break;
8221            case AccessibilityNodeInfo.ACTION_SELECT: {
8222                if (!isSelected()) {
8223                    setSelected(true);
8224                    return isSelected();
8225                }
8226            } break;
8227            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8228                if (isSelected()) {
8229                    setSelected(false);
8230                    return !isSelected();
8231                }
8232            } break;
8233            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8234                if (!isAccessibilityFocused()) {
8235                    return requestAccessibilityFocus();
8236                }
8237            } break;
8238            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8239                if (isAccessibilityFocused()) {
8240                    clearAccessibilityFocus();
8241                    return true;
8242                }
8243            } break;
8244            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8245                if (arguments != null) {
8246                    final int granularity = arguments.getInt(
8247                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8248                    final boolean extendSelection = arguments.getBoolean(
8249                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8250                    return traverseAtGranularity(granularity, true, extendSelection);
8251                }
8252            } break;
8253            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8254                if (arguments != null) {
8255                    final int granularity = arguments.getInt(
8256                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8257                    final boolean extendSelection = arguments.getBoolean(
8258                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8259                    return traverseAtGranularity(granularity, false, extendSelection);
8260                }
8261            } break;
8262            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8263                CharSequence text = getIterableTextForAccessibility();
8264                if (text == null) {
8265                    return false;
8266                }
8267                final int start = (arguments != null) ? arguments.getInt(
8268                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8269                final int end = (arguments != null) ? arguments.getInt(
8270                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8271                // Only cursor position can be specified (selection length == 0)
8272                if ((getAccessibilitySelectionStart() != start
8273                        || getAccessibilitySelectionEnd() != end)
8274                        && (start == end)) {
8275                    setAccessibilitySelection(start, end);
8276                    notifyViewAccessibilityStateChangedIfNeeded(
8277                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8278                    return true;
8279                }
8280            } break;
8281        }
8282        return false;
8283    }
8284
8285    private boolean traverseAtGranularity(int granularity, boolean forward,
8286            boolean extendSelection) {
8287        CharSequence text = getIterableTextForAccessibility();
8288        if (text == null || text.length() == 0) {
8289            return false;
8290        }
8291        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8292        if (iterator == null) {
8293            return false;
8294        }
8295        int current = getAccessibilitySelectionEnd();
8296        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8297            current = forward ? 0 : text.length();
8298        }
8299        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8300        if (range == null) {
8301            return false;
8302        }
8303        final int segmentStart = range[0];
8304        final int segmentEnd = range[1];
8305        int selectionStart;
8306        int selectionEnd;
8307        if (extendSelection && isAccessibilitySelectionExtendable()) {
8308            selectionStart = getAccessibilitySelectionStart();
8309            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8310                selectionStart = forward ? segmentStart : segmentEnd;
8311            }
8312            selectionEnd = forward ? segmentEnd : segmentStart;
8313        } else {
8314            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8315        }
8316        setAccessibilitySelection(selectionStart, selectionEnd);
8317        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8318                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8319        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8320        return true;
8321    }
8322
8323    /**
8324     * Gets the text reported for accessibility purposes.
8325     *
8326     * @return The accessibility text.
8327     *
8328     * @hide
8329     */
8330    public CharSequence getIterableTextForAccessibility() {
8331        return getContentDescription();
8332    }
8333
8334    /**
8335     * Gets whether accessibility selection can be extended.
8336     *
8337     * @return If selection is extensible.
8338     *
8339     * @hide
8340     */
8341    public boolean isAccessibilitySelectionExtendable() {
8342        return false;
8343    }
8344
8345    /**
8346     * @hide
8347     */
8348    public int getAccessibilitySelectionStart() {
8349        return mAccessibilityCursorPosition;
8350    }
8351
8352    /**
8353     * @hide
8354     */
8355    public int getAccessibilitySelectionEnd() {
8356        return getAccessibilitySelectionStart();
8357    }
8358
8359    /**
8360     * @hide
8361     */
8362    public void setAccessibilitySelection(int start, int end) {
8363        if (start ==  end && end == mAccessibilityCursorPosition) {
8364            return;
8365        }
8366        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8367            mAccessibilityCursorPosition = start;
8368        } else {
8369            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8370        }
8371        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8372    }
8373
8374    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8375            int fromIndex, int toIndex) {
8376        if (mParent == null) {
8377            return;
8378        }
8379        AccessibilityEvent event = AccessibilityEvent.obtain(
8380                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8381        onInitializeAccessibilityEvent(event);
8382        onPopulateAccessibilityEvent(event);
8383        event.setFromIndex(fromIndex);
8384        event.setToIndex(toIndex);
8385        event.setAction(action);
8386        event.setMovementGranularity(granularity);
8387        mParent.requestSendAccessibilityEvent(this, event);
8388    }
8389
8390    /**
8391     * @hide
8392     */
8393    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8394        switch (granularity) {
8395            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8396                CharSequence text = getIterableTextForAccessibility();
8397                if (text != null && text.length() > 0) {
8398                    CharacterTextSegmentIterator iterator =
8399                        CharacterTextSegmentIterator.getInstance(
8400                                mContext.getResources().getConfiguration().locale);
8401                    iterator.initialize(text.toString());
8402                    return iterator;
8403                }
8404            } break;
8405            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8406                CharSequence text = getIterableTextForAccessibility();
8407                if (text != null && text.length() > 0) {
8408                    WordTextSegmentIterator iterator =
8409                        WordTextSegmentIterator.getInstance(
8410                                mContext.getResources().getConfiguration().locale);
8411                    iterator.initialize(text.toString());
8412                    return iterator;
8413                }
8414            } break;
8415            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8416                CharSequence text = getIterableTextForAccessibility();
8417                if (text != null && text.length() > 0) {
8418                    ParagraphTextSegmentIterator iterator =
8419                        ParagraphTextSegmentIterator.getInstance();
8420                    iterator.initialize(text.toString());
8421                    return iterator;
8422                }
8423            } break;
8424        }
8425        return null;
8426    }
8427
8428    /**
8429     * @hide
8430     */
8431    public void dispatchStartTemporaryDetach() {
8432        onStartTemporaryDetach();
8433    }
8434
8435    /**
8436     * This is called when a container is going to temporarily detach a child, with
8437     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8438     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8439     * {@link #onDetachedFromWindow()} when the container is done.
8440     */
8441    public void onStartTemporaryDetach() {
8442        removeUnsetPressCallback();
8443        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8444    }
8445
8446    /**
8447     * @hide
8448     */
8449    public void dispatchFinishTemporaryDetach() {
8450        onFinishTemporaryDetach();
8451    }
8452
8453    /**
8454     * Called after {@link #onStartTemporaryDetach} when the container is done
8455     * changing the view.
8456     */
8457    public void onFinishTemporaryDetach() {
8458    }
8459
8460    /**
8461     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8462     * for this view's window.  Returns null if the view is not currently attached
8463     * to the window.  Normally you will not need to use this directly, but
8464     * just use the standard high-level event callbacks like
8465     * {@link #onKeyDown(int, KeyEvent)}.
8466     */
8467    public KeyEvent.DispatcherState getKeyDispatcherState() {
8468        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8469    }
8470
8471    /**
8472     * Dispatch a key event before it is processed by any input method
8473     * associated with the view hierarchy.  This can be used to intercept
8474     * key events in special situations before the IME consumes them; a
8475     * typical example would be handling the BACK key to update the application's
8476     * UI instead of allowing the IME to see it and close itself.
8477     *
8478     * @param event The key event to be dispatched.
8479     * @return True if the event was handled, false otherwise.
8480     */
8481    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8482        return onKeyPreIme(event.getKeyCode(), event);
8483    }
8484
8485    /**
8486     * Dispatch a key event to the next view on the focus path. This path runs
8487     * from the top of the view tree down to the currently focused view. If this
8488     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8489     * the next node down the focus path. This method also fires any key
8490     * listeners.
8491     *
8492     * @param event The key event to be dispatched.
8493     * @return True if the event was handled, false otherwise.
8494     */
8495    public boolean dispatchKeyEvent(KeyEvent event) {
8496        if (mInputEventConsistencyVerifier != null) {
8497            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8498        }
8499
8500        // Give any attached key listener a first crack at the event.
8501        //noinspection SimplifiableIfStatement
8502        ListenerInfo li = mListenerInfo;
8503        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8504                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8505            return true;
8506        }
8507
8508        if (event.dispatch(this, mAttachInfo != null
8509                ? mAttachInfo.mKeyDispatchState : null, this)) {
8510            return true;
8511        }
8512
8513        if (mInputEventConsistencyVerifier != null) {
8514            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8515        }
8516        return false;
8517    }
8518
8519    /**
8520     * Dispatches a key shortcut event.
8521     *
8522     * @param event The key event to be dispatched.
8523     * @return True if the event was handled by the view, false otherwise.
8524     */
8525    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8526        return onKeyShortcut(event.getKeyCode(), event);
8527    }
8528
8529    /**
8530     * Pass the touch screen motion event down to the target view, or this
8531     * view if it is the target.
8532     *
8533     * @param event The motion event to be dispatched.
8534     * @return True if the event was handled by the view, false otherwise.
8535     */
8536    public boolean dispatchTouchEvent(MotionEvent event) {
8537        boolean result = false;
8538
8539        if (mInputEventConsistencyVerifier != null) {
8540            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8541        }
8542
8543        final int actionMasked = event.getActionMasked();
8544        if (actionMasked == MotionEvent.ACTION_DOWN) {
8545            // Defensive cleanup for new gesture
8546            stopNestedScroll();
8547        }
8548
8549        if (onFilterTouchEventForSecurity(event)) {
8550            //noinspection SimplifiableIfStatement
8551            ListenerInfo li = mListenerInfo;
8552            if (li != null && li.mOnTouchListener != null
8553                    && (mViewFlags & ENABLED_MASK) == ENABLED
8554                    && li.mOnTouchListener.onTouch(this, event)) {
8555                result = true;
8556            }
8557
8558            if (!result && onTouchEvent(event)) {
8559                result = true;
8560            }
8561        }
8562
8563        if (!result && mInputEventConsistencyVerifier != null) {
8564            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8565        }
8566
8567        // Clean up after nested scrolls if this is the end of a gesture;
8568        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8569        // of the gesture.
8570        if (actionMasked == MotionEvent.ACTION_UP ||
8571                actionMasked == MotionEvent.ACTION_CANCEL ||
8572                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8573            stopNestedScroll();
8574        }
8575
8576        return result;
8577    }
8578
8579    /**
8580     * Filter the touch event to apply security policies.
8581     *
8582     * @param event The motion event to be filtered.
8583     * @return True if the event should be dispatched, false if the event should be dropped.
8584     *
8585     * @see #getFilterTouchesWhenObscured
8586     */
8587    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8588        //noinspection RedundantIfStatement
8589        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8590                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8591            // Window is obscured, drop this touch.
8592            return false;
8593        }
8594        return true;
8595    }
8596
8597    /**
8598     * Pass a trackball motion event down to the focused view.
8599     *
8600     * @param event The motion event to be dispatched.
8601     * @return True if the event was handled by the view, false otherwise.
8602     */
8603    public boolean dispatchTrackballEvent(MotionEvent event) {
8604        if (mInputEventConsistencyVerifier != null) {
8605            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8606        }
8607
8608        return onTrackballEvent(event);
8609    }
8610
8611    /**
8612     * Dispatch a generic motion event.
8613     * <p>
8614     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8615     * are delivered to the view under the pointer.  All other generic motion events are
8616     * delivered to the focused view.  Hover events are handled specially and are delivered
8617     * to {@link #onHoverEvent(MotionEvent)}.
8618     * </p>
8619     *
8620     * @param event The motion event to be dispatched.
8621     * @return True if the event was handled by the view, false otherwise.
8622     */
8623    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8624        if (mInputEventConsistencyVerifier != null) {
8625            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8626        }
8627
8628        final int source = event.getSource();
8629        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8630            final int action = event.getAction();
8631            if (action == MotionEvent.ACTION_HOVER_ENTER
8632                    || action == MotionEvent.ACTION_HOVER_MOVE
8633                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8634                if (dispatchHoverEvent(event)) {
8635                    return true;
8636                }
8637            } else if (dispatchGenericPointerEvent(event)) {
8638                return true;
8639            }
8640        } else if (dispatchGenericFocusedEvent(event)) {
8641            return true;
8642        }
8643
8644        if (dispatchGenericMotionEventInternal(event)) {
8645            return true;
8646        }
8647
8648        if (mInputEventConsistencyVerifier != null) {
8649            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8650        }
8651        return false;
8652    }
8653
8654    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8655        //noinspection SimplifiableIfStatement
8656        ListenerInfo li = mListenerInfo;
8657        if (li != null && li.mOnGenericMotionListener != null
8658                && (mViewFlags & ENABLED_MASK) == ENABLED
8659                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8660            return true;
8661        }
8662
8663        if (onGenericMotionEvent(event)) {
8664            return true;
8665        }
8666
8667        if (mInputEventConsistencyVerifier != null) {
8668            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8669        }
8670        return false;
8671    }
8672
8673    /**
8674     * Dispatch a hover event.
8675     * <p>
8676     * Do not call this method directly.
8677     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8678     * </p>
8679     *
8680     * @param event The motion event to be dispatched.
8681     * @return True if the event was handled by the view, false otherwise.
8682     */
8683    protected boolean dispatchHoverEvent(MotionEvent event) {
8684        ListenerInfo li = mListenerInfo;
8685        //noinspection SimplifiableIfStatement
8686        if (li != null && li.mOnHoverListener != null
8687                && (mViewFlags & ENABLED_MASK) == ENABLED
8688                && li.mOnHoverListener.onHover(this, event)) {
8689            return true;
8690        }
8691
8692        return onHoverEvent(event);
8693    }
8694
8695    /**
8696     * Returns true if the view has a child to which it has recently sent
8697     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8698     * it does not have a hovered child, then it must be the innermost hovered view.
8699     * @hide
8700     */
8701    protected boolean hasHoveredChild() {
8702        return false;
8703    }
8704
8705    /**
8706     * Dispatch a generic motion event to the view under the first pointer.
8707     * <p>
8708     * Do not call this method directly.
8709     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8710     * </p>
8711     *
8712     * @param event The motion event to be dispatched.
8713     * @return True if the event was handled by the view, false otherwise.
8714     */
8715    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8716        return false;
8717    }
8718
8719    /**
8720     * Dispatch a generic motion event to the currently focused view.
8721     * <p>
8722     * Do not call this method directly.
8723     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8724     * </p>
8725     *
8726     * @param event The motion event to be dispatched.
8727     * @return True if the event was handled by the view, false otherwise.
8728     */
8729    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8730        return false;
8731    }
8732
8733    /**
8734     * Dispatch a pointer event.
8735     * <p>
8736     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8737     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8738     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8739     * and should not be expected to handle other pointing device features.
8740     * </p>
8741     *
8742     * @param event The motion event to be dispatched.
8743     * @return True if the event was handled by the view, false otherwise.
8744     * @hide
8745     */
8746    public final boolean dispatchPointerEvent(MotionEvent event) {
8747        if (event.isTouchEvent()) {
8748            return dispatchTouchEvent(event);
8749        } else {
8750            return dispatchGenericMotionEvent(event);
8751        }
8752    }
8753
8754    /**
8755     * Called when the window containing this view gains or loses window focus.
8756     * ViewGroups should override to route to their children.
8757     *
8758     * @param hasFocus True if the window containing this view now has focus,
8759     *        false otherwise.
8760     */
8761    public void dispatchWindowFocusChanged(boolean hasFocus) {
8762        onWindowFocusChanged(hasFocus);
8763    }
8764
8765    /**
8766     * Called when the window containing this view gains or loses focus.  Note
8767     * that this is separate from view focus: to receive key events, both
8768     * your view and its window must have focus.  If a window is displayed
8769     * on top of yours that takes input focus, then your own window will lose
8770     * focus but the view focus will remain unchanged.
8771     *
8772     * @param hasWindowFocus True if the window containing this view now has
8773     *        focus, false otherwise.
8774     */
8775    public void onWindowFocusChanged(boolean hasWindowFocus) {
8776        InputMethodManager imm = InputMethodManager.peekInstance();
8777        if (!hasWindowFocus) {
8778            if (isPressed()) {
8779                setPressed(false);
8780            }
8781            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8782                imm.focusOut(this);
8783            }
8784            removeLongPressCallback();
8785            removeTapCallback();
8786            onFocusLost();
8787        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8788            imm.focusIn(this);
8789        }
8790        refreshDrawableState();
8791    }
8792
8793    /**
8794     * Returns true if this view is in a window that currently has window focus.
8795     * Note that this is not the same as the view itself having focus.
8796     *
8797     * @return True if this view is in a window that currently has window focus.
8798     */
8799    public boolean hasWindowFocus() {
8800        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8801    }
8802
8803    /**
8804     * Dispatch a view visibility change down the view hierarchy.
8805     * ViewGroups should override to route to their children.
8806     * @param changedView The view whose visibility changed. Could be 'this' or
8807     * an ancestor view.
8808     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8809     * {@link #INVISIBLE} or {@link #GONE}.
8810     */
8811    protected void dispatchVisibilityChanged(@NonNull View changedView,
8812            @Visibility int visibility) {
8813        onVisibilityChanged(changedView, visibility);
8814    }
8815
8816    /**
8817     * Called when the visibility of the view or an ancestor of the view is changed.
8818     * @param changedView The view whose visibility changed. Could be 'this' or
8819     * an ancestor view.
8820     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8821     * {@link #INVISIBLE} or {@link #GONE}.
8822     */
8823    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8824        if (visibility == VISIBLE) {
8825            if (mAttachInfo != null) {
8826                initialAwakenScrollBars();
8827            } else {
8828                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8829            }
8830        }
8831    }
8832
8833    /**
8834     * Dispatch a hint about whether this view is displayed. For instance, when
8835     * a View moves out of the screen, it might receives a display hint indicating
8836     * the view is not displayed. Applications should not <em>rely</em> on this hint
8837     * as there is no guarantee that they will receive one.
8838     *
8839     * @param hint A hint about whether or not this view is displayed:
8840     * {@link #VISIBLE} or {@link #INVISIBLE}.
8841     */
8842    public void dispatchDisplayHint(@Visibility int hint) {
8843        onDisplayHint(hint);
8844    }
8845
8846    /**
8847     * Gives this view a hint about whether is displayed or not. For instance, when
8848     * a View moves out of the screen, it might receives a display hint indicating
8849     * the view is not displayed. Applications should not <em>rely</em> on this hint
8850     * as there is no guarantee that they will receive one.
8851     *
8852     * @param hint A hint about whether or not this view is displayed:
8853     * {@link #VISIBLE} or {@link #INVISIBLE}.
8854     */
8855    protected void onDisplayHint(@Visibility int hint) {
8856    }
8857
8858    /**
8859     * Dispatch a window visibility change down the view hierarchy.
8860     * ViewGroups should override to route to their children.
8861     *
8862     * @param visibility The new visibility of the window.
8863     *
8864     * @see #onWindowVisibilityChanged(int)
8865     */
8866    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8867        onWindowVisibilityChanged(visibility);
8868    }
8869
8870    /**
8871     * Called when the window containing has change its visibility
8872     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8873     * that this tells you whether or not your window is being made visible
8874     * to the window manager; this does <em>not</em> tell you whether or not
8875     * your window is obscured by other windows on the screen, even if it
8876     * is itself visible.
8877     *
8878     * @param visibility The new visibility of the window.
8879     */
8880    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8881        if (visibility == VISIBLE) {
8882            initialAwakenScrollBars();
8883        }
8884    }
8885
8886    /**
8887     * Returns the current visibility of the window this view is attached to
8888     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8889     *
8890     * @return Returns the current visibility of the view's window.
8891     */
8892    @Visibility
8893    public int getWindowVisibility() {
8894        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8895    }
8896
8897    /**
8898     * Retrieve the overall visible display size in which the window this view is
8899     * attached to has been positioned in.  This takes into account screen
8900     * decorations above the window, for both cases where the window itself
8901     * is being position inside of them or the window is being placed under
8902     * then and covered insets are used for the window to position its content
8903     * inside.  In effect, this tells you the available area where content can
8904     * be placed and remain visible to users.
8905     *
8906     * <p>This function requires an IPC back to the window manager to retrieve
8907     * the requested information, so should not be used in performance critical
8908     * code like drawing.
8909     *
8910     * @param outRect Filled in with the visible display frame.  If the view
8911     * is not attached to a window, this is simply the raw display size.
8912     */
8913    public void getWindowVisibleDisplayFrame(Rect outRect) {
8914        if (mAttachInfo != null) {
8915            try {
8916                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8917            } catch (RemoteException e) {
8918                return;
8919            }
8920            // XXX This is really broken, and probably all needs to be done
8921            // in the window manager, and we need to know more about whether
8922            // we want the area behind or in front of the IME.
8923            final Rect insets = mAttachInfo.mVisibleInsets;
8924            outRect.left += insets.left;
8925            outRect.top += insets.top;
8926            outRect.right -= insets.right;
8927            outRect.bottom -= insets.bottom;
8928            return;
8929        }
8930        // The view is not attached to a display so we don't have a context.
8931        // Make a best guess about the display size.
8932        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8933        d.getRectSize(outRect);
8934    }
8935
8936    /**
8937     * Dispatch a notification about a resource configuration change down
8938     * the view hierarchy.
8939     * ViewGroups should override to route to their children.
8940     *
8941     * @param newConfig The new resource configuration.
8942     *
8943     * @see #onConfigurationChanged(android.content.res.Configuration)
8944     */
8945    public void dispatchConfigurationChanged(Configuration newConfig) {
8946        onConfigurationChanged(newConfig);
8947    }
8948
8949    /**
8950     * Called when the current configuration of the resources being used
8951     * by the application have changed.  You can use this to decide when
8952     * to reload resources that can changed based on orientation and other
8953     * configuration characteristics.  You only need to use this if you are
8954     * not relying on the normal {@link android.app.Activity} mechanism of
8955     * recreating the activity instance upon a configuration change.
8956     *
8957     * @param newConfig The new resource configuration.
8958     */
8959    protected void onConfigurationChanged(Configuration newConfig) {
8960    }
8961
8962    /**
8963     * Private function to aggregate all per-view attributes in to the view
8964     * root.
8965     */
8966    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8967        performCollectViewAttributes(attachInfo, visibility);
8968    }
8969
8970    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8971        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8972            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8973                attachInfo.mKeepScreenOn = true;
8974            }
8975            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8976            ListenerInfo li = mListenerInfo;
8977            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8978                attachInfo.mHasSystemUiListeners = true;
8979            }
8980        }
8981    }
8982
8983    void needGlobalAttributesUpdate(boolean force) {
8984        final AttachInfo ai = mAttachInfo;
8985        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8986            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8987                    || ai.mHasSystemUiListeners) {
8988                ai.mRecomputeGlobalAttributes = true;
8989            }
8990        }
8991    }
8992
8993    /**
8994     * Returns whether the device is currently in touch mode.  Touch mode is entered
8995     * once the user begins interacting with the device by touch, and affects various
8996     * things like whether focus is always visible to the user.
8997     *
8998     * @return Whether the device is in touch mode.
8999     */
9000    @ViewDebug.ExportedProperty
9001    public boolean isInTouchMode() {
9002        if (mAttachInfo != null) {
9003            return mAttachInfo.mInTouchMode;
9004        } else {
9005            return ViewRootImpl.isInTouchMode();
9006        }
9007    }
9008
9009    /**
9010     * Returns the context the view is running in, through which it can
9011     * access the current theme, resources, etc.
9012     *
9013     * @return The view's Context.
9014     */
9015    @ViewDebug.CapturedViewProperty
9016    public final Context getContext() {
9017        return mContext;
9018    }
9019
9020    /**
9021     * Handle a key event before it is processed by any input method
9022     * associated with the view hierarchy.  This can be used to intercept
9023     * key events in special situations before the IME consumes them; a
9024     * typical example would be handling the BACK key to update the application's
9025     * UI instead of allowing the IME to see it and close itself.
9026     *
9027     * @param keyCode The value in event.getKeyCode().
9028     * @param event Description of the key event.
9029     * @return If you handled the event, return true. If you want to allow the
9030     *         event to be handled by the next receiver, return false.
9031     */
9032    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9033        return false;
9034    }
9035
9036    /**
9037     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9038     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9039     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9040     * is released, if the view is enabled and clickable.
9041     *
9042     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9043     * although some may elect to do so in some situations. Do not rely on this to
9044     * catch software key presses.
9045     *
9046     * @param keyCode A key code that represents the button pressed, from
9047     *                {@link android.view.KeyEvent}.
9048     * @param event   The KeyEvent object that defines the button action.
9049     */
9050    public boolean onKeyDown(int keyCode, KeyEvent event) {
9051        boolean result = false;
9052
9053        if (KeyEvent.isConfirmKey(keyCode)) {
9054            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9055                return true;
9056            }
9057            // Long clickable items don't necessarily have to be clickable
9058            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9059                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9060                    (event.getRepeatCount() == 0)) {
9061                setPressed(true);
9062                checkForLongClick(0);
9063                return true;
9064            }
9065        }
9066        return result;
9067    }
9068
9069    /**
9070     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9071     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9072     * the event).
9073     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9074     * although some may elect to do so in some situations. Do not rely on this to
9075     * catch software key presses.
9076     */
9077    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9078        return false;
9079    }
9080
9081    /**
9082     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9083     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9084     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9085     * {@link KeyEvent#KEYCODE_ENTER} is released.
9086     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9087     * although some may elect to do so in some situations. Do not rely on this to
9088     * catch software key presses.
9089     *
9090     * @param keyCode A key code that represents the button pressed, from
9091     *                {@link android.view.KeyEvent}.
9092     * @param event   The KeyEvent object that defines the button action.
9093     */
9094    public boolean onKeyUp(int keyCode, KeyEvent event) {
9095        if (KeyEvent.isConfirmKey(keyCode)) {
9096            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9097                return true;
9098            }
9099            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9100                setPressed(false);
9101
9102                if (!mHasPerformedLongPress) {
9103                    // This is a tap, so remove the longpress check
9104                    removeLongPressCallback();
9105                    return performClick();
9106                }
9107            }
9108        }
9109        return false;
9110    }
9111
9112    /**
9113     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9114     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9115     * the event).
9116     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9117     * although some may elect to do so in some situations. Do not rely on this to
9118     * catch software key presses.
9119     *
9120     * @param keyCode     A key code that represents the button pressed, from
9121     *                    {@link android.view.KeyEvent}.
9122     * @param repeatCount The number of times the action was made.
9123     * @param event       The KeyEvent object that defines the button action.
9124     */
9125    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9126        return false;
9127    }
9128
9129    /**
9130     * Called on the focused view when a key shortcut event is not handled.
9131     * Override this method to implement local key shortcuts for the View.
9132     * Key shortcuts can also be implemented by setting the
9133     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9134     *
9135     * @param keyCode The value in event.getKeyCode().
9136     * @param event Description of the key event.
9137     * @return If you handled the event, return true. If you want to allow the
9138     *         event to be handled by the next receiver, return false.
9139     */
9140    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9141        return false;
9142    }
9143
9144    /**
9145     * Check whether the called view is a text editor, in which case it
9146     * would make sense to automatically display a soft input window for
9147     * it.  Subclasses should override this if they implement
9148     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9149     * a call on that method would return a non-null InputConnection, and
9150     * they are really a first-class editor that the user would normally
9151     * start typing on when the go into a window containing your view.
9152     *
9153     * <p>The default implementation always returns false.  This does
9154     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9155     * will not be called or the user can not otherwise perform edits on your
9156     * view; it is just a hint to the system that this is not the primary
9157     * purpose of this view.
9158     *
9159     * @return Returns true if this view is a text editor, else false.
9160     */
9161    public boolean onCheckIsTextEditor() {
9162        return false;
9163    }
9164
9165    /**
9166     * Create a new InputConnection for an InputMethod to interact
9167     * with the view.  The default implementation returns null, since it doesn't
9168     * support input methods.  You can override this to implement such support.
9169     * This is only needed for views that take focus and text input.
9170     *
9171     * <p>When implementing this, you probably also want to implement
9172     * {@link #onCheckIsTextEditor()} to indicate you will return a
9173     * non-null InputConnection.</p>
9174     *
9175     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9176     * object correctly and in its entirety, so that the connected IME can rely
9177     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9178     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9179     * must be filled in with the correct cursor position for IMEs to work correctly
9180     * with your application.</p>
9181     *
9182     * @param outAttrs Fill in with attribute information about the connection.
9183     */
9184    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9185        return null;
9186    }
9187
9188    /**
9189     * Called by the {@link android.view.inputmethod.InputMethodManager}
9190     * when a view who is not the current
9191     * input connection target is trying to make a call on the manager.  The
9192     * default implementation returns false; you can override this to return
9193     * true for certain views if you are performing InputConnection proxying
9194     * to them.
9195     * @param view The View that is making the InputMethodManager call.
9196     * @return Return true to allow the call, false to reject.
9197     */
9198    public boolean checkInputConnectionProxy(View view) {
9199        return false;
9200    }
9201
9202    /**
9203     * Show the context menu for this view. It is not safe to hold on to the
9204     * menu after returning from this method.
9205     *
9206     * You should normally not overload this method. Overload
9207     * {@link #onCreateContextMenu(ContextMenu)} or define an
9208     * {@link OnCreateContextMenuListener} to add items to the context menu.
9209     *
9210     * @param menu The context menu to populate
9211     */
9212    public void createContextMenu(ContextMenu menu) {
9213        ContextMenuInfo menuInfo = getContextMenuInfo();
9214
9215        // Sets the current menu info so all items added to menu will have
9216        // my extra info set.
9217        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9218
9219        onCreateContextMenu(menu);
9220        ListenerInfo li = mListenerInfo;
9221        if (li != null && li.mOnCreateContextMenuListener != null) {
9222            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9223        }
9224
9225        // Clear the extra information so subsequent items that aren't mine don't
9226        // have my extra info.
9227        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9228
9229        if (mParent != null) {
9230            mParent.createContextMenu(menu);
9231        }
9232    }
9233
9234    /**
9235     * Views should implement this if they have extra information to associate
9236     * with the context menu. The return result is supplied as a parameter to
9237     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9238     * callback.
9239     *
9240     * @return Extra information about the item for which the context menu
9241     *         should be shown. This information will vary across different
9242     *         subclasses of View.
9243     */
9244    protected ContextMenuInfo getContextMenuInfo() {
9245        return null;
9246    }
9247
9248    /**
9249     * Views should implement this if the view itself is going to add items to
9250     * the context menu.
9251     *
9252     * @param menu the context menu to populate
9253     */
9254    protected void onCreateContextMenu(ContextMenu menu) {
9255    }
9256
9257    /**
9258     * Implement this method to handle trackball motion events.  The
9259     * <em>relative</em> movement of the trackball since the last event
9260     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9261     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9262     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9263     * they will often be fractional values, representing the more fine-grained
9264     * movement information available from a trackball).
9265     *
9266     * @param event The motion event.
9267     * @return True if the event was handled, false otherwise.
9268     */
9269    public boolean onTrackballEvent(MotionEvent event) {
9270        return false;
9271    }
9272
9273    /**
9274     * Implement this method to handle generic motion events.
9275     * <p>
9276     * Generic motion events describe joystick movements, mouse hovers, track pad
9277     * touches, scroll wheel movements and other input events.  The
9278     * {@link MotionEvent#getSource() source} of the motion event specifies
9279     * the class of input that was received.  Implementations of this method
9280     * must examine the bits in the source before processing the event.
9281     * The following code example shows how this is done.
9282     * </p><p>
9283     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9284     * are delivered to the view under the pointer.  All other generic motion events are
9285     * delivered to the focused view.
9286     * </p>
9287     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9288     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9289     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9290     *             // process the joystick movement...
9291     *             return true;
9292     *         }
9293     *     }
9294     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9295     *         switch (event.getAction()) {
9296     *             case MotionEvent.ACTION_HOVER_MOVE:
9297     *                 // process the mouse hover movement...
9298     *                 return true;
9299     *             case MotionEvent.ACTION_SCROLL:
9300     *                 // process the scroll wheel movement...
9301     *                 return true;
9302     *         }
9303     *     }
9304     *     return super.onGenericMotionEvent(event);
9305     * }</pre>
9306     *
9307     * @param event The generic motion event being processed.
9308     * @return True if the event was handled, false otherwise.
9309     */
9310    public boolean onGenericMotionEvent(MotionEvent event) {
9311        return false;
9312    }
9313
9314    /**
9315     * Implement this method to handle hover events.
9316     * <p>
9317     * This method is called whenever a pointer is hovering into, over, or out of the
9318     * bounds of a view and the view is not currently being touched.
9319     * Hover events are represented as pointer events with action
9320     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9321     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9322     * </p>
9323     * <ul>
9324     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9325     * when the pointer enters the bounds of the view.</li>
9326     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9327     * when the pointer has already entered the bounds of the view and has moved.</li>
9328     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9329     * when the pointer has exited the bounds of the view or when the pointer is
9330     * about to go down due to a button click, tap, or similar user action that
9331     * causes the view to be touched.</li>
9332     * </ul>
9333     * <p>
9334     * The view should implement this method to return true to indicate that it is
9335     * handling the hover event, such as by changing its drawable state.
9336     * </p><p>
9337     * The default implementation calls {@link #setHovered} to update the hovered state
9338     * of the view when a hover enter or hover exit event is received, if the view
9339     * is enabled and is clickable.  The default implementation also sends hover
9340     * accessibility events.
9341     * </p>
9342     *
9343     * @param event The motion event that describes the hover.
9344     * @return True if the view handled the hover event.
9345     *
9346     * @see #isHovered
9347     * @see #setHovered
9348     * @see #onHoverChanged
9349     */
9350    public boolean onHoverEvent(MotionEvent event) {
9351        // The root view may receive hover (or touch) events that are outside the bounds of
9352        // the window.  This code ensures that we only send accessibility events for
9353        // hovers that are actually within the bounds of the root view.
9354        final int action = event.getActionMasked();
9355        if (!mSendingHoverAccessibilityEvents) {
9356            if ((action == MotionEvent.ACTION_HOVER_ENTER
9357                    || action == MotionEvent.ACTION_HOVER_MOVE)
9358                    && !hasHoveredChild()
9359                    && pointInView(event.getX(), event.getY())) {
9360                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9361                mSendingHoverAccessibilityEvents = true;
9362            }
9363        } else {
9364            if (action == MotionEvent.ACTION_HOVER_EXIT
9365                    || (action == MotionEvent.ACTION_MOVE
9366                            && !pointInView(event.getX(), event.getY()))) {
9367                mSendingHoverAccessibilityEvents = false;
9368                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9369            }
9370        }
9371
9372        if (isHoverable()) {
9373            switch (action) {
9374                case MotionEvent.ACTION_HOVER_ENTER:
9375                    setHovered(true);
9376                    break;
9377                case MotionEvent.ACTION_HOVER_EXIT:
9378                    setHovered(false);
9379                    break;
9380            }
9381
9382            // Dispatch the event to onGenericMotionEvent before returning true.
9383            // This is to provide compatibility with existing applications that
9384            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9385            // break because of the new default handling for hoverable views
9386            // in onHoverEvent.
9387            // Note that onGenericMotionEvent will be called by default when
9388            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9389            dispatchGenericMotionEventInternal(event);
9390            // The event was already handled by calling setHovered(), so always
9391            // return true.
9392            return true;
9393        }
9394
9395        return false;
9396    }
9397
9398    /**
9399     * Returns true if the view should handle {@link #onHoverEvent}
9400     * by calling {@link #setHovered} to change its hovered state.
9401     *
9402     * @return True if the view is hoverable.
9403     */
9404    private boolean isHoverable() {
9405        final int viewFlags = mViewFlags;
9406        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9407            return false;
9408        }
9409
9410        return (viewFlags & CLICKABLE) == CLICKABLE
9411                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9412    }
9413
9414    /**
9415     * Returns true if the view is currently hovered.
9416     *
9417     * @return True if the view is currently hovered.
9418     *
9419     * @see #setHovered
9420     * @see #onHoverChanged
9421     */
9422    @ViewDebug.ExportedProperty
9423    public boolean isHovered() {
9424        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9425    }
9426
9427    /**
9428     * Sets whether the view is currently hovered.
9429     * <p>
9430     * Calling this method also changes the drawable state of the view.  This
9431     * enables the view to react to hover by using different drawable resources
9432     * to change its appearance.
9433     * </p><p>
9434     * The {@link #onHoverChanged} method is called when the hovered state changes.
9435     * </p>
9436     *
9437     * @param hovered True if the view is hovered.
9438     *
9439     * @see #isHovered
9440     * @see #onHoverChanged
9441     */
9442    public void setHovered(boolean hovered) {
9443        if (hovered) {
9444            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9445                mPrivateFlags |= PFLAG_HOVERED;
9446                refreshDrawableState();
9447                onHoverChanged(true);
9448            }
9449        } else {
9450            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9451                mPrivateFlags &= ~PFLAG_HOVERED;
9452                refreshDrawableState();
9453                onHoverChanged(false);
9454            }
9455        }
9456    }
9457
9458    /**
9459     * Implement this method to handle hover state changes.
9460     * <p>
9461     * This method is called whenever the hover state changes as a result of a
9462     * call to {@link #setHovered}.
9463     * </p>
9464     *
9465     * @param hovered The current hover state, as returned by {@link #isHovered}.
9466     *
9467     * @see #isHovered
9468     * @see #setHovered
9469     */
9470    public void onHoverChanged(boolean hovered) {
9471    }
9472
9473    /**
9474     * Implement this method to handle touch screen motion events.
9475     * <p>
9476     * If this method is used to detect click actions, it is recommended that
9477     * the actions be performed by implementing and calling
9478     * {@link #performClick()}. This will ensure consistent system behavior,
9479     * including:
9480     * <ul>
9481     * <li>obeying click sound preferences
9482     * <li>dispatching OnClickListener calls
9483     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9484     * accessibility features are enabled
9485     * </ul>
9486     *
9487     * @param event The motion event.
9488     * @return True if the event was handled, false otherwise.
9489     */
9490    public boolean onTouchEvent(MotionEvent event) {
9491        final float x = event.getX();
9492        final float y = event.getY();
9493        final int viewFlags = mViewFlags;
9494
9495        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9496            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9497                setPressed(false);
9498            }
9499            // A disabled view that is clickable still consumes the touch
9500            // events, it just doesn't respond to them.
9501            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9502                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9503        }
9504
9505        if (mTouchDelegate != null) {
9506            if (mTouchDelegate.onTouchEvent(event)) {
9507                return true;
9508            }
9509        }
9510
9511        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9512                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9513            switch (event.getAction()) {
9514                case MotionEvent.ACTION_UP:
9515                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9516                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9517                        // take focus if we don't have it already and we should in
9518                        // touch mode.
9519                        boolean focusTaken = false;
9520                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9521                            focusTaken = requestFocus();
9522                        }
9523
9524                        if (prepressed) {
9525                            // The button is being released before we actually
9526                            // showed it as pressed.  Make it show the pressed
9527                            // state now (before scheduling the click) to ensure
9528                            // the user sees it.
9529                            setPressed(true, x, y);
9530                       }
9531
9532                        if (!mHasPerformedLongPress) {
9533                            // This is a tap, so remove the longpress check
9534                            removeLongPressCallback();
9535
9536                            // Only perform take click actions if we were in the pressed state
9537                            if (!focusTaken) {
9538                                // Use a Runnable and post this rather than calling
9539                                // performClick directly. This lets other visual state
9540                                // of the view update before click actions start.
9541                                if (mPerformClick == null) {
9542                                    mPerformClick = new PerformClick();
9543                                }
9544                                if (!post(mPerformClick)) {
9545                                    performClick();
9546                                }
9547                            }
9548                        }
9549
9550                        if (mUnsetPressedState == null) {
9551                            mUnsetPressedState = new UnsetPressedState();
9552                        }
9553
9554                        if (prepressed) {
9555                            postDelayed(mUnsetPressedState,
9556                                    ViewConfiguration.getPressedStateDuration());
9557                        } else if (!post(mUnsetPressedState)) {
9558                            // If the post failed, unpress right now
9559                            mUnsetPressedState.run();
9560                        }
9561
9562                        removeTapCallback();
9563                    }
9564                    break;
9565
9566                case MotionEvent.ACTION_DOWN:
9567                    mHasPerformedLongPress = false;
9568
9569                    if (performButtonActionOnTouchDown(event)) {
9570                        break;
9571                    }
9572
9573                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9574                    boolean isInScrollingContainer = isInScrollingContainer();
9575
9576                    // For views inside a scrolling container, delay the pressed feedback for
9577                    // a short period in case this is a scroll.
9578                    if (isInScrollingContainer) {
9579                        mPrivateFlags |= PFLAG_PREPRESSED;
9580                        if (mPendingCheckForTap == null) {
9581                            mPendingCheckForTap = new CheckForTap();
9582                        }
9583                        mPendingCheckForTap.x = event.getX();
9584                        mPendingCheckForTap.y = event.getY();
9585                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9586                    } else {
9587                        // Not inside a scrolling container, so show the feedback right away
9588                        setPressed(true, x, y);
9589                        checkForLongClick(0);
9590                    }
9591                    break;
9592
9593                case MotionEvent.ACTION_CANCEL:
9594                    setPressed(false);
9595                    removeTapCallback();
9596                    removeLongPressCallback();
9597                    break;
9598
9599                case MotionEvent.ACTION_MOVE:
9600                    drawableHotspotChanged(x, y);
9601
9602                    // Be lenient about moving outside of buttons
9603                    if (!pointInView(x, y, mTouchSlop)) {
9604                        // Outside button
9605                        removeTapCallback();
9606                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9607                            // Remove any future long press/tap checks
9608                            removeLongPressCallback();
9609
9610                            setPressed(false);
9611                        }
9612                    }
9613                    break;
9614            }
9615
9616            return true;
9617        }
9618
9619        return false;
9620    }
9621
9622    /**
9623     * @hide
9624     */
9625    public boolean isInScrollingContainer() {
9626        ViewParent p = getParent();
9627        while (p != null && p instanceof ViewGroup) {
9628            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9629                return true;
9630            }
9631            p = p.getParent();
9632        }
9633        return false;
9634    }
9635
9636    /**
9637     * Remove the longpress detection timer.
9638     */
9639    private void removeLongPressCallback() {
9640        if (mPendingCheckForLongPress != null) {
9641          removeCallbacks(mPendingCheckForLongPress);
9642        }
9643    }
9644
9645    /**
9646     * Remove the pending click action
9647     */
9648    private void removePerformClickCallback() {
9649        if (mPerformClick != null) {
9650            removeCallbacks(mPerformClick);
9651        }
9652    }
9653
9654    /**
9655     * Remove the prepress detection timer.
9656     */
9657    private void removeUnsetPressCallback() {
9658        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9659            setPressed(false);
9660            removeCallbacks(mUnsetPressedState);
9661        }
9662    }
9663
9664    /**
9665     * Remove the tap detection timer.
9666     */
9667    private void removeTapCallback() {
9668        if (mPendingCheckForTap != null) {
9669            mPrivateFlags &= ~PFLAG_PREPRESSED;
9670            removeCallbacks(mPendingCheckForTap);
9671        }
9672    }
9673
9674    /**
9675     * Cancels a pending long press.  Your subclass can use this if you
9676     * want the context menu to come up if the user presses and holds
9677     * at the same place, but you don't want it to come up if they press
9678     * and then move around enough to cause scrolling.
9679     */
9680    public void cancelLongPress() {
9681        removeLongPressCallback();
9682
9683        /*
9684         * The prepressed state handled by the tap callback is a display
9685         * construct, but the tap callback will post a long press callback
9686         * less its own timeout. Remove it here.
9687         */
9688        removeTapCallback();
9689    }
9690
9691    /**
9692     * Remove the pending callback for sending a
9693     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9694     */
9695    private void removeSendViewScrolledAccessibilityEventCallback() {
9696        if (mSendViewScrolledAccessibilityEvent != null) {
9697            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9698            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9699        }
9700    }
9701
9702    /**
9703     * Sets the TouchDelegate for this View.
9704     */
9705    public void setTouchDelegate(TouchDelegate delegate) {
9706        mTouchDelegate = delegate;
9707    }
9708
9709    /**
9710     * Gets the TouchDelegate for this View.
9711     */
9712    public TouchDelegate getTouchDelegate() {
9713        return mTouchDelegate;
9714    }
9715
9716    /**
9717     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9718     *
9719     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9720     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9721     * available. This method should only be called for touch events.
9722     *
9723     * <p class="note">This api is not intended for most applications. Buffered dispatch
9724     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9725     * streams will not improve your input latency. Side effects include: increased latency,
9726     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9727     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9728     * you.</p>
9729     */
9730    public final void requestUnbufferedDispatch(MotionEvent event) {
9731        final int action = event.getAction();
9732        if (mAttachInfo == null
9733                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9734                || !event.isTouchEvent()) {
9735            return;
9736        }
9737        mAttachInfo.mUnbufferedDispatchRequested = true;
9738    }
9739
9740    /**
9741     * Set flags controlling behavior of this view.
9742     *
9743     * @param flags Constant indicating the value which should be set
9744     * @param mask Constant indicating the bit range that should be changed
9745     */
9746    void setFlags(int flags, int mask) {
9747        final boolean accessibilityEnabled =
9748                AccessibilityManager.getInstance(mContext).isEnabled();
9749        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9750
9751        int old = mViewFlags;
9752        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9753
9754        int changed = mViewFlags ^ old;
9755        if (changed == 0) {
9756            return;
9757        }
9758        int privateFlags = mPrivateFlags;
9759
9760        /* Check if the FOCUSABLE bit has changed */
9761        if (((changed & FOCUSABLE_MASK) != 0) &&
9762                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9763            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9764                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9765                /* Give up focus if we are no longer focusable */
9766                clearFocus();
9767            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9768                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9769                /*
9770                 * Tell the view system that we are now available to take focus
9771                 * if no one else already has it.
9772                 */
9773                if (mParent != null) mParent.focusableViewAvailable(this);
9774            }
9775        }
9776
9777        final int newVisibility = flags & VISIBILITY_MASK;
9778        if (newVisibility == VISIBLE) {
9779            if ((changed & VISIBILITY_MASK) != 0) {
9780                /*
9781                 * If this view is becoming visible, invalidate it in case it changed while
9782                 * it was not visible. Marking it drawn ensures that the invalidation will
9783                 * go through.
9784                 */
9785                mPrivateFlags |= PFLAG_DRAWN;
9786                invalidate(true);
9787
9788                needGlobalAttributesUpdate(true);
9789
9790                // a view becoming visible is worth notifying the parent
9791                // about in case nothing has focus.  even if this specific view
9792                // isn't focusable, it may contain something that is, so let
9793                // the root view try to give this focus if nothing else does.
9794                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9795                    mParent.focusableViewAvailable(this);
9796                }
9797            }
9798        }
9799
9800        /* Check if the GONE bit has changed */
9801        if ((changed & GONE) != 0) {
9802            needGlobalAttributesUpdate(false);
9803            requestLayout();
9804
9805            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9806                if (hasFocus()) clearFocus();
9807                clearAccessibilityFocus();
9808                destroyDrawingCache();
9809                if (mParent instanceof View) {
9810                    // GONE views noop invalidation, so invalidate the parent
9811                    ((View) mParent).invalidate(true);
9812                }
9813                // Mark the view drawn to ensure that it gets invalidated properly the next
9814                // time it is visible and gets invalidated
9815                mPrivateFlags |= PFLAG_DRAWN;
9816            }
9817            if (mAttachInfo != null) {
9818                mAttachInfo.mViewVisibilityChanged = true;
9819            }
9820        }
9821
9822        /* Check if the VISIBLE bit has changed */
9823        if ((changed & INVISIBLE) != 0) {
9824            needGlobalAttributesUpdate(false);
9825            /*
9826             * If this view is becoming invisible, set the DRAWN flag so that
9827             * the next invalidate() will not be skipped.
9828             */
9829            mPrivateFlags |= PFLAG_DRAWN;
9830
9831            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9832                // root view becoming invisible shouldn't clear focus and accessibility focus
9833                if (getRootView() != this) {
9834                    if (hasFocus()) clearFocus();
9835                    clearAccessibilityFocus();
9836                }
9837            }
9838            if (mAttachInfo != null) {
9839                mAttachInfo.mViewVisibilityChanged = true;
9840            }
9841        }
9842
9843        if ((changed & VISIBILITY_MASK) != 0) {
9844            // If the view is invisible, cleanup its display list to free up resources
9845            if (newVisibility != VISIBLE && mAttachInfo != null) {
9846                cleanupDraw();
9847            }
9848
9849            if (mParent instanceof ViewGroup) {
9850                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9851                        (changed & VISIBILITY_MASK), newVisibility);
9852                ((View) mParent).invalidate(true);
9853            } else if (mParent != null) {
9854                mParent.invalidateChild(this, null);
9855            }
9856            dispatchVisibilityChanged(this, newVisibility);
9857
9858            notifySubtreeAccessibilityStateChangedIfNeeded();
9859        }
9860
9861        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9862            destroyDrawingCache();
9863        }
9864
9865        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9866            destroyDrawingCache();
9867            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9868            invalidateParentCaches();
9869        }
9870
9871        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9872            destroyDrawingCache();
9873            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9874        }
9875
9876        if ((changed & DRAW_MASK) != 0) {
9877            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9878                if (mBackground != null) {
9879                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9880                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9881                } else {
9882                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9883                }
9884            } else {
9885                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9886            }
9887            requestLayout();
9888            invalidate(true);
9889        }
9890
9891        if ((changed & KEEP_SCREEN_ON) != 0) {
9892            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9893                mParent.recomputeViewAttributes(this);
9894            }
9895        }
9896
9897        if (accessibilityEnabled) {
9898            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9899                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9900                if (oldIncludeForAccessibility != includeForAccessibility()) {
9901                    notifySubtreeAccessibilityStateChangedIfNeeded();
9902                } else {
9903                    notifyViewAccessibilityStateChangedIfNeeded(
9904                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9905                }
9906            } else if ((changed & ENABLED_MASK) != 0) {
9907                notifyViewAccessibilityStateChangedIfNeeded(
9908                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9909            }
9910        }
9911    }
9912
9913    /**
9914     * Change the view's z order in the tree, so it's on top of other sibling
9915     * views. This ordering change may affect layout, if the parent container
9916     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9917     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9918     * method should be followed by calls to {@link #requestLayout()} and
9919     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9920     * with the new child ordering.
9921     *
9922     * @see ViewGroup#bringChildToFront(View)
9923     */
9924    public void bringToFront() {
9925        if (mParent != null) {
9926            mParent.bringChildToFront(this);
9927        }
9928    }
9929
9930    /**
9931     * This is called in response to an internal scroll in this view (i.e., the
9932     * view scrolled its own contents). This is typically as a result of
9933     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9934     * called.
9935     *
9936     * @param l Current horizontal scroll origin.
9937     * @param t Current vertical scroll origin.
9938     * @param oldl Previous horizontal scroll origin.
9939     * @param oldt Previous vertical scroll origin.
9940     */
9941    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9942        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9943            postSendViewScrolledAccessibilityEventCallback();
9944        }
9945
9946        mBackgroundSizeChanged = true;
9947
9948        final AttachInfo ai = mAttachInfo;
9949        if (ai != null) {
9950            ai.mViewScrollChanged = true;
9951        }
9952
9953        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
9954            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
9955        }
9956    }
9957
9958    /**
9959     * Interface definition for a callback to be invoked when the scroll
9960     * position of a view changes.
9961     *
9962     * @hide Only used internally.
9963     */
9964    public interface OnScrollChangeListener {
9965        /**
9966         * Called when the scroll position of a view changes.
9967         *
9968         * @param v The view whose scroll position has changed.
9969         * @param scrollX Current horizontal scroll origin.
9970         * @param scrollY Current vertical scroll origin.
9971         * @param oldScrollX Previous horizontal scroll origin.
9972         * @param oldScrollY Previous vertical scroll origin.
9973         */
9974        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
9975    }
9976
9977    /**
9978     * Interface definition for a callback to be invoked when the layout bounds of a view
9979     * changes due to layout processing.
9980     */
9981    public interface OnLayoutChangeListener {
9982        /**
9983         * Called when the layout bounds of a view changes due to layout processing.
9984         *
9985         * @param v The view whose bounds have changed.
9986         * @param left The new value of the view's left property.
9987         * @param top The new value of the view's top property.
9988         * @param right The new value of the view's right property.
9989         * @param bottom The new value of the view's bottom property.
9990         * @param oldLeft The previous value of the view's left property.
9991         * @param oldTop The previous value of the view's top property.
9992         * @param oldRight The previous value of the view's right property.
9993         * @param oldBottom The previous value of the view's bottom property.
9994         */
9995        void onLayoutChange(View v, int left, int top, int right, int bottom,
9996            int oldLeft, int oldTop, int oldRight, int oldBottom);
9997    }
9998
9999    /**
10000     * This is called during layout when the size of this view has changed. If
10001     * you were just added to the view hierarchy, you're called with the old
10002     * values of 0.
10003     *
10004     * @param w Current width of this view.
10005     * @param h Current height of this view.
10006     * @param oldw Old width of this view.
10007     * @param oldh Old height of this view.
10008     */
10009    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10010    }
10011
10012    /**
10013     * Called by draw to draw the child views. This may be overridden
10014     * by derived classes to gain control just before its children are drawn
10015     * (but after its own view has been drawn).
10016     * @param canvas the canvas on which to draw the view
10017     */
10018    protected void dispatchDraw(Canvas canvas) {
10019
10020    }
10021
10022    /**
10023     * Gets the parent of this view. Note that the parent is a
10024     * ViewParent and not necessarily a View.
10025     *
10026     * @return Parent of this view.
10027     */
10028    public final ViewParent getParent() {
10029        return mParent;
10030    }
10031
10032    /**
10033     * Set the horizontal scrolled position of your view. This will cause a call to
10034     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10035     * invalidated.
10036     * @param value the x position to scroll to
10037     */
10038    public void setScrollX(int value) {
10039        scrollTo(value, mScrollY);
10040    }
10041
10042    /**
10043     * Set the vertical scrolled position of your view. This will cause a call to
10044     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10045     * invalidated.
10046     * @param value the y position to scroll to
10047     */
10048    public void setScrollY(int value) {
10049        scrollTo(mScrollX, value);
10050    }
10051
10052    /**
10053     * Return the scrolled left position of this view. This is the left edge of
10054     * the displayed part of your view. You do not need to draw any pixels
10055     * farther left, since those are outside of the frame of your view on
10056     * screen.
10057     *
10058     * @return The left edge of the displayed part of your view, in pixels.
10059     */
10060    public final int getScrollX() {
10061        return mScrollX;
10062    }
10063
10064    /**
10065     * Return the scrolled top position of this view. This is the top edge of
10066     * the displayed part of your view. You do not need to draw any pixels above
10067     * it, since those are outside of the frame of your view on screen.
10068     *
10069     * @return The top edge of the displayed part of your view, in pixels.
10070     */
10071    public final int getScrollY() {
10072        return mScrollY;
10073    }
10074
10075    /**
10076     * Return the width of the your view.
10077     *
10078     * @return The width of your view, in pixels.
10079     */
10080    @ViewDebug.ExportedProperty(category = "layout")
10081    public final int getWidth() {
10082        return mRight - mLeft;
10083    }
10084
10085    /**
10086     * Return the height of your view.
10087     *
10088     * @return The height of your view, in pixels.
10089     */
10090    @ViewDebug.ExportedProperty(category = "layout")
10091    public final int getHeight() {
10092        return mBottom - mTop;
10093    }
10094
10095    /**
10096     * Return the visible drawing bounds of your view. Fills in the output
10097     * rectangle with the values from getScrollX(), getScrollY(),
10098     * getWidth(), and getHeight(). These bounds do not account for any
10099     * transformation properties currently set on the view, such as
10100     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10101     *
10102     * @param outRect The (scrolled) drawing bounds of the view.
10103     */
10104    public void getDrawingRect(Rect outRect) {
10105        outRect.left = mScrollX;
10106        outRect.top = mScrollY;
10107        outRect.right = mScrollX + (mRight - mLeft);
10108        outRect.bottom = mScrollY + (mBottom - mTop);
10109    }
10110
10111    /**
10112     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10113     * raw width component (that is the result is masked by
10114     * {@link #MEASURED_SIZE_MASK}).
10115     *
10116     * @return The raw measured width of this view.
10117     */
10118    public final int getMeasuredWidth() {
10119        return mMeasuredWidth & MEASURED_SIZE_MASK;
10120    }
10121
10122    /**
10123     * Return the full width measurement information for this view as computed
10124     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10125     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10126     * This should be used during measurement and layout calculations only. Use
10127     * {@link #getWidth()} to see how wide a view is after layout.
10128     *
10129     * @return The measured width of this view as a bit mask.
10130     */
10131    public final int getMeasuredWidthAndState() {
10132        return mMeasuredWidth;
10133    }
10134
10135    /**
10136     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10137     * raw width component (that is the result is masked by
10138     * {@link #MEASURED_SIZE_MASK}).
10139     *
10140     * @return The raw measured height of this view.
10141     */
10142    public final int getMeasuredHeight() {
10143        return mMeasuredHeight & MEASURED_SIZE_MASK;
10144    }
10145
10146    /**
10147     * Return the full height measurement information for this view as computed
10148     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10149     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10150     * This should be used during measurement and layout calculations only. Use
10151     * {@link #getHeight()} to see how wide a view is after layout.
10152     *
10153     * @return The measured width of this view as a bit mask.
10154     */
10155    public final int getMeasuredHeightAndState() {
10156        return mMeasuredHeight;
10157    }
10158
10159    /**
10160     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10161     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10162     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10163     * and the height component is at the shifted bits
10164     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10165     */
10166    public final int getMeasuredState() {
10167        return (mMeasuredWidth&MEASURED_STATE_MASK)
10168                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10169                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10170    }
10171
10172    /**
10173     * The transform matrix of this view, which is calculated based on the current
10174     * rotation, scale, and pivot properties.
10175     *
10176     * @see #getRotation()
10177     * @see #getScaleX()
10178     * @see #getScaleY()
10179     * @see #getPivotX()
10180     * @see #getPivotY()
10181     * @return The current transform matrix for the view
10182     */
10183    public Matrix getMatrix() {
10184        ensureTransformationInfo();
10185        final Matrix matrix = mTransformationInfo.mMatrix;
10186        mRenderNode.getMatrix(matrix);
10187        return matrix;
10188    }
10189
10190    /**
10191     * Returns true if the transform matrix is the identity matrix.
10192     * Recomputes the matrix if necessary.
10193     *
10194     * @return True if the transform matrix is the identity matrix, false otherwise.
10195     */
10196    final boolean hasIdentityMatrix() {
10197        return mRenderNode.hasIdentityMatrix();
10198    }
10199
10200    void ensureTransformationInfo() {
10201        if (mTransformationInfo == null) {
10202            mTransformationInfo = new TransformationInfo();
10203        }
10204    }
10205
10206   /**
10207     * Utility method to retrieve the inverse of the current mMatrix property.
10208     * We cache the matrix to avoid recalculating it when transform properties
10209     * have not changed.
10210     *
10211     * @return The inverse of the current matrix of this view.
10212     * @hide
10213     */
10214    public final Matrix getInverseMatrix() {
10215        ensureTransformationInfo();
10216        if (mTransformationInfo.mInverseMatrix == null) {
10217            mTransformationInfo.mInverseMatrix = new Matrix();
10218        }
10219        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10220        mRenderNode.getInverseMatrix(matrix);
10221        return matrix;
10222    }
10223
10224    /**
10225     * Gets the distance along the Z axis from the camera to this view.
10226     *
10227     * @see #setCameraDistance(float)
10228     *
10229     * @return The distance along the Z axis.
10230     */
10231    public float getCameraDistance() {
10232        final float dpi = mResources.getDisplayMetrics().densityDpi;
10233        return -(mRenderNode.getCameraDistance() * dpi);
10234    }
10235
10236    /**
10237     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10238     * views are drawn) from the camera to this view. The camera's distance
10239     * affects 3D transformations, for instance rotations around the X and Y
10240     * axis. If the rotationX or rotationY properties are changed and this view is
10241     * large (more than half the size of the screen), it is recommended to always
10242     * use a camera distance that's greater than the height (X axis rotation) or
10243     * the width (Y axis rotation) of this view.</p>
10244     *
10245     * <p>The distance of the camera from the view plane can have an affect on the
10246     * perspective distortion of the view when it is rotated around the x or y axis.
10247     * For example, a large distance will result in a large viewing angle, and there
10248     * will not be much perspective distortion of the view as it rotates. A short
10249     * distance may cause much more perspective distortion upon rotation, and can
10250     * also result in some drawing artifacts if the rotated view ends up partially
10251     * behind the camera (which is why the recommendation is to use a distance at
10252     * least as far as the size of the view, if the view is to be rotated.)</p>
10253     *
10254     * <p>The distance is expressed in "depth pixels." The default distance depends
10255     * on the screen density. For instance, on a medium density display, the
10256     * default distance is 1280. On a high density display, the default distance
10257     * is 1920.</p>
10258     *
10259     * <p>If you want to specify a distance that leads to visually consistent
10260     * results across various densities, use the following formula:</p>
10261     * <pre>
10262     * float scale = context.getResources().getDisplayMetrics().density;
10263     * view.setCameraDistance(distance * scale);
10264     * </pre>
10265     *
10266     * <p>The density scale factor of a high density display is 1.5,
10267     * and 1920 = 1280 * 1.5.</p>
10268     *
10269     * @param distance The distance in "depth pixels", if negative the opposite
10270     *        value is used
10271     *
10272     * @see #setRotationX(float)
10273     * @see #setRotationY(float)
10274     */
10275    public void setCameraDistance(float distance) {
10276        final float dpi = mResources.getDisplayMetrics().densityDpi;
10277
10278        invalidateViewProperty(true, false);
10279        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10280        invalidateViewProperty(false, false);
10281
10282        invalidateParentIfNeededAndWasQuickRejected();
10283    }
10284
10285    /**
10286     * The degrees that the view is rotated around the pivot point.
10287     *
10288     * @see #setRotation(float)
10289     * @see #getPivotX()
10290     * @see #getPivotY()
10291     *
10292     * @return The degrees of rotation.
10293     */
10294    @ViewDebug.ExportedProperty(category = "drawing")
10295    public float getRotation() {
10296        return mRenderNode.getRotation();
10297    }
10298
10299    /**
10300     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10301     * result in clockwise rotation.
10302     *
10303     * @param rotation The degrees of rotation.
10304     *
10305     * @see #getRotation()
10306     * @see #getPivotX()
10307     * @see #getPivotY()
10308     * @see #setRotationX(float)
10309     * @see #setRotationY(float)
10310     *
10311     * @attr ref android.R.styleable#View_rotation
10312     */
10313    public void setRotation(float rotation) {
10314        if (rotation != getRotation()) {
10315            // Double-invalidation is necessary to capture view's old and new areas
10316            invalidateViewProperty(true, false);
10317            mRenderNode.setRotation(rotation);
10318            invalidateViewProperty(false, true);
10319
10320            invalidateParentIfNeededAndWasQuickRejected();
10321            notifySubtreeAccessibilityStateChangedIfNeeded();
10322        }
10323    }
10324
10325    /**
10326     * The degrees that the view is rotated around the vertical axis through the pivot point.
10327     *
10328     * @see #getPivotX()
10329     * @see #getPivotY()
10330     * @see #setRotationY(float)
10331     *
10332     * @return The degrees of Y rotation.
10333     */
10334    @ViewDebug.ExportedProperty(category = "drawing")
10335    public float getRotationY() {
10336        return mRenderNode.getRotationY();
10337    }
10338
10339    /**
10340     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10341     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10342     * down the y axis.
10343     *
10344     * When rotating large views, it is recommended to adjust the camera distance
10345     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10346     *
10347     * @param rotationY The degrees of Y rotation.
10348     *
10349     * @see #getRotationY()
10350     * @see #getPivotX()
10351     * @see #getPivotY()
10352     * @see #setRotation(float)
10353     * @see #setRotationX(float)
10354     * @see #setCameraDistance(float)
10355     *
10356     * @attr ref android.R.styleable#View_rotationY
10357     */
10358    public void setRotationY(float rotationY) {
10359        if (rotationY != getRotationY()) {
10360            invalidateViewProperty(true, false);
10361            mRenderNode.setRotationY(rotationY);
10362            invalidateViewProperty(false, true);
10363
10364            invalidateParentIfNeededAndWasQuickRejected();
10365            notifySubtreeAccessibilityStateChangedIfNeeded();
10366        }
10367    }
10368
10369    /**
10370     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10371     *
10372     * @see #getPivotX()
10373     * @see #getPivotY()
10374     * @see #setRotationX(float)
10375     *
10376     * @return The degrees of X rotation.
10377     */
10378    @ViewDebug.ExportedProperty(category = "drawing")
10379    public float getRotationX() {
10380        return mRenderNode.getRotationX();
10381    }
10382
10383    /**
10384     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10385     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10386     * x axis.
10387     *
10388     * When rotating large views, it is recommended to adjust the camera distance
10389     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10390     *
10391     * @param rotationX The degrees of X rotation.
10392     *
10393     * @see #getRotationX()
10394     * @see #getPivotX()
10395     * @see #getPivotY()
10396     * @see #setRotation(float)
10397     * @see #setRotationY(float)
10398     * @see #setCameraDistance(float)
10399     *
10400     * @attr ref android.R.styleable#View_rotationX
10401     */
10402    public void setRotationX(float rotationX) {
10403        if (rotationX != getRotationX()) {
10404            invalidateViewProperty(true, false);
10405            mRenderNode.setRotationX(rotationX);
10406            invalidateViewProperty(false, true);
10407
10408            invalidateParentIfNeededAndWasQuickRejected();
10409            notifySubtreeAccessibilityStateChangedIfNeeded();
10410        }
10411    }
10412
10413    /**
10414     * The amount that the view is scaled in x around the pivot point, as a proportion of
10415     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10416     *
10417     * <p>By default, this is 1.0f.
10418     *
10419     * @see #getPivotX()
10420     * @see #getPivotY()
10421     * @return The scaling factor.
10422     */
10423    @ViewDebug.ExportedProperty(category = "drawing")
10424    public float getScaleX() {
10425        return mRenderNode.getScaleX();
10426    }
10427
10428    /**
10429     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10430     * the view's unscaled width. A value of 1 means that no scaling is applied.
10431     *
10432     * @param scaleX The scaling factor.
10433     * @see #getPivotX()
10434     * @see #getPivotY()
10435     *
10436     * @attr ref android.R.styleable#View_scaleX
10437     */
10438    public void setScaleX(float scaleX) {
10439        if (scaleX != getScaleX()) {
10440            invalidateViewProperty(true, false);
10441            mRenderNode.setScaleX(scaleX);
10442            invalidateViewProperty(false, true);
10443
10444            invalidateParentIfNeededAndWasQuickRejected();
10445            notifySubtreeAccessibilityStateChangedIfNeeded();
10446        }
10447    }
10448
10449    /**
10450     * The amount that the view is scaled in y around the pivot point, as a proportion of
10451     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10452     *
10453     * <p>By default, this is 1.0f.
10454     *
10455     * @see #getPivotX()
10456     * @see #getPivotY()
10457     * @return The scaling factor.
10458     */
10459    @ViewDebug.ExportedProperty(category = "drawing")
10460    public float getScaleY() {
10461        return mRenderNode.getScaleY();
10462    }
10463
10464    /**
10465     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10466     * the view's unscaled width. A value of 1 means that no scaling is applied.
10467     *
10468     * @param scaleY The scaling factor.
10469     * @see #getPivotX()
10470     * @see #getPivotY()
10471     *
10472     * @attr ref android.R.styleable#View_scaleY
10473     */
10474    public void setScaleY(float scaleY) {
10475        if (scaleY != getScaleY()) {
10476            invalidateViewProperty(true, false);
10477            mRenderNode.setScaleY(scaleY);
10478            invalidateViewProperty(false, true);
10479
10480            invalidateParentIfNeededAndWasQuickRejected();
10481            notifySubtreeAccessibilityStateChangedIfNeeded();
10482        }
10483    }
10484
10485    /**
10486     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10487     * and {@link #setScaleX(float) scaled}.
10488     *
10489     * @see #getRotation()
10490     * @see #getScaleX()
10491     * @see #getScaleY()
10492     * @see #getPivotY()
10493     * @return The x location of the pivot point.
10494     *
10495     * @attr ref android.R.styleable#View_transformPivotX
10496     */
10497    @ViewDebug.ExportedProperty(category = "drawing")
10498    public float getPivotX() {
10499        return mRenderNode.getPivotX();
10500    }
10501
10502    /**
10503     * Sets the x location of the point around which the view is
10504     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10505     * By default, the pivot point is centered on the object.
10506     * Setting this property disables this behavior and causes the view to use only the
10507     * explicitly set pivotX and pivotY values.
10508     *
10509     * @param pivotX The x location of the pivot point.
10510     * @see #getRotation()
10511     * @see #getScaleX()
10512     * @see #getScaleY()
10513     * @see #getPivotY()
10514     *
10515     * @attr ref android.R.styleable#View_transformPivotX
10516     */
10517    public void setPivotX(float pivotX) {
10518        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10519            invalidateViewProperty(true, false);
10520            mRenderNode.setPivotX(pivotX);
10521            invalidateViewProperty(false, true);
10522
10523            invalidateParentIfNeededAndWasQuickRejected();
10524        }
10525    }
10526
10527    /**
10528     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10529     * and {@link #setScaleY(float) scaled}.
10530     *
10531     * @see #getRotation()
10532     * @see #getScaleX()
10533     * @see #getScaleY()
10534     * @see #getPivotY()
10535     * @return The y location of the pivot point.
10536     *
10537     * @attr ref android.R.styleable#View_transformPivotY
10538     */
10539    @ViewDebug.ExportedProperty(category = "drawing")
10540    public float getPivotY() {
10541        return mRenderNode.getPivotY();
10542    }
10543
10544    /**
10545     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10546     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10547     * Setting this property disables this behavior and causes the view to use only the
10548     * explicitly set pivotX and pivotY values.
10549     *
10550     * @param pivotY The y location of the pivot point.
10551     * @see #getRotation()
10552     * @see #getScaleX()
10553     * @see #getScaleY()
10554     * @see #getPivotY()
10555     *
10556     * @attr ref android.R.styleable#View_transformPivotY
10557     */
10558    public void setPivotY(float pivotY) {
10559        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10560            invalidateViewProperty(true, false);
10561            mRenderNode.setPivotY(pivotY);
10562            invalidateViewProperty(false, true);
10563
10564            invalidateParentIfNeededAndWasQuickRejected();
10565        }
10566    }
10567
10568    /**
10569     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10570     * completely transparent and 1 means the view is completely opaque.
10571     *
10572     * <p>By default this is 1.0f.
10573     * @return The opacity of the view.
10574     */
10575    @ViewDebug.ExportedProperty(category = "drawing")
10576    public float getAlpha() {
10577        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10578    }
10579
10580    /**
10581     * Returns whether this View has content which overlaps.
10582     *
10583     * <p>This function, intended to be overridden by specific View types, is an optimization when
10584     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10585     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10586     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10587     * directly. An example of overlapping rendering is a TextView with a background image, such as
10588     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10589     * ImageView with only the foreground image. The default implementation returns true; subclasses
10590     * should override if they have cases which can be optimized.</p>
10591     *
10592     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10593     * necessitates that a View return true if it uses the methods internally without passing the
10594     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10595     *
10596     * @return true if the content in this view might overlap, false otherwise.
10597     */
10598    @ViewDebug.ExportedProperty(category = "drawing")
10599    public boolean hasOverlappingRendering() {
10600        return true;
10601    }
10602
10603    /**
10604     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10605     * completely transparent and 1 means the view is completely opaque.</p>
10606     *
10607     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10608     * performance implications, especially for large views. It is best to use the alpha property
10609     * sparingly and transiently, as in the case of fading animations.</p>
10610     *
10611     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10612     * strongly recommended for performance reasons to either override
10613     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10614     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10615     *
10616     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10617     * responsible for applying the opacity itself.</p>
10618     *
10619     * <p>Note that if the view is backed by a
10620     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10621     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10622     * 1.0 will supersede the alpha of the layer paint.</p>
10623     *
10624     * @param alpha The opacity of the view.
10625     *
10626     * @see #hasOverlappingRendering()
10627     * @see #setLayerType(int, android.graphics.Paint)
10628     *
10629     * @attr ref android.R.styleable#View_alpha
10630     */
10631    public void setAlpha(float alpha) {
10632        ensureTransformationInfo();
10633        if (mTransformationInfo.mAlpha != alpha) {
10634            mTransformationInfo.mAlpha = alpha;
10635            if (onSetAlpha((int) (alpha * 255))) {
10636                mPrivateFlags |= PFLAG_ALPHA_SET;
10637                // subclass is handling alpha - don't optimize rendering cache invalidation
10638                invalidateParentCaches();
10639                invalidate(true);
10640            } else {
10641                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10642                invalidateViewProperty(true, false);
10643                mRenderNode.setAlpha(getFinalAlpha());
10644                notifyViewAccessibilityStateChangedIfNeeded(
10645                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10646            }
10647        }
10648    }
10649
10650    /**
10651     * Faster version of setAlpha() which performs the same steps except there are
10652     * no calls to invalidate(). The caller of this function should perform proper invalidation
10653     * on the parent and this object. The return value indicates whether the subclass handles
10654     * alpha (the return value for onSetAlpha()).
10655     *
10656     * @param alpha The new value for the alpha property
10657     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10658     *         the new value for the alpha property is different from the old value
10659     */
10660    boolean setAlphaNoInvalidation(float alpha) {
10661        ensureTransformationInfo();
10662        if (mTransformationInfo.mAlpha != alpha) {
10663            mTransformationInfo.mAlpha = alpha;
10664            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10665            if (subclassHandlesAlpha) {
10666                mPrivateFlags |= PFLAG_ALPHA_SET;
10667                return true;
10668            } else {
10669                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10670                mRenderNode.setAlpha(getFinalAlpha());
10671            }
10672        }
10673        return false;
10674    }
10675
10676    /**
10677     * This property is hidden and intended only for use by the Fade transition, which
10678     * animates it to produce a visual translucency that does not side-effect (or get
10679     * affected by) the real alpha property. This value is composited with the other
10680     * alpha value (and the AlphaAnimation value, when that is present) to produce
10681     * a final visual translucency result, which is what is passed into the DisplayList.
10682     *
10683     * @hide
10684     */
10685    public void setTransitionAlpha(float alpha) {
10686        ensureTransformationInfo();
10687        if (mTransformationInfo.mTransitionAlpha != alpha) {
10688            mTransformationInfo.mTransitionAlpha = alpha;
10689            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10690            invalidateViewProperty(true, false);
10691            mRenderNode.setAlpha(getFinalAlpha());
10692        }
10693    }
10694
10695    /**
10696     * Calculates the visual alpha of this view, which is a combination of the actual
10697     * alpha value and the transitionAlpha value (if set).
10698     */
10699    private float getFinalAlpha() {
10700        if (mTransformationInfo != null) {
10701            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10702        }
10703        return 1;
10704    }
10705
10706    /**
10707     * This property is hidden and intended only for use by the Fade transition, which
10708     * animates it to produce a visual translucency that does not side-effect (or get
10709     * affected by) the real alpha property. This value is composited with the other
10710     * alpha value (and the AlphaAnimation value, when that is present) to produce
10711     * a final visual translucency result, which is what is passed into the DisplayList.
10712     *
10713     * @hide
10714     */
10715    @ViewDebug.ExportedProperty(category = "drawing")
10716    public float getTransitionAlpha() {
10717        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10718    }
10719
10720    /**
10721     * Top position of this view relative to its parent.
10722     *
10723     * @return The top of this view, in pixels.
10724     */
10725    @ViewDebug.CapturedViewProperty
10726    public final int getTop() {
10727        return mTop;
10728    }
10729
10730    /**
10731     * Sets the top position of this view relative to its parent. This method is meant to be called
10732     * by the layout system and should not generally be called otherwise, because the property
10733     * may be changed at any time by the layout.
10734     *
10735     * @param top The top of this view, in pixels.
10736     */
10737    public final void setTop(int top) {
10738        if (top != mTop) {
10739            final boolean matrixIsIdentity = hasIdentityMatrix();
10740            if (matrixIsIdentity) {
10741                if (mAttachInfo != null) {
10742                    int minTop;
10743                    int yLoc;
10744                    if (top < mTop) {
10745                        minTop = top;
10746                        yLoc = top - mTop;
10747                    } else {
10748                        minTop = mTop;
10749                        yLoc = 0;
10750                    }
10751                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10752                }
10753            } else {
10754                // Double-invalidation is necessary to capture view's old and new areas
10755                invalidate(true);
10756            }
10757
10758            int width = mRight - mLeft;
10759            int oldHeight = mBottom - mTop;
10760
10761            mTop = top;
10762            mRenderNode.setTop(mTop);
10763
10764            sizeChange(width, mBottom - mTop, width, oldHeight);
10765
10766            if (!matrixIsIdentity) {
10767                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10768                invalidate(true);
10769            }
10770            mBackgroundSizeChanged = true;
10771            invalidateParentIfNeeded();
10772            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10773                // View was rejected last time it was drawn by its parent; this may have changed
10774                invalidateParentIfNeeded();
10775            }
10776        }
10777    }
10778
10779    /**
10780     * Bottom position of this view relative to its parent.
10781     *
10782     * @return The bottom of this view, in pixels.
10783     */
10784    @ViewDebug.CapturedViewProperty
10785    public final int getBottom() {
10786        return mBottom;
10787    }
10788
10789    /**
10790     * True if this view has changed since the last time being drawn.
10791     *
10792     * @return The dirty state of this view.
10793     */
10794    public boolean isDirty() {
10795        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10796    }
10797
10798    /**
10799     * Sets the bottom position of this view relative to its parent. This method is meant to be
10800     * called by the layout system and should not generally be called otherwise, because the
10801     * property may be changed at any time by the layout.
10802     *
10803     * @param bottom The bottom of this view, in pixels.
10804     */
10805    public final void setBottom(int bottom) {
10806        if (bottom != mBottom) {
10807            final boolean matrixIsIdentity = hasIdentityMatrix();
10808            if (matrixIsIdentity) {
10809                if (mAttachInfo != null) {
10810                    int maxBottom;
10811                    if (bottom < mBottom) {
10812                        maxBottom = mBottom;
10813                    } else {
10814                        maxBottom = bottom;
10815                    }
10816                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10817                }
10818            } else {
10819                // Double-invalidation is necessary to capture view's old and new areas
10820                invalidate(true);
10821            }
10822
10823            int width = mRight - mLeft;
10824            int oldHeight = mBottom - mTop;
10825
10826            mBottom = bottom;
10827            mRenderNode.setBottom(mBottom);
10828
10829            sizeChange(width, mBottom - mTop, width, oldHeight);
10830
10831            if (!matrixIsIdentity) {
10832                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10833                invalidate(true);
10834            }
10835            mBackgroundSizeChanged = true;
10836            invalidateParentIfNeeded();
10837            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10838                // View was rejected last time it was drawn by its parent; this may have changed
10839                invalidateParentIfNeeded();
10840            }
10841        }
10842    }
10843
10844    /**
10845     * Left position of this view relative to its parent.
10846     *
10847     * @return The left edge of this view, in pixels.
10848     */
10849    @ViewDebug.CapturedViewProperty
10850    public final int getLeft() {
10851        return mLeft;
10852    }
10853
10854    /**
10855     * Sets the left position of this view relative to its parent. This method is meant to be called
10856     * by the layout system and should not generally be called otherwise, because the property
10857     * may be changed at any time by the layout.
10858     *
10859     * @param left The left of this view, in pixels.
10860     */
10861    public final void setLeft(int left) {
10862        if (left != mLeft) {
10863            final boolean matrixIsIdentity = hasIdentityMatrix();
10864            if (matrixIsIdentity) {
10865                if (mAttachInfo != null) {
10866                    int minLeft;
10867                    int xLoc;
10868                    if (left < mLeft) {
10869                        minLeft = left;
10870                        xLoc = left - mLeft;
10871                    } else {
10872                        minLeft = mLeft;
10873                        xLoc = 0;
10874                    }
10875                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10876                }
10877            } else {
10878                // Double-invalidation is necessary to capture view's old and new areas
10879                invalidate(true);
10880            }
10881
10882            int oldWidth = mRight - mLeft;
10883            int height = mBottom - mTop;
10884
10885            mLeft = left;
10886            mRenderNode.setLeft(left);
10887
10888            sizeChange(mRight - mLeft, height, oldWidth, height);
10889
10890            if (!matrixIsIdentity) {
10891                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10892                invalidate(true);
10893            }
10894            mBackgroundSizeChanged = true;
10895            invalidateParentIfNeeded();
10896            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10897                // View was rejected last time it was drawn by its parent; this may have changed
10898                invalidateParentIfNeeded();
10899            }
10900        }
10901    }
10902
10903    /**
10904     * Right position of this view relative to its parent.
10905     *
10906     * @return The right edge of this view, in pixels.
10907     */
10908    @ViewDebug.CapturedViewProperty
10909    public final int getRight() {
10910        return mRight;
10911    }
10912
10913    /**
10914     * Sets the right position of this view relative to its parent. This method is meant to be called
10915     * by the layout system and should not generally be called otherwise, because the property
10916     * may be changed at any time by the layout.
10917     *
10918     * @param right The right of this view, in pixels.
10919     */
10920    public final void setRight(int right) {
10921        if (right != mRight) {
10922            final boolean matrixIsIdentity = hasIdentityMatrix();
10923            if (matrixIsIdentity) {
10924                if (mAttachInfo != null) {
10925                    int maxRight;
10926                    if (right < mRight) {
10927                        maxRight = mRight;
10928                    } else {
10929                        maxRight = right;
10930                    }
10931                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10932                }
10933            } else {
10934                // Double-invalidation is necessary to capture view's old and new areas
10935                invalidate(true);
10936            }
10937
10938            int oldWidth = mRight - mLeft;
10939            int height = mBottom - mTop;
10940
10941            mRight = right;
10942            mRenderNode.setRight(mRight);
10943
10944            sizeChange(mRight - mLeft, height, oldWidth, height);
10945
10946            if (!matrixIsIdentity) {
10947                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10948                invalidate(true);
10949            }
10950            mBackgroundSizeChanged = true;
10951            invalidateParentIfNeeded();
10952            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10953                // View was rejected last time it was drawn by its parent; this may have changed
10954                invalidateParentIfNeeded();
10955            }
10956        }
10957    }
10958
10959    /**
10960     * The visual x position of this view, in pixels. This is equivalent to the
10961     * {@link #setTranslationX(float) translationX} property plus the current
10962     * {@link #getLeft() left} property.
10963     *
10964     * @return The visual x position of this view, in pixels.
10965     */
10966    @ViewDebug.ExportedProperty(category = "drawing")
10967    public float getX() {
10968        return mLeft + getTranslationX();
10969    }
10970
10971    /**
10972     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10973     * {@link #setTranslationX(float) translationX} property to be the difference between
10974     * the x value passed in and the current {@link #getLeft() left} property.
10975     *
10976     * @param x The visual x position of this view, in pixels.
10977     */
10978    public void setX(float x) {
10979        setTranslationX(x - mLeft);
10980    }
10981
10982    /**
10983     * The visual y position of this view, in pixels. This is equivalent to the
10984     * {@link #setTranslationY(float) translationY} property plus the current
10985     * {@link #getTop() top} property.
10986     *
10987     * @return The visual y position of this view, in pixels.
10988     */
10989    @ViewDebug.ExportedProperty(category = "drawing")
10990    public float getY() {
10991        return mTop + getTranslationY();
10992    }
10993
10994    /**
10995     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10996     * {@link #setTranslationY(float) translationY} property to be the difference between
10997     * the y value passed in and the current {@link #getTop() top} property.
10998     *
10999     * @param y The visual y position of this view, in pixels.
11000     */
11001    public void setY(float y) {
11002        setTranslationY(y - mTop);
11003    }
11004
11005    /**
11006     * The visual z position of this view, in pixels. This is equivalent to the
11007     * {@link #setTranslationZ(float) translationZ} property plus the current
11008     * {@link #getElevation() elevation} property.
11009     *
11010     * @return The visual z position of this view, in pixels.
11011     */
11012    @ViewDebug.ExportedProperty(category = "drawing")
11013    public float getZ() {
11014        return getElevation() + getTranslationZ();
11015    }
11016
11017    /**
11018     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11019     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11020     * the x value passed in and the current {@link #getElevation() elevation} property.
11021     *
11022     * @param z The visual z position of this view, in pixels.
11023     */
11024    public void setZ(float z) {
11025        setTranslationZ(z - getElevation());
11026    }
11027
11028    /**
11029     * The base elevation of this view relative to its parent, in pixels.
11030     *
11031     * @return The base depth position of the view, in pixels.
11032     */
11033    @ViewDebug.ExportedProperty(category = "drawing")
11034    public float getElevation() {
11035        return mRenderNode.getElevation();
11036    }
11037
11038    /**
11039     * Sets the base elevation of this view, in pixels.
11040     *
11041     * @attr ref android.R.styleable#View_elevation
11042     */
11043    public void setElevation(float elevation) {
11044        if (elevation != getElevation()) {
11045            invalidateViewProperty(true, false);
11046            mRenderNode.setElevation(elevation);
11047            invalidateViewProperty(false, true);
11048
11049            invalidateParentIfNeededAndWasQuickRejected();
11050        }
11051    }
11052
11053    /**
11054     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11055     * This position is post-layout, in addition to wherever the object's
11056     * layout placed it.
11057     *
11058     * @return The horizontal position of this view relative to its left position, in pixels.
11059     */
11060    @ViewDebug.ExportedProperty(category = "drawing")
11061    public float getTranslationX() {
11062        return mRenderNode.getTranslationX();
11063    }
11064
11065    /**
11066     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11067     * This effectively positions the object post-layout, in addition to wherever the object's
11068     * layout placed it.
11069     *
11070     * @param translationX The horizontal position of this view relative to its left position,
11071     * in pixels.
11072     *
11073     * @attr ref android.R.styleable#View_translationX
11074     */
11075    public void setTranslationX(float translationX) {
11076        if (translationX != getTranslationX()) {
11077            invalidateViewProperty(true, false);
11078            mRenderNode.setTranslationX(translationX);
11079            invalidateViewProperty(false, true);
11080
11081            invalidateParentIfNeededAndWasQuickRejected();
11082            notifySubtreeAccessibilityStateChangedIfNeeded();
11083        }
11084    }
11085
11086    /**
11087     * The vertical location of this view relative to its {@link #getTop() top} position.
11088     * This position is post-layout, in addition to wherever the object's
11089     * layout placed it.
11090     *
11091     * @return The vertical position of this view relative to its top position,
11092     * in pixels.
11093     */
11094    @ViewDebug.ExportedProperty(category = "drawing")
11095    public float getTranslationY() {
11096        return mRenderNode.getTranslationY();
11097    }
11098
11099    /**
11100     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11101     * This effectively positions the object post-layout, in addition to wherever the object's
11102     * layout placed it.
11103     *
11104     * @param translationY The vertical position of this view relative to its top position,
11105     * in pixels.
11106     *
11107     * @attr ref android.R.styleable#View_translationY
11108     */
11109    public void setTranslationY(float translationY) {
11110        if (translationY != getTranslationY()) {
11111            invalidateViewProperty(true, false);
11112            mRenderNode.setTranslationY(translationY);
11113            invalidateViewProperty(false, true);
11114
11115            invalidateParentIfNeededAndWasQuickRejected();
11116        }
11117    }
11118
11119    /**
11120     * The depth location of this view relative to its {@link #getElevation() elevation}.
11121     *
11122     * @return The depth of this view relative to its elevation.
11123     */
11124    @ViewDebug.ExportedProperty(category = "drawing")
11125    public float getTranslationZ() {
11126        return mRenderNode.getTranslationZ();
11127    }
11128
11129    /**
11130     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11131     *
11132     * @attr ref android.R.styleable#View_translationZ
11133     */
11134    public void setTranslationZ(float translationZ) {
11135        if (translationZ != getTranslationZ()) {
11136            invalidateViewProperty(true, false);
11137            mRenderNode.setTranslationZ(translationZ);
11138            invalidateViewProperty(false, true);
11139
11140            invalidateParentIfNeededAndWasQuickRejected();
11141        }
11142    }
11143
11144    /** @hide */
11145    public void setAnimationMatrix(Matrix matrix) {
11146        invalidateViewProperty(true, false);
11147        mRenderNode.setAnimationMatrix(matrix);
11148        invalidateViewProperty(false, true);
11149
11150        invalidateParentIfNeededAndWasQuickRejected();
11151    }
11152
11153    /**
11154     * Returns the current StateListAnimator if exists.
11155     *
11156     * @return StateListAnimator or null if it does not exists
11157     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11158     */
11159    public StateListAnimator getStateListAnimator() {
11160        return mStateListAnimator;
11161    }
11162
11163    /**
11164     * Attaches the provided StateListAnimator to this View.
11165     * <p>
11166     * Any previously attached StateListAnimator will be detached.
11167     *
11168     * @param stateListAnimator The StateListAnimator to update the view
11169     * @see {@link android.animation.StateListAnimator}
11170     */
11171    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11172        if (mStateListAnimator == stateListAnimator) {
11173            return;
11174        }
11175        if (mStateListAnimator != null) {
11176            mStateListAnimator.setTarget(null);
11177        }
11178        mStateListAnimator = stateListAnimator;
11179        if (stateListAnimator != null) {
11180            stateListAnimator.setTarget(this);
11181            if (isAttachedToWindow()) {
11182                stateListAnimator.setState(getDrawableState());
11183            }
11184        }
11185    }
11186
11187    /**
11188     * Returns whether the Outline should be used to clip the contents of the View.
11189     * <p>
11190     * Note that this flag will only be respected if the View's Outline returns true from
11191     * {@link Outline#canClip()}.
11192     *
11193     * @see #setOutlineProvider(ViewOutlineProvider)
11194     * @see #setClipToOutline(boolean)
11195     */
11196    public final boolean getClipToOutline() {
11197        return mRenderNode.getClipToOutline();
11198    }
11199
11200    /**
11201     * Sets whether the View's Outline should be used to clip the contents of the View.
11202     * <p>
11203     * Only a single non-rectangular clip can be applied on a View at any time.
11204     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11205     * circular reveal} animation take priority over Outline clipping, and
11206     * child Outline clipping takes priority over Outline clipping done by a
11207     * parent.
11208     * <p>
11209     * Note that this flag will only be respected if the View's Outline returns true from
11210     * {@link Outline#canClip()}.
11211     *
11212     * @see #setOutlineProvider(ViewOutlineProvider)
11213     * @see #getClipToOutline()
11214     */
11215    public void setClipToOutline(boolean clipToOutline) {
11216        damageInParent();
11217        if (getClipToOutline() != clipToOutline) {
11218            mRenderNode.setClipToOutline(clipToOutline);
11219        }
11220    }
11221
11222    // correspond to the enum values of View_outlineProvider
11223    private static final int PROVIDER_BACKGROUND = 0;
11224    private static final int PROVIDER_NONE = 1;
11225    private static final int PROVIDER_BOUNDS = 2;
11226    private static final int PROVIDER_PADDED_BOUNDS = 3;
11227    private void setOutlineProviderFromAttribute(int providerInt) {
11228        switch (providerInt) {
11229            case PROVIDER_BACKGROUND:
11230                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11231                break;
11232            case PROVIDER_NONE:
11233                setOutlineProvider(null);
11234                break;
11235            case PROVIDER_BOUNDS:
11236                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11237                break;
11238            case PROVIDER_PADDED_BOUNDS:
11239                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11240                break;
11241        }
11242    }
11243
11244    /**
11245     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11246     * the shape of the shadow it casts, and enables outline clipping.
11247     * <p>
11248     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11249     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11250     * outline provider with this method allows this behavior to be overridden.
11251     * <p>
11252     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11253     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11254     * <p>
11255     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11256     *
11257     * @see #setClipToOutline(boolean)
11258     * @see #getClipToOutline()
11259     * @see #getOutlineProvider()
11260     */
11261    public void setOutlineProvider(ViewOutlineProvider provider) {
11262        mOutlineProvider = provider;
11263        invalidateOutline();
11264    }
11265
11266    /**
11267     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11268     * that defines the shape of the shadow it casts, and enables outline clipping.
11269     *
11270     * @see #setOutlineProvider(ViewOutlineProvider)
11271     */
11272    public ViewOutlineProvider getOutlineProvider() {
11273        return mOutlineProvider;
11274    }
11275
11276    /**
11277     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11278     *
11279     * @see #setOutlineProvider(ViewOutlineProvider)
11280     */
11281    public void invalidateOutline() {
11282        rebuildOutline();
11283
11284        notifySubtreeAccessibilityStateChangedIfNeeded();
11285        invalidateViewProperty(false, false);
11286    }
11287
11288    /**
11289     * Internal version of {@link #invalidateOutline()} which invalidates the
11290     * outline without invalidating the view itself. This is intended to be called from
11291     * within methods in the View class itself which are the result of the view being
11292     * invalidated already. For example, when we are drawing the background of a View,
11293     * we invalidate the outline in case it changed in the meantime, but we do not
11294     * need to invalidate the view because we're already drawing the background as part
11295     * of drawing the view in response to an earlier invalidation of the view.
11296     */
11297    private void rebuildOutline() {
11298        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11299        if (mAttachInfo == null) return;
11300
11301        if (mOutlineProvider == null) {
11302            // no provider, remove outline
11303            mRenderNode.setOutline(null);
11304        } else {
11305            final Outline outline = mAttachInfo.mTmpOutline;
11306            outline.setEmpty();
11307            outline.setAlpha(1.0f);
11308
11309            mOutlineProvider.getOutline(this, outline);
11310            mRenderNode.setOutline(outline);
11311        }
11312    }
11313
11314    /**
11315     * HierarchyViewer only
11316     *
11317     * @hide
11318     */
11319    @ViewDebug.ExportedProperty(category = "drawing")
11320    public boolean hasShadow() {
11321        return mRenderNode.hasShadow();
11322    }
11323
11324
11325    /** @hide */
11326    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11327        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11328        invalidateViewProperty(false, false);
11329    }
11330
11331    /**
11332     * Hit rectangle in parent's coordinates
11333     *
11334     * @param outRect The hit rectangle of the view.
11335     */
11336    public void getHitRect(Rect outRect) {
11337        if (hasIdentityMatrix() || mAttachInfo == null) {
11338            outRect.set(mLeft, mTop, mRight, mBottom);
11339        } else {
11340            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11341            tmpRect.set(0, 0, getWidth(), getHeight());
11342            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11343            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11344                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11345        }
11346    }
11347
11348    /**
11349     * Determines whether the given point, in local coordinates is inside the view.
11350     */
11351    /*package*/ final boolean pointInView(float localX, float localY) {
11352        return localX >= 0 && localX < (mRight - mLeft)
11353                && localY >= 0 && localY < (mBottom - mTop);
11354    }
11355
11356    /**
11357     * Utility method to determine whether the given point, in local coordinates,
11358     * is inside the view, where the area of the view is expanded by the slop factor.
11359     * This method is called while processing touch-move events to determine if the event
11360     * is still within the view.
11361     *
11362     * @hide
11363     */
11364    public boolean pointInView(float localX, float localY, float slop) {
11365        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11366                localY < ((mBottom - mTop) + slop);
11367    }
11368
11369    /**
11370     * When a view has focus and the user navigates away from it, the next view is searched for
11371     * starting from the rectangle filled in by this method.
11372     *
11373     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11374     * of the view.  However, if your view maintains some idea of internal selection,
11375     * such as a cursor, or a selected row or column, you should override this method and
11376     * fill in a more specific rectangle.
11377     *
11378     * @param r The rectangle to fill in, in this view's coordinates.
11379     */
11380    public void getFocusedRect(Rect r) {
11381        getDrawingRect(r);
11382    }
11383
11384    /**
11385     * If some part of this view is not clipped by any of its parents, then
11386     * return that area in r in global (root) coordinates. To convert r to local
11387     * coordinates (without taking possible View rotations into account), offset
11388     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11389     * If the view is completely clipped or translated out, return false.
11390     *
11391     * @param r If true is returned, r holds the global coordinates of the
11392     *        visible portion of this view.
11393     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11394     *        between this view and its root. globalOffet may be null.
11395     * @return true if r is non-empty (i.e. part of the view is visible at the
11396     *         root level.
11397     */
11398    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11399        int width = mRight - mLeft;
11400        int height = mBottom - mTop;
11401        if (width > 0 && height > 0) {
11402            r.set(0, 0, width, height);
11403            if (globalOffset != null) {
11404                globalOffset.set(-mScrollX, -mScrollY);
11405            }
11406            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11407        }
11408        return false;
11409    }
11410
11411    public final boolean getGlobalVisibleRect(Rect r) {
11412        return getGlobalVisibleRect(r, null);
11413    }
11414
11415    public final boolean getLocalVisibleRect(Rect r) {
11416        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11417        if (getGlobalVisibleRect(r, offset)) {
11418            r.offset(-offset.x, -offset.y); // make r local
11419            return true;
11420        }
11421        return false;
11422    }
11423
11424    /**
11425     * Offset this view's vertical location by the specified number of pixels.
11426     *
11427     * @param offset the number of pixels to offset the view by
11428     */
11429    public void offsetTopAndBottom(int offset) {
11430        if (offset != 0) {
11431            final boolean matrixIsIdentity = hasIdentityMatrix();
11432            if (matrixIsIdentity) {
11433                if (isHardwareAccelerated()) {
11434                    invalidateViewProperty(false, false);
11435                } else {
11436                    final ViewParent p = mParent;
11437                    if (p != null && mAttachInfo != null) {
11438                        final Rect r = mAttachInfo.mTmpInvalRect;
11439                        int minTop;
11440                        int maxBottom;
11441                        int yLoc;
11442                        if (offset < 0) {
11443                            minTop = mTop + offset;
11444                            maxBottom = mBottom;
11445                            yLoc = offset;
11446                        } else {
11447                            minTop = mTop;
11448                            maxBottom = mBottom + offset;
11449                            yLoc = 0;
11450                        }
11451                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11452                        p.invalidateChild(this, r);
11453                    }
11454                }
11455            } else {
11456                invalidateViewProperty(false, false);
11457            }
11458
11459            mTop += offset;
11460            mBottom += offset;
11461            mRenderNode.offsetTopAndBottom(offset);
11462            if (isHardwareAccelerated()) {
11463                invalidateViewProperty(false, false);
11464            } else {
11465                if (!matrixIsIdentity) {
11466                    invalidateViewProperty(false, true);
11467                }
11468                invalidateParentIfNeeded();
11469            }
11470            notifySubtreeAccessibilityStateChangedIfNeeded();
11471        }
11472    }
11473
11474    /**
11475     * Offset this view's horizontal location by the specified amount of pixels.
11476     *
11477     * @param offset the number of pixels to offset the view by
11478     */
11479    public void offsetLeftAndRight(int offset) {
11480        if (offset != 0) {
11481            final boolean matrixIsIdentity = hasIdentityMatrix();
11482            if (matrixIsIdentity) {
11483                if (isHardwareAccelerated()) {
11484                    invalidateViewProperty(false, false);
11485                } else {
11486                    final ViewParent p = mParent;
11487                    if (p != null && mAttachInfo != null) {
11488                        final Rect r = mAttachInfo.mTmpInvalRect;
11489                        int minLeft;
11490                        int maxRight;
11491                        if (offset < 0) {
11492                            minLeft = mLeft + offset;
11493                            maxRight = mRight;
11494                        } else {
11495                            minLeft = mLeft;
11496                            maxRight = mRight + offset;
11497                        }
11498                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11499                        p.invalidateChild(this, r);
11500                    }
11501                }
11502            } else {
11503                invalidateViewProperty(false, false);
11504            }
11505
11506            mLeft += offset;
11507            mRight += offset;
11508            mRenderNode.offsetLeftAndRight(offset);
11509            if (isHardwareAccelerated()) {
11510                invalidateViewProperty(false, false);
11511            } else {
11512                if (!matrixIsIdentity) {
11513                    invalidateViewProperty(false, true);
11514                }
11515                invalidateParentIfNeeded();
11516            }
11517            notifySubtreeAccessibilityStateChangedIfNeeded();
11518        }
11519    }
11520
11521    /**
11522     * Get the LayoutParams associated with this view. All views should have
11523     * layout parameters. These supply parameters to the <i>parent</i> of this
11524     * view specifying how it should be arranged. There are many subclasses of
11525     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11526     * of ViewGroup that are responsible for arranging their children.
11527     *
11528     * This method may return null if this View is not attached to a parent
11529     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11530     * was not invoked successfully. When a View is attached to a parent
11531     * ViewGroup, this method must not return null.
11532     *
11533     * @return The LayoutParams associated with this view, or null if no
11534     *         parameters have been set yet
11535     */
11536    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11537    public ViewGroup.LayoutParams getLayoutParams() {
11538        return mLayoutParams;
11539    }
11540
11541    /**
11542     * Set the layout parameters associated with this view. These supply
11543     * parameters to the <i>parent</i> of this view specifying how it should be
11544     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11545     * correspond to the different subclasses of ViewGroup that are responsible
11546     * for arranging their children.
11547     *
11548     * @param params The layout parameters for this view, cannot be null
11549     */
11550    public void setLayoutParams(ViewGroup.LayoutParams params) {
11551        if (params == null) {
11552            throw new NullPointerException("Layout parameters cannot be null");
11553        }
11554        mLayoutParams = params;
11555        resolveLayoutParams();
11556        if (mParent instanceof ViewGroup) {
11557            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11558        }
11559        requestLayout();
11560    }
11561
11562    /**
11563     * Resolve the layout parameters depending on the resolved layout direction
11564     *
11565     * @hide
11566     */
11567    public void resolveLayoutParams() {
11568        if (mLayoutParams != null) {
11569            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11570        }
11571    }
11572
11573    /**
11574     * Set the scrolled position of your view. This will cause a call to
11575     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11576     * invalidated.
11577     * @param x the x position to scroll to
11578     * @param y the y position to scroll to
11579     */
11580    public void scrollTo(int x, int y) {
11581        if (mScrollX != x || mScrollY != y) {
11582            int oldX = mScrollX;
11583            int oldY = mScrollY;
11584            mScrollX = x;
11585            mScrollY = y;
11586            invalidateParentCaches();
11587            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11588            if (!awakenScrollBars()) {
11589                postInvalidateOnAnimation();
11590            }
11591        }
11592    }
11593
11594    /**
11595     * Move the scrolled position of your view. This will cause a call to
11596     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11597     * invalidated.
11598     * @param x the amount of pixels to scroll by horizontally
11599     * @param y the amount of pixels to scroll by vertically
11600     */
11601    public void scrollBy(int x, int y) {
11602        scrollTo(mScrollX + x, mScrollY + y);
11603    }
11604
11605    /**
11606     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11607     * animation to fade the scrollbars out after a default delay. If a subclass
11608     * provides animated scrolling, the start delay should equal the duration
11609     * of the scrolling animation.</p>
11610     *
11611     * <p>The animation starts only if at least one of the scrollbars is
11612     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11613     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11614     * this method returns true, and false otherwise. If the animation is
11615     * started, this method calls {@link #invalidate()}; in that case the
11616     * caller should not call {@link #invalidate()}.</p>
11617     *
11618     * <p>This method should be invoked every time a subclass directly updates
11619     * the scroll parameters.</p>
11620     *
11621     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11622     * and {@link #scrollTo(int, int)}.</p>
11623     *
11624     * @return true if the animation is played, false otherwise
11625     *
11626     * @see #awakenScrollBars(int)
11627     * @see #scrollBy(int, int)
11628     * @see #scrollTo(int, int)
11629     * @see #isHorizontalScrollBarEnabled()
11630     * @see #isVerticalScrollBarEnabled()
11631     * @see #setHorizontalScrollBarEnabled(boolean)
11632     * @see #setVerticalScrollBarEnabled(boolean)
11633     */
11634    protected boolean awakenScrollBars() {
11635        return mScrollCache != null &&
11636                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11637    }
11638
11639    /**
11640     * Trigger the scrollbars to draw.
11641     * This method differs from awakenScrollBars() only in its default duration.
11642     * initialAwakenScrollBars() will show the scroll bars for longer than
11643     * usual to give the user more of a chance to notice them.
11644     *
11645     * @return true if the animation is played, false otherwise.
11646     */
11647    private boolean initialAwakenScrollBars() {
11648        return mScrollCache != null &&
11649                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11650    }
11651
11652    /**
11653     * <p>
11654     * Trigger the scrollbars to draw. When invoked this method starts an
11655     * animation to fade the scrollbars out after a fixed delay. If a subclass
11656     * provides animated scrolling, the start delay should equal the duration of
11657     * the scrolling animation.
11658     * </p>
11659     *
11660     * <p>
11661     * The animation starts only if at least one of the scrollbars is enabled,
11662     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11663     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11664     * this method returns true, and false otherwise. If the animation is
11665     * started, this method calls {@link #invalidate()}; in that case the caller
11666     * should not call {@link #invalidate()}.
11667     * </p>
11668     *
11669     * <p>
11670     * This method should be invoked every time a subclass directly updates the
11671     * scroll parameters.
11672     * </p>
11673     *
11674     * @param startDelay the delay, in milliseconds, after which the animation
11675     *        should start; when the delay is 0, the animation starts
11676     *        immediately
11677     * @return true if the animation is played, false otherwise
11678     *
11679     * @see #scrollBy(int, int)
11680     * @see #scrollTo(int, int)
11681     * @see #isHorizontalScrollBarEnabled()
11682     * @see #isVerticalScrollBarEnabled()
11683     * @see #setHorizontalScrollBarEnabled(boolean)
11684     * @see #setVerticalScrollBarEnabled(boolean)
11685     */
11686    protected boolean awakenScrollBars(int startDelay) {
11687        return awakenScrollBars(startDelay, true);
11688    }
11689
11690    /**
11691     * <p>
11692     * Trigger the scrollbars to draw. When invoked this method starts an
11693     * animation to fade the scrollbars out after a fixed delay. If a subclass
11694     * provides animated scrolling, the start delay should equal the duration of
11695     * the scrolling animation.
11696     * </p>
11697     *
11698     * <p>
11699     * The animation starts only if at least one of the scrollbars is enabled,
11700     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11701     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11702     * this method returns true, and false otherwise. If the animation is
11703     * started, this method calls {@link #invalidate()} if the invalidate parameter
11704     * is set to true; in that case the caller
11705     * should not call {@link #invalidate()}.
11706     * </p>
11707     *
11708     * <p>
11709     * This method should be invoked every time a subclass directly updates the
11710     * scroll parameters.
11711     * </p>
11712     *
11713     * @param startDelay the delay, in milliseconds, after which the animation
11714     *        should start; when the delay is 0, the animation starts
11715     *        immediately
11716     *
11717     * @param invalidate Whether this method should call invalidate
11718     *
11719     * @return true if the animation is played, false otherwise
11720     *
11721     * @see #scrollBy(int, int)
11722     * @see #scrollTo(int, int)
11723     * @see #isHorizontalScrollBarEnabled()
11724     * @see #isVerticalScrollBarEnabled()
11725     * @see #setHorizontalScrollBarEnabled(boolean)
11726     * @see #setVerticalScrollBarEnabled(boolean)
11727     */
11728    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11729        final ScrollabilityCache scrollCache = mScrollCache;
11730
11731        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11732            return false;
11733        }
11734
11735        if (scrollCache.scrollBar == null) {
11736            scrollCache.scrollBar = new ScrollBarDrawable();
11737        }
11738
11739        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11740
11741            if (invalidate) {
11742                // Invalidate to show the scrollbars
11743                postInvalidateOnAnimation();
11744            }
11745
11746            if (scrollCache.state == ScrollabilityCache.OFF) {
11747                // FIXME: this is copied from WindowManagerService.
11748                // We should get this value from the system when it
11749                // is possible to do so.
11750                final int KEY_REPEAT_FIRST_DELAY = 750;
11751                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11752            }
11753
11754            // Tell mScrollCache when we should start fading. This may
11755            // extend the fade start time if one was already scheduled
11756            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11757            scrollCache.fadeStartTime = fadeStartTime;
11758            scrollCache.state = ScrollabilityCache.ON;
11759
11760            // Schedule our fader to run, unscheduling any old ones first
11761            if (mAttachInfo != null) {
11762                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11763                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11764            }
11765
11766            return true;
11767        }
11768
11769        return false;
11770    }
11771
11772    /**
11773     * Do not invalidate views which are not visible and which are not running an animation. They
11774     * will not get drawn and they should not set dirty flags as if they will be drawn
11775     */
11776    private boolean skipInvalidate() {
11777        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11778                (!(mParent instanceof ViewGroup) ||
11779                        !((ViewGroup) mParent).isViewTransitioning(this));
11780    }
11781
11782    /**
11783     * Mark the area defined by dirty as needing to be drawn. If the view is
11784     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11785     * point in the future.
11786     * <p>
11787     * This must be called from a UI thread. To call from a non-UI thread, call
11788     * {@link #postInvalidate()}.
11789     * <p>
11790     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11791     * {@code dirty}.
11792     *
11793     * @param dirty the rectangle representing the bounds of the dirty region
11794     */
11795    public void invalidate(Rect dirty) {
11796        final int scrollX = mScrollX;
11797        final int scrollY = mScrollY;
11798        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11799                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11800    }
11801
11802    /**
11803     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11804     * coordinates of the dirty rect are relative to the view. If the view is
11805     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11806     * point in the future.
11807     * <p>
11808     * This must be called from a UI thread. To call from a non-UI thread, call
11809     * {@link #postInvalidate()}.
11810     *
11811     * @param l the left position of the dirty region
11812     * @param t the top position of the dirty region
11813     * @param r the right position of the dirty region
11814     * @param b the bottom position of the dirty region
11815     */
11816    public void invalidate(int l, int t, int r, int b) {
11817        final int scrollX = mScrollX;
11818        final int scrollY = mScrollY;
11819        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11820    }
11821
11822    /**
11823     * Invalidate the whole view. If the view is visible,
11824     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11825     * the future.
11826     * <p>
11827     * This must be called from a UI thread. To call from a non-UI thread, call
11828     * {@link #postInvalidate()}.
11829     */
11830    public void invalidate() {
11831        invalidate(true);
11832    }
11833
11834    /**
11835     * This is where the invalidate() work actually happens. A full invalidate()
11836     * causes the drawing cache to be invalidated, but this function can be
11837     * called with invalidateCache set to false to skip that invalidation step
11838     * for cases that do not need it (for example, a component that remains at
11839     * the same dimensions with the same content).
11840     *
11841     * @param invalidateCache Whether the drawing cache for this view should be
11842     *            invalidated as well. This is usually true for a full
11843     *            invalidate, but may be set to false if the View's contents or
11844     *            dimensions have not changed.
11845     */
11846    void invalidate(boolean invalidateCache) {
11847        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11848    }
11849
11850    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11851            boolean fullInvalidate) {
11852        if (mGhostView != null) {
11853            mGhostView.invalidate(true);
11854            return;
11855        }
11856
11857        if (skipInvalidate()) {
11858            return;
11859        }
11860
11861        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11862                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11863                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11864                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11865            if (fullInvalidate) {
11866                mLastIsOpaque = isOpaque();
11867                mPrivateFlags &= ~PFLAG_DRAWN;
11868            }
11869
11870            mPrivateFlags |= PFLAG_DIRTY;
11871
11872            if (invalidateCache) {
11873                mPrivateFlags |= PFLAG_INVALIDATED;
11874                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11875            }
11876
11877            // Propagate the damage rectangle to the parent view.
11878            final AttachInfo ai = mAttachInfo;
11879            final ViewParent p = mParent;
11880            if (p != null && ai != null && l < r && t < b) {
11881                final Rect damage = ai.mTmpInvalRect;
11882                damage.set(l, t, r, b);
11883                p.invalidateChild(this, damage);
11884            }
11885
11886            // Damage the entire projection receiver, if necessary.
11887            if (mBackground != null && mBackground.isProjected()) {
11888                final View receiver = getProjectionReceiver();
11889                if (receiver != null) {
11890                    receiver.damageInParent();
11891                }
11892            }
11893
11894            // Damage the entire IsolatedZVolume receiving this view's shadow.
11895            if (isHardwareAccelerated() && getZ() != 0) {
11896                damageShadowReceiver();
11897            }
11898        }
11899    }
11900
11901    /**
11902     * @return this view's projection receiver, or {@code null} if none exists
11903     */
11904    private View getProjectionReceiver() {
11905        ViewParent p = getParent();
11906        while (p != null && p instanceof View) {
11907            final View v = (View) p;
11908            if (v.isProjectionReceiver()) {
11909                return v;
11910            }
11911            p = p.getParent();
11912        }
11913
11914        return null;
11915    }
11916
11917    /**
11918     * @return whether the view is a projection receiver
11919     */
11920    private boolean isProjectionReceiver() {
11921        return mBackground != null;
11922    }
11923
11924    /**
11925     * Damage area of the screen that can be covered by this View's shadow.
11926     *
11927     * This method will guarantee that any changes to shadows cast by a View
11928     * are damaged on the screen for future redraw.
11929     */
11930    private void damageShadowReceiver() {
11931        final AttachInfo ai = mAttachInfo;
11932        if (ai != null) {
11933            ViewParent p = getParent();
11934            if (p != null && p instanceof ViewGroup) {
11935                final ViewGroup vg = (ViewGroup) p;
11936                vg.damageInParent();
11937            }
11938        }
11939    }
11940
11941    /**
11942     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11943     * set any flags or handle all of the cases handled by the default invalidation methods.
11944     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11945     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11946     * walk up the hierarchy, transforming the dirty rect as necessary.
11947     *
11948     * The method also handles normal invalidation logic if display list properties are not
11949     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11950     * backup approach, to handle these cases used in the various property-setting methods.
11951     *
11952     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11953     * are not being used in this view
11954     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11955     * list properties are not being used in this view
11956     */
11957    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11958        if (!isHardwareAccelerated()
11959                || !mRenderNode.isValid()
11960                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11961            if (invalidateParent) {
11962                invalidateParentCaches();
11963            }
11964            if (forceRedraw) {
11965                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11966            }
11967            invalidate(false);
11968        } else {
11969            damageInParent();
11970        }
11971        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11972            damageShadowReceiver();
11973        }
11974    }
11975
11976    /**
11977     * Tells the parent view to damage this view's bounds.
11978     *
11979     * @hide
11980     */
11981    protected void damageInParent() {
11982        final AttachInfo ai = mAttachInfo;
11983        final ViewParent p = mParent;
11984        if (p != null && ai != null) {
11985            final Rect r = ai.mTmpInvalRect;
11986            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11987            if (mParent instanceof ViewGroup) {
11988                ((ViewGroup) mParent).damageChild(this, r);
11989            } else {
11990                mParent.invalidateChild(this, r);
11991            }
11992        }
11993    }
11994
11995    /**
11996     * Utility method to transform a given Rect by the current matrix of this view.
11997     */
11998    void transformRect(final Rect rect) {
11999        if (!getMatrix().isIdentity()) {
12000            RectF boundingRect = mAttachInfo.mTmpTransformRect;
12001            boundingRect.set(rect);
12002            getMatrix().mapRect(boundingRect);
12003            rect.set((int) Math.floor(boundingRect.left),
12004                    (int) Math.floor(boundingRect.top),
12005                    (int) Math.ceil(boundingRect.right),
12006                    (int) Math.ceil(boundingRect.bottom));
12007        }
12008    }
12009
12010    /**
12011     * Used to indicate that the parent of this view should clear its caches. This functionality
12012     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12013     * which is necessary when various parent-managed properties of the view change, such as
12014     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12015     * clears the parent caches and does not causes an invalidate event.
12016     *
12017     * @hide
12018     */
12019    protected void invalidateParentCaches() {
12020        if (mParent instanceof View) {
12021            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12022        }
12023    }
12024
12025    /**
12026     * Used to indicate that the parent of this view should be invalidated. This functionality
12027     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12028     * which is necessary when various parent-managed properties of the view change, such as
12029     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12030     * an invalidation event to the parent.
12031     *
12032     * @hide
12033     */
12034    protected void invalidateParentIfNeeded() {
12035        if (isHardwareAccelerated() && mParent instanceof View) {
12036            ((View) mParent).invalidate(true);
12037        }
12038    }
12039
12040    /**
12041     * @hide
12042     */
12043    protected void invalidateParentIfNeededAndWasQuickRejected() {
12044        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12045            // View was rejected last time it was drawn by its parent; this may have changed
12046            invalidateParentIfNeeded();
12047        }
12048    }
12049
12050    /**
12051     * Indicates whether this View is opaque. An opaque View guarantees that it will
12052     * draw all the pixels overlapping its bounds using a fully opaque color.
12053     *
12054     * Subclasses of View should override this method whenever possible to indicate
12055     * whether an instance is opaque. Opaque Views are treated in a special way by
12056     * the View hierarchy, possibly allowing it to perform optimizations during
12057     * invalidate/draw passes.
12058     *
12059     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12060     */
12061    @ViewDebug.ExportedProperty(category = "drawing")
12062    public boolean isOpaque() {
12063        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12064                getFinalAlpha() >= 1.0f;
12065    }
12066
12067    /**
12068     * @hide
12069     */
12070    protected void computeOpaqueFlags() {
12071        // Opaque if:
12072        //   - Has a background
12073        //   - Background is opaque
12074        //   - Doesn't have scrollbars or scrollbars overlay
12075
12076        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12077            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12078        } else {
12079            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12080        }
12081
12082        final int flags = mViewFlags;
12083        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12084                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12085                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12086            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12087        } else {
12088            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12089        }
12090    }
12091
12092    /**
12093     * @hide
12094     */
12095    protected boolean hasOpaqueScrollbars() {
12096        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12097    }
12098
12099    /**
12100     * @return A handler associated with the thread running the View. This
12101     * handler can be used to pump events in the UI events queue.
12102     */
12103    public Handler getHandler() {
12104        final AttachInfo attachInfo = mAttachInfo;
12105        if (attachInfo != null) {
12106            return attachInfo.mHandler;
12107        }
12108        return null;
12109    }
12110
12111    /**
12112     * Gets the view root associated with the View.
12113     * @return The view root, or null if none.
12114     * @hide
12115     */
12116    public ViewRootImpl getViewRootImpl() {
12117        if (mAttachInfo != null) {
12118            return mAttachInfo.mViewRootImpl;
12119        }
12120        return null;
12121    }
12122
12123    /**
12124     * @hide
12125     */
12126    public HardwareRenderer getHardwareRenderer() {
12127        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12128    }
12129
12130    /**
12131     * <p>Causes the Runnable to be added to the message queue.
12132     * The runnable will be run on the user interface thread.</p>
12133     *
12134     * @param action The Runnable that will be executed.
12135     *
12136     * @return Returns true if the Runnable was successfully placed in to the
12137     *         message queue.  Returns false on failure, usually because the
12138     *         looper processing the message queue is exiting.
12139     *
12140     * @see #postDelayed
12141     * @see #removeCallbacks
12142     */
12143    public boolean post(Runnable action) {
12144        final AttachInfo attachInfo = mAttachInfo;
12145        if (attachInfo != null) {
12146            return attachInfo.mHandler.post(action);
12147        }
12148        // Assume that post will succeed later
12149        ViewRootImpl.getRunQueue().post(action);
12150        return true;
12151    }
12152
12153    /**
12154     * <p>Causes the Runnable to be added to the message queue, to be run
12155     * after the specified amount of time elapses.
12156     * The runnable will be run on the user interface thread.</p>
12157     *
12158     * @param action The Runnable that will be executed.
12159     * @param delayMillis The delay (in milliseconds) until the Runnable
12160     *        will be executed.
12161     *
12162     * @return true if the Runnable was successfully placed in to the
12163     *         message queue.  Returns false on failure, usually because the
12164     *         looper processing the message queue is exiting.  Note that a
12165     *         result of true does not mean the Runnable will be processed --
12166     *         if the looper is quit before the delivery time of the message
12167     *         occurs then the message will be dropped.
12168     *
12169     * @see #post
12170     * @see #removeCallbacks
12171     */
12172    public boolean postDelayed(Runnable action, long delayMillis) {
12173        final AttachInfo attachInfo = mAttachInfo;
12174        if (attachInfo != null) {
12175            return attachInfo.mHandler.postDelayed(action, delayMillis);
12176        }
12177        // Assume that post will succeed later
12178        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12179        return true;
12180    }
12181
12182    /**
12183     * <p>Causes the Runnable to execute on the next animation time step.
12184     * The runnable will be run on the user interface thread.</p>
12185     *
12186     * @param action The Runnable that will be executed.
12187     *
12188     * @see #postOnAnimationDelayed
12189     * @see #removeCallbacks
12190     */
12191    public void postOnAnimation(Runnable action) {
12192        final AttachInfo attachInfo = mAttachInfo;
12193        if (attachInfo != null) {
12194            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12195                    Choreographer.CALLBACK_ANIMATION, action, null);
12196        } else {
12197            // Assume that post will succeed later
12198            ViewRootImpl.getRunQueue().post(action);
12199        }
12200    }
12201
12202    /**
12203     * <p>Causes the Runnable to execute on the next animation time step,
12204     * after the specified amount of time elapses.
12205     * The runnable will be run on the user interface thread.</p>
12206     *
12207     * @param action The Runnable that will be executed.
12208     * @param delayMillis The delay (in milliseconds) until the Runnable
12209     *        will be executed.
12210     *
12211     * @see #postOnAnimation
12212     * @see #removeCallbacks
12213     */
12214    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12215        final AttachInfo attachInfo = mAttachInfo;
12216        if (attachInfo != null) {
12217            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12218                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12219        } else {
12220            // Assume that post will succeed later
12221            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12222        }
12223    }
12224
12225    /**
12226     * <p>Removes the specified Runnable from the message queue.</p>
12227     *
12228     * @param action The Runnable to remove from the message handling queue
12229     *
12230     * @return true if this view could ask the Handler to remove the Runnable,
12231     *         false otherwise. When the returned value is true, the Runnable
12232     *         may or may not have been actually removed from the message queue
12233     *         (for instance, if the Runnable was not in the queue already.)
12234     *
12235     * @see #post
12236     * @see #postDelayed
12237     * @see #postOnAnimation
12238     * @see #postOnAnimationDelayed
12239     */
12240    public boolean removeCallbacks(Runnable action) {
12241        if (action != null) {
12242            final AttachInfo attachInfo = mAttachInfo;
12243            if (attachInfo != null) {
12244                attachInfo.mHandler.removeCallbacks(action);
12245                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12246                        Choreographer.CALLBACK_ANIMATION, action, null);
12247            }
12248            // Assume that post will succeed later
12249            ViewRootImpl.getRunQueue().removeCallbacks(action);
12250        }
12251        return true;
12252    }
12253
12254    /**
12255     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12256     * Use this to invalidate the View from a non-UI thread.</p>
12257     *
12258     * <p>This method can be invoked from outside of the UI thread
12259     * only when this View is attached to a window.</p>
12260     *
12261     * @see #invalidate()
12262     * @see #postInvalidateDelayed(long)
12263     */
12264    public void postInvalidate() {
12265        postInvalidateDelayed(0);
12266    }
12267
12268    /**
12269     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12270     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12271     *
12272     * <p>This method can be invoked from outside of the UI thread
12273     * only when this View is attached to a window.</p>
12274     *
12275     * @param left The left coordinate of the rectangle to invalidate.
12276     * @param top The top coordinate of the rectangle to invalidate.
12277     * @param right The right coordinate of the rectangle to invalidate.
12278     * @param bottom The bottom coordinate of the rectangle to invalidate.
12279     *
12280     * @see #invalidate(int, int, int, int)
12281     * @see #invalidate(Rect)
12282     * @see #postInvalidateDelayed(long, int, int, int, int)
12283     */
12284    public void postInvalidate(int left, int top, int right, int bottom) {
12285        postInvalidateDelayed(0, left, top, right, bottom);
12286    }
12287
12288    /**
12289     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12290     * loop. Waits for the specified amount of time.</p>
12291     *
12292     * <p>This method can be invoked from outside of the UI thread
12293     * only when this View is attached to a window.</p>
12294     *
12295     * @param delayMilliseconds the duration in milliseconds to delay the
12296     *         invalidation by
12297     *
12298     * @see #invalidate()
12299     * @see #postInvalidate()
12300     */
12301    public void postInvalidateDelayed(long delayMilliseconds) {
12302        // We try only with the AttachInfo because there's no point in invalidating
12303        // if we are not attached to our window
12304        final AttachInfo attachInfo = mAttachInfo;
12305        if (attachInfo != null) {
12306            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12307        }
12308    }
12309
12310    /**
12311     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12312     * through the event loop. Waits for the specified amount of time.</p>
12313     *
12314     * <p>This method can be invoked from outside of the UI thread
12315     * only when this View is attached to a window.</p>
12316     *
12317     * @param delayMilliseconds the duration in milliseconds to delay the
12318     *         invalidation by
12319     * @param left The left coordinate of the rectangle to invalidate.
12320     * @param top The top coordinate of the rectangle to invalidate.
12321     * @param right The right coordinate of the rectangle to invalidate.
12322     * @param bottom The bottom coordinate of the rectangle to invalidate.
12323     *
12324     * @see #invalidate(int, int, int, int)
12325     * @see #invalidate(Rect)
12326     * @see #postInvalidate(int, int, int, int)
12327     */
12328    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12329            int right, int bottom) {
12330
12331        // We try only with the AttachInfo because there's no point in invalidating
12332        // if we are not attached to our window
12333        final AttachInfo attachInfo = mAttachInfo;
12334        if (attachInfo != null) {
12335            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12336            info.target = this;
12337            info.left = left;
12338            info.top = top;
12339            info.right = right;
12340            info.bottom = bottom;
12341
12342            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12343        }
12344    }
12345
12346    /**
12347     * <p>Cause an invalidate to happen on the next animation time step, typically the
12348     * next display frame.</p>
12349     *
12350     * <p>This method can be invoked from outside of the UI thread
12351     * only when this View is attached to a window.</p>
12352     *
12353     * @see #invalidate()
12354     */
12355    public void postInvalidateOnAnimation() {
12356        // We try only with the AttachInfo because there's no point in invalidating
12357        // if we are not attached to our window
12358        final AttachInfo attachInfo = mAttachInfo;
12359        if (attachInfo != null) {
12360            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12361        }
12362    }
12363
12364    /**
12365     * <p>Cause an invalidate of the specified area to happen on the next animation
12366     * time step, typically the next display frame.</p>
12367     *
12368     * <p>This method can be invoked from outside of the UI thread
12369     * only when this View is attached to a window.</p>
12370     *
12371     * @param left The left coordinate of the rectangle to invalidate.
12372     * @param top The top coordinate of the rectangle to invalidate.
12373     * @param right The right coordinate of the rectangle to invalidate.
12374     * @param bottom The bottom coordinate of the rectangle to invalidate.
12375     *
12376     * @see #invalidate(int, int, int, int)
12377     * @see #invalidate(Rect)
12378     */
12379    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12380        // We try only with the AttachInfo because there's no point in invalidating
12381        // if we are not attached to our window
12382        final AttachInfo attachInfo = mAttachInfo;
12383        if (attachInfo != null) {
12384            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12385            info.target = this;
12386            info.left = left;
12387            info.top = top;
12388            info.right = right;
12389            info.bottom = bottom;
12390
12391            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12392        }
12393    }
12394
12395    /**
12396     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12397     * This event is sent at most once every
12398     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12399     */
12400    private void postSendViewScrolledAccessibilityEventCallback() {
12401        if (mSendViewScrolledAccessibilityEvent == null) {
12402            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12403        }
12404        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12405            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12406            postDelayed(mSendViewScrolledAccessibilityEvent,
12407                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12408        }
12409    }
12410
12411    /**
12412     * Called by a parent to request that a child update its values for mScrollX
12413     * and mScrollY if necessary. This will typically be done if the child is
12414     * animating a scroll using a {@link android.widget.Scroller Scroller}
12415     * object.
12416     */
12417    public void computeScroll() {
12418    }
12419
12420    /**
12421     * <p>Indicate whether the horizontal edges are faded when the view is
12422     * scrolled horizontally.</p>
12423     *
12424     * @return true if the horizontal edges should are faded on scroll, false
12425     *         otherwise
12426     *
12427     * @see #setHorizontalFadingEdgeEnabled(boolean)
12428     *
12429     * @attr ref android.R.styleable#View_requiresFadingEdge
12430     */
12431    public boolean isHorizontalFadingEdgeEnabled() {
12432        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12433    }
12434
12435    /**
12436     * <p>Define whether the horizontal edges should be faded when this view
12437     * is scrolled horizontally.</p>
12438     *
12439     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12440     *                                    be faded when the view is scrolled
12441     *                                    horizontally
12442     *
12443     * @see #isHorizontalFadingEdgeEnabled()
12444     *
12445     * @attr ref android.R.styleable#View_requiresFadingEdge
12446     */
12447    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12448        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12449            if (horizontalFadingEdgeEnabled) {
12450                initScrollCache();
12451            }
12452
12453            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12454        }
12455    }
12456
12457    /**
12458     * <p>Indicate whether the vertical edges are faded when the view is
12459     * scrolled horizontally.</p>
12460     *
12461     * @return true if the vertical edges should are faded on scroll, false
12462     *         otherwise
12463     *
12464     * @see #setVerticalFadingEdgeEnabled(boolean)
12465     *
12466     * @attr ref android.R.styleable#View_requiresFadingEdge
12467     */
12468    public boolean isVerticalFadingEdgeEnabled() {
12469        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12470    }
12471
12472    /**
12473     * <p>Define whether the vertical edges should be faded when this view
12474     * is scrolled vertically.</p>
12475     *
12476     * @param verticalFadingEdgeEnabled true if the vertical edges should
12477     *                                  be faded when the view is scrolled
12478     *                                  vertically
12479     *
12480     * @see #isVerticalFadingEdgeEnabled()
12481     *
12482     * @attr ref android.R.styleable#View_requiresFadingEdge
12483     */
12484    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12485        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12486            if (verticalFadingEdgeEnabled) {
12487                initScrollCache();
12488            }
12489
12490            mViewFlags ^= FADING_EDGE_VERTICAL;
12491        }
12492    }
12493
12494    /**
12495     * Returns the strength, or intensity, of the top faded edge. The strength is
12496     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12497     * returns 0.0 or 1.0 but no value in between.
12498     *
12499     * Subclasses should override this method to provide a smoother fade transition
12500     * when scrolling occurs.
12501     *
12502     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12503     */
12504    protected float getTopFadingEdgeStrength() {
12505        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12506    }
12507
12508    /**
12509     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12510     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12511     * returns 0.0 or 1.0 but no value in between.
12512     *
12513     * Subclasses should override this method to provide a smoother fade transition
12514     * when scrolling occurs.
12515     *
12516     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12517     */
12518    protected float getBottomFadingEdgeStrength() {
12519        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12520                computeVerticalScrollRange() ? 1.0f : 0.0f;
12521    }
12522
12523    /**
12524     * Returns the strength, or intensity, of the left faded edge. The strength is
12525     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12526     * returns 0.0 or 1.0 but no value in between.
12527     *
12528     * Subclasses should override this method to provide a smoother fade transition
12529     * when scrolling occurs.
12530     *
12531     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12532     */
12533    protected float getLeftFadingEdgeStrength() {
12534        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12535    }
12536
12537    /**
12538     * Returns the strength, or intensity, of the right faded edge. The strength is
12539     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12540     * returns 0.0 or 1.0 but no value in between.
12541     *
12542     * Subclasses should override this method to provide a smoother fade transition
12543     * when scrolling occurs.
12544     *
12545     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12546     */
12547    protected float getRightFadingEdgeStrength() {
12548        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12549                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12550    }
12551
12552    /**
12553     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12554     * scrollbar is not drawn by default.</p>
12555     *
12556     * @return true if the horizontal scrollbar should be painted, false
12557     *         otherwise
12558     *
12559     * @see #setHorizontalScrollBarEnabled(boolean)
12560     */
12561    public boolean isHorizontalScrollBarEnabled() {
12562        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12563    }
12564
12565    /**
12566     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12567     * scrollbar is not drawn by default.</p>
12568     *
12569     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12570     *                                   be painted
12571     *
12572     * @see #isHorizontalScrollBarEnabled()
12573     */
12574    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12575        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12576            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12577            computeOpaqueFlags();
12578            resolvePadding();
12579        }
12580    }
12581
12582    /**
12583     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12584     * scrollbar is not drawn by default.</p>
12585     *
12586     * @return true if the vertical scrollbar should be painted, false
12587     *         otherwise
12588     *
12589     * @see #setVerticalScrollBarEnabled(boolean)
12590     */
12591    public boolean isVerticalScrollBarEnabled() {
12592        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12593    }
12594
12595    /**
12596     * <p>Define whether the vertical scrollbar should be drawn or not. The
12597     * scrollbar is not drawn by default.</p>
12598     *
12599     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12600     *                                 be painted
12601     *
12602     * @see #isVerticalScrollBarEnabled()
12603     */
12604    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12605        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12606            mViewFlags ^= SCROLLBARS_VERTICAL;
12607            computeOpaqueFlags();
12608            resolvePadding();
12609        }
12610    }
12611
12612    /**
12613     * @hide
12614     */
12615    protected void recomputePadding() {
12616        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12617    }
12618
12619    /**
12620     * Define whether scrollbars will fade when the view is not scrolling.
12621     *
12622     * @param fadeScrollbars whether to enable fading
12623     *
12624     * @attr ref android.R.styleable#View_fadeScrollbars
12625     */
12626    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12627        initScrollCache();
12628        final ScrollabilityCache scrollabilityCache = mScrollCache;
12629        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12630        if (fadeScrollbars) {
12631            scrollabilityCache.state = ScrollabilityCache.OFF;
12632        } else {
12633            scrollabilityCache.state = ScrollabilityCache.ON;
12634        }
12635    }
12636
12637    /**
12638     *
12639     * Returns true if scrollbars will fade when this view is not scrolling
12640     *
12641     * @return true if scrollbar fading is enabled
12642     *
12643     * @attr ref android.R.styleable#View_fadeScrollbars
12644     */
12645    public boolean isScrollbarFadingEnabled() {
12646        return mScrollCache != null && mScrollCache.fadeScrollBars;
12647    }
12648
12649    /**
12650     *
12651     * Returns the delay before scrollbars fade.
12652     *
12653     * @return the delay before scrollbars fade
12654     *
12655     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12656     */
12657    public int getScrollBarDefaultDelayBeforeFade() {
12658        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12659                mScrollCache.scrollBarDefaultDelayBeforeFade;
12660    }
12661
12662    /**
12663     * Define the delay before scrollbars fade.
12664     *
12665     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12666     *
12667     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12668     */
12669    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12670        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12671    }
12672
12673    /**
12674     *
12675     * Returns the scrollbar fade duration.
12676     *
12677     * @return the scrollbar fade duration
12678     *
12679     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12680     */
12681    public int getScrollBarFadeDuration() {
12682        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12683                mScrollCache.scrollBarFadeDuration;
12684    }
12685
12686    /**
12687     * Define the scrollbar fade duration.
12688     *
12689     * @param scrollBarFadeDuration - the scrollbar fade duration
12690     *
12691     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12692     */
12693    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12694        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12695    }
12696
12697    /**
12698     *
12699     * Returns the scrollbar size.
12700     *
12701     * @return the scrollbar size
12702     *
12703     * @attr ref android.R.styleable#View_scrollbarSize
12704     */
12705    public int getScrollBarSize() {
12706        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12707                mScrollCache.scrollBarSize;
12708    }
12709
12710    /**
12711     * Define the scrollbar size.
12712     *
12713     * @param scrollBarSize - the scrollbar size
12714     *
12715     * @attr ref android.R.styleable#View_scrollbarSize
12716     */
12717    public void setScrollBarSize(int scrollBarSize) {
12718        getScrollCache().scrollBarSize = scrollBarSize;
12719    }
12720
12721    /**
12722     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12723     * inset. When inset, they add to the padding of the view. And the scrollbars
12724     * can be drawn inside the padding area or on the edge of the view. For example,
12725     * if a view has a background drawable and you want to draw the scrollbars
12726     * inside the padding specified by the drawable, you can use
12727     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12728     * appear at the edge of the view, ignoring the padding, then you can use
12729     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12730     * @param style the style of the scrollbars. Should be one of
12731     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12732     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12733     * @see #SCROLLBARS_INSIDE_OVERLAY
12734     * @see #SCROLLBARS_INSIDE_INSET
12735     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12736     * @see #SCROLLBARS_OUTSIDE_INSET
12737     *
12738     * @attr ref android.R.styleable#View_scrollbarStyle
12739     */
12740    public void setScrollBarStyle(@ScrollBarStyle int style) {
12741        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12742            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12743            computeOpaqueFlags();
12744            resolvePadding();
12745        }
12746    }
12747
12748    /**
12749     * <p>Returns the current scrollbar style.</p>
12750     * @return the current scrollbar style
12751     * @see #SCROLLBARS_INSIDE_OVERLAY
12752     * @see #SCROLLBARS_INSIDE_INSET
12753     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12754     * @see #SCROLLBARS_OUTSIDE_INSET
12755     *
12756     * @attr ref android.R.styleable#View_scrollbarStyle
12757     */
12758    @ViewDebug.ExportedProperty(mapping = {
12759            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12760            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12761            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12762            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12763    })
12764    @ScrollBarStyle
12765    public int getScrollBarStyle() {
12766        return mViewFlags & SCROLLBARS_STYLE_MASK;
12767    }
12768
12769    /**
12770     * <p>Compute the horizontal range that the horizontal scrollbar
12771     * represents.</p>
12772     *
12773     * <p>The range is expressed in arbitrary units that must be the same as the
12774     * units used by {@link #computeHorizontalScrollExtent()} and
12775     * {@link #computeHorizontalScrollOffset()}.</p>
12776     *
12777     * <p>The default range is the drawing width of this view.</p>
12778     *
12779     * @return the total horizontal range represented by the horizontal
12780     *         scrollbar
12781     *
12782     * @see #computeHorizontalScrollExtent()
12783     * @see #computeHorizontalScrollOffset()
12784     * @see android.widget.ScrollBarDrawable
12785     */
12786    protected int computeHorizontalScrollRange() {
12787        return getWidth();
12788    }
12789
12790    /**
12791     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12792     * within the horizontal range. This value is used to compute the position
12793     * of the thumb within the scrollbar's track.</p>
12794     *
12795     * <p>The range is expressed in arbitrary units that must be the same as the
12796     * units used by {@link #computeHorizontalScrollRange()} and
12797     * {@link #computeHorizontalScrollExtent()}.</p>
12798     *
12799     * <p>The default offset is the scroll offset of this view.</p>
12800     *
12801     * @return the horizontal offset of the scrollbar's thumb
12802     *
12803     * @see #computeHorizontalScrollRange()
12804     * @see #computeHorizontalScrollExtent()
12805     * @see android.widget.ScrollBarDrawable
12806     */
12807    protected int computeHorizontalScrollOffset() {
12808        return mScrollX;
12809    }
12810
12811    /**
12812     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12813     * within the horizontal range. This value is used to compute the length
12814     * of the thumb within the scrollbar's track.</p>
12815     *
12816     * <p>The range is expressed in arbitrary units that must be the same as the
12817     * units used by {@link #computeHorizontalScrollRange()} and
12818     * {@link #computeHorizontalScrollOffset()}.</p>
12819     *
12820     * <p>The default extent is the drawing width of this view.</p>
12821     *
12822     * @return the horizontal extent of the scrollbar's thumb
12823     *
12824     * @see #computeHorizontalScrollRange()
12825     * @see #computeHorizontalScrollOffset()
12826     * @see android.widget.ScrollBarDrawable
12827     */
12828    protected int computeHorizontalScrollExtent() {
12829        return getWidth();
12830    }
12831
12832    /**
12833     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12834     *
12835     * <p>The range is expressed in arbitrary units that must be the same as the
12836     * units used by {@link #computeVerticalScrollExtent()} and
12837     * {@link #computeVerticalScrollOffset()}.</p>
12838     *
12839     * @return the total vertical range represented by the vertical scrollbar
12840     *
12841     * <p>The default range is the drawing height of this view.</p>
12842     *
12843     * @see #computeVerticalScrollExtent()
12844     * @see #computeVerticalScrollOffset()
12845     * @see android.widget.ScrollBarDrawable
12846     */
12847    protected int computeVerticalScrollRange() {
12848        return getHeight();
12849    }
12850
12851    /**
12852     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12853     * within the horizontal range. This value is used to compute the position
12854     * of the thumb within the scrollbar's track.</p>
12855     *
12856     * <p>The range is expressed in arbitrary units that must be the same as the
12857     * units used by {@link #computeVerticalScrollRange()} and
12858     * {@link #computeVerticalScrollExtent()}.</p>
12859     *
12860     * <p>The default offset is the scroll offset of this view.</p>
12861     *
12862     * @return the vertical offset of the scrollbar's thumb
12863     *
12864     * @see #computeVerticalScrollRange()
12865     * @see #computeVerticalScrollExtent()
12866     * @see android.widget.ScrollBarDrawable
12867     */
12868    protected int computeVerticalScrollOffset() {
12869        return mScrollY;
12870    }
12871
12872    /**
12873     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12874     * within the vertical range. This value is used to compute the length
12875     * of the thumb within the scrollbar's track.</p>
12876     *
12877     * <p>The range is expressed in arbitrary units that must be the same as the
12878     * units used by {@link #computeVerticalScrollRange()} and
12879     * {@link #computeVerticalScrollOffset()}.</p>
12880     *
12881     * <p>The default extent is the drawing height of this view.</p>
12882     *
12883     * @return the vertical extent of the scrollbar's thumb
12884     *
12885     * @see #computeVerticalScrollRange()
12886     * @see #computeVerticalScrollOffset()
12887     * @see android.widget.ScrollBarDrawable
12888     */
12889    protected int computeVerticalScrollExtent() {
12890        return getHeight();
12891    }
12892
12893    /**
12894     * Check if this view can be scrolled horizontally in a certain direction.
12895     *
12896     * @param direction Negative to check scrolling left, positive to check scrolling right.
12897     * @return true if this view can be scrolled in the specified direction, false otherwise.
12898     */
12899    public boolean canScrollHorizontally(int direction) {
12900        final int offset = computeHorizontalScrollOffset();
12901        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12902        if (range == 0) return false;
12903        if (direction < 0) {
12904            return offset > 0;
12905        } else {
12906            return offset < range - 1;
12907        }
12908    }
12909
12910    /**
12911     * Check if this view can be scrolled vertically in a certain direction.
12912     *
12913     * @param direction Negative to check scrolling up, positive to check scrolling down.
12914     * @return true if this view can be scrolled in the specified direction, false otherwise.
12915     */
12916    public boolean canScrollVertically(int direction) {
12917        final int offset = computeVerticalScrollOffset();
12918        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12919        if (range == 0) return false;
12920        if (direction < 0) {
12921            return offset > 0;
12922        } else {
12923            return offset < range - 1;
12924        }
12925    }
12926
12927    /**
12928     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12929     * scrollbars are painted only if they have been awakened first.</p>
12930     *
12931     * @param canvas the canvas on which to draw the scrollbars
12932     *
12933     * @see #awakenScrollBars(int)
12934     */
12935    protected final void onDrawScrollBars(Canvas canvas) {
12936        // scrollbars are drawn only when the animation is running
12937        final ScrollabilityCache cache = mScrollCache;
12938        if (cache != null) {
12939
12940            int state = cache.state;
12941
12942            if (state == ScrollabilityCache.OFF) {
12943                return;
12944            }
12945
12946            boolean invalidate = false;
12947
12948            if (state == ScrollabilityCache.FADING) {
12949                // We're fading -- get our fade interpolation
12950                if (cache.interpolatorValues == null) {
12951                    cache.interpolatorValues = new float[1];
12952                }
12953
12954                float[] values = cache.interpolatorValues;
12955
12956                // Stops the animation if we're done
12957                if (cache.scrollBarInterpolator.timeToValues(values) ==
12958                        Interpolator.Result.FREEZE_END) {
12959                    cache.state = ScrollabilityCache.OFF;
12960                } else {
12961                    cache.scrollBar.setAlpha(Math.round(values[0]));
12962                }
12963
12964                // This will make the scroll bars inval themselves after
12965                // drawing. We only want this when we're fading so that
12966                // we prevent excessive redraws
12967                invalidate = true;
12968            } else {
12969                // We're just on -- but we may have been fading before so
12970                // reset alpha
12971                cache.scrollBar.setAlpha(255);
12972            }
12973
12974
12975            final int viewFlags = mViewFlags;
12976
12977            final boolean drawHorizontalScrollBar =
12978                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12979            final boolean drawVerticalScrollBar =
12980                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12981                && !isVerticalScrollBarHidden();
12982
12983            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12984                final int width = mRight - mLeft;
12985                final int height = mBottom - mTop;
12986
12987                final ScrollBarDrawable scrollBar = cache.scrollBar;
12988
12989                final int scrollX = mScrollX;
12990                final int scrollY = mScrollY;
12991                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12992
12993                int left;
12994                int top;
12995                int right;
12996                int bottom;
12997
12998                if (drawHorizontalScrollBar) {
12999                    int size = scrollBar.getSize(false);
13000                    if (size <= 0) {
13001                        size = cache.scrollBarSize;
13002                    }
13003
13004                    scrollBar.setParameters(computeHorizontalScrollRange(),
13005                                            computeHorizontalScrollOffset(),
13006                                            computeHorizontalScrollExtent(), false);
13007                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13008                            getVerticalScrollbarWidth() : 0;
13009                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13010                    left = scrollX + (mPaddingLeft & inside);
13011                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13012                    bottom = top + size;
13013                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13014                    if (invalidate) {
13015                        invalidate(left, top, right, bottom);
13016                    }
13017                }
13018
13019                if (drawVerticalScrollBar) {
13020                    int size = scrollBar.getSize(true);
13021                    if (size <= 0) {
13022                        size = cache.scrollBarSize;
13023                    }
13024
13025                    scrollBar.setParameters(computeVerticalScrollRange(),
13026                                            computeVerticalScrollOffset(),
13027                                            computeVerticalScrollExtent(), true);
13028                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13029                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13030                        verticalScrollbarPosition = isLayoutRtl() ?
13031                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13032                    }
13033                    switch (verticalScrollbarPosition) {
13034                        default:
13035                        case SCROLLBAR_POSITION_RIGHT:
13036                            left = scrollX + width - size - (mUserPaddingRight & inside);
13037                            break;
13038                        case SCROLLBAR_POSITION_LEFT:
13039                            left = scrollX + (mUserPaddingLeft & inside);
13040                            break;
13041                    }
13042                    top = scrollY + (mPaddingTop & inside);
13043                    right = left + size;
13044                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13045                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13046                    if (invalidate) {
13047                        invalidate(left, top, right, bottom);
13048                    }
13049                }
13050            }
13051        }
13052    }
13053
13054    /**
13055     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13056     * FastScroller is visible.
13057     * @return whether to temporarily hide the vertical scrollbar
13058     * @hide
13059     */
13060    protected boolean isVerticalScrollBarHidden() {
13061        return false;
13062    }
13063
13064    /**
13065     * <p>Draw the horizontal scrollbar if
13066     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13067     *
13068     * @param canvas the canvas on which to draw the scrollbar
13069     * @param scrollBar the scrollbar's drawable
13070     *
13071     * @see #isHorizontalScrollBarEnabled()
13072     * @see #computeHorizontalScrollRange()
13073     * @see #computeHorizontalScrollExtent()
13074     * @see #computeHorizontalScrollOffset()
13075     * @see android.widget.ScrollBarDrawable
13076     * @hide
13077     */
13078    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13079            int l, int t, int r, int b) {
13080        scrollBar.setBounds(l, t, r, b);
13081        scrollBar.draw(canvas);
13082    }
13083
13084    /**
13085     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13086     * returns true.</p>
13087     *
13088     * @param canvas the canvas on which to draw the scrollbar
13089     * @param scrollBar the scrollbar's drawable
13090     *
13091     * @see #isVerticalScrollBarEnabled()
13092     * @see #computeVerticalScrollRange()
13093     * @see #computeVerticalScrollExtent()
13094     * @see #computeVerticalScrollOffset()
13095     * @see android.widget.ScrollBarDrawable
13096     * @hide
13097     */
13098    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13099            int l, int t, int r, int b) {
13100        scrollBar.setBounds(l, t, r, b);
13101        scrollBar.draw(canvas);
13102    }
13103
13104    /**
13105     * Implement this to do your drawing.
13106     *
13107     * @param canvas the canvas on which the background will be drawn
13108     */
13109    protected void onDraw(Canvas canvas) {
13110    }
13111
13112    /*
13113     * Caller is responsible for calling requestLayout if necessary.
13114     * (This allows addViewInLayout to not request a new layout.)
13115     */
13116    void assignParent(ViewParent parent) {
13117        if (mParent == null) {
13118            mParent = parent;
13119        } else if (parent == null) {
13120            mParent = null;
13121        } else {
13122            throw new RuntimeException("view " + this + " being added, but"
13123                    + " it already has a parent");
13124        }
13125    }
13126
13127    /**
13128     * This is called when the view is attached to a window.  At this point it
13129     * has a Surface and will start drawing.  Note that this function is
13130     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13131     * however it may be called any time before the first onDraw -- including
13132     * before or after {@link #onMeasure(int, int)}.
13133     *
13134     * @see #onDetachedFromWindow()
13135     */
13136    protected void onAttachedToWindow() {
13137        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13138            mParent.requestTransparentRegion(this);
13139        }
13140
13141        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13142            initialAwakenScrollBars();
13143            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13144        }
13145
13146        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13147
13148        jumpDrawablesToCurrentState();
13149
13150        resetSubtreeAccessibilityStateChanged();
13151
13152        // rebuild, since Outline not maintained while View is detached
13153        rebuildOutline();
13154
13155        if (isFocused()) {
13156            InputMethodManager imm = InputMethodManager.peekInstance();
13157            imm.focusIn(this);
13158        }
13159    }
13160
13161    /**
13162     * Resolve all RTL related properties.
13163     *
13164     * @return true if resolution of RTL properties has been done
13165     *
13166     * @hide
13167     */
13168    public boolean resolveRtlPropertiesIfNeeded() {
13169        if (!needRtlPropertiesResolution()) return false;
13170
13171        // Order is important here: LayoutDirection MUST be resolved first
13172        if (!isLayoutDirectionResolved()) {
13173            resolveLayoutDirection();
13174            resolveLayoutParams();
13175        }
13176        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13177        if (!isTextDirectionResolved()) {
13178            resolveTextDirection();
13179        }
13180        if (!isTextAlignmentResolved()) {
13181            resolveTextAlignment();
13182        }
13183        // Should resolve Drawables before Padding because we need the layout direction of the
13184        // Drawable to correctly resolve Padding.
13185        if (!areDrawablesResolved()) {
13186            resolveDrawables();
13187        }
13188        if (!isPaddingResolved()) {
13189            resolvePadding();
13190        }
13191        onRtlPropertiesChanged(getLayoutDirection());
13192        return true;
13193    }
13194
13195    /**
13196     * Reset resolution of all RTL related properties.
13197     *
13198     * @hide
13199     */
13200    public void resetRtlProperties() {
13201        resetResolvedLayoutDirection();
13202        resetResolvedTextDirection();
13203        resetResolvedTextAlignment();
13204        resetResolvedPadding();
13205        resetResolvedDrawables();
13206    }
13207
13208    /**
13209     * @see #onScreenStateChanged(int)
13210     */
13211    void dispatchScreenStateChanged(int screenState) {
13212        onScreenStateChanged(screenState);
13213    }
13214
13215    /**
13216     * This method is called whenever the state of the screen this view is
13217     * attached to changes. A state change will usually occurs when the screen
13218     * turns on or off (whether it happens automatically or the user does it
13219     * manually.)
13220     *
13221     * @param screenState The new state of the screen. Can be either
13222     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13223     */
13224    public void onScreenStateChanged(int screenState) {
13225    }
13226
13227    /**
13228     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13229     */
13230    private boolean hasRtlSupport() {
13231        return mContext.getApplicationInfo().hasRtlSupport();
13232    }
13233
13234    /**
13235     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13236     * RTL not supported)
13237     */
13238    private boolean isRtlCompatibilityMode() {
13239        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13240        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13241    }
13242
13243    /**
13244     * @return true if RTL properties need resolution.
13245     *
13246     */
13247    private boolean needRtlPropertiesResolution() {
13248        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13249    }
13250
13251    /**
13252     * Called when any RTL property (layout direction or text direction or text alignment) has
13253     * been changed.
13254     *
13255     * Subclasses need to override this method to take care of cached information that depends on the
13256     * resolved layout direction, or to inform child views that inherit their layout direction.
13257     *
13258     * The default implementation does nothing.
13259     *
13260     * @param layoutDirection the direction of the layout
13261     *
13262     * @see #LAYOUT_DIRECTION_LTR
13263     * @see #LAYOUT_DIRECTION_RTL
13264     */
13265    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13266    }
13267
13268    /**
13269     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13270     * that the parent directionality can and will be resolved before its children.
13271     *
13272     * @return true if resolution has been done, false otherwise.
13273     *
13274     * @hide
13275     */
13276    public boolean resolveLayoutDirection() {
13277        // Clear any previous layout direction resolution
13278        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13279
13280        if (hasRtlSupport()) {
13281            // Set resolved depending on layout direction
13282            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13283                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13284                case LAYOUT_DIRECTION_INHERIT:
13285                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13286                    // later to get the correct resolved value
13287                    if (!canResolveLayoutDirection()) return false;
13288
13289                    // Parent has not yet resolved, LTR is still the default
13290                    try {
13291                        if (!mParent.isLayoutDirectionResolved()) return false;
13292
13293                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13294                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13295                        }
13296                    } catch (AbstractMethodError e) {
13297                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13298                                " does not fully implement ViewParent", e);
13299                    }
13300                    break;
13301                case LAYOUT_DIRECTION_RTL:
13302                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13303                    break;
13304                case LAYOUT_DIRECTION_LOCALE:
13305                    if((LAYOUT_DIRECTION_RTL ==
13306                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13307                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13308                    }
13309                    break;
13310                default:
13311                    // Nothing to do, LTR by default
13312            }
13313        }
13314
13315        // Set to resolved
13316        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13317        return true;
13318    }
13319
13320    /**
13321     * Check if layout direction resolution can be done.
13322     *
13323     * @return true if layout direction resolution can be done otherwise return false.
13324     */
13325    public boolean canResolveLayoutDirection() {
13326        switch (getRawLayoutDirection()) {
13327            case LAYOUT_DIRECTION_INHERIT:
13328                if (mParent != null) {
13329                    try {
13330                        return mParent.canResolveLayoutDirection();
13331                    } catch (AbstractMethodError e) {
13332                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13333                                " does not fully implement ViewParent", e);
13334                    }
13335                }
13336                return false;
13337
13338            default:
13339                return true;
13340        }
13341    }
13342
13343    /**
13344     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13345     * {@link #onMeasure(int, int)}.
13346     *
13347     * @hide
13348     */
13349    public void resetResolvedLayoutDirection() {
13350        // Reset the current resolved bits
13351        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13352    }
13353
13354    /**
13355     * @return true if the layout direction is inherited.
13356     *
13357     * @hide
13358     */
13359    public boolean isLayoutDirectionInherited() {
13360        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13361    }
13362
13363    /**
13364     * @return true if layout direction has been resolved.
13365     */
13366    public boolean isLayoutDirectionResolved() {
13367        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13368    }
13369
13370    /**
13371     * Return if padding has been resolved
13372     *
13373     * @hide
13374     */
13375    boolean isPaddingResolved() {
13376        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13377    }
13378
13379    /**
13380     * Resolves padding depending on layout direction, if applicable, and
13381     * recomputes internal padding values to adjust for scroll bars.
13382     *
13383     * @hide
13384     */
13385    public void resolvePadding() {
13386        final int resolvedLayoutDirection = getLayoutDirection();
13387
13388        if (!isRtlCompatibilityMode()) {
13389            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13390            // If start / end padding are defined, they will be resolved (hence overriding) to
13391            // left / right or right / left depending on the resolved layout direction.
13392            // If start / end padding are not defined, use the left / right ones.
13393            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13394                Rect padding = sThreadLocal.get();
13395                if (padding == null) {
13396                    padding = new Rect();
13397                    sThreadLocal.set(padding);
13398                }
13399                mBackground.getPadding(padding);
13400                if (!mLeftPaddingDefined) {
13401                    mUserPaddingLeftInitial = padding.left;
13402                }
13403                if (!mRightPaddingDefined) {
13404                    mUserPaddingRightInitial = padding.right;
13405                }
13406            }
13407            switch (resolvedLayoutDirection) {
13408                case LAYOUT_DIRECTION_RTL:
13409                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13410                        mUserPaddingRight = mUserPaddingStart;
13411                    } else {
13412                        mUserPaddingRight = mUserPaddingRightInitial;
13413                    }
13414                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13415                        mUserPaddingLeft = mUserPaddingEnd;
13416                    } else {
13417                        mUserPaddingLeft = mUserPaddingLeftInitial;
13418                    }
13419                    break;
13420                case LAYOUT_DIRECTION_LTR:
13421                default:
13422                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13423                        mUserPaddingLeft = mUserPaddingStart;
13424                    } else {
13425                        mUserPaddingLeft = mUserPaddingLeftInitial;
13426                    }
13427                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13428                        mUserPaddingRight = mUserPaddingEnd;
13429                    } else {
13430                        mUserPaddingRight = mUserPaddingRightInitial;
13431                    }
13432            }
13433
13434            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13435        }
13436
13437        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13438        onRtlPropertiesChanged(resolvedLayoutDirection);
13439
13440        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13441    }
13442
13443    /**
13444     * Reset the resolved layout direction.
13445     *
13446     * @hide
13447     */
13448    public void resetResolvedPadding() {
13449        resetResolvedPaddingInternal();
13450    }
13451
13452    /**
13453     * Used when we only want to reset *this* view's padding and not trigger overrides
13454     * in ViewGroup that reset children too.
13455     */
13456    void resetResolvedPaddingInternal() {
13457        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13458    }
13459
13460    /**
13461     * This is called when the view is detached from a window.  At this point it
13462     * no longer has a surface for drawing.
13463     *
13464     * @see #onAttachedToWindow()
13465     */
13466    protected void onDetachedFromWindow() {
13467    }
13468
13469    /**
13470     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13471     * after onDetachedFromWindow().
13472     *
13473     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13474     * The super method should be called at the end of the overridden method to ensure
13475     * subclasses are destroyed first
13476     *
13477     * @hide
13478     */
13479    protected void onDetachedFromWindowInternal() {
13480        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13481        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13482
13483        removeUnsetPressCallback();
13484        removeLongPressCallback();
13485        removePerformClickCallback();
13486        removeSendViewScrolledAccessibilityEventCallback();
13487        stopNestedScroll();
13488
13489        // Anything that started animating right before detach should already
13490        // be in its final state when re-attached.
13491        jumpDrawablesToCurrentState();
13492
13493        destroyDrawingCache();
13494
13495        cleanupDraw();
13496        mCurrentAnimation = null;
13497    }
13498
13499    private void cleanupDraw() {
13500        resetDisplayList();
13501        if (mAttachInfo != null) {
13502            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13503        }
13504    }
13505
13506    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13507    }
13508
13509    /**
13510     * @return The number of times this view has been attached to a window
13511     */
13512    protected int getWindowAttachCount() {
13513        return mWindowAttachCount;
13514    }
13515
13516    /**
13517     * Retrieve a unique token identifying the window this view is attached to.
13518     * @return Return the window's token for use in
13519     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13520     */
13521    public IBinder getWindowToken() {
13522        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13523    }
13524
13525    /**
13526     * Retrieve the {@link WindowId} for the window this view is
13527     * currently attached to.
13528     */
13529    public WindowId getWindowId() {
13530        if (mAttachInfo == null) {
13531            return null;
13532        }
13533        if (mAttachInfo.mWindowId == null) {
13534            try {
13535                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13536                        mAttachInfo.mWindowToken);
13537                mAttachInfo.mWindowId = new WindowId(
13538                        mAttachInfo.mIWindowId);
13539            } catch (RemoteException e) {
13540            }
13541        }
13542        return mAttachInfo.mWindowId;
13543    }
13544
13545    /**
13546     * Retrieve a unique token identifying the top-level "real" window of
13547     * the window that this view is attached to.  That is, this is like
13548     * {@link #getWindowToken}, except if the window this view in is a panel
13549     * window (attached to another containing window), then the token of
13550     * the containing window is returned instead.
13551     *
13552     * @return Returns the associated window token, either
13553     * {@link #getWindowToken()} or the containing window's token.
13554     */
13555    public IBinder getApplicationWindowToken() {
13556        AttachInfo ai = mAttachInfo;
13557        if (ai != null) {
13558            IBinder appWindowToken = ai.mPanelParentWindowToken;
13559            if (appWindowToken == null) {
13560                appWindowToken = ai.mWindowToken;
13561            }
13562            return appWindowToken;
13563        }
13564        return null;
13565    }
13566
13567    /**
13568     * Gets the logical display to which the view's window has been attached.
13569     *
13570     * @return The logical display, or null if the view is not currently attached to a window.
13571     */
13572    public Display getDisplay() {
13573        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13574    }
13575
13576    /**
13577     * Retrieve private session object this view hierarchy is using to
13578     * communicate with the window manager.
13579     * @return the session object to communicate with the window manager
13580     */
13581    /*package*/ IWindowSession getWindowSession() {
13582        return mAttachInfo != null ? mAttachInfo.mSession : null;
13583    }
13584
13585    /**
13586     * @param info the {@link android.view.View.AttachInfo} to associated with
13587     *        this view
13588     */
13589    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13590        //System.out.println("Attached! " + this);
13591        mAttachInfo = info;
13592        if (mOverlay != null) {
13593            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13594        }
13595        mWindowAttachCount++;
13596        // We will need to evaluate the drawable state at least once.
13597        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13598        if (mFloatingTreeObserver != null) {
13599            info.mTreeObserver.merge(mFloatingTreeObserver);
13600            mFloatingTreeObserver = null;
13601        }
13602        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13603            mAttachInfo.mScrollContainers.add(this);
13604            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13605        }
13606        performCollectViewAttributes(mAttachInfo, visibility);
13607        onAttachedToWindow();
13608
13609        ListenerInfo li = mListenerInfo;
13610        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13611                li != null ? li.mOnAttachStateChangeListeners : null;
13612        if (listeners != null && listeners.size() > 0) {
13613            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13614            // perform the dispatching. The iterator is a safe guard against listeners that
13615            // could mutate the list by calling the various add/remove methods. This prevents
13616            // the array from being modified while we iterate it.
13617            for (OnAttachStateChangeListener listener : listeners) {
13618                listener.onViewAttachedToWindow(this);
13619            }
13620        }
13621
13622        int vis = info.mWindowVisibility;
13623        if (vis != GONE) {
13624            onWindowVisibilityChanged(vis);
13625        }
13626        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13627            // If nobody has evaluated the drawable state yet, then do it now.
13628            refreshDrawableState();
13629        }
13630        needGlobalAttributesUpdate(false);
13631    }
13632
13633    void dispatchDetachedFromWindow() {
13634        AttachInfo info = mAttachInfo;
13635        if (info != null) {
13636            int vis = info.mWindowVisibility;
13637            if (vis != GONE) {
13638                onWindowVisibilityChanged(GONE);
13639            }
13640        }
13641
13642        onDetachedFromWindow();
13643        onDetachedFromWindowInternal();
13644
13645        ListenerInfo li = mListenerInfo;
13646        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13647                li != null ? li.mOnAttachStateChangeListeners : null;
13648        if (listeners != null && listeners.size() > 0) {
13649            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13650            // perform the dispatching. The iterator is a safe guard against listeners that
13651            // could mutate the list by calling the various add/remove methods. This prevents
13652            // the array from being modified while we iterate it.
13653            for (OnAttachStateChangeListener listener : listeners) {
13654                listener.onViewDetachedFromWindow(this);
13655            }
13656        }
13657
13658        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13659            mAttachInfo.mScrollContainers.remove(this);
13660            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13661        }
13662
13663        mAttachInfo = null;
13664        if (mOverlay != null) {
13665            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13666        }
13667    }
13668
13669    /**
13670     * Cancel any deferred high-level input events that were previously posted to the event queue.
13671     *
13672     * <p>Many views post high-level events such as click handlers to the event queue
13673     * to run deferred in order to preserve a desired user experience - clearing visible
13674     * pressed states before executing, etc. This method will abort any events of this nature
13675     * that are currently in flight.</p>
13676     *
13677     * <p>Custom views that generate their own high-level deferred input events should override
13678     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13679     *
13680     * <p>This will also cancel pending input events for any child views.</p>
13681     *
13682     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13683     * This will not impact newer events posted after this call that may occur as a result of
13684     * lower-level input events still waiting in the queue. If you are trying to prevent
13685     * double-submitted  events for the duration of some sort of asynchronous transaction
13686     * you should also take other steps to protect against unexpected double inputs e.g. calling
13687     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13688     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13689     */
13690    public final void cancelPendingInputEvents() {
13691        dispatchCancelPendingInputEvents();
13692    }
13693
13694    /**
13695     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13696     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13697     */
13698    void dispatchCancelPendingInputEvents() {
13699        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13700        onCancelPendingInputEvents();
13701        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13702            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13703                    " did not call through to super.onCancelPendingInputEvents()");
13704        }
13705    }
13706
13707    /**
13708     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13709     * a parent view.
13710     *
13711     * <p>This method is responsible for removing any pending high-level input events that were
13712     * posted to the event queue to run later. Custom view classes that post their own deferred
13713     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13714     * {@link android.os.Handler} should override this method, call
13715     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13716     * </p>
13717     */
13718    public void onCancelPendingInputEvents() {
13719        removePerformClickCallback();
13720        cancelLongPress();
13721        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13722    }
13723
13724    /**
13725     * Store this view hierarchy's frozen state into the given container.
13726     *
13727     * @param container The SparseArray in which to save the view's state.
13728     *
13729     * @see #restoreHierarchyState(android.util.SparseArray)
13730     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13731     * @see #onSaveInstanceState()
13732     */
13733    public void saveHierarchyState(SparseArray<Parcelable> container) {
13734        dispatchSaveInstanceState(container);
13735    }
13736
13737    /**
13738     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13739     * this view and its children. May be overridden to modify how freezing happens to a
13740     * view's children; for example, some views may want to not store state for their children.
13741     *
13742     * @param container The SparseArray in which to save the view's state.
13743     *
13744     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13745     * @see #saveHierarchyState(android.util.SparseArray)
13746     * @see #onSaveInstanceState()
13747     */
13748    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13749        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13750            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13751            Parcelable state = onSaveInstanceState();
13752            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13753                throw new IllegalStateException(
13754                        "Derived class did not call super.onSaveInstanceState()");
13755            }
13756            if (state != null) {
13757                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13758                // + ": " + state);
13759                container.put(mID, state);
13760            }
13761        }
13762    }
13763
13764    /**
13765     * Hook allowing a view to generate a representation of its internal state
13766     * that can later be used to create a new instance with that same state.
13767     * This state should only contain information that is not persistent or can
13768     * not be reconstructed later. For example, you will never store your
13769     * current position on screen because that will be computed again when a
13770     * new instance of the view is placed in its view hierarchy.
13771     * <p>
13772     * Some examples of things you may store here: the current cursor position
13773     * in a text view (but usually not the text itself since that is stored in a
13774     * content provider or other persistent storage), the currently selected
13775     * item in a list view.
13776     *
13777     * @return Returns a Parcelable object containing the view's current dynamic
13778     *         state, or null if there is nothing interesting to save. The
13779     *         default implementation returns null.
13780     * @see #onRestoreInstanceState(android.os.Parcelable)
13781     * @see #saveHierarchyState(android.util.SparseArray)
13782     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13783     * @see #setSaveEnabled(boolean)
13784     */
13785    protected Parcelable onSaveInstanceState() {
13786        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13787        return BaseSavedState.EMPTY_STATE;
13788    }
13789
13790    /**
13791     * Restore this view hierarchy's frozen state from the given container.
13792     *
13793     * @param container The SparseArray which holds previously frozen states.
13794     *
13795     * @see #saveHierarchyState(android.util.SparseArray)
13796     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13797     * @see #onRestoreInstanceState(android.os.Parcelable)
13798     */
13799    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13800        dispatchRestoreInstanceState(container);
13801    }
13802
13803    /**
13804     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13805     * state for this view and its children. May be overridden to modify how restoring
13806     * happens to a view's children; for example, some views may want to not store state
13807     * for their children.
13808     *
13809     * @param container The SparseArray which holds previously saved state.
13810     *
13811     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13812     * @see #restoreHierarchyState(android.util.SparseArray)
13813     * @see #onRestoreInstanceState(android.os.Parcelable)
13814     */
13815    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13816        if (mID != NO_ID) {
13817            Parcelable state = container.get(mID);
13818            if (state != null) {
13819                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13820                // + ": " + state);
13821                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13822                onRestoreInstanceState(state);
13823                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13824                    throw new IllegalStateException(
13825                            "Derived class did not call super.onRestoreInstanceState()");
13826                }
13827            }
13828        }
13829    }
13830
13831    /**
13832     * Hook allowing a view to re-apply a representation of its internal state that had previously
13833     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13834     * null state.
13835     *
13836     * @param state The frozen state that had previously been returned by
13837     *        {@link #onSaveInstanceState}.
13838     *
13839     * @see #onSaveInstanceState()
13840     * @see #restoreHierarchyState(android.util.SparseArray)
13841     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13842     */
13843    protected void onRestoreInstanceState(Parcelable state) {
13844        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13845        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13846            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13847                    + "received " + state.getClass().toString() + " instead. This usually happens "
13848                    + "when two views of different type have the same id in the same hierarchy. "
13849                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13850                    + "other views do not use the same id.");
13851        }
13852    }
13853
13854    /**
13855     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13856     *
13857     * @return the drawing start time in milliseconds
13858     */
13859    public long getDrawingTime() {
13860        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13861    }
13862
13863    /**
13864     * <p>Enables or disables the duplication of the parent's state into this view. When
13865     * duplication is enabled, this view gets its drawable state from its parent rather
13866     * than from its own internal properties.</p>
13867     *
13868     * <p>Note: in the current implementation, setting this property to true after the
13869     * view was added to a ViewGroup might have no effect at all. This property should
13870     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13871     *
13872     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13873     * property is enabled, an exception will be thrown.</p>
13874     *
13875     * <p>Note: if the child view uses and updates additional states which are unknown to the
13876     * parent, these states should not be affected by this method.</p>
13877     *
13878     * @param enabled True to enable duplication of the parent's drawable state, false
13879     *                to disable it.
13880     *
13881     * @see #getDrawableState()
13882     * @see #isDuplicateParentStateEnabled()
13883     */
13884    public void setDuplicateParentStateEnabled(boolean enabled) {
13885        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13886    }
13887
13888    /**
13889     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13890     *
13891     * @return True if this view's drawable state is duplicated from the parent,
13892     *         false otherwise
13893     *
13894     * @see #getDrawableState()
13895     * @see #setDuplicateParentStateEnabled(boolean)
13896     */
13897    public boolean isDuplicateParentStateEnabled() {
13898        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13899    }
13900
13901    /**
13902     * <p>Specifies the type of layer backing this view. The layer can be
13903     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13904     * {@link #LAYER_TYPE_HARDWARE}.</p>
13905     *
13906     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13907     * instance that controls how the layer is composed on screen. The following
13908     * properties of the paint are taken into account when composing the layer:</p>
13909     * <ul>
13910     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13911     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13912     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13913     * </ul>
13914     *
13915     * <p>If this view has an alpha value set to < 1.0 by calling
13916     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
13917     * by this view's alpha value.</p>
13918     *
13919     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13920     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13921     * for more information on when and how to use layers.</p>
13922     *
13923     * @param layerType The type of layer to use with this view, must be one of
13924     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13925     *        {@link #LAYER_TYPE_HARDWARE}
13926     * @param paint The paint used to compose the layer. This argument is optional
13927     *        and can be null. It is ignored when the layer type is
13928     *        {@link #LAYER_TYPE_NONE}
13929     *
13930     * @see #getLayerType()
13931     * @see #LAYER_TYPE_NONE
13932     * @see #LAYER_TYPE_SOFTWARE
13933     * @see #LAYER_TYPE_HARDWARE
13934     * @see #setAlpha(float)
13935     *
13936     * @attr ref android.R.styleable#View_layerType
13937     */
13938    public void setLayerType(int layerType, Paint paint) {
13939        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13940            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13941                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13942        }
13943
13944        boolean typeChanged = mRenderNode.setLayerType(layerType);
13945
13946        if (!typeChanged) {
13947            setLayerPaint(paint);
13948            return;
13949        }
13950
13951        // Destroy any previous software drawing cache if needed
13952        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13953            destroyDrawingCache();
13954        }
13955
13956        mLayerType = layerType;
13957        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13958        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13959        mRenderNode.setLayerPaint(mLayerPaint);
13960
13961        // draw() behaves differently if we are on a layer, so we need to
13962        // invalidate() here
13963        invalidateParentCaches();
13964        invalidate(true);
13965    }
13966
13967    /**
13968     * Updates the {@link Paint} object used with the current layer (used only if the current
13969     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13970     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13971     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13972     * ensure that the view gets redrawn immediately.
13973     *
13974     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13975     * instance that controls how the layer is composed on screen. The following
13976     * properties of the paint are taken into account when composing the layer:</p>
13977     * <ul>
13978     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13979     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13980     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13981     * </ul>
13982     *
13983     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13984     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
13985     *
13986     * @param paint The paint used to compose the layer. This argument is optional
13987     *        and can be null. It is ignored when the layer type is
13988     *        {@link #LAYER_TYPE_NONE}
13989     *
13990     * @see #setLayerType(int, android.graphics.Paint)
13991     */
13992    public void setLayerPaint(Paint paint) {
13993        int layerType = getLayerType();
13994        if (layerType != LAYER_TYPE_NONE) {
13995            mLayerPaint = paint == null ? new Paint() : paint;
13996            if (layerType == LAYER_TYPE_HARDWARE) {
13997                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13998                    invalidateViewProperty(false, false);
13999                }
14000            } else {
14001                invalidate();
14002            }
14003        }
14004    }
14005
14006    /**
14007     * Indicates whether this view has a static layer. A view with layer type
14008     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
14009     * dynamic.
14010     */
14011    boolean hasStaticLayer() {
14012        return true;
14013    }
14014
14015    /**
14016     * Indicates what type of layer is currently associated with this view. By default
14017     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14018     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14019     * for more information on the different types of layers.
14020     *
14021     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14022     *         {@link #LAYER_TYPE_HARDWARE}
14023     *
14024     * @see #setLayerType(int, android.graphics.Paint)
14025     * @see #buildLayer()
14026     * @see #LAYER_TYPE_NONE
14027     * @see #LAYER_TYPE_SOFTWARE
14028     * @see #LAYER_TYPE_HARDWARE
14029     */
14030    public int getLayerType() {
14031        return mLayerType;
14032    }
14033
14034    /**
14035     * Forces this view's layer to be created and this view to be rendered
14036     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14037     * invoking this method will have no effect.
14038     *
14039     * This method can for instance be used to render a view into its layer before
14040     * starting an animation. If this view is complex, rendering into the layer
14041     * before starting the animation will avoid skipping frames.
14042     *
14043     * @throws IllegalStateException If this view is not attached to a window
14044     *
14045     * @see #setLayerType(int, android.graphics.Paint)
14046     */
14047    public void buildLayer() {
14048        if (mLayerType == LAYER_TYPE_NONE) return;
14049
14050        final AttachInfo attachInfo = mAttachInfo;
14051        if (attachInfo == null) {
14052            throw new IllegalStateException("This view must be attached to a window first");
14053        }
14054
14055        if (getWidth() == 0 || getHeight() == 0) {
14056            return;
14057        }
14058
14059        switch (mLayerType) {
14060            case LAYER_TYPE_HARDWARE:
14061                updateDisplayListIfDirty();
14062                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14063                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14064                }
14065                break;
14066            case LAYER_TYPE_SOFTWARE:
14067                buildDrawingCache(true);
14068                break;
14069        }
14070    }
14071
14072    /**
14073     * If this View draws with a HardwareLayer, returns it.
14074     * Otherwise returns null
14075     *
14076     * TODO: Only TextureView uses this, can we eliminate it?
14077     */
14078    HardwareLayer getHardwareLayer() {
14079        return null;
14080    }
14081
14082    /**
14083     * Destroys all hardware rendering resources. This method is invoked
14084     * when the system needs to reclaim resources. Upon execution of this
14085     * method, you should free any OpenGL resources created by the view.
14086     *
14087     * Note: you <strong>must</strong> call
14088     * <code>super.destroyHardwareResources()</code> when overriding
14089     * this method.
14090     *
14091     * @hide
14092     */
14093    protected void destroyHardwareResources() {
14094        // Although the Layer will be destroyed by RenderNode, we want to release
14095        // the staging display list, which is also a signal to RenderNode that it's
14096        // safe to free its copy of the display list as it knows that we will
14097        // push an updated DisplayList if we try to draw again
14098        resetDisplayList();
14099    }
14100
14101    /**
14102     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14103     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14104     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14105     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14106     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14107     * null.</p>
14108     *
14109     * <p>Enabling the drawing cache is similar to
14110     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14111     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14112     * drawing cache has no effect on rendering because the system uses a different mechanism
14113     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14114     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14115     * for information on how to enable software and hardware layers.</p>
14116     *
14117     * <p>This API can be used to manually generate
14118     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14119     * {@link #getDrawingCache()}.</p>
14120     *
14121     * @param enabled true to enable the drawing cache, false otherwise
14122     *
14123     * @see #isDrawingCacheEnabled()
14124     * @see #getDrawingCache()
14125     * @see #buildDrawingCache()
14126     * @see #setLayerType(int, android.graphics.Paint)
14127     */
14128    public void setDrawingCacheEnabled(boolean enabled) {
14129        mCachingFailed = false;
14130        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14131    }
14132
14133    /**
14134     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14135     *
14136     * @return true if the drawing cache is enabled
14137     *
14138     * @see #setDrawingCacheEnabled(boolean)
14139     * @see #getDrawingCache()
14140     */
14141    @ViewDebug.ExportedProperty(category = "drawing")
14142    public boolean isDrawingCacheEnabled() {
14143        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14144    }
14145
14146    /**
14147     * Debugging utility which recursively outputs the dirty state of a view and its
14148     * descendants.
14149     *
14150     * @hide
14151     */
14152    @SuppressWarnings({"UnusedDeclaration"})
14153    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14154        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14155                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14156                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14157                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14158        if (clear) {
14159            mPrivateFlags &= clearMask;
14160        }
14161        if (this instanceof ViewGroup) {
14162            ViewGroup parent = (ViewGroup) this;
14163            final int count = parent.getChildCount();
14164            for (int i = 0; i < count; i++) {
14165                final View child = parent.getChildAt(i);
14166                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14167            }
14168        }
14169    }
14170
14171    /**
14172     * This method is used by ViewGroup to cause its children to restore or recreate their
14173     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14174     * to recreate its own display list, which would happen if it went through the normal
14175     * draw/dispatchDraw mechanisms.
14176     *
14177     * @hide
14178     */
14179    protected void dispatchGetDisplayList() {}
14180
14181    /**
14182     * A view that is not attached or hardware accelerated cannot create a display list.
14183     * This method checks these conditions and returns the appropriate result.
14184     *
14185     * @return true if view has the ability to create a display list, false otherwise.
14186     *
14187     * @hide
14188     */
14189    public boolean canHaveDisplayList() {
14190        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14191    }
14192
14193    private void updateDisplayListIfDirty() {
14194        final RenderNode renderNode = mRenderNode;
14195        if (!canHaveDisplayList()) {
14196            // can't populate RenderNode, don't try
14197            return;
14198        }
14199
14200        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14201                || !renderNode.isValid()
14202                || (mRecreateDisplayList)) {
14203            // Don't need to recreate the display list, just need to tell our
14204            // children to restore/recreate theirs
14205            if (renderNode.isValid()
14206                    && !mRecreateDisplayList) {
14207                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14208                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14209                dispatchGetDisplayList();
14210
14211                return; // no work needed
14212            }
14213
14214            // If we got here, we're recreating it. Mark it as such to ensure that
14215            // we copy in child display lists into ours in drawChild()
14216            mRecreateDisplayList = true;
14217
14218            int width = mRight - mLeft;
14219            int height = mBottom - mTop;
14220            int layerType = getLayerType();
14221
14222            final HardwareCanvas canvas = renderNode.start(width, height);
14223            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14224
14225            try {
14226                final HardwareLayer layer = getHardwareLayer();
14227                if (layer != null && layer.isValid()) {
14228                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14229                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14230                    buildDrawingCache(true);
14231                    Bitmap cache = getDrawingCache(true);
14232                    if (cache != null) {
14233                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14234                    }
14235                } else {
14236                    computeScroll();
14237
14238                    canvas.translate(-mScrollX, -mScrollY);
14239                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14240                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14241
14242                    // Fast path for layouts with no backgrounds
14243                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14244                        dispatchDraw(canvas);
14245                        if (mOverlay != null && !mOverlay.isEmpty()) {
14246                            mOverlay.getOverlayView().draw(canvas);
14247                        }
14248                    } else {
14249                        draw(canvas);
14250                    }
14251                }
14252            } finally {
14253                renderNode.end(canvas);
14254                setDisplayListProperties(renderNode);
14255            }
14256        } else {
14257            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14258            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14259        }
14260    }
14261
14262    /**
14263     * Returns a RenderNode with View draw content recorded, which can be
14264     * used to draw this view again without executing its draw method.
14265     *
14266     * @return A RenderNode ready to replay, or null if caching is not enabled.
14267     *
14268     * @hide
14269     */
14270    public RenderNode getDisplayList() {
14271        updateDisplayListIfDirty();
14272        return mRenderNode;
14273    }
14274
14275    private void resetDisplayList() {
14276        if (mRenderNode.isValid()) {
14277            mRenderNode.destroyDisplayListData();
14278        }
14279
14280        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14281            mBackgroundRenderNode.destroyDisplayListData();
14282        }
14283    }
14284
14285    /**
14286     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14287     *
14288     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14289     *
14290     * @see #getDrawingCache(boolean)
14291     */
14292    public Bitmap getDrawingCache() {
14293        return getDrawingCache(false);
14294    }
14295
14296    /**
14297     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14298     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14299     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14300     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14301     * request the drawing cache by calling this method and draw it on screen if the
14302     * returned bitmap is not null.</p>
14303     *
14304     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14305     * this method will create a bitmap of the same size as this view. Because this bitmap
14306     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14307     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14308     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14309     * size than the view. This implies that your application must be able to handle this
14310     * size.</p>
14311     *
14312     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14313     *        the current density of the screen when the application is in compatibility
14314     *        mode.
14315     *
14316     * @return A bitmap representing this view or null if cache is disabled.
14317     *
14318     * @see #setDrawingCacheEnabled(boolean)
14319     * @see #isDrawingCacheEnabled()
14320     * @see #buildDrawingCache(boolean)
14321     * @see #destroyDrawingCache()
14322     */
14323    public Bitmap getDrawingCache(boolean autoScale) {
14324        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14325            return null;
14326        }
14327        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14328            buildDrawingCache(autoScale);
14329        }
14330        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14331    }
14332
14333    /**
14334     * <p>Frees the resources used by the drawing cache. If you call
14335     * {@link #buildDrawingCache()} manually without calling
14336     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14337     * should cleanup the cache with this method afterwards.</p>
14338     *
14339     * @see #setDrawingCacheEnabled(boolean)
14340     * @see #buildDrawingCache()
14341     * @see #getDrawingCache()
14342     */
14343    public void destroyDrawingCache() {
14344        if (mDrawingCache != null) {
14345            mDrawingCache.recycle();
14346            mDrawingCache = null;
14347        }
14348        if (mUnscaledDrawingCache != null) {
14349            mUnscaledDrawingCache.recycle();
14350            mUnscaledDrawingCache = null;
14351        }
14352    }
14353
14354    /**
14355     * Setting a solid background color for the drawing cache's bitmaps will improve
14356     * performance and memory usage. Note, though that this should only be used if this
14357     * view will always be drawn on top of a solid color.
14358     *
14359     * @param color The background color to use for the drawing cache's bitmap
14360     *
14361     * @see #setDrawingCacheEnabled(boolean)
14362     * @see #buildDrawingCache()
14363     * @see #getDrawingCache()
14364     */
14365    public void setDrawingCacheBackgroundColor(int color) {
14366        if (color != mDrawingCacheBackgroundColor) {
14367            mDrawingCacheBackgroundColor = color;
14368            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14369        }
14370    }
14371
14372    /**
14373     * @see #setDrawingCacheBackgroundColor(int)
14374     *
14375     * @return The background color to used for the drawing cache's bitmap
14376     */
14377    public int getDrawingCacheBackgroundColor() {
14378        return mDrawingCacheBackgroundColor;
14379    }
14380
14381    /**
14382     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14383     *
14384     * @see #buildDrawingCache(boolean)
14385     */
14386    public void buildDrawingCache() {
14387        buildDrawingCache(false);
14388    }
14389
14390    /**
14391     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14392     *
14393     * <p>If you call {@link #buildDrawingCache()} manually without calling
14394     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14395     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14396     *
14397     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14398     * this method will create a bitmap of the same size as this view. Because this bitmap
14399     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14400     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14401     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14402     * size than the view. This implies that your application must be able to handle this
14403     * size.</p>
14404     *
14405     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14406     * you do not need the drawing cache bitmap, calling this method will increase memory
14407     * usage and cause the view to be rendered in software once, thus negatively impacting
14408     * performance.</p>
14409     *
14410     * @see #getDrawingCache()
14411     * @see #destroyDrawingCache()
14412     */
14413    public void buildDrawingCache(boolean autoScale) {
14414        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14415                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14416            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14417                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14418                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14419            }
14420            try {
14421                buildDrawingCacheImpl(autoScale);
14422            } finally {
14423                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14424            }
14425        }
14426    }
14427
14428    /**
14429     * private, internal implementation of buildDrawingCache, used to enable tracing
14430     */
14431    private void buildDrawingCacheImpl(boolean autoScale) {
14432        mCachingFailed = false;
14433
14434        int width = mRight - mLeft;
14435        int height = mBottom - mTop;
14436
14437        final AttachInfo attachInfo = mAttachInfo;
14438        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14439
14440        if (autoScale && scalingRequired) {
14441            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14442            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14443        }
14444
14445        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14446        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14447        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14448
14449        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14450        final long drawingCacheSize =
14451                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14452        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14453            if (width > 0 && height > 0) {
14454                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14455                        + projectedBitmapSize + " bytes, only "
14456                        + drawingCacheSize + " available");
14457            }
14458            destroyDrawingCache();
14459            mCachingFailed = true;
14460            return;
14461        }
14462
14463        boolean clear = true;
14464        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14465
14466        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14467            Bitmap.Config quality;
14468            if (!opaque) {
14469                // Never pick ARGB_4444 because it looks awful
14470                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14471                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14472                    case DRAWING_CACHE_QUALITY_AUTO:
14473                    case DRAWING_CACHE_QUALITY_LOW:
14474                    case DRAWING_CACHE_QUALITY_HIGH:
14475                    default:
14476                        quality = Bitmap.Config.ARGB_8888;
14477                        break;
14478                }
14479            } else {
14480                // Optimization for translucent windows
14481                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14482                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14483            }
14484
14485            // Try to cleanup memory
14486            if (bitmap != null) bitmap.recycle();
14487
14488            try {
14489                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14490                        width, height, quality);
14491                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14492                if (autoScale) {
14493                    mDrawingCache = bitmap;
14494                } else {
14495                    mUnscaledDrawingCache = bitmap;
14496                }
14497                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14498            } catch (OutOfMemoryError e) {
14499                // If there is not enough memory to create the bitmap cache, just
14500                // ignore the issue as bitmap caches are not required to draw the
14501                // view hierarchy
14502                if (autoScale) {
14503                    mDrawingCache = null;
14504                } else {
14505                    mUnscaledDrawingCache = null;
14506                }
14507                mCachingFailed = true;
14508                return;
14509            }
14510
14511            clear = drawingCacheBackgroundColor != 0;
14512        }
14513
14514        Canvas canvas;
14515        if (attachInfo != null) {
14516            canvas = attachInfo.mCanvas;
14517            if (canvas == null) {
14518                canvas = new Canvas();
14519            }
14520            canvas.setBitmap(bitmap);
14521            // Temporarily clobber the cached Canvas in case one of our children
14522            // is also using a drawing cache. Without this, the children would
14523            // steal the canvas by attaching their own bitmap to it and bad, bad
14524            // thing would happen (invisible views, corrupted drawings, etc.)
14525            attachInfo.mCanvas = null;
14526        } else {
14527            // This case should hopefully never or seldom happen
14528            canvas = new Canvas(bitmap);
14529        }
14530
14531        if (clear) {
14532            bitmap.eraseColor(drawingCacheBackgroundColor);
14533        }
14534
14535        computeScroll();
14536        final int restoreCount = canvas.save();
14537
14538        if (autoScale && scalingRequired) {
14539            final float scale = attachInfo.mApplicationScale;
14540            canvas.scale(scale, scale);
14541        }
14542
14543        canvas.translate(-mScrollX, -mScrollY);
14544
14545        mPrivateFlags |= PFLAG_DRAWN;
14546        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14547                mLayerType != LAYER_TYPE_NONE) {
14548            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14549        }
14550
14551        // Fast path for layouts with no backgrounds
14552        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14553            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14554            dispatchDraw(canvas);
14555            if (mOverlay != null && !mOverlay.isEmpty()) {
14556                mOverlay.getOverlayView().draw(canvas);
14557            }
14558        } else {
14559            draw(canvas);
14560        }
14561
14562        canvas.restoreToCount(restoreCount);
14563        canvas.setBitmap(null);
14564
14565        if (attachInfo != null) {
14566            // Restore the cached Canvas for our siblings
14567            attachInfo.mCanvas = canvas;
14568        }
14569    }
14570
14571    /**
14572     * Create a snapshot of the view into a bitmap.  We should probably make
14573     * some form of this public, but should think about the API.
14574     */
14575    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14576        int width = mRight - mLeft;
14577        int height = mBottom - mTop;
14578
14579        final AttachInfo attachInfo = mAttachInfo;
14580        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14581        width = (int) ((width * scale) + 0.5f);
14582        height = (int) ((height * scale) + 0.5f);
14583
14584        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14585                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14586        if (bitmap == null) {
14587            throw new OutOfMemoryError();
14588        }
14589
14590        Resources resources = getResources();
14591        if (resources != null) {
14592            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14593        }
14594
14595        Canvas canvas;
14596        if (attachInfo != null) {
14597            canvas = attachInfo.mCanvas;
14598            if (canvas == null) {
14599                canvas = new Canvas();
14600            }
14601            canvas.setBitmap(bitmap);
14602            // Temporarily clobber the cached Canvas in case one of our children
14603            // is also using a drawing cache. Without this, the children would
14604            // steal the canvas by attaching their own bitmap to it and bad, bad
14605            // things would happen (invisible views, corrupted drawings, etc.)
14606            attachInfo.mCanvas = null;
14607        } else {
14608            // This case should hopefully never or seldom happen
14609            canvas = new Canvas(bitmap);
14610        }
14611
14612        if ((backgroundColor & 0xff000000) != 0) {
14613            bitmap.eraseColor(backgroundColor);
14614        }
14615
14616        computeScroll();
14617        final int restoreCount = canvas.save();
14618        canvas.scale(scale, scale);
14619        canvas.translate(-mScrollX, -mScrollY);
14620
14621        // Temporarily remove the dirty mask
14622        int flags = mPrivateFlags;
14623        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14624
14625        // Fast path for layouts with no backgrounds
14626        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14627            dispatchDraw(canvas);
14628            if (mOverlay != null && !mOverlay.isEmpty()) {
14629                mOverlay.getOverlayView().draw(canvas);
14630            }
14631        } else {
14632            draw(canvas);
14633        }
14634
14635        mPrivateFlags = flags;
14636
14637        canvas.restoreToCount(restoreCount);
14638        canvas.setBitmap(null);
14639
14640        if (attachInfo != null) {
14641            // Restore the cached Canvas for our siblings
14642            attachInfo.mCanvas = canvas;
14643        }
14644
14645        return bitmap;
14646    }
14647
14648    /**
14649     * Indicates whether this View is currently in edit mode. A View is usually
14650     * in edit mode when displayed within a developer tool. For instance, if
14651     * this View is being drawn by a visual user interface builder, this method
14652     * should return true.
14653     *
14654     * Subclasses should check the return value of this method to provide
14655     * different behaviors if their normal behavior might interfere with the
14656     * host environment. For instance: the class spawns a thread in its
14657     * constructor, the drawing code relies on device-specific features, etc.
14658     *
14659     * This method is usually checked in the drawing code of custom widgets.
14660     *
14661     * @return True if this View is in edit mode, false otherwise.
14662     */
14663    public boolean isInEditMode() {
14664        return false;
14665    }
14666
14667    /**
14668     * If the View draws content inside its padding and enables fading edges,
14669     * it needs to support padding offsets. Padding offsets are added to the
14670     * fading edges to extend the length of the fade so that it covers pixels
14671     * drawn inside the padding.
14672     *
14673     * Subclasses of this class should override this method if they need
14674     * to draw content inside the padding.
14675     *
14676     * @return True if padding offset must be applied, false otherwise.
14677     *
14678     * @see #getLeftPaddingOffset()
14679     * @see #getRightPaddingOffset()
14680     * @see #getTopPaddingOffset()
14681     * @see #getBottomPaddingOffset()
14682     *
14683     * @since CURRENT
14684     */
14685    protected boolean isPaddingOffsetRequired() {
14686        return false;
14687    }
14688
14689    /**
14690     * Amount by which to extend the left fading region. Called only when
14691     * {@link #isPaddingOffsetRequired()} returns true.
14692     *
14693     * @return The left padding offset in pixels.
14694     *
14695     * @see #isPaddingOffsetRequired()
14696     *
14697     * @since CURRENT
14698     */
14699    protected int getLeftPaddingOffset() {
14700        return 0;
14701    }
14702
14703    /**
14704     * Amount by which to extend the right fading region. Called only when
14705     * {@link #isPaddingOffsetRequired()} returns true.
14706     *
14707     * @return The right padding offset in pixels.
14708     *
14709     * @see #isPaddingOffsetRequired()
14710     *
14711     * @since CURRENT
14712     */
14713    protected int getRightPaddingOffset() {
14714        return 0;
14715    }
14716
14717    /**
14718     * Amount by which to extend the top fading region. Called only when
14719     * {@link #isPaddingOffsetRequired()} returns true.
14720     *
14721     * @return The top padding offset in pixels.
14722     *
14723     * @see #isPaddingOffsetRequired()
14724     *
14725     * @since CURRENT
14726     */
14727    protected int getTopPaddingOffset() {
14728        return 0;
14729    }
14730
14731    /**
14732     * Amount by which to extend the bottom fading region. Called only when
14733     * {@link #isPaddingOffsetRequired()} returns true.
14734     *
14735     * @return The bottom padding offset in pixels.
14736     *
14737     * @see #isPaddingOffsetRequired()
14738     *
14739     * @since CURRENT
14740     */
14741    protected int getBottomPaddingOffset() {
14742        return 0;
14743    }
14744
14745    /**
14746     * @hide
14747     * @param offsetRequired
14748     */
14749    protected int getFadeTop(boolean offsetRequired) {
14750        int top = mPaddingTop;
14751        if (offsetRequired) top += getTopPaddingOffset();
14752        return top;
14753    }
14754
14755    /**
14756     * @hide
14757     * @param offsetRequired
14758     */
14759    protected int getFadeHeight(boolean offsetRequired) {
14760        int padding = mPaddingTop;
14761        if (offsetRequired) padding += getTopPaddingOffset();
14762        return mBottom - mTop - mPaddingBottom - padding;
14763    }
14764
14765    /**
14766     * <p>Indicates whether this view is attached to a hardware accelerated
14767     * window or not.</p>
14768     *
14769     * <p>Even if this method returns true, it does not mean that every call
14770     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14771     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14772     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14773     * window is hardware accelerated,
14774     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14775     * return false, and this method will return true.</p>
14776     *
14777     * @return True if the view is attached to a window and the window is
14778     *         hardware accelerated; false in any other case.
14779     */
14780    @ViewDebug.ExportedProperty(category = "drawing")
14781    public boolean isHardwareAccelerated() {
14782        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14783    }
14784
14785    /**
14786     * Sets a rectangular area on this view to which the view will be clipped
14787     * when it is drawn. Setting the value to null will remove the clip bounds
14788     * and the view will draw normally, using its full bounds.
14789     *
14790     * @param clipBounds The rectangular area, in the local coordinates of
14791     * this view, to which future drawing operations will be clipped.
14792     */
14793    public void setClipBounds(Rect clipBounds) {
14794        if (clipBounds == mClipBounds
14795                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
14796            return;
14797        }
14798        if (clipBounds != null) {
14799            if (mClipBounds == null) {
14800                mClipBounds = new Rect(clipBounds);
14801            } else {
14802                mClipBounds.set(clipBounds);
14803            }
14804        } else {
14805            mClipBounds = null;
14806        }
14807        mRenderNode.setClipBounds(mClipBounds);
14808        invalidateViewProperty(false, false);
14809    }
14810
14811    /**
14812     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14813     *
14814     * @return A copy of the current clip bounds if clip bounds are set,
14815     * otherwise null.
14816     */
14817    public Rect getClipBounds() {
14818        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14819    }
14820
14821    /**
14822     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14823     * case of an active Animation being run on the view.
14824     */
14825    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14826            Animation a, boolean scalingRequired) {
14827        Transformation invalidationTransform;
14828        final int flags = parent.mGroupFlags;
14829        final boolean initialized = a.isInitialized();
14830        if (!initialized) {
14831            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14832            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14833            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14834            onAnimationStart();
14835        }
14836
14837        final Transformation t = parent.getChildTransformation();
14838        boolean more = a.getTransformation(drawingTime, t, 1f);
14839        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14840            if (parent.mInvalidationTransformation == null) {
14841                parent.mInvalidationTransformation = new Transformation();
14842            }
14843            invalidationTransform = parent.mInvalidationTransformation;
14844            a.getTransformation(drawingTime, invalidationTransform, 1f);
14845        } else {
14846            invalidationTransform = t;
14847        }
14848
14849        if (more) {
14850            if (!a.willChangeBounds()) {
14851                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14852                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14853                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14854                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14855                    // The child need to draw an animation, potentially offscreen, so
14856                    // make sure we do not cancel invalidate requests
14857                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14858                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14859                }
14860            } else {
14861                if (parent.mInvalidateRegion == null) {
14862                    parent.mInvalidateRegion = new RectF();
14863                }
14864                final RectF region = parent.mInvalidateRegion;
14865                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14866                        invalidationTransform);
14867
14868                // The child need to draw an animation, potentially offscreen, so
14869                // make sure we do not cancel invalidate requests
14870                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14871
14872                final int left = mLeft + (int) region.left;
14873                final int top = mTop + (int) region.top;
14874                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14875                        top + (int) (region.height() + .5f));
14876            }
14877        }
14878        return more;
14879    }
14880
14881    /**
14882     * This method is called by getDisplayList() when a display list is recorded for a View.
14883     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14884     */
14885    void setDisplayListProperties(RenderNode renderNode) {
14886        if (renderNode != null) {
14887            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14888            if (mParent instanceof ViewGroup) {
14889                renderNode.setClipToBounds(
14890                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14891            }
14892            float alpha = 1;
14893            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14894                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14895                ViewGroup parentVG = (ViewGroup) mParent;
14896                final Transformation t = parentVG.getChildTransformation();
14897                if (parentVG.getChildStaticTransformation(this, t)) {
14898                    final int transformType = t.getTransformationType();
14899                    if (transformType != Transformation.TYPE_IDENTITY) {
14900                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14901                            alpha = t.getAlpha();
14902                        }
14903                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14904                            renderNode.setStaticMatrix(t.getMatrix());
14905                        }
14906                    }
14907                }
14908            }
14909            if (mTransformationInfo != null) {
14910                alpha *= getFinalAlpha();
14911                if (alpha < 1) {
14912                    final int multipliedAlpha = (int) (255 * alpha);
14913                    if (onSetAlpha(multipliedAlpha)) {
14914                        alpha = 1;
14915                    }
14916                }
14917                renderNode.setAlpha(alpha);
14918            } else if (alpha < 1) {
14919                renderNode.setAlpha(alpha);
14920            }
14921        }
14922    }
14923
14924    /**
14925     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14926     * This draw() method is an implementation detail and is not intended to be overridden or
14927     * to be called from anywhere else other than ViewGroup.drawChild().
14928     */
14929    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14930        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14931        boolean more = false;
14932        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14933        final int flags = parent.mGroupFlags;
14934
14935        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14936            parent.getChildTransformation().clear();
14937            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14938        }
14939
14940        Transformation transformToApply = null;
14941        boolean concatMatrix = false;
14942
14943        boolean scalingRequired = false;
14944        boolean caching;
14945        int layerType = getLayerType();
14946
14947        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14948        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14949                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14950            caching = true;
14951            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14952            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14953        } else {
14954            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14955        }
14956
14957        final Animation a = getAnimation();
14958        if (a != null) {
14959            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14960            concatMatrix = a.willChangeTransformationMatrix();
14961            if (concatMatrix) {
14962                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14963            }
14964            transformToApply = parent.getChildTransformation();
14965        } else {
14966            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14967                // No longer animating: clear out old animation matrix
14968                mRenderNode.setAnimationMatrix(null);
14969                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14970            }
14971            if (!usingRenderNodeProperties &&
14972                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14973                final Transformation t = parent.getChildTransformation();
14974                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14975                if (hasTransform) {
14976                    final int transformType = t.getTransformationType();
14977                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14978                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14979                }
14980            }
14981        }
14982
14983        concatMatrix |= !childHasIdentityMatrix;
14984
14985        // Sets the flag as early as possible to allow draw() implementations
14986        // to call invalidate() successfully when doing animations
14987        mPrivateFlags |= PFLAG_DRAWN;
14988
14989        if (!concatMatrix &&
14990                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14991                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14992                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14993                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14994            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14995            return more;
14996        }
14997        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14998
14999        if (hardwareAccelerated) {
15000            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15001            // retain the flag's value temporarily in the mRecreateDisplayList flag
15002            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
15003            mPrivateFlags &= ~PFLAG_INVALIDATED;
15004        }
15005
15006        RenderNode renderNode = null;
15007        Bitmap cache = null;
15008        boolean hasDisplayList = false;
15009        if (caching) {
15010            if (!hardwareAccelerated) {
15011                if (layerType != LAYER_TYPE_NONE) {
15012                    layerType = LAYER_TYPE_SOFTWARE;
15013                    buildDrawingCache(true);
15014                }
15015                cache = getDrawingCache(true);
15016            } else {
15017                switch (layerType) {
15018                    case LAYER_TYPE_SOFTWARE:
15019                        if (usingRenderNodeProperties) {
15020                            hasDisplayList = canHaveDisplayList();
15021                        } else {
15022                            buildDrawingCache(true);
15023                            cache = getDrawingCache(true);
15024                        }
15025                        break;
15026                    case LAYER_TYPE_HARDWARE:
15027                        if (usingRenderNodeProperties) {
15028                            hasDisplayList = canHaveDisplayList();
15029                        }
15030                        break;
15031                    case LAYER_TYPE_NONE:
15032                        // Delay getting the display list until animation-driven alpha values are
15033                        // set up and possibly passed on to the view
15034                        hasDisplayList = canHaveDisplayList();
15035                        break;
15036                }
15037            }
15038        }
15039        usingRenderNodeProperties &= hasDisplayList;
15040        if (usingRenderNodeProperties) {
15041            renderNode = getDisplayList();
15042            if (!renderNode.isValid()) {
15043                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15044                // to getDisplayList(), the display list will be marked invalid and we should not
15045                // try to use it again.
15046                renderNode = null;
15047                hasDisplayList = false;
15048                usingRenderNodeProperties = false;
15049            }
15050        }
15051
15052        int sx = 0;
15053        int sy = 0;
15054        if (!hasDisplayList) {
15055            computeScroll();
15056            sx = mScrollX;
15057            sy = mScrollY;
15058        }
15059
15060        final boolean hasNoCache = cache == null || hasDisplayList;
15061        final boolean offsetForScroll = cache == null && !hasDisplayList &&
15062                layerType != LAYER_TYPE_HARDWARE;
15063
15064        int restoreTo = -1;
15065        if (!usingRenderNodeProperties || transformToApply != null) {
15066            restoreTo = canvas.save();
15067        }
15068        if (offsetForScroll) {
15069            canvas.translate(mLeft - sx, mTop - sy);
15070        } else {
15071            if (!usingRenderNodeProperties) {
15072                canvas.translate(mLeft, mTop);
15073            }
15074            if (scalingRequired) {
15075                if (usingRenderNodeProperties) {
15076                    // TODO: Might not need this if we put everything inside the DL
15077                    restoreTo = canvas.save();
15078                }
15079                // mAttachInfo cannot be null, otherwise scalingRequired == false
15080                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15081                canvas.scale(scale, scale);
15082            }
15083        }
15084
15085        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
15086        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
15087                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15088            if (transformToApply != null || !childHasIdentityMatrix) {
15089                int transX = 0;
15090                int transY = 0;
15091
15092                if (offsetForScroll) {
15093                    transX = -sx;
15094                    transY = -sy;
15095                }
15096
15097                if (transformToApply != null) {
15098                    if (concatMatrix) {
15099                        if (usingRenderNodeProperties) {
15100                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15101                        } else {
15102                            // Undo the scroll translation, apply the transformation matrix,
15103                            // then redo the scroll translate to get the correct result.
15104                            canvas.translate(-transX, -transY);
15105                            canvas.concat(transformToApply.getMatrix());
15106                            canvas.translate(transX, transY);
15107                        }
15108                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15109                    }
15110
15111                    float transformAlpha = transformToApply.getAlpha();
15112                    if (transformAlpha < 1) {
15113                        alpha *= transformAlpha;
15114                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15115                    }
15116                }
15117
15118                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
15119                    canvas.translate(-transX, -transY);
15120                    canvas.concat(getMatrix());
15121                    canvas.translate(transX, transY);
15122                }
15123            }
15124
15125            // Deal with alpha if it is or used to be <1
15126            if (alpha < 1 ||
15127                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15128                if (alpha < 1) {
15129                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15130                } else {
15131                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15132                }
15133                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15134                if (hasNoCache) {
15135                    final int multipliedAlpha = (int) (255 * alpha);
15136                    if (!onSetAlpha(multipliedAlpha)) {
15137                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15138                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
15139                                layerType != LAYER_TYPE_NONE) {
15140                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
15141                        }
15142                        if (usingRenderNodeProperties) {
15143                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15144                        } else  if (layerType == LAYER_TYPE_NONE) {
15145                            final int scrollX = hasDisplayList ? 0 : sx;
15146                            final int scrollY = hasDisplayList ? 0 : sy;
15147                            canvas.saveLayerAlpha(scrollX, scrollY,
15148                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
15149                                    multipliedAlpha, layerFlags);
15150                        }
15151                    } else {
15152                        // Alpha is handled by the child directly, clobber the layer's alpha
15153                        mPrivateFlags |= PFLAG_ALPHA_SET;
15154                    }
15155                }
15156            }
15157        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15158            onSetAlpha(255);
15159            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15160        }
15161
15162        if (!usingRenderNodeProperties) {
15163            // apply clips directly, since RenderNode won't do it for this draw
15164            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
15165                    && cache == null) {
15166                if (offsetForScroll) {
15167                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
15168                } else {
15169                    if (!scalingRequired || cache == null) {
15170                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
15171                    } else {
15172                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15173                    }
15174                }
15175            }
15176
15177            if (mClipBounds != null) {
15178                // clip bounds ignore scroll
15179                canvas.clipRect(mClipBounds);
15180            }
15181        }
15182
15183
15184
15185        if (!usingRenderNodeProperties && hasDisplayList) {
15186            renderNode = getDisplayList();
15187            if (!renderNode.isValid()) {
15188                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15189                // to getDisplayList(), the display list will be marked invalid and we should not
15190                // try to use it again.
15191                renderNode = null;
15192                hasDisplayList = false;
15193            }
15194        }
15195
15196        if (hasNoCache) {
15197            boolean layerRendered = false;
15198            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
15199                final HardwareLayer layer = getHardwareLayer();
15200                if (layer != null && layer.isValid()) {
15201                    int restoreAlpha = mLayerPaint.getAlpha();
15202                    mLayerPaint.setAlpha((int) (alpha * 255));
15203                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
15204                    mLayerPaint.setAlpha(restoreAlpha);
15205                    layerRendered = true;
15206                } else {
15207                    final int scrollX = hasDisplayList ? 0 : sx;
15208                    final int scrollY = hasDisplayList ? 0 : sy;
15209                    canvas.saveLayer(scrollX, scrollY,
15210                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
15211                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
15212                }
15213            }
15214
15215            if (!layerRendered) {
15216                if (!hasDisplayList) {
15217                    // Fast path for layouts with no backgrounds
15218                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15219                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15220                        dispatchDraw(canvas);
15221                    } else {
15222                        draw(canvas);
15223                    }
15224                } else {
15225                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15226                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, flags);
15227                }
15228            }
15229        } else if (cache != null) {
15230            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15231            Paint cachePaint;
15232            int restoreAlpha = 0;
15233
15234            if (layerType == LAYER_TYPE_NONE) {
15235                cachePaint = parent.mCachePaint;
15236                if (cachePaint == null) {
15237                    cachePaint = new Paint();
15238                    cachePaint.setDither(false);
15239                    parent.mCachePaint = cachePaint;
15240                }
15241            } else {
15242                cachePaint = mLayerPaint;
15243                restoreAlpha = mLayerPaint.getAlpha();
15244            }
15245            cachePaint.setAlpha((int) (alpha * 255));
15246            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15247            cachePaint.setAlpha(restoreAlpha);
15248        }
15249
15250        if (restoreTo >= 0) {
15251            canvas.restoreToCount(restoreTo);
15252        }
15253
15254        if (a != null && !more) {
15255            if (!hardwareAccelerated && !a.getFillAfter()) {
15256                onSetAlpha(255);
15257            }
15258            parent.finishAnimatingView(this, a);
15259        }
15260
15261        if (more && hardwareAccelerated) {
15262            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15263                // alpha animations should cause the child to recreate its display list
15264                invalidate(true);
15265            }
15266        }
15267
15268        mRecreateDisplayList = false;
15269
15270        return more;
15271    }
15272
15273    /**
15274     * Manually render this view (and all of its children) to the given Canvas.
15275     * The view must have already done a full layout before this function is
15276     * called.  When implementing a view, implement
15277     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15278     * If you do need to override this method, call the superclass version.
15279     *
15280     * @param canvas The Canvas to which the View is rendered.
15281     */
15282    public void draw(Canvas canvas) {
15283        final int privateFlags = mPrivateFlags;
15284        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15285                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15286        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15287
15288        /*
15289         * Draw traversal performs several drawing steps which must be executed
15290         * in the appropriate order:
15291         *
15292         *      1. Draw the background
15293         *      2. If necessary, save the canvas' layers to prepare for fading
15294         *      3. Draw view's content
15295         *      4. Draw children
15296         *      5. If necessary, draw the fading edges and restore layers
15297         *      6. Draw decorations (scrollbars for instance)
15298         */
15299
15300        // Step 1, draw the background, if needed
15301        int saveCount;
15302
15303        if (!dirtyOpaque) {
15304            drawBackground(canvas);
15305        }
15306
15307        // skip step 2 & 5 if possible (common case)
15308        final int viewFlags = mViewFlags;
15309        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15310        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15311        if (!verticalEdges && !horizontalEdges) {
15312            // Step 3, draw the content
15313            if (!dirtyOpaque) onDraw(canvas);
15314
15315            // Step 4, draw the children
15316            dispatchDraw(canvas);
15317
15318            // Step 6, draw decorations (scrollbars)
15319            onDrawScrollBars(canvas);
15320
15321            if (mOverlay != null && !mOverlay.isEmpty()) {
15322                mOverlay.getOverlayView().dispatchDraw(canvas);
15323            }
15324
15325            // we're done...
15326            return;
15327        }
15328
15329        /*
15330         * Here we do the full fledged routine...
15331         * (this is an uncommon case where speed matters less,
15332         * this is why we repeat some of the tests that have been
15333         * done above)
15334         */
15335
15336        boolean drawTop = false;
15337        boolean drawBottom = false;
15338        boolean drawLeft = false;
15339        boolean drawRight = false;
15340
15341        float topFadeStrength = 0.0f;
15342        float bottomFadeStrength = 0.0f;
15343        float leftFadeStrength = 0.0f;
15344        float rightFadeStrength = 0.0f;
15345
15346        // Step 2, save the canvas' layers
15347        int paddingLeft = mPaddingLeft;
15348
15349        final boolean offsetRequired = isPaddingOffsetRequired();
15350        if (offsetRequired) {
15351            paddingLeft += getLeftPaddingOffset();
15352        }
15353
15354        int left = mScrollX + paddingLeft;
15355        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15356        int top = mScrollY + getFadeTop(offsetRequired);
15357        int bottom = top + getFadeHeight(offsetRequired);
15358
15359        if (offsetRequired) {
15360            right += getRightPaddingOffset();
15361            bottom += getBottomPaddingOffset();
15362        }
15363
15364        final ScrollabilityCache scrollabilityCache = mScrollCache;
15365        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15366        int length = (int) fadeHeight;
15367
15368        // clip the fade length if top and bottom fades overlap
15369        // overlapping fades produce odd-looking artifacts
15370        if (verticalEdges && (top + length > bottom - length)) {
15371            length = (bottom - top) / 2;
15372        }
15373
15374        // also clip horizontal fades if necessary
15375        if (horizontalEdges && (left + length > right - length)) {
15376            length = (right - left) / 2;
15377        }
15378
15379        if (verticalEdges) {
15380            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15381            drawTop = topFadeStrength * fadeHeight > 1.0f;
15382            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15383            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15384        }
15385
15386        if (horizontalEdges) {
15387            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15388            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15389            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15390            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15391        }
15392
15393        saveCount = canvas.getSaveCount();
15394
15395        int solidColor = getSolidColor();
15396        if (solidColor == 0) {
15397            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15398
15399            if (drawTop) {
15400                canvas.saveLayer(left, top, right, top + length, null, flags);
15401            }
15402
15403            if (drawBottom) {
15404                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15405            }
15406
15407            if (drawLeft) {
15408                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15409            }
15410
15411            if (drawRight) {
15412                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15413            }
15414        } else {
15415            scrollabilityCache.setFadeColor(solidColor);
15416        }
15417
15418        // Step 3, draw the content
15419        if (!dirtyOpaque) onDraw(canvas);
15420
15421        // Step 4, draw the children
15422        dispatchDraw(canvas);
15423
15424        // Step 5, draw the fade effect and restore layers
15425        final Paint p = scrollabilityCache.paint;
15426        final Matrix matrix = scrollabilityCache.matrix;
15427        final Shader fade = scrollabilityCache.shader;
15428
15429        if (drawTop) {
15430            matrix.setScale(1, fadeHeight * topFadeStrength);
15431            matrix.postTranslate(left, top);
15432            fade.setLocalMatrix(matrix);
15433            p.setShader(fade);
15434            canvas.drawRect(left, top, right, top + length, p);
15435        }
15436
15437        if (drawBottom) {
15438            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15439            matrix.postRotate(180);
15440            matrix.postTranslate(left, bottom);
15441            fade.setLocalMatrix(matrix);
15442            p.setShader(fade);
15443            canvas.drawRect(left, bottom - length, right, bottom, p);
15444        }
15445
15446        if (drawLeft) {
15447            matrix.setScale(1, fadeHeight * leftFadeStrength);
15448            matrix.postRotate(-90);
15449            matrix.postTranslate(left, top);
15450            fade.setLocalMatrix(matrix);
15451            p.setShader(fade);
15452            canvas.drawRect(left, top, left + length, bottom, p);
15453        }
15454
15455        if (drawRight) {
15456            matrix.setScale(1, fadeHeight * rightFadeStrength);
15457            matrix.postRotate(90);
15458            matrix.postTranslate(right, top);
15459            fade.setLocalMatrix(matrix);
15460            p.setShader(fade);
15461            canvas.drawRect(right - length, top, right, bottom, p);
15462        }
15463
15464        canvas.restoreToCount(saveCount);
15465
15466        // Step 6, draw decorations (scrollbars)
15467        onDrawScrollBars(canvas);
15468
15469        if (mOverlay != null && !mOverlay.isEmpty()) {
15470            mOverlay.getOverlayView().dispatchDraw(canvas);
15471        }
15472    }
15473
15474    /**
15475     * Draws the background onto the specified canvas.
15476     *
15477     * @param canvas Canvas on which to draw the background
15478     */
15479    private void drawBackground(Canvas canvas) {
15480        final Drawable background = mBackground;
15481        if (background == null) {
15482            return;
15483        }
15484
15485        if (mBackgroundSizeChanged) {
15486            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15487            mBackgroundSizeChanged = false;
15488            rebuildOutline();
15489        }
15490
15491        // Attempt to use a display list if requested.
15492        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15493                && mAttachInfo.mHardwareRenderer != null) {
15494            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15495
15496            final RenderNode renderNode = mBackgroundRenderNode;
15497            if (renderNode != null && renderNode.isValid()) {
15498                setBackgroundRenderNodeProperties(renderNode);
15499                ((HardwareCanvas) canvas).drawRenderNode(renderNode);
15500                return;
15501            }
15502        }
15503
15504        final int scrollX = mScrollX;
15505        final int scrollY = mScrollY;
15506        if ((scrollX | scrollY) == 0) {
15507            background.draw(canvas);
15508        } else {
15509            canvas.translate(scrollX, scrollY);
15510            background.draw(canvas);
15511            canvas.translate(-scrollX, -scrollY);
15512        }
15513    }
15514
15515    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15516        renderNode.setTranslationX(mScrollX);
15517        renderNode.setTranslationY(mScrollY);
15518    }
15519
15520    /**
15521     * Creates a new display list or updates the existing display list for the
15522     * specified Drawable.
15523     *
15524     * @param drawable Drawable for which to create a display list
15525     * @param renderNode Existing RenderNode, or {@code null}
15526     * @return A valid display list for the specified drawable
15527     */
15528    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15529        if (renderNode == null) {
15530            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15531        }
15532
15533        final Rect bounds = drawable.getBounds();
15534        final int width = bounds.width();
15535        final int height = bounds.height();
15536        final HardwareCanvas canvas = renderNode.start(width, height);
15537
15538        // Reverse left/top translation done by drawable canvas, which will
15539        // instead be applied by rendernode's LTRB bounds below. This way, the
15540        // drawable's bounds match with its rendernode bounds and its content
15541        // will lie within those bounds in the rendernode tree.
15542        canvas.translate(-bounds.left, -bounds.top);
15543
15544        try {
15545            drawable.draw(canvas);
15546        } finally {
15547            renderNode.end(canvas);
15548        }
15549
15550        // Set up drawable properties that are view-independent.
15551        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15552        renderNode.setProjectBackwards(drawable.isProjected());
15553        renderNode.setProjectionReceiver(true);
15554        renderNode.setClipToBounds(false);
15555        return renderNode;
15556    }
15557
15558    /**
15559     * Returns the overlay for this view, creating it if it does not yet exist.
15560     * Adding drawables to the overlay will cause them to be displayed whenever
15561     * the view itself is redrawn. Objects in the overlay should be actively
15562     * managed: remove them when they should not be displayed anymore. The
15563     * overlay will always have the same size as its host view.
15564     *
15565     * <p>Note: Overlays do not currently work correctly with {@link
15566     * SurfaceView} or {@link TextureView}; contents in overlays for these
15567     * types of views may not display correctly.</p>
15568     *
15569     * @return The ViewOverlay object for this view.
15570     * @see ViewOverlay
15571     */
15572    public ViewOverlay getOverlay() {
15573        if (mOverlay == null) {
15574            mOverlay = new ViewOverlay(mContext, this);
15575        }
15576        return mOverlay;
15577    }
15578
15579    /**
15580     * Override this if your view is known to always be drawn on top of a solid color background,
15581     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15582     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15583     * should be set to 0xFF.
15584     *
15585     * @see #setVerticalFadingEdgeEnabled(boolean)
15586     * @see #setHorizontalFadingEdgeEnabled(boolean)
15587     *
15588     * @return The known solid color background for this view, or 0 if the color may vary
15589     */
15590    @ViewDebug.ExportedProperty(category = "drawing")
15591    public int getSolidColor() {
15592        return 0;
15593    }
15594
15595    /**
15596     * Build a human readable string representation of the specified view flags.
15597     *
15598     * @param flags the view flags to convert to a string
15599     * @return a String representing the supplied flags
15600     */
15601    private static String printFlags(int flags) {
15602        String output = "";
15603        int numFlags = 0;
15604        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15605            output += "TAKES_FOCUS";
15606            numFlags++;
15607        }
15608
15609        switch (flags & VISIBILITY_MASK) {
15610        case INVISIBLE:
15611            if (numFlags > 0) {
15612                output += " ";
15613            }
15614            output += "INVISIBLE";
15615            // USELESS HERE numFlags++;
15616            break;
15617        case GONE:
15618            if (numFlags > 0) {
15619                output += " ";
15620            }
15621            output += "GONE";
15622            // USELESS HERE numFlags++;
15623            break;
15624        default:
15625            break;
15626        }
15627        return output;
15628    }
15629
15630    /**
15631     * Build a human readable string representation of the specified private
15632     * view flags.
15633     *
15634     * @param privateFlags the private view flags to convert to a string
15635     * @return a String representing the supplied flags
15636     */
15637    private static String printPrivateFlags(int privateFlags) {
15638        String output = "";
15639        int numFlags = 0;
15640
15641        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15642            output += "WANTS_FOCUS";
15643            numFlags++;
15644        }
15645
15646        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15647            if (numFlags > 0) {
15648                output += " ";
15649            }
15650            output += "FOCUSED";
15651            numFlags++;
15652        }
15653
15654        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15655            if (numFlags > 0) {
15656                output += " ";
15657            }
15658            output += "SELECTED";
15659            numFlags++;
15660        }
15661
15662        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15663            if (numFlags > 0) {
15664                output += " ";
15665            }
15666            output += "IS_ROOT_NAMESPACE";
15667            numFlags++;
15668        }
15669
15670        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15671            if (numFlags > 0) {
15672                output += " ";
15673            }
15674            output += "HAS_BOUNDS";
15675            numFlags++;
15676        }
15677
15678        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15679            if (numFlags > 0) {
15680                output += " ";
15681            }
15682            output += "DRAWN";
15683            // USELESS HERE numFlags++;
15684        }
15685        return output;
15686    }
15687
15688    /**
15689     * <p>Indicates whether or not this view's layout will be requested during
15690     * the next hierarchy layout pass.</p>
15691     *
15692     * @return true if the layout will be forced during next layout pass
15693     */
15694    public boolean isLayoutRequested() {
15695        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15696    }
15697
15698    /**
15699     * Return true if o is a ViewGroup that is laying out using optical bounds.
15700     * @hide
15701     */
15702    public static boolean isLayoutModeOptical(Object o) {
15703        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15704    }
15705
15706    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15707        Insets parentInsets = mParent instanceof View ?
15708                ((View) mParent).getOpticalInsets() : Insets.NONE;
15709        Insets childInsets = getOpticalInsets();
15710        return setFrame(
15711                left   + parentInsets.left - childInsets.left,
15712                top    + parentInsets.top  - childInsets.top,
15713                right  + parentInsets.left + childInsets.right,
15714                bottom + parentInsets.top  + childInsets.bottom);
15715    }
15716
15717    /**
15718     * Assign a size and position to a view and all of its
15719     * descendants
15720     *
15721     * <p>This is the second phase of the layout mechanism.
15722     * (The first is measuring). In this phase, each parent calls
15723     * layout on all of its children to position them.
15724     * This is typically done using the child measurements
15725     * that were stored in the measure pass().</p>
15726     *
15727     * <p>Derived classes should not override this method.
15728     * Derived classes with children should override
15729     * onLayout. In that method, they should
15730     * call layout on each of their children.</p>
15731     *
15732     * @param l Left position, relative to parent
15733     * @param t Top position, relative to parent
15734     * @param r Right position, relative to parent
15735     * @param b Bottom position, relative to parent
15736     */
15737    @SuppressWarnings({"unchecked"})
15738    public void layout(int l, int t, int r, int b) {
15739        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15740            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15741            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15742        }
15743
15744        int oldL = mLeft;
15745        int oldT = mTop;
15746        int oldB = mBottom;
15747        int oldR = mRight;
15748
15749        boolean changed = isLayoutModeOptical(mParent) ?
15750                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15751
15752        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15753            onLayout(changed, l, t, r, b);
15754            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15755
15756            ListenerInfo li = mListenerInfo;
15757            if (li != null && li.mOnLayoutChangeListeners != null) {
15758                ArrayList<OnLayoutChangeListener> listenersCopy =
15759                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15760                int numListeners = listenersCopy.size();
15761                for (int i = 0; i < numListeners; ++i) {
15762                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15763                }
15764            }
15765        }
15766
15767        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15768        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15769    }
15770
15771    /**
15772     * Called from layout when this view should
15773     * assign a size and position to each of its children.
15774     *
15775     * Derived classes with children should override
15776     * this method and call layout on each of
15777     * their children.
15778     * @param changed This is a new size or position for this view
15779     * @param left Left position, relative to parent
15780     * @param top Top position, relative to parent
15781     * @param right Right position, relative to parent
15782     * @param bottom Bottom position, relative to parent
15783     */
15784    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15785    }
15786
15787    /**
15788     * Assign a size and position to this view.
15789     *
15790     * This is called from layout.
15791     *
15792     * @param left Left position, relative to parent
15793     * @param top Top position, relative to parent
15794     * @param right Right position, relative to parent
15795     * @param bottom Bottom position, relative to parent
15796     * @return true if the new size and position are different than the
15797     *         previous ones
15798     * {@hide}
15799     */
15800    protected boolean setFrame(int left, int top, int right, int bottom) {
15801        boolean changed = false;
15802
15803        if (DBG) {
15804            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15805                    + right + "," + bottom + ")");
15806        }
15807
15808        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15809            changed = true;
15810
15811            // Remember our drawn bit
15812            int drawn = mPrivateFlags & PFLAG_DRAWN;
15813
15814            int oldWidth = mRight - mLeft;
15815            int oldHeight = mBottom - mTop;
15816            int newWidth = right - left;
15817            int newHeight = bottom - top;
15818            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15819
15820            // Invalidate our old position
15821            invalidate(sizeChanged);
15822
15823            mLeft = left;
15824            mTop = top;
15825            mRight = right;
15826            mBottom = bottom;
15827            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15828
15829            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15830
15831
15832            if (sizeChanged) {
15833                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15834            }
15835
15836            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
15837                // If we are visible, force the DRAWN bit to on so that
15838                // this invalidate will go through (at least to our parent).
15839                // This is because someone may have invalidated this view
15840                // before this call to setFrame came in, thereby clearing
15841                // the DRAWN bit.
15842                mPrivateFlags |= PFLAG_DRAWN;
15843                invalidate(sizeChanged);
15844                // parent display list may need to be recreated based on a change in the bounds
15845                // of any child
15846                invalidateParentCaches();
15847            }
15848
15849            // Reset drawn bit to original value (invalidate turns it off)
15850            mPrivateFlags |= drawn;
15851
15852            mBackgroundSizeChanged = true;
15853
15854            notifySubtreeAccessibilityStateChangedIfNeeded();
15855        }
15856        return changed;
15857    }
15858
15859    /**
15860     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
15861     * @hide
15862     */
15863    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
15864        setFrame(left, top, right, bottom);
15865    }
15866
15867    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15868        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15869        if (mOverlay != null) {
15870            mOverlay.getOverlayView().setRight(newWidth);
15871            mOverlay.getOverlayView().setBottom(newHeight);
15872        }
15873        rebuildOutline();
15874    }
15875
15876    /**
15877     * Finalize inflating a view from XML.  This is called as the last phase
15878     * of inflation, after all child views have been added.
15879     *
15880     * <p>Even if the subclass overrides onFinishInflate, they should always be
15881     * sure to call the super method, so that we get called.
15882     */
15883    protected void onFinishInflate() {
15884    }
15885
15886    /**
15887     * Returns the resources associated with this view.
15888     *
15889     * @return Resources object.
15890     */
15891    public Resources getResources() {
15892        return mResources;
15893    }
15894
15895    /**
15896     * Invalidates the specified Drawable.
15897     *
15898     * @param drawable the drawable to invalidate
15899     */
15900    @Override
15901    public void invalidateDrawable(@NonNull Drawable drawable) {
15902        if (verifyDrawable(drawable)) {
15903            final Rect dirty = drawable.getDirtyBounds();
15904            final int scrollX = mScrollX;
15905            final int scrollY = mScrollY;
15906
15907            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15908                    dirty.right + scrollX, dirty.bottom + scrollY);
15909            rebuildOutline();
15910        }
15911    }
15912
15913    /**
15914     * Schedules an action on a drawable to occur at a specified time.
15915     *
15916     * @param who the recipient of the action
15917     * @param what the action to run on the drawable
15918     * @param when the time at which the action must occur. Uses the
15919     *        {@link SystemClock#uptimeMillis} timebase.
15920     */
15921    @Override
15922    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15923        if (verifyDrawable(who) && what != null) {
15924            final long delay = when - SystemClock.uptimeMillis();
15925            if (mAttachInfo != null) {
15926                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15927                        Choreographer.CALLBACK_ANIMATION, what, who,
15928                        Choreographer.subtractFrameDelay(delay));
15929            } else {
15930                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15931            }
15932        }
15933    }
15934
15935    /**
15936     * Cancels a scheduled action on a drawable.
15937     *
15938     * @param who the recipient of the action
15939     * @param what the action to cancel
15940     */
15941    @Override
15942    public void unscheduleDrawable(Drawable who, Runnable what) {
15943        if (verifyDrawable(who) && what != null) {
15944            if (mAttachInfo != null) {
15945                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15946                        Choreographer.CALLBACK_ANIMATION, what, who);
15947            }
15948            ViewRootImpl.getRunQueue().removeCallbacks(what);
15949        }
15950    }
15951
15952    /**
15953     * Unschedule any events associated with the given Drawable.  This can be
15954     * used when selecting a new Drawable into a view, so that the previous
15955     * one is completely unscheduled.
15956     *
15957     * @param who The Drawable to unschedule.
15958     *
15959     * @see #drawableStateChanged
15960     */
15961    public void unscheduleDrawable(Drawable who) {
15962        if (mAttachInfo != null && who != null) {
15963            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15964                    Choreographer.CALLBACK_ANIMATION, null, who);
15965        }
15966    }
15967
15968    /**
15969     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15970     * that the View directionality can and will be resolved before its Drawables.
15971     *
15972     * Will call {@link View#onResolveDrawables} when resolution is done.
15973     *
15974     * @hide
15975     */
15976    protected void resolveDrawables() {
15977        // Drawables resolution may need to happen before resolving the layout direction (which is
15978        // done only during the measure() call).
15979        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15980        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15981        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15982        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15983        // direction to be resolved as its resolved value will be the same as its raw value.
15984        if (!isLayoutDirectionResolved() &&
15985                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15986            return;
15987        }
15988
15989        final int layoutDirection = isLayoutDirectionResolved() ?
15990                getLayoutDirection() : getRawLayoutDirection();
15991
15992        if (mBackground != null) {
15993            mBackground.setLayoutDirection(layoutDirection);
15994        }
15995        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15996        onResolveDrawables(layoutDirection);
15997    }
15998
15999    boolean areDrawablesResolved() {
16000        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16001    }
16002
16003    /**
16004     * Called when layout direction has been resolved.
16005     *
16006     * The default implementation does nothing.
16007     *
16008     * @param layoutDirection The resolved layout direction.
16009     *
16010     * @see #LAYOUT_DIRECTION_LTR
16011     * @see #LAYOUT_DIRECTION_RTL
16012     *
16013     * @hide
16014     */
16015    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16016    }
16017
16018    /**
16019     * @hide
16020     */
16021    protected void resetResolvedDrawables() {
16022        resetResolvedDrawablesInternal();
16023    }
16024
16025    void resetResolvedDrawablesInternal() {
16026        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16027    }
16028
16029    /**
16030     * If your view subclass is displaying its own Drawable objects, it should
16031     * override this function and return true for any Drawable it is
16032     * displaying.  This allows animations for those drawables to be
16033     * scheduled.
16034     *
16035     * <p>Be sure to call through to the super class when overriding this
16036     * function.
16037     *
16038     * @param who The Drawable to verify.  Return true if it is one you are
16039     *            displaying, else return the result of calling through to the
16040     *            super class.
16041     *
16042     * @return boolean If true than the Drawable is being displayed in the
16043     *         view; else false and it is not allowed to animate.
16044     *
16045     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16046     * @see #drawableStateChanged()
16047     */
16048    protected boolean verifyDrawable(Drawable who) {
16049        return who == mBackground;
16050    }
16051
16052    /**
16053     * This function is called whenever the state of the view changes in such
16054     * a way that it impacts the state of drawables being shown.
16055     * <p>
16056     * If the View has a StateListAnimator, it will also be called to run necessary state
16057     * change animations.
16058     * <p>
16059     * Be sure to call through to the superclass when overriding this function.
16060     *
16061     * @see Drawable#setState(int[])
16062     */
16063    protected void drawableStateChanged() {
16064        final Drawable d = mBackground;
16065        if (d != null && d.isStateful()) {
16066            d.setState(getDrawableState());
16067        }
16068
16069        if (mStateListAnimator != null) {
16070            mStateListAnimator.setState(getDrawableState());
16071        }
16072    }
16073
16074    /**
16075     * This function is called whenever the view hotspot changes and needs to
16076     * be propagated to drawables or child views managed by the view.
16077     * <p>
16078     * Dispatching to child views is handled by
16079     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16080     * <p>
16081     * Be sure to call through to the superclass when overriding this function.
16082     *
16083     * @param x hotspot x coordinate
16084     * @param y hotspot y coordinate
16085     */
16086    public void drawableHotspotChanged(float x, float y) {
16087        if (mBackground != null) {
16088            mBackground.setHotspot(x, y);
16089        }
16090
16091        dispatchDrawableHotspotChanged(x, y);
16092    }
16093
16094    /**
16095     * Dispatches drawableHotspotChanged to all of this View's children.
16096     *
16097     * @param x hotspot x coordinate
16098     * @param y hotspot y coordinate
16099     * @see #drawableHotspotChanged(float, float)
16100     */
16101    public void dispatchDrawableHotspotChanged(float x, float y) {
16102    }
16103
16104    /**
16105     * Call this to force a view to update its drawable state. This will cause
16106     * drawableStateChanged to be called on this view. Views that are interested
16107     * in the new state should call getDrawableState.
16108     *
16109     * @see #drawableStateChanged
16110     * @see #getDrawableState
16111     */
16112    public void refreshDrawableState() {
16113        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16114        drawableStateChanged();
16115
16116        ViewParent parent = mParent;
16117        if (parent != null) {
16118            parent.childDrawableStateChanged(this);
16119        }
16120    }
16121
16122    /**
16123     * Return an array of resource IDs of the drawable states representing the
16124     * current state of the view.
16125     *
16126     * @return The current drawable state
16127     *
16128     * @see Drawable#setState(int[])
16129     * @see #drawableStateChanged()
16130     * @see #onCreateDrawableState(int)
16131     */
16132    public final int[] getDrawableState() {
16133        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16134            return mDrawableState;
16135        } else {
16136            mDrawableState = onCreateDrawableState(0);
16137            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16138            return mDrawableState;
16139        }
16140    }
16141
16142    /**
16143     * Generate the new {@link android.graphics.drawable.Drawable} state for
16144     * this view. This is called by the view
16145     * system when the cached Drawable state is determined to be invalid.  To
16146     * retrieve the current state, you should use {@link #getDrawableState}.
16147     *
16148     * @param extraSpace if non-zero, this is the number of extra entries you
16149     * would like in the returned array in which you can place your own
16150     * states.
16151     *
16152     * @return Returns an array holding the current {@link Drawable} state of
16153     * the view.
16154     *
16155     * @see #mergeDrawableStates(int[], int[])
16156     */
16157    protected int[] onCreateDrawableState(int extraSpace) {
16158        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16159                mParent instanceof View) {
16160            return ((View) mParent).onCreateDrawableState(extraSpace);
16161        }
16162
16163        int[] drawableState;
16164
16165        int privateFlags = mPrivateFlags;
16166
16167        int viewStateIndex = 0;
16168        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
16169        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
16170        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
16171        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
16172        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
16173        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
16174        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16175                HardwareRenderer.isAvailable()) {
16176            // This is set if HW acceleration is requested, even if the current
16177            // process doesn't allow it.  This is just to allow app preview
16178            // windows to better match their app.
16179            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
16180        }
16181        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
16182
16183        final int privateFlags2 = mPrivateFlags2;
16184        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
16185            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
16186        }
16187        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
16188            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
16189        }
16190
16191        drawableState = StateSet.get(viewStateIndex);
16192
16193        //noinspection ConstantIfStatement
16194        if (false) {
16195            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16196            Log.i("View", toString()
16197                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16198                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16199                    + " fo=" + hasFocus()
16200                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16201                    + " wf=" + hasWindowFocus()
16202                    + ": " + Arrays.toString(drawableState));
16203        }
16204
16205        if (extraSpace == 0) {
16206            return drawableState;
16207        }
16208
16209        final int[] fullState;
16210        if (drawableState != null) {
16211            fullState = new int[drawableState.length + extraSpace];
16212            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16213        } else {
16214            fullState = new int[extraSpace];
16215        }
16216
16217        return fullState;
16218    }
16219
16220    /**
16221     * Merge your own state values in <var>additionalState</var> into the base
16222     * state values <var>baseState</var> that were returned by
16223     * {@link #onCreateDrawableState(int)}.
16224     *
16225     * @param baseState The base state values returned by
16226     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16227     * own additional state values.
16228     *
16229     * @param additionalState The additional state values you would like
16230     * added to <var>baseState</var>; this array is not modified.
16231     *
16232     * @return As a convenience, the <var>baseState</var> array you originally
16233     * passed into the function is returned.
16234     *
16235     * @see #onCreateDrawableState(int)
16236     */
16237    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16238        final int N = baseState.length;
16239        int i = N - 1;
16240        while (i >= 0 && baseState[i] == 0) {
16241            i--;
16242        }
16243        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16244        return baseState;
16245    }
16246
16247    /**
16248     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16249     * on all Drawable objects associated with this view.
16250     * <p>
16251     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16252     * attached to this view.
16253     */
16254    public void jumpDrawablesToCurrentState() {
16255        if (mBackground != null) {
16256            mBackground.jumpToCurrentState();
16257        }
16258        if (mStateListAnimator != null) {
16259            mStateListAnimator.jumpToCurrentState();
16260        }
16261    }
16262
16263    /**
16264     * Sets the background color for this view.
16265     * @param color the color of the background
16266     */
16267    @RemotableViewMethod
16268    public void setBackgroundColor(int color) {
16269        if (mBackground instanceof ColorDrawable) {
16270            ((ColorDrawable) mBackground.mutate()).setColor(color);
16271            computeOpaqueFlags();
16272            mBackgroundResource = 0;
16273        } else {
16274            setBackground(new ColorDrawable(color));
16275        }
16276    }
16277
16278    /**
16279     * If the view has a ColorDrawable background, returns the color of that
16280     * drawable.
16281     *
16282     * @return The color of the ColorDrawable background, if set, otherwise 0.
16283     */
16284    public int getBackgroundColor() {
16285        if (mBackground instanceof ColorDrawable) {
16286            return ((ColorDrawable) mBackground).getColor();
16287        }
16288        return 0;
16289    }
16290
16291    /**
16292     * Set the background to a given resource. The resource should refer to
16293     * a Drawable object or 0 to remove the background.
16294     * @param resid The identifier of the resource.
16295     *
16296     * @attr ref android.R.styleable#View_background
16297     */
16298    @RemotableViewMethod
16299    public void setBackgroundResource(int resid) {
16300        if (resid != 0 && resid == mBackgroundResource) {
16301            return;
16302        }
16303
16304        Drawable d = null;
16305        if (resid != 0) {
16306            d = mContext.getDrawable(resid);
16307        }
16308        setBackground(d);
16309
16310        mBackgroundResource = resid;
16311    }
16312
16313    /**
16314     * Set the background to a given Drawable, or remove the background. If the
16315     * background has padding, this View's padding is set to the background's
16316     * padding. However, when a background is removed, this View's padding isn't
16317     * touched. If setting the padding is desired, please use
16318     * {@link #setPadding(int, int, int, int)}.
16319     *
16320     * @param background The Drawable to use as the background, or null to remove the
16321     *        background
16322     */
16323    public void setBackground(Drawable background) {
16324        //noinspection deprecation
16325        setBackgroundDrawable(background);
16326    }
16327
16328    /**
16329     * @deprecated use {@link #setBackground(Drawable)} instead
16330     */
16331    @Deprecated
16332    public void setBackgroundDrawable(Drawable background) {
16333        computeOpaqueFlags();
16334
16335        if (background == mBackground) {
16336            return;
16337        }
16338
16339        boolean requestLayout = false;
16340
16341        mBackgroundResource = 0;
16342
16343        /*
16344         * Regardless of whether we're setting a new background or not, we want
16345         * to clear the previous drawable.
16346         */
16347        if (mBackground != null) {
16348            mBackground.setCallback(null);
16349            unscheduleDrawable(mBackground);
16350        }
16351
16352        if (background != null) {
16353            Rect padding = sThreadLocal.get();
16354            if (padding == null) {
16355                padding = new Rect();
16356                sThreadLocal.set(padding);
16357            }
16358            resetResolvedDrawablesInternal();
16359            background.setLayoutDirection(getLayoutDirection());
16360            if (background.getPadding(padding)) {
16361                resetResolvedPaddingInternal();
16362                switch (background.getLayoutDirection()) {
16363                    case LAYOUT_DIRECTION_RTL:
16364                        mUserPaddingLeftInitial = padding.right;
16365                        mUserPaddingRightInitial = padding.left;
16366                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16367                        break;
16368                    case LAYOUT_DIRECTION_LTR:
16369                    default:
16370                        mUserPaddingLeftInitial = padding.left;
16371                        mUserPaddingRightInitial = padding.right;
16372                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16373                }
16374                mLeftPaddingDefined = false;
16375                mRightPaddingDefined = false;
16376            }
16377
16378            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16379            // if it has a different minimum size, we should layout again
16380            if (mBackground == null
16381                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16382                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16383                requestLayout = true;
16384            }
16385
16386            background.setCallback(this);
16387            if (background.isStateful()) {
16388                background.setState(getDrawableState());
16389            }
16390            background.setVisible(getVisibility() == VISIBLE, false);
16391            mBackground = background;
16392
16393            applyBackgroundTint();
16394
16395            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16396                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16397                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16398                requestLayout = true;
16399            }
16400        } else {
16401            /* Remove the background */
16402            mBackground = null;
16403
16404            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16405                /*
16406                 * This view ONLY drew the background before and we're removing
16407                 * the background, so now it won't draw anything
16408                 * (hence we SKIP_DRAW)
16409                 */
16410                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16411                mPrivateFlags |= PFLAG_SKIP_DRAW;
16412            }
16413
16414            /*
16415             * When the background is set, we try to apply its padding to this
16416             * View. When the background is removed, we don't touch this View's
16417             * padding. This is noted in the Javadocs. Hence, we don't need to
16418             * requestLayout(), the invalidate() below is sufficient.
16419             */
16420
16421            // The old background's minimum size could have affected this
16422            // View's layout, so let's requestLayout
16423            requestLayout = true;
16424        }
16425
16426        computeOpaqueFlags();
16427
16428        if (requestLayout) {
16429            requestLayout();
16430        }
16431
16432        mBackgroundSizeChanged = true;
16433        invalidate(true);
16434    }
16435
16436    /**
16437     * Gets the background drawable
16438     *
16439     * @return The drawable used as the background for this view, if any.
16440     *
16441     * @see #setBackground(Drawable)
16442     *
16443     * @attr ref android.R.styleable#View_background
16444     */
16445    public Drawable getBackground() {
16446        return mBackground;
16447    }
16448
16449    /**
16450     * Applies a tint to the background drawable. Does not modify the current tint
16451     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16452     * <p>
16453     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16454     * mutate the drawable and apply the specified tint and tint mode using
16455     * {@link Drawable#setTintList(ColorStateList)}.
16456     *
16457     * @param tint the tint to apply, may be {@code null} to clear tint
16458     *
16459     * @attr ref android.R.styleable#View_backgroundTint
16460     * @see #getBackgroundTintList()
16461     * @see Drawable#setTintList(ColorStateList)
16462     */
16463    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16464        if (mBackgroundTint == null) {
16465            mBackgroundTint = new TintInfo();
16466        }
16467        mBackgroundTint.mTintList = tint;
16468        mBackgroundTint.mHasTintList = true;
16469
16470        applyBackgroundTint();
16471    }
16472
16473    /**
16474     * Return the tint applied to the background drawable, if specified.
16475     *
16476     * @return the tint applied to the background drawable
16477     * @attr ref android.R.styleable#View_backgroundTint
16478     * @see #setBackgroundTintList(ColorStateList)
16479     */
16480    @Nullable
16481    public ColorStateList getBackgroundTintList() {
16482        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16483    }
16484
16485    /**
16486     * Specifies the blending mode used to apply the tint specified by
16487     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16488     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16489     *
16490     * @param tintMode the blending mode used to apply the tint, may be
16491     *                 {@code null} to clear tint
16492     * @attr ref android.R.styleable#View_backgroundTintMode
16493     * @see #getBackgroundTintMode()
16494     * @see Drawable#setTintMode(PorterDuff.Mode)
16495     */
16496    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16497        if (mBackgroundTint == null) {
16498            mBackgroundTint = new TintInfo();
16499        }
16500        mBackgroundTint.mTintMode = tintMode;
16501        mBackgroundTint.mHasTintMode = true;
16502
16503        applyBackgroundTint();
16504    }
16505
16506    /**
16507     * Return the blending mode used to apply the tint to the background
16508     * drawable, if specified.
16509     *
16510     * @return the blending mode used to apply the tint to the background
16511     *         drawable
16512     * @attr ref android.R.styleable#View_backgroundTintMode
16513     * @see #setBackgroundTintMode(PorterDuff.Mode)
16514     */
16515    @Nullable
16516    public PorterDuff.Mode getBackgroundTintMode() {
16517        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16518    }
16519
16520    private void applyBackgroundTint() {
16521        if (mBackground != null && mBackgroundTint != null) {
16522            final TintInfo tintInfo = mBackgroundTint;
16523            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16524                mBackground = mBackground.mutate();
16525
16526                if (tintInfo.mHasTintList) {
16527                    mBackground.setTintList(tintInfo.mTintList);
16528                }
16529
16530                if (tintInfo.mHasTintMode) {
16531                    mBackground.setTintMode(tintInfo.mTintMode);
16532                }
16533
16534                // The drawable (or one of its children) may not have been
16535                // stateful before applying the tint, so let's try again.
16536                if (mBackground.isStateful()) {
16537                    mBackground.setState(getDrawableState());
16538                }
16539            }
16540        }
16541    }
16542
16543    /**
16544     * Sets the padding. The view may add on the space required to display
16545     * the scrollbars, depending on the style and visibility of the scrollbars.
16546     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16547     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16548     * from the values set in this call.
16549     *
16550     * @attr ref android.R.styleable#View_padding
16551     * @attr ref android.R.styleable#View_paddingBottom
16552     * @attr ref android.R.styleable#View_paddingLeft
16553     * @attr ref android.R.styleable#View_paddingRight
16554     * @attr ref android.R.styleable#View_paddingTop
16555     * @param left the left padding in pixels
16556     * @param top the top padding in pixels
16557     * @param right the right padding in pixels
16558     * @param bottom the bottom padding in pixels
16559     */
16560    public void setPadding(int left, int top, int right, int bottom) {
16561        resetResolvedPaddingInternal();
16562
16563        mUserPaddingStart = UNDEFINED_PADDING;
16564        mUserPaddingEnd = UNDEFINED_PADDING;
16565
16566        mUserPaddingLeftInitial = left;
16567        mUserPaddingRightInitial = right;
16568
16569        mLeftPaddingDefined = true;
16570        mRightPaddingDefined = true;
16571
16572        internalSetPadding(left, top, right, bottom);
16573    }
16574
16575    /**
16576     * @hide
16577     */
16578    protected void internalSetPadding(int left, int top, int right, int bottom) {
16579        mUserPaddingLeft = left;
16580        mUserPaddingRight = right;
16581        mUserPaddingBottom = bottom;
16582
16583        final int viewFlags = mViewFlags;
16584        boolean changed = false;
16585
16586        // Common case is there are no scroll bars.
16587        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16588            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16589                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16590                        ? 0 : getVerticalScrollbarWidth();
16591                switch (mVerticalScrollbarPosition) {
16592                    case SCROLLBAR_POSITION_DEFAULT:
16593                        if (isLayoutRtl()) {
16594                            left += offset;
16595                        } else {
16596                            right += offset;
16597                        }
16598                        break;
16599                    case SCROLLBAR_POSITION_RIGHT:
16600                        right += offset;
16601                        break;
16602                    case SCROLLBAR_POSITION_LEFT:
16603                        left += offset;
16604                        break;
16605                }
16606            }
16607            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16608                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16609                        ? 0 : getHorizontalScrollbarHeight();
16610            }
16611        }
16612
16613        if (mPaddingLeft != left) {
16614            changed = true;
16615            mPaddingLeft = left;
16616        }
16617        if (mPaddingTop != top) {
16618            changed = true;
16619            mPaddingTop = top;
16620        }
16621        if (mPaddingRight != right) {
16622            changed = true;
16623            mPaddingRight = right;
16624        }
16625        if (mPaddingBottom != bottom) {
16626            changed = true;
16627            mPaddingBottom = bottom;
16628        }
16629
16630        if (changed) {
16631            requestLayout();
16632        }
16633    }
16634
16635    /**
16636     * Sets the relative padding. The view may add on the space required to display
16637     * the scrollbars, depending on the style and visibility of the scrollbars.
16638     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16639     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16640     * from the values set in this call.
16641     *
16642     * @attr ref android.R.styleable#View_padding
16643     * @attr ref android.R.styleable#View_paddingBottom
16644     * @attr ref android.R.styleable#View_paddingStart
16645     * @attr ref android.R.styleable#View_paddingEnd
16646     * @attr ref android.R.styleable#View_paddingTop
16647     * @param start the start padding in pixels
16648     * @param top the top padding in pixels
16649     * @param end the end padding in pixels
16650     * @param bottom the bottom padding in pixels
16651     */
16652    public void setPaddingRelative(int start, int top, int end, int bottom) {
16653        resetResolvedPaddingInternal();
16654
16655        mUserPaddingStart = start;
16656        mUserPaddingEnd = end;
16657        mLeftPaddingDefined = true;
16658        mRightPaddingDefined = true;
16659
16660        switch(getLayoutDirection()) {
16661            case LAYOUT_DIRECTION_RTL:
16662                mUserPaddingLeftInitial = end;
16663                mUserPaddingRightInitial = start;
16664                internalSetPadding(end, top, start, bottom);
16665                break;
16666            case LAYOUT_DIRECTION_LTR:
16667            default:
16668                mUserPaddingLeftInitial = start;
16669                mUserPaddingRightInitial = end;
16670                internalSetPadding(start, top, end, bottom);
16671        }
16672    }
16673
16674    /**
16675     * Returns the top padding of this view.
16676     *
16677     * @return the top padding in pixels
16678     */
16679    public int getPaddingTop() {
16680        return mPaddingTop;
16681    }
16682
16683    /**
16684     * Returns the bottom padding of this view. If there are inset and enabled
16685     * scrollbars, this value may include the space required to display the
16686     * scrollbars as well.
16687     *
16688     * @return the bottom padding in pixels
16689     */
16690    public int getPaddingBottom() {
16691        return mPaddingBottom;
16692    }
16693
16694    /**
16695     * Returns the left padding of this view. If there are inset and enabled
16696     * scrollbars, this value may include the space required to display the
16697     * scrollbars as well.
16698     *
16699     * @return the left padding in pixels
16700     */
16701    public int getPaddingLeft() {
16702        if (!isPaddingResolved()) {
16703            resolvePadding();
16704        }
16705        return mPaddingLeft;
16706    }
16707
16708    /**
16709     * Returns the start padding of this view depending on its resolved layout direction.
16710     * If there are inset and enabled scrollbars, this value may include the space
16711     * required to display the scrollbars as well.
16712     *
16713     * @return the start padding in pixels
16714     */
16715    public int getPaddingStart() {
16716        if (!isPaddingResolved()) {
16717            resolvePadding();
16718        }
16719        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16720                mPaddingRight : mPaddingLeft;
16721    }
16722
16723    /**
16724     * Returns the right padding of this view. If there are inset and enabled
16725     * scrollbars, this value may include the space required to display the
16726     * scrollbars as well.
16727     *
16728     * @return the right padding in pixels
16729     */
16730    public int getPaddingRight() {
16731        if (!isPaddingResolved()) {
16732            resolvePadding();
16733        }
16734        return mPaddingRight;
16735    }
16736
16737    /**
16738     * Returns the end padding of this view depending on its resolved layout direction.
16739     * If there are inset and enabled scrollbars, this value may include the space
16740     * required to display the scrollbars as well.
16741     *
16742     * @return the end padding in pixels
16743     */
16744    public int getPaddingEnd() {
16745        if (!isPaddingResolved()) {
16746            resolvePadding();
16747        }
16748        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16749                mPaddingLeft : mPaddingRight;
16750    }
16751
16752    /**
16753     * Return if the padding has been set through relative values
16754     * {@link #setPaddingRelative(int, int, int, int)} or through
16755     * @attr ref android.R.styleable#View_paddingStart or
16756     * @attr ref android.R.styleable#View_paddingEnd
16757     *
16758     * @return true if the padding is relative or false if it is not.
16759     */
16760    public boolean isPaddingRelative() {
16761        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16762    }
16763
16764    Insets computeOpticalInsets() {
16765        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16766    }
16767
16768    /**
16769     * @hide
16770     */
16771    public void resetPaddingToInitialValues() {
16772        if (isRtlCompatibilityMode()) {
16773            mPaddingLeft = mUserPaddingLeftInitial;
16774            mPaddingRight = mUserPaddingRightInitial;
16775            return;
16776        }
16777        if (isLayoutRtl()) {
16778            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16779            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16780        } else {
16781            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16782            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16783        }
16784    }
16785
16786    /**
16787     * @hide
16788     */
16789    public Insets getOpticalInsets() {
16790        if (mLayoutInsets == null) {
16791            mLayoutInsets = computeOpticalInsets();
16792        }
16793        return mLayoutInsets;
16794    }
16795
16796    /**
16797     * Set this view's optical insets.
16798     *
16799     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16800     * property. Views that compute their own optical insets should call it as part of measurement.
16801     * This method does not request layout. If you are setting optical insets outside of
16802     * measure/layout itself you will want to call requestLayout() yourself.
16803     * </p>
16804     * @hide
16805     */
16806    public void setOpticalInsets(Insets insets) {
16807        mLayoutInsets = insets;
16808    }
16809
16810    /**
16811     * Changes the selection state of this view. A view can be selected or not.
16812     * Note that selection is not the same as focus. Views are typically
16813     * selected in the context of an AdapterView like ListView or GridView;
16814     * the selected view is the view that is highlighted.
16815     *
16816     * @param selected true if the view must be selected, false otherwise
16817     */
16818    public void setSelected(boolean selected) {
16819        //noinspection DoubleNegation
16820        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16821            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16822            if (!selected) resetPressedState();
16823            invalidate(true);
16824            refreshDrawableState();
16825            dispatchSetSelected(selected);
16826            if (selected) {
16827                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
16828            } else {
16829                notifyViewAccessibilityStateChangedIfNeeded(
16830                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16831            }
16832        }
16833    }
16834
16835    /**
16836     * Dispatch setSelected to all of this View's children.
16837     *
16838     * @see #setSelected(boolean)
16839     *
16840     * @param selected The new selected state
16841     */
16842    protected void dispatchSetSelected(boolean selected) {
16843    }
16844
16845    /**
16846     * Indicates the selection state of this view.
16847     *
16848     * @return true if the view is selected, false otherwise
16849     */
16850    @ViewDebug.ExportedProperty
16851    public boolean isSelected() {
16852        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16853    }
16854
16855    /**
16856     * Changes the activated state of this view. A view can be activated or not.
16857     * Note that activation is not the same as selection.  Selection is
16858     * a transient property, representing the view (hierarchy) the user is
16859     * currently interacting with.  Activation is a longer-term state that the
16860     * user can move views in and out of.  For example, in a list view with
16861     * single or multiple selection enabled, the views in the current selection
16862     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16863     * here.)  The activated state is propagated down to children of the view it
16864     * is set on.
16865     *
16866     * @param activated true if the view must be activated, false otherwise
16867     */
16868    public void setActivated(boolean activated) {
16869        //noinspection DoubleNegation
16870        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16871            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16872            invalidate(true);
16873            refreshDrawableState();
16874            dispatchSetActivated(activated);
16875        }
16876    }
16877
16878    /**
16879     * Dispatch setActivated to all of this View's children.
16880     *
16881     * @see #setActivated(boolean)
16882     *
16883     * @param activated The new activated state
16884     */
16885    protected void dispatchSetActivated(boolean activated) {
16886    }
16887
16888    /**
16889     * Indicates the activation state of this view.
16890     *
16891     * @return true if the view is activated, false otherwise
16892     */
16893    @ViewDebug.ExportedProperty
16894    public boolean isActivated() {
16895        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16896    }
16897
16898    /**
16899     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16900     * observer can be used to get notifications when global events, like
16901     * layout, happen.
16902     *
16903     * The returned ViewTreeObserver observer is not guaranteed to remain
16904     * valid for the lifetime of this View. If the caller of this method keeps
16905     * a long-lived reference to ViewTreeObserver, it should always check for
16906     * the return value of {@link ViewTreeObserver#isAlive()}.
16907     *
16908     * @return The ViewTreeObserver for this view's hierarchy.
16909     */
16910    public ViewTreeObserver getViewTreeObserver() {
16911        if (mAttachInfo != null) {
16912            return mAttachInfo.mTreeObserver;
16913        }
16914        if (mFloatingTreeObserver == null) {
16915            mFloatingTreeObserver = new ViewTreeObserver();
16916        }
16917        return mFloatingTreeObserver;
16918    }
16919
16920    /**
16921     * <p>Finds the topmost view in the current view hierarchy.</p>
16922     *
16923     * @return the topmost view containing this view
16924     */
16925    public View getRootView() {
16926        if (mAttachInfo != null) {
16927            final View v = mAttachInfo.mRootView;
16928            if (v != null) {
16929                return v;
16930            }
16931        }
16932
16933        View parent = this;
16934
16935        while (parent.mParent != null && parent.mParent instanceof View) {
16936            parent = (View) parent.mParent;
16937        }
16938
16939        return parent;
16940    }
16941
16942    /**
16943     * Transforms a motion event from view-local coordinates to on-screen
16944     * coordinates.
16945     *
16946     * @param ev the view-local motion event
16947     * @return false if the transformation could not be applied
16948     * @hide
16949     */
16950    public boolean toGlobalMotionEvent(MotionEvent ev) {
16951        final AttachInfo info = mAttachInfo;
16952        if (info == null) {
16953            return false;
16954        }
16955
16956        final Matrix m = info.mTmpMatrix;
16957        m.set(Matrix.IDENTITY_MATRIX);
16958        transformMatrixToGlobal(m);
16959        ev.transform(m);
16960        return true;
16961    }
16962
16963    /**
16964     * Transforms a motion event from on-screen coordinates to view-local
16965     * coordinates.
16966     *
16967     * @param ev the on-screen motion event
16968     * @return false if the transformation could not be applied
16969     * @hide
16970     */
16971    public boolean toLocalMotionEvent(MotionEvent ev) {
16972        final AttachInfo info = mAttachInfo;
16973        if (info == null) {
16974            return false;
16975        }
16976
16977        final Matrix m = info.mTmpMatrix;
16978        m.set(Matrix.IDENTITY_MATRIX);
16979        transformMatrixToLocal(m);
16980        ev.transform(m);
16981        return true;
16982    }
16983
16984    /**
16985     * Modifies the input matrix such that it maps view-local coordinates to
16986     * on-screen coordinates.
16987     *
16988     * @param m input matrix to modify
16989     * @hide
16990     */
16991    public void transformMatrixToGlobal(Matrix m) {
16992        final ViewParent parent = mParent;
16993        if (parent instanceof View) {
16994            final View vp = (View) parent;
16995            vp.transformMatrixToGlobal(m);
16996            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16997        } else if (parent instanceof ViewRootImpl) {
16998            final ViewRootImpl vr = (ViewRootImpl) parent;
16999            vr.transformMatrixToGlobal(m);
17000            m.preTranslate(0, -vr.mCurScrollY);
17001        }
17002
17003        m.preTranslate(mLeft, mTop);
17004
17005        if (!hasIdentityMatrix()) {
17006            m.preConcat(getMatrix());
17007        }
17008    }
17009
17010    /**
17011     * Modifies the input matrix such that it maps on-screen coordinates to
17012     * view-local coordinates.
17013     *
17014     * @param m input matrix to modify
17015     * @hide
17016     */
17017    public void transformMatrixToLocal(Matrix m) {
17018        final ViewParent parent = mParent;
17019        if (parent instanceof View) {
17020            final View vp = (View) parent;
17021            vp.transformMatrixToLocal(m);
17022            m.postTranslate(vp.mScrollX, vp.mScrollY);
17023        } else if (parent instanceof ViewRootImpl) {
17024            final ViewRootImpl vr = (ViewRootImpl) parent;
17025            vr.transformMatrixToLocal(m);
17026            m.postTranslate(0, vr.mCurScrollY);
17027        }
17028
17029        m.postTranslate(-mLeft, -mTop);
17030
17031        if (!hasIdentityMatrix()) {
17032            m.postConcat(getInverseMatrix());
17033        }
17034    }
17035
17036    /**
17037     * @hide
17038     */
17039    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
17040            @ViewDebug.IntToString(from = 0, to = "x"),
17041            @ViewDebug.IntToString(from = 1, to = "y")
17042    })
17043    public int[] getLocationOnScreen() {
17044        int[] location = new int[2];
17045        getLocationOnScreen(location);
17046        return location;
17047    }
17048
17049    /**
17050     * <p>Computes the coordinates of this view on the screen. The argument
17051     * must be an array of two integers. After the method returns, the array
17052     * contains the x and y location in that order.</p>
17053     *
17054     * @param location an array of two integers in which to hold the coordinates
17055     */
17056    public void getLocationOnScreen(int[] location) {
17057        getLocationInWindow(location);
17058
17059        final AttachInfo info = mAttachInfo;
17060        if (info != null) {
17061            location[0] += info.mWindowLeft;
17062            location[1] += info.mWindowTop;
17063        }
17064    }
17065
17066    /**
17067     * <p>Computes the coordinates of this view in its window. The argument
17068     * must be an array of two integers. After the method returns, the array
17069     * contains the x and y location in that order.</p>
17070     *
17071     * @param location an array of two integers in which to hold the coordinates
17072     */
17073    public void getLocationInWindow(int[] location) {
17074        if (location == null || location.length < 2) {
17075            throw new IllegalArgumentException("location must be an array of two integers");
17076        }
17077
17078        if (mAttachInfo == null) {
17079            // When the view is not attached to a window, this method does not make sense
17080            location[0] = location[1] = 0;
17081            return;
17082        }
17083
17084        float[] position = mAttachInfo.mTmpTransformLocation;
17085        position[0] = position[1] = 0.0f;
17086
17087        if (!hasIdentityMatrix()) {
17088            getMatrix().mapPoints(position);
17089        }
17090
17091        position[0] += mLeft;
17092        position[1] += mTop;
17093
17094        ViewParent viewParent = mParent;
17095        while (viewParent instanceof View) {
17096            final View view = (View) viewParent;
17097
17098            position[0] -= view.mScrollX;
17099            position[1] -= view.mScrollY;
17100
17101            if (!view.hasIdentityMatrix()) {
17102                view.getMatrix().mapPoints(position);
17103            }
17104
17105            position[0] += view.mLeft;
17106            position[1] += view.mTop;
17107
17108            viewParent = view.mParent;
17109         }
17110
17111        if (viewParent instanceof ViewRootImpl) {
17112            // *cough*
17113            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17114            position[1] -= vr.mCurScrollY;
17115        }
17116
17117        location[0] = (int) (position[0] + 0.5f);
17118        location[1] = (int) (position[1] + 0.5f);
17119    }
17120
17121    /**
17122     * {@hide}
17123     * @param id the id of the view to be found
17124     * @return the view of the specified id, null if cannot be found
17125     */
17126    protected View findViewTraversal(int id) {
17127        if (id == mID) {
17128            return this;
17129        }
17130        return null;
17131    }
17132
17133    /**
17134     * {@hide}
17135     * @param tag the tag of the view to be found
17136     * @return the view of specified tag, null if cannot be found
17137     */
17138    protected View findViewWithTagTraversal(Object tag) {
17139        if (tag != null && tag.equals(mTag)) {
17140            return this;
17141        }
17142        return null;
17143    }
17144
17145    /**
17146     * {@hide}
17147     * @param predicate The predicate to evaluate.
17148     * @param childToSkip If not null, ignores this child during the recursive traversal.
17149     * @return The first view that matches the predicate or null.
17150     */
17151    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17152        if (predicate.apply(this)) {
17153            return this;
17154        }
17155        return null;
17156    }
17157
17158    /**
17159     * Look for a child view with the given id.  If this view has the given
17160     * id, return this view.
17161     *
17162     * @param id The id to search for.
17163     * @return The view that has the given id in the hierarchy or null
17164     */
17165    public final View findViewById(int id) {
17166        if (id < 0) {
17167            return null;
17168        }
17169        return findViewTraversal(id);
17170    }
17171
17172    /**
17173     * Finds a view by its unuque and stable accessibility id.
17174     *
17175     * @param accessibilityId The searched accessibility id.
17176     * @return The found view.
17177     */
17178    final View findViewByAccessibilityId(int accessibilityId) {
17179        if (accessibilityId < 0) {
17180            return null;
17181        }
17182        return findViewByAccessibilityIdTraversal(accessibilityId);
17183    }
17184
17185    /**
17186     * Performs the traversal to find a view by its unuque and stable accessibility id.
17187     *
17188     * <strong>Note:</strong>This method does not stop at the root namespace
17189     * boundary since the user can touch the screen at an arbitrary location
17190     * potentially crossing the root namespace bounday which will send an
17191     * accessibility event to accessibility services and they should be able
17192     * to obtain the event source. Also accessibility ids are guaranteed to be
17193     * unique in the window.
17194     *
17195     * @param accessibilityId The accessibility id.
17196     * @return The found view.
17197     *
17198     * @hide
17199     */
17200    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17201        if (getAccessibilityViewId() == accessibilityId) {
17202            return this;
17203        }
17204        return null;
17205    }
17206
17207    /**
17208     * Look for a child view with the given tag.  If this view has the given
17209     * tag, return this view.
17210     *
17211     * @param tag The tag to search for, using "tag.equals(getTag())".
17212     * @return The View that has the given tag in the hierarchy or null
17213     */
17214    public final View findViewWithTag(Object tag) {
17215        if (tag == null) {
17216            return null;
17217        }
17218        return findViewWithTagTraversal(tag);
17219    }
17220
17221    /**
17222     * {@hide}
17223     * Look for a child view that matches the specified predicate.
17224     * If this view matches the predicate, return this view.
17225     *
17226     * @param predicate The predicate to evaluate.
17227     * @return The first view that matches the predicate or null.
17228     */
17229    public final View findViewByPredicate(Predicate<View> predicate) {
17230        return findViewByPredicateTraversal(predicate, null);
17231    }
17232
17233    /**
17234     * {@hide}
17235     * Look for a child view that matches the specified predicate,
17236     * starting with the specified view and its descendents and then
17237     * recusively searching the ancestors and siblings of that view
17238     * until this view is reached.
17239     *
17240     * This method is useful in cases where the predicate does not match
17241     * a single unique view (perhaps multiple views use the same id)
17242     * and we are trying to find the view that is "closest" in scope to the
17243     * starting view.
17244     *
17245     * @param start The view to start from.
17246     * @param predicate The predicate to evaluate.
17247     * @return The first view that matches the predicate or null.
17248     */
17249    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17250        View childToSkip = null;
17251        for (;;) {
17252            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17253            if (view != null || start == this) {
17254                return view;
17255            }
17256
17257            ViewParent parent = start.getParent();
17258            if (parent == null || !(parent instanceof View)) {
17259                return null;
17260            }
17261
17262            childToSkip = start;
17263            start = (View) parent;
17264        }
17265    }
17266
17267    /**
17268     * Sets the identifier for this view. The identifier does not have to be
17269     * unique in this view's hierarchy. The identifier should be a positive
17270     * number.
17271     *
17272     * @see #NO_ID
17273     * @see #getId()
17274     * @see #findViewById(int)
17275     *
17276     * @param id a number used to identify the view
17277     *
17278     * @attr ref android.R.styleable#View_id
17279     */
17280    public void setId(int id) {
17281        mID = id;
17282        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17283            mID = generateViewId();
17284        }
17285    }
17286
17287    /**
17288     * {@hide}
17289     *
17290     * @param isRoot true if the view belongs to the root namespace, false
17291     *        otherwise
17292     */
17293    public void setIsRootNamespace(boolean isRoot) {
17294        if (isRoot) {
17295            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17296        } else {
17297            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17298        }
17299    }
17300
17301    /**
17302     * {@hide}
17303     *
17304     * @return true if the view belongs to the root namespace, false otherwise
17305     */
17306    public boolean isRootNamespace() {
17307        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17308    }
17309
17310    /**
17311     * Returns this view's identifier.
17312     *
17313     * @return a positive integer used to identify the view or {@link #NO_ID}
17314     *         if the view has no ID
17315     *
17316     * @see #setId(int)
17317     * @see #findViewById(int)
17318     * @attr ref android.R.styleable#View_id
17319     */
17320    @ViewDebug.CapturedViewProperty
17321    public int getId() {
17322        return mID;
17323    }
17324
17325    /**
17326     * Returns this view's tag.
17327     *
17328     * @return the Object stored in this view as a tag, or {@code null} if not
17329     *         set
17330     *
17331     * @see #setTag(Object)
17332     * @see #getTag(int)
17333     */
17334    @ViewDebug.ExportedProperty
17335    public Object getTag() {
17336        return mTag;
17337    }
17338
17339    /**
17340     * Sets the tag associated with this view. A tag can be used to mark
17341     * a view in its hierarchy and does not have to be unique within the
17342     * hierarchy. Tags can also be used to store data within a view without
17343     * resorting to another data structure.
17344     *
17345     * @param tag an Object to tag the view with
17346     *
17347     * @see #getTag()
17348     * @see #setTag(int, Object)
17349     */
17350    public void setTag(final Object tag) {
17351        mTag = tag;
17352    }
17353
17354    /**
17355     * Returns the tag associated with this view and the specified key.
17356     *
17357     * @param key The key identifying the tag
17358     *
17359     * @return the Object stored in this view as a tag, or {@code null} if not
17360     *         set
17361     *
17362     * @see #setTag(int, Object)
17363     * @see #getTag()
17364     */
17365    public Object getTag(int key) {
17366        if (mKeyedTags != null) return mKeyedTags.get(key);
17367        return null;
17368    }
17369
17370    /**
17371     * Sets a tag associated with this view and a key. A tag can be used
17372     * to mark a view in its hierarchy and does not have to be unique within
17373     * the hierarchy. Tags can also be used to store data within a view
17374     * without resorting to another data structure.
17375     *
17376     * The specified key should be an id declared in the resources of the
17377     * application to ensure it is unique (see the <a
17378     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17379     * Keys identified as belonging to
17380     * the Android framework or not associated with any package will cause
17381     * an {@link IllegalArgumentException} to be thrown.
17382     *
17383     * @param key The key identifying the tag
17384     * @param tag An Object to tag the view with
17385     *
17386     * @throws IllegalArgumentException If they specified key is not valid
17387     *
17388     * @see #setTag(Object)
17389     * @see #getTag(int)
17390     */
17391    public void setTag(int key, final Object tag) {
17392        // If the package id is 0x00 or 0x01, it's either an undefined package
17393        // or a framework id
17394        if ((key >>> 24) < 2) {
17395            throw new IllegalArgumentException("The key must be an application-specific "
17396                    + "resource id.");
17397        }
17398
17399        setKeyedTag(key, tag);
17400    }
17401
17402    /**
17403     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
17404     * framework id.
17405     *
17406     * @hide
17407     */
17408    public void setTagInternal(int key, Object tag) {
17409        if ((key >>> 24) != 0x1) {
17410            throw new IllegalArgumentException("The key must be a framework-specific "
17411                    + "resource id.");
17412        }
17413
17414        setKeyedTag(key, tag);
17415    }
17416
17417    private void setKeyedTag(int key, Object tag) {
17418        if (mKeyedTags == null) {
17419            mKeyedTags = new SparseArray<Object>(2);
17420        }
17421
17422        mKeyedTags.put(key, tag);
17423    }
17424
17425    /**
17426     * Prints information about this view in the log output, with the tag
17427     * {@link #VIEW_LOG_TAG}.
17428     *
17429     * @hide
17430     */
17431    public void debug() {
17432        debug(0);
17433    }
17434
17435    /**
17436     * Prints information about this view in the log output, with the tag
17437     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17438     * indentation defined by the <code>depth</code>.
17439     *
17440     * @param depth the indentation level
17441     *
17442     * @hide
17443     */
17444    protected void debug(int depth) {
17445        String output = debugIndent(depth - 1);
17446
17447        output += "+ " + this;
17448        int id = getId();
17449        if (id != -1) {
17450            output += " (id=" + id + ")";
17451        }
17452        Object tag = getTag();
17453        if (tag != null) {
17454            output += " (tag=" + tag + ")";
17455        }
17456        Log.d(VIEW_LOG_TAG, output);
17457
17458        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17459            output = debugIndent(depth) + " FOCUSED";
17460            Log.d(VIEW_LOG_TAG, output);
17461        }
17462
17463        output = debugIndent(depth);
17464        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17465                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17466                + "} ";
17467        Log.d(VIEW_LOG_TAG, output);
17468
17469        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17470                || mPaddingBottom != 0) {
17471            output = debugIndent(depth);
17472            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17473                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17474            Log.d(VIEW_LOG_TAG, output);
17475        }
17476
17477        output = debugIndent(depth);
17478        output += "mMeasureWidth=" + mMeasuredWidth +
17479                " mMeasureHeight=" + mMeasuredHeight;
17480        Log.d(VIEW_LOG_TAG, output);
17481
17482        output = debugIndent(depth);
17483        if (mLayoutParams == null) {
17484            output += "BAD! no layout params";
17485        } else {
17486            output = mLayoutParams.debug(output);
17487        }
17488        Log.d(VIEW_LOG_TAG, output);
17489
17490        output = debugIndent(depth);
17491        output += "flags={";
17492        output += View.printFlags(mViewFlags);
17493        output += "}";
17494        Log.d(VIEW_LOG_TAG, output);
17495
17496        output = debugIndent(depth);
17497        output += "privateFlags={";
17498        output += View.printPrivateFlags(mPrivateFlags);
17499        output += "}";
17500        Log.d(VIEW_LOG_TAG, output);
17501    }
17502
17503    /**
17504     * Creates a string of whitespaces used for indentation.
17505     *
17506     * @param depth the indentation level
17507     * @return a String containing (depth * 2 + 3) * 2 white spaces
17508     *
17509     * @hide
17510     */
17511    protected static String debugIndent(int depth) {
17512        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17513        for (int i = 0; i < (depth * 2) + 3; i++) {
17514            spaces.append(' ').append(' ');
17515        }
17516        return spaces.toString();
17517    }
17518
17519    /**
17520     * <p>Return the offset of the widget's text baseline from the widget's top
17521     * boundary. If this widget does not support baseline alignment, this
17522     * method returns -1. </p>
17523     *
17524     * @return the offset of the baseline within the widget's bounds or -1
17525     *         if baseline alignment is not supported
17526     */
17527    @ViewDebug.ExportedProperty(category = "layout")
17528    public int getBaseline() {
17529        return -1;
17530    }
17531
17532    /**
17533     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17534     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17535     * a layout pass.
17536     *
17537     * @return whether the view hierarchy is currently undergoing a layout pass
17538     */
17539    public boolean isInLayout() {
17540        ViewRootImpl viewRoot = getViewRootImpl();
17541        return (viewRoot != null && viewRoot.isInLayout());
17542    }
17543
17544    /**
17545     * Call this when something has changed which has invalidated the
17546     * layout of this view. This will schedule a layout pass of the view
17547     * tree. This should not be called while the view hierarchy is currently in a layout
17548     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17549     * end of the current layout pass (and then layout will run again) or after the current
17550     * frame is drawn and the next layout occurs.
17551     *
17552     * <p>Subclasses which override this method should call the superclass method to
17553     * handle possible request-during-layout errors correctly.</p>
17554     */
17555    public void requestLayout() {
17556        if (mMeasureCache != null) mMeasureCache.clear();
17557
17558        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17559            // Only trigger request-during-layout logic if this is the view requesting it,
17560            // not the views in its parent hierarchy
17561            ViewRootImpl viewRoot = getViewRootImpl();
17562            if (viewRoot != null && viewRoot.isInLayout()) {
17563                if (!viewRoot.requestLayoutDuringLayout(this)) {
17564                    return;
17565                }
17566            }
17567            mAttachInfo.mViewRequestingLayout = this;
17568        }
17569
17570        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17571        mPrivateFlags |= PFLAG_INVALIDATED;
17572
17573        if (mParent != null && !mParent.isLayoutRequested()) {
17574            mParent.requestLayout();
17575        }
17576        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17577            mAttachInfo.mViewRequestingLayout = null;
17578        }
17579    }
17580
17581    /**
17582     * Forces this view to be laid out during the next layout pass.
17583     * This method does not call requestLayout() or forceLayout()
17584     * on the parent.
17585     */
17586    public void forceLayout() {
17587        if (mMeasureCache != null) mMeasureCache.clear();
17588
17589        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17590        mPrivateFlags |= PFLAG_INVALIDATED;
17591    }
17592
17593    /**
17594     * <p>
17595     * This is called to find out how big a view should be. The parent
17596     * supplies constraint information in the width and height parameters.
17597     * </p>
17598     *
17599     * <p>
17600     * The actual measurement work of a view is performed in
17601     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17602     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17603     * </p>
17604     *
17605     *
17606     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17607     *        parent
17608     * @param heightMeasureSpec Vertical space requirements as imposed by the
17609     *        parent
17610     *
17611     * @see #onMeasure(int, int)
17612     */
17613    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17614        boolean optical = isLayoutModeOptical(this);
17615        if (optical != isLayoutModeOptical(mParent)) {
17616            Insets insets = getOpticalInsets();
17617            int oWidth  = insets.left + insets.right;
17618            int oHeight = insets.top  + insets.bottom;
17619            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17620            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17621        }
17622
17623        // Suppress sign extension for the low bytes
17624        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17625        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17626
17627        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17628        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
17629                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
17630        final boolean matchingSize = isExactly &&
17631                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
17632                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
17633        if (forceLayout || !matchingSize &&
17634                (widthMeasureSpec != mOldWidthMeasureSpec ||
17635                        heightMeasureSpec != mOldHeightMeasureSpec)) {
17636
17637            // first clears the measured dimension flag
17638            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17639
17640            resolveRtlPropertiesIfNeeded();
17641
17642            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
17643            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17644                // measure ourselves, this should set the measured dimension flag back
17645                onMeasure(widthMeasureSpec, heightMeasureSpec);
17646                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17647            } else {
17648                long value = mMeasureCache.valueAt(cacheIndex);
17649                // Casting a long to int drops the high 32 bits, no mask needed
17650                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17651                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17652            }
17653
17654            // flag not set, setMeasuredDimension() was not invoked, we raise
17655            // an exception to warn the developer
17656            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17657                throw new IllegalStateException("onMeasure() did not set the"
17658                        + " measured dimension by calling"
17659                        + " setMeasuredDimension()");
17660            }
17661
17662            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17663        }
17664
17665        mOldWidthMeasureSpec = widthMeasureSpec;
17666        mOldHeightMeasureSpec = heightMeasureSpec;
17667
17668        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17669                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17670    }
17671
17672    /**
17673     * <p>
17674     * Measure the view and its content to determine the measured width and the
17675     * measured height. This method is invoked by {@link #measure(int, int)} and
17676     * should be overridden by subclasses to provide accurate and efficient
17677     * measurement of their contents.
17678     * </p>
17679     *
17680     * <p>
17681     * <strong>CONTRACT:</strong> When overriding this method, you
17682     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17683     * measured width and height of this view. Failure to do so will trigger an
17684     * <code>IllegalStateException</code>, thrown by
17685     * {@link #measure(int, int)}. Calling the superclass'
17686     * {@link #onMeasure(int, int)} is a valid use.
17687     * </p>
17688     *
17689     * <p>
17690     * The base class implementation of measure defaults to the background size,
17691     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17692     * override {@link #onMeasure(int, int)} to provide better measurements of
17693     * their content.
17694     * </p>
17695     *
17696     * <p>
17697     * If this method is overridden, it is the subclass's responsibility to make
17698     * sure the measured height and width are at least the view's minimum height
17699     * and width ({@link #getSuggestedMinimumHeight()} and
17700     * {@link #getSuggestedMinimumWidth()}).
17701     * </p>
17702     *
17703     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17704     *                         The requirements are encoded with
17705     *                         {@link android.view.View.MeasureSpec}.
17706     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17707     *                         The requirements are encoded with
17708     *                         {@link android.view.View.MeasureSpec}.
17709     *
17710     * @see #getMeasuredWidth()
17711     * @see #getMeasuredHeight()
17712     * @see #setMeasuredDimension(int, int)
17713     * @see #getSuggestedMinimumHeight()
17714     * @see #getSuggestedMinimumWidth()
17715     * @see android.view.View.MeasureSpec#getMode(int)
17716     * @see android.view.View.MeasureSpec#getSize(int)
17717     */
17718    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17719        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17720                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17721    }
17722
17723    /**
17724     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17725     * measured width and measured height. Failing to do so will trigger an
17726     * exception at measurement time.</p>
17727     *
17728     * @param measuredWidth The measured width of this view.  May be a complex
17729     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17730     * {@link #MEASURED_STATE_TOO_SMALL}.
17731     * @param measuredHeight The measured height of this view.  May be a complex
17732     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17733     * {@link #MEASURED_STATE_TOO_SMALL}.
17734     */
17735    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17736        boolean optical = isLayoutModeOptical(this);
17737        if (optical != isLayoutModeOptical(mParent)) {
17738            Insets insets = getOpticalInsets();
17739            int opticalWidth  = insets.left + insets.right;
17740            int opticalHeight = insets.top  + insets.bottom;
17741
17742            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17743            measuredHeight += optical ? opticalHeight : -opticalHeight;
17744        }
17745        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17746    }
17747
17748    /**
17749     * Sets the measured dimension without extra processing for things like optical bounds.
17750     * Useful for reapplying consistent values that have already been cooked with adjustments
17751     * for optical bounds, etc. such as those from the measurement cache.
17752     *
17753     * @param measuredWidth The measured width of this view.  May be a complex
17754     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17755     * {@link #MEASURED_STATE_TOO_SMALL}.
17756     * @param measuredHeight The measured height of this view.  May be a complex
17757     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17758     * {@link #MEASURED_STATE_TOO_SMALL}.
17759     */
17760    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17761        mMeasuredWidth = measuredWidth;
17762        mMeasuredHeight = measuredHeight;
17763
17764        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17765    }
17766
17767    /**
17768     * Merge two states as returned by {@link #getMeasuredState()}.
17769     * @param curState The current state as returned from a view or the result
17770     * of combining multiple views.
17771     * @param newState The new view state to combine.
17772     * @return Returns a new integer reflecting the combination of the two
17773     * states.
17774     */
17775    public static int combineMeasuredStates(int curState, int newState) {
17776        return curState | newState;
17777    }
17778
17779    /**
17780     * Version of {@link #resolveSizeAndState(int, int, int)}
17781     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17782     */
17783    public static int resolveSize(int size, int measureSpec) {
17784        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17785    }
17786
17787    /**
17788     * Utility to reconcile a desired size and state, with constraints imposed
17789     * by a MeasureSpec.  Will take the desired size, unless a different size
17790     * is imposed by the constraints.  The returned value is a compound integer,
17791     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17792     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17793     * size is smaller than the size the view wants to be.
17794     *
17795     * @param size How big the view wants to be
17796     * @param measureSpec Constraints imposed by the parent
17797     * @return Size information bit mask as defined by
17798     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17799     */
17800    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17801        int result = size;
17802        int specMode = MeasureSpec.getMode(measureSpec);
17803        int specSize =  MeasureSpec.getSize(measureSpec);
17804        switch (specMode) {
17805        case MeasureSpec.UNSPECIFIED:
17806            result = size;
17807            break;
17808        case MeasureSpec.AT_MOST:
17809            if (specSize < size) {
17810                result = specSize | MEASURED_STATE_TOO_SMALL;
17811            } else {
17812                result = size;
17813            }
17814            break;
17815        case MeasureSpec.EXACTLY:
17816            result = specSize;
17817            break;
17818        }
17819        return result | (childMeasuredState&MEASURED_STATE_MASK);
17820    }
17821
17822    /**
17823     * Utility to return a default size. Uses the supplied size if the
17824     * MeasureSpec imposed no constraints. Will get larger if allowed
17825     * by the MeasureSpec.
17826     *
17827     * @param size Default size for this view
17828     * @param measureSpec Constraints imposed by the parent
17829     * @return The size this view should be.
17830     */
17831    public static int getDefaultSize(int size, int measureSpec) {
17832        int result = size;
17833        int specMode = MeasureSpec.getMode(measureSpec);
17834        int specSize = MeasureSpec.getSize(measureSpec);
17835
17836        switch (specMode) {
17837        case MeasureSpec.UNSPECIFIED:
17838            result = size;
17839            break;
17840        case MeasureSpec.AT_MOST:
17841        case MeasureSpec.EXACTLY:
17842            result = specSize;
17843            break;
17844        }
17845        return result;
17846    }
17847
17848    /**
17849     * Returns the suggested minimum height that the view should use. This
17850     * returns the maximum of the view's minimum height
17851     * and the background's minimum height
17852     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17853     * <p>
17854     * When being used in {@link #onMeasure(int, int)}, the caller should still
17855     * ensure the returned height is within the requirements of the parent.
17856     *
17857     * @return The suggested minimum height of the view.
17858     */
17859    protected int getSuggestedMinimumHeight() {
17860        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17861
17862    }
17863
17864    /**
17865     * Returns the suggested minimum width that the view should use. This
17866     * returns the maximum of the view's minimum width)
17867     * and the background's minimum width
17868     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17869     * <p>
17870     * When being used in {@link #onMeasure(int, int)}, the caller should still
17871     * ensure the returned width is within the requirements of the parent.
17872     *
17873     * @return The suggested minimum width of the view.
17874     */
17875    protected int getSuggestedMinimumWidth() {
17876        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17877    }
17878
17879    /**
17880     * Returns the minimum height of the view.
17881     *
17882     * @return the minimum height the view will try to be.
17883     *
17884     * @see #setMinimumHeight(int)
17885     *
17886     * @attr ref android.R.styleable#View_minHeight
17887     */
17888    public int getMinimumHeight() {
17889        return mMinHeight;
17890    }
17891
17892    /**
17893     * Sets the minimum height of the view. It is not guaranteed the view will
17894     * be able to achieve this minimum height (for example, if its parent layout
17895     * constrains it with less available height).
17896     *
17897     * @param minHeight The minimum height the view will try to be.
17898     *
17899     * @see #getMinimumHeight()
17900     *
17901     * @attr ref android.R.styleable#View_minHeight
17902     */
17903    public void setMinimumHeight(int minHeight) {
17904        mMinHeight = minHeight;
17905        requestLayout();
17906    }
17907
17908    /**
17909     * Returns the minimum width of the view.
17910     *
17911     * @return the minimum width the view will try to be.
17912     *
17913     * @see #setMinimumWidth(int)
17914     *
17915     * @attr ref android.R.styleable#View_minWidth
17916     */
17917    public int getMinimumWidth() {
17918        return mMinWidth;
17919    }
17920
17921    /**
17922     * Sets the minimum width of the view. It is not guaranteed the view will
17923     * be able to achieve this minimum width (for example, if its parent layout
17924     * constrains it with less available width).
17925     *
17926     * @param minWidth The minimum width the view will try to be.
17927     *
17928     * @see #getMinimumWidth()
17929     *
17930     * @attr ref android.R.styleable#View_minWidth
17931     */
17932    public void setMinimumWidth(int minWidth) {
17933        mMinWidth = minWidth;
17934        requestLayout();
17935
17936    }
17937
17938    /**
17939     * Get the animation currently associated with this view.
17940     *
17941     * @return The animation that is currently playing or
17942     *         scheduled to play for this view.
17943     */
17944    public Animation getAnimation() {
17945        return mCurrentAnimation;
17946    }
17947
17948    /**
17949     * Start the specified animation now.
17950     *
17951     * @param animation the animation to start now
17952     */
17953    public void startAnimation(Animation animation) {
17954        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17955        setAnimation(animation);
17956        invalidateParentCaches();
17957        invalidate(true);
17958    }
17959
17960    /**
17961     * Cancels any animations for this view.
17962     */
17963    public void clearAnimation() {
17964        if (mCurrentAnimation != null) {
17965            mCurrentAnimation.detach();
17966        }
17967        mCurrentAnimation = null;
17968        invalidateParentIfNeeded();
17969    }
17970
17971    /**
17972     * Sets the next animation to play for this view.
17973     * If you want the animation to play immediately, use
17974     * {@link #startAnimation(android.view.animation.Animation)} instead.
17975     * This method provides allows fine-grained
17976     * control over the start time and invalidation, but you
17977     * must make sure that 1) the animation has a start time set, and
17978     * 2) the view's parent (which controls animations on its children)
17979     * will be invalidated when the animation is supposed to
17980     * start.
17981     *
17982     * @param animation The next animation, or null.
17983     */
17984    public void setAnimation(Animation animation) {
17985        mCurrentAnimation = animation;
17986
17987        if (animation != null) {
17988            // If the screen is off assume the animation start time is now instead of
17989            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17990            // would cause the animation to start when the screen turns back on
17991            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17992                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17993                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17994            }
17995            animation.reset();
17996        }
17997    }
17998
17999    /**
18000     * Invoked by a parent ViewGroup to notify the start of the animation
18001     * currently associated with this view. If you override this method,
18002     * always call super.onAnimationStart();
18003     *
18004     * @see #setAnimation(android.view.animation.Animation)
18005     * @see #getAnimation()
18006     */
18007    protected void onAnimationStart() {
18008        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
18009    }
18010
18011    /**
18012     * Invoked by a parent ViewGroup to notify the end of the animation
18013     * currently associated with this view. If you override this method,
18014     * always call super.onAnimationEnd();
18015     *
18016     * @see #setAnimation(android.view.animation.Animation)
18017     * @see #getAnimation()
18018     */
18019    protected void onAnimationEnd() {
18020        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
18021    }
18022
18023    /**
18024     * Invoked if there is a Transform that involves alpha. Subclass that can
18025     * draw themselves with the specified alpha should return true, and then
18026     * respect that alpha when their onDraw() is called. If this returns false
18027     * then the view may be redirected to draw into an offscreen buffer to
18028     * fulfill the request, which will look fine, but may be slower than if the
18029     * subclass handles it internally. The default implementation returns false.
18030     *
18031     * @param alpha The alpha (0..255) to apply to the view's drawing
18032     * @return true if the view can draw with the specified alpha.
18033     */
18034    protected boolean onSetAlpha(int alpha) {
18035        return false;
18036    }
18037
18038    /**
18039     * This is used by the RootView to perform an optimization when
18040     * the view hierarchy contains one or several SurfaceView.
18041     * SurfaceView is always considered transparent, but its children are not,
18042     * therefore all View objects remove themselves from the global transparent
18043     * region (passed as a parameter to this function).
18044     *
18045     * @param region The transparent region for this ViewAncestor (window).
18046     *
18047     * @return Returns true if the effective visibility of the view at this
18048     * point is opaque, regardless of the transparent region; returns false
18049     * if it is possible for underlying windows to be seen behind the view.
18050     *
18051     * {@hide}
18052     */
18053    public boolean gatherTransparentRegion(Region region) {
18054        final AttachInfo attachInfo = mAttachInfo;
18055        if (region != null && attachInfo != null) {
18056            final int pflags = mPrivateFlags;
18057            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18058                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18059                // remove it from the transparent region.
18060                final int[] location = attachInfo.mTransparentLocation;
18061                getLocationInWindow(location);
18062                region.op(location[0], location[1], location[0] + mRight - mLeft,
18063                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18064            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18065                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18066                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18067                // exists, so we remove the background drawable's non-transparent
18068                // parts from this transparent region.
18069                applyDrawableToTransparentRegion(mBackground, region);
18070            }
18071        }
18072        return true;
18073    }
18074
18075    /**
18076     * Play a sound effect for this view.
18077     *
18078     * <p>The framework will play sound effects for some built in actions, such as
18079     * clicking, but you may wish to play these effects in your widget,
18080     * for instance, for internal navigation.
18081     *
18082     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18083     * {@link #isSoundEffectsEnabled()} is true.
18084     *
18085     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18086     */
18087    public void playSoundEffect(int soundConstant) {
18088        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18089            return;
18090        }
18091        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18092    }
18093
18094    /**
18095     * BZZZTT!!1!
18096     *
18097     * <p>Provide haptic feedback to the user for this view.
18098     *
18099     * <p>The framework will provide haptic feedback for some built in actions,
18100     * such as long presses, but you may wish to provide feedback for your
18101     * own widget.
18102     *
18103     * <p>The feedback will only be performed if
18104     * {@link #isHapticFeedbackEnabled()} is true.
18105     *
18106     * @param feedbackConstant One of the constants defined in
18107     * {@link HapticFeedbackConstants}
18108     */
18109    public boolean performHapticFeedback(int feedbackConstant) {
18110        return performHapticFeedback(feedbackConstant, 0);
18111    }
18112
18113    /**
18114     * BZZZTT!!1!
18115     *
18116     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18117     *
18118     * @param feedbackConstant One of the constants defined in
18119     * {@link HapticFeedbackConstants}
18120     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18121     */
18122    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18123        if (mAttachInfo == null) {
18124            return false;
18125        }
18126        //noinspection SimplifiableIfStatement
18127        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18128                && !isHapticFeedbackEnabled()) {
18129            return false;
18130        }
18131        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18132                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18133    }
18134
18135    /**
18136     * Request that the visibility of the status bar or other screen/window
18137     * decorations be changed.
18138     *
18139     * <p>This method is used to put the over device UI into temporary modes
18140     * where the user's attention is focused more on the application content,
18141     * by dimming or hiding surrounding system affordances.  This is typically
18142     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18143     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18144     * to be placed behind the action bar (and with these flags other system
18145     * affordances) so that smooth transitions between hiding and showing them
18146     * can be done.
18147     *
18148     * <p>Two representative examples of the use of system UI visibility is
18149     * implementing a content browsing application (like a magazine reader)
18150     * and a video playing application.
18151     *
18152     * <p>The first code shows a typical implementation of a View in a content
18153     * browsing application.  In this implementation, the application goes
18154     * into a content-oriented mode by hiding the status bar and action bar,
18155     * and putting the navigation elements into lights out mode.  The user can
18156     * then interact with content while in this mode.  Such an application should
18157     * provide an easy way for the user to toggle out of the mode (such as to
18158     * check information in the status bar or access notifications).  In the
18159     * implementation here, this is done simply by tapping on the content.
18160     *
18161     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18162     *      content}
18163     *
18164     * <p>This second code sample shows a typical implementation of a View
18165     * in a video playing application.  In this situation, while the video is
18166     * playing the application would like to go into a complete full-screen mode,
18167     * to use as much of the display as possible for the video.  When in this state
18168     * the user can not interact with the application; the system intercepts
18169     * touching on the screen to pop the UI out of full screen mode.  See
18170     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18171     *
18172     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18173     *      content}
18174     *
18175     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18176     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18177     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18178     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18179     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18180     */
18181    public void setSystemUiVisibility(int visibility) {
18182        if (visibility != mSystemUiVisibility) {
18183            mSystemUiVisibility = visibility;
18184            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18185                mParent.recomputeViewAttributes(this);
18186            }
18187        }
18188    }
18189
18190    /**
18191     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18192     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18193     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18194     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18195     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18196     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18197     */
18198    public int getSystemUiVisibility() {
18199        return mSystemUiVisibility;
18200    }
18201
18202    /**
18203     * Returns the current system UI visibility that is currently set for
18204     * the entire window.  This is the combination of the
18205     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18206     * views in the window.
18207     */
18208    public int getWindowSystemUiVisibility() {
18209        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18210    }
18211
18212    /**
18213     * Override to find out when the window's requested system UI visibility
18214     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18215     * This is different from the callbacks received through
18216     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18217     * in that this is only telling you about the local request of the window,
18218     * not the actual values applied by the system.
18219     */
18220    public void onWindowSystemUiVisibilityChanged(int visible) {
18221    }
18222
18223    /**
18224     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18225     * the view hierarchy.
18226     */
18227    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18228        onWindowSystemUiVisibilityChanged(visible);
18229    }
18230
18231    /**
18232     * Set a listener to receive callbacks when the visibility of the system bar changes.
18233     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18234     */
18235    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18236        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18237        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18238            mParent.recomputeViewAttributes(this);
18239        }
18240    }
18241
18242    /**
18243     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18244     * the view hierarchy.
18245     */
18246    public void dispatchSystemUiVisibilityChanged(int visibility) {
18247        ListenerInfo li = mListenerInfo;
18248        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18249            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18250                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18251        }
18252    }
18253
18254    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18255        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18256        if (val != mSystemUiVisibility) {
18257            setSystemUiVisibility(val);
18258            return true;
18259        }
18260        return false;
18261    }
18262
18263    /** @hide */
18264    public void setDisabledSystemUiVisibility(int flags) {
18265        if (mAttachInfo != null) {
18266            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18267                mAttachInfo.mDisabledSystemUiVisibility = flags;
18268                if (mParent != null) {
18269                    mParent.recomputeViewAttributes(this);
18270                }
18271            }
18272        }
18273    }
18274
18275    /**
18276     * Creates an image that the system displays during the drag and drop
18277     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18278     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18279     * appearance as the given View. The default also positions the center of the drag shadow
18280     * directly under the touch point. If no View is provided (the constructor with no parameters
18281     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18282     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
18283     * default is an invisible drag shadow.
18284     * <p>
18285     * You are not required to use the View you provide to the constructor as the basis of the
18286     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18287     * anything you want as the drag shadow.
18288     * </p>
18289     * <p>
18290     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18291     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18292     *  size and position of the drag shadow. It uses this data to construct a
18293     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18294     *  so that your application can draw the shadow image in the Canvas.
18295     * </p>
18296     *
18297     * <div class="special reference">
18298     * <h3>Developer Guides</h3>
18299     * <p>For a guide to implementing drag and drop features, read the
18300     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18301     * </div>
18302     */
18303    public static class DragShadowBuilder {
18304        private final WeakReference<View> mView;
18305
18306        /**
18307         * Constructs a shadow image builder based on a View. By default, the resulting drag
18308         * shadow will have the same appearance and dimensions as the View, with the touch point
18309         * over the center of the View.
18310         * @param view A View. Any View in scope can be used.
18311         */
18312        public DragShadowBuilder(View view) {
18313            mView = new WeakReference<View>(view);
18314        }
18315
18316        /**
18317         * Construct a shadow builder object with no associated View.  This
18318         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18319         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18320         * to supply the drag shadow's dimensions and appearance without
18321         * reference to any View object. If they are not overridden, then the result is an
18322         * invisible drag shadow.
18323         */
18324        public DragShadowBuilder() {
18325            mView = new WeakReference<View>(null);
18326        }
18327
18328        /**
18329         * Returns the View object that had been passed to the
18330         * {@link #View.DragShadowBuilder(View)}
18331         * constructor.  If that View parameter was {@code null} or if the
18332         * {@link #View.DragShadowBuilder()}
18333         * constructor was used to instantiate the builder object, this method will return
18334         * null.
18335         *
18336         * @return The View object associate with this builder object.
18337         */
18338        @SuppressWarnings({"JavadocReference"})
18339        final public View getView() {
18340            return mView.get();
18341        }
18342
18343        /**
18344         * Provides the metrics for the shadow image. These include the dimensions of
18345         * the shadow image, and the point within that shadow that should
18346         * be centered under the touch location while dragging.
18347         * <p>
18348         * The default implementation sets the dimensions of the shadow to be the
18349         * same as the dimensions of the View itself and centers the shadow under
18350         * the touch point.
18351         * </p>
18352         *
18353         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18354         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18355         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18356         * image.
18357         *
18358         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18359         * shadow image that should be underneath the touch point during the drag and drop
18360         * operation. Your application must set {@link android.graphics.Point#x} to the
18361         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18362         */
18363        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18364            final View view = mView.get();
18365            if (view != null) {
18366                shadowSize.set(view.getWidth(), view.getHeight());
18367                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18368            } else {
18369                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18370            }
18371        }
18372
18373        /**
18374         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18375         * based on the dimensions it received from the
18376         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18377         *
18378         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18379         */
18380        public void onDrawShadow(Canvas canvas) {
18381            final View view = mView.get();
18382            if (view != null) {
18383                view.draw(canvas);
18384            } else {
18385                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
18386            }
18387        }
18388    }
18389
18390    /**
18391     * Starts a drag and drop operation. When your application calls this method, it passes a
18392     * {@link android.view.View.DragShadowBuilder} object to the system. The
18393     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
18394     * to get metrics for the drag shadow, and then calls the object's
18395     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
18396     * <p>
18397     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
18398     *  drag events to all the View objects in your application that are currently visible. It does
18399     *  this either by calling the View object's drag listener (an implementation of
18400     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
18401     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
18402     *  Both are passed a {@link android.view.DragEvent} object that has a
18403     *  {@link android.view.DragEvent#getAction()} value of
18404     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
18405     * </p>
18406     * <p>
18407     * Your application can invoke startDrag() on any attached View object. The View object does not
18408     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
18409     * be related to the View the user selected for dragging.
18410     * </p>
18411     * @param data A {@link android.content.ClipData} object pointing to the data to be
18412     * transferred by the drag and drop operation.
18413     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
18414     * drag shadow.
18415     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
18416     * drop operation. This Object is put into every DragEvent object sent by the system during the
18417     * current drag.
18418     * <p>
18419     * myLocalState is a lightweight mechanism for the sending information from the dragged View
18420     * to the target Views. For example, it can contain flags that differentiate between a
18421     * a copy operation and a move operation.
18422     * </p>
18423     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
18424     * so the parameter should be set to 0.
18425     * @return {@code true} if the method completes successfully, or
18426     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
18427     * do a drag, and so no drag operation is in progress.
18428     */
18429    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
18430            Object myLocalState, int flags) {
18431        if (ViewDebug.DEBUG_DRAG) {
18432            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
18433        }
18434        boolean okay = false;
18435
18436        Point shadowSize = new Point();
18437        Point shadowTouchPoint = new Point();
18438        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18439
18440        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18441                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18442            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18443        }
18444
18445        if (ViewDebug.DEBUG_DRAG) {
18446            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18447                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18448        }
18449        Surface surface = new Surface();
18450        try {
18451            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18452                    flags, shadowSize.x, shadowSize.y, surface);
18453            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18454                    + " surface=" + surface);
18455            if (token != null) {
18456                Canvas canvas = surface.lockCanvas(null);
18457                try {
18458                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18459                    shadowBuilder.onDrawShadow(canvas);
18460                } finally {
18461                    surface.unlockCanvasAndPost(canvas);
18462                }
18463
18464                final ViewRootImpl root = getViewRootImpl();
18465
18466                // Cache the local state object for delivery with DragEvents
18467                root.setLocalDragState(myLocalState);
18468
18469                // repurpose 'shadowSize' for the last touch point
18470                root.getLastTouchPoint(shadowSize);
18471
18472                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18473                        shadowSize.x, shadowSize.y,
18474                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18475                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18476
18477                // Off and running!  Release our local surface instance; the drag
18478                // shadow surface is now managed by the system process.
18479                surface.release();
18480            }
18481        } catch (Exception e) {
18482            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18483            surface.destroy();
18484        }
18485
18486        return okay;
18487    }
18488
18489    /**
18490     * Handles drag events sent by the system following a call to
18491     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18492     *<p>
18493     * When the system calls this method, it passes a
18494     * {@link android.view.DragEvent} object. A call to
18495     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18496     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18497     * operation.
18498     * @param event The {@link android.view.DragEvent} sent by the system.
18499     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18500     * in DragEvent, indicating the type of drag event represented by this object.
18501     * @return {@code true} if the method was successful, otherwise {@code false}.
18502     * <p>
18503     *  The method should return {@code true} in response to an action type of
18504     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18505     *  operation.
18506     * </p>
18507     * <p>
18508     *  The method should also return {@code true} in response to an action type of
18509     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18510     *  {@code false} if it didn't.
18511     * </p>
18512     */
18513    public boolean onDragEvent(DragEvent event) {
18514        return false;
18515    }
18516
18517    /**
18518     * Detects if this View is enabled and has a drag event listener.
18519     * If both are true, then it calls the drag event listener with the
18520     * {@link android.view.DragEvent} it received. If the drag event listener returns
18521     * {@code true}, then dispatchDragEvent() returns {@code true}.
18522     * <p>
18523     * For all other cases, the method calls the
18524     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18525     * method and returns its result.
18526     * </p>
18527     * <p>
18528     * This ensures that a drag event is always consumed, even if the View does not have a drag
18529     * event listener. However, if the View has a listener and the listener returns true, then
18530     * onDragEvent() is not called.
18531     * </p>
18532     */
18533    public boolean dispatchDragEvent(DragEvent event) {
18534        ListenerInfo li = mListenerInfo;
18535        //noinspection SimplifiableIfStatement
18536        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18537                && li.mOnDragListener.onDrag(this, event)) {
18538            return true;
18539        }
18540        return onDragEvent(event);
18541    }
18542
18543    boolean canAcceptDrag() {
18544        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18545    }
18546
18547    /**
18548     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18549     * it is ever exposed at all.
18550     * @hide
18551     */
18552    public void onCloseSystemDialogs(String reason) {
18553    }
18554
18555    /**
18556     * Given a Drawable whose bounds have been set to draw into this view,
18557     * update a Region being computed for
18558     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18559     * that any non-transparent parts of the Drawable are removed from the
18560     * given transparent region.
18561     *
18562     * @param dr The Drawable whose transparency is to be applied to the region.
18563     * @param region A Region holding the current transparency information,
18564     * where any parts of the region that are set are considered to be
18565     * transparent.  On return, this region will be modified to have the
18566     * transparency information reduced by the corresponding parts of the
18567     * Drawable that are not transparent.
18568     * {@hide}
18569     */
18570    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18571        if (DBG) {
18572            Log.i("View", "Getting transparent region for: " + this);
18573        }
18574        final Region r = dr.getTransparentRegion();
18575        final Rect db = dr.getBounds();
18576        final AttachInfo attachInfo = mAttachInfo;
18577        if (r != null && attachInfo != null) {
18578            final int w = getRight()-getLeft();
18579            final int h = getBottom()-getTop();
18580            if (db.left > 0) {
18581                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18582                r.op(0, 0, db.left, h, Region.Op.UNION);
18583            }
18584            if (db.right < w) {
18585                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18586                r.op(db.right, 0, w, h, Region.Op.UNION);
18587            }
18588            if (db.top > 0) {
18589                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18590                r.op(0, 0, w, db.top, Region.Op.UNION);
18591            }
18592            if (db.bottom < h) {
18593                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18594                r.op(0, db.bottom, w, h, Region.Op.UNION);
18595            }
18596            final int[] location = attachInfo.mTransparentLocation;
18597            getLocationInWindow(location);
18598            r.translate(location[0], location[1]);
18599            region.op(r, Region.Op.INTERSECT);
18600        } else {
18601            region.op(db, Region.Op.DIFFERENCE);
18602        }
18603    }
18604
18605    private void checkForLongClick(int delayOffset) {
18606        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18607            mHasPerformedLongPress = false;
18608
18609            if (mPendingCheckForLongPress == null) {
18610                mPendingCheckForLongPress = new CheckForLongPress();
18611            }
18612            mPendingCheckForLongPress.rememberWindowAttachCount();
18613            postDelayed(mPendingCheckForLongPress,
18614                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18615        }
18616    }
18617
18618    /**
18619     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18620     * LayoutInflater} class, which provides a full range of options for view inflation.
18621     *
18622     * @param context The Context object for your activity or application.
18623     * @param resource The resource ID to inflate
18624     * @param root A view group that will be the parent.  Used to properly inflate the
18625     * layout_* parameters.
18626     * @see LayoutInflater
18627     */
18628    public static View inflate(Context context, int resource, ViewGroup root) {
18629        LayoutInflater factory = LayoutInflater.from(context);
18630        return factory.inflate(resource, root);
18631    }
18632
18633    /**
18634     * Scroll the view with standard behavior for scrolling beyond the normal
18635     * content boundaries. Views that call this method should override
18636     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18637     * results of an over-scroll operation.
18638     *
18639     * Views can use this method to handle any touch or fling-based scrolling.
18640     *
18641     * @param deltaX Change in X in pixels
18642     * @param deltaY Change in Y in pixels
18643     * @param scrollX Current X scroll value in pixels before applying deltaX
18644     * @param scrollY Current Y scroll value in pixels before applying deltaY
18645     * @param scrollRangeX Maximum content scroll range along the X axis
18646     * @param scrollRangeY Maximum content scroll range along the Y axis
18647     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18648     *          along the X axis.
18649     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18650     *          along the Y axis.
18651     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18652     * @return true if scrolling was clamped to an over-scroll boundary along either
18653     *          axis, false otherwise.
18654     */
18655    @SuppressWarnings({"UnusedParameters"})
18656    protected boolean overScrollBy(int deltaX, int deltaY,
18657            int scrollX, int scrollY,
18658            int scrollRangeX, int scrollRangeY,
18659            int maxOverScrollX, int maxOverScrollY,
18660            boolean isTouchEvent) {
18661        final int overScrollMode = mOverScrollMode;
18662        final boolean canScrollHorizontal =
18663                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18664        final boolean canScrollVertical =
18665                computeVerticalScrollRange() > computeVerticalScrollExtent();
18666        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18667                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18668        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18669                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18670
18671        int newScrollX = scrollX + deltaX;
18672        if (!overScrollHorizontal) {
18673            maxOverScrollX = 0;
18674        }
18675
18676        int newScrollY = scrollY + deltaY;
18677        if (!overScrollVertical) {
18678            maxOverScrollY = 0;
18679        }
18680
18681        // Clamp values if at the limits and record
18682        final int left = -maxOverScrollX;
18683        final int right = maxOverScrollX + scrollRangeX;
18684        final int top = -maxOverScrollY;
18685        final int bottom = maxOverScrollY + scrollRangeY;
18686
18687        boolean clampedX = false;
18688        if (newScrollX > right) {
18689            newScrollX = right;
18690            clampedX = true;
18691        } else if (newScrollX < left) {
18692            newScrollX = left;
18693            clampedX = true;
18694        }
18695
18696        boolean clampedY = false;
18697        if (newScrollY > bottom) {
18698            newScrollY = bottom;
18699            clampedY = true;
18700        } else if (newScrollY < top) {
18701            newScrollY = top;
18702            clampedY = true;
18703        }
18704
18705        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18706
18707        return clampedX || clampedY;
18708    }
18709
18710    /**
18711     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18712     * respond to the results of an over-scroll operation.
18713     *
18714     * @param scrollX New X scroll value in pixels
18715     * @param scrollY New Y scroll value in pixels
18716     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18717     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18718     */
18719    protected void onOverScrolled(int scrollX, int scrollY,
18720            boolean clampedX, boolean clampedY) {
18721        // Intentionally empty.
18722    }
18723
18724    /**
18725     * Returns the over-scroll mode for this view. The result will be
18726     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18727     * (allow over-scrolling only if the view content is larger than the container),
18728     * or {@link #OVER_SCROLL_NEVER}.
18729     *
18730     * @return This view's over-scroll mode.
18731     */
18732    public int getOverScrollMode() {
18733        return mOverScrollMode;
18734    }
18735
18736    /**
18737     * Set the over-scroll mode for this view. Valid over-scroll modes are
18738     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18739     * (allow over-scrolling only if the view content is larger than the container),
18740     * or {@link #OVER_SCROLL_NEVER}.
18741     *
18742     * Setting the over-scroll mode of a view will have an effect only if the
18743     * view is capable of scrolling.
18744     *
18745     * @param overScrollMode The new over-scroll mode for this view.
18746     */
18747    public void setOverScrollMode(int overScrollMode) {
18748        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18749                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18750                overScrollMode != OVER_SCROLL_NEVER) {
18751            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18752        }
18753        mOverScrollMode = overScrollMode;
18754    }
18755
18756    /**
18757     * Enable or disable nested scrolling for this view.
18758     *
18759     * <p>If this property is set to true the view will be permitted to initiate nested
18760     * scrolling operations with a compatible parent view in the current hierarchy. If this
18761     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18762     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18763     * the nested scroll.</p>
18764     *
18765     * @param enabled true to enable nested scrolling, false to disable
18766     *
18767     * @see #isNestedScrollingEnabled()
18768     */
18769    public void setNestedScrollingEnabled(boolean enabled) {
18770        if (enabled) {
18771            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18772        } else {
18773            stopNestedScroll();
18774            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18775        }
18776    }
18777
18778    /**
18779     * Returns true if nested scrolling is enabled for this view.
18780     *
18781     * <p>If nested scrolling is enabled and this View class implementation supports it,
18782     * this view will act as a nested scrolling child view when applicable, forwarding data
18783     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18784     * parent.</p>
18785     *
18786     * @return true if nested scrolling is enabled
18787     *
18788     * @see #setNestedScrollingEnabled(boolean)
18789     */
18790    public boolean isNestedScrollingEnabled() {
18791        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18792                PFLAG3_NESTED_SCROLLING_ENABLED;
18793    }
18794
18795    /**
18796     * Begin a nestable scroll operation along the given axes.
18797     *
18798     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18799     *
18800     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18801     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18802     * In the case of touch scrolling the nested scroll will be terminated automatically in
18803     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18804     * In the event of programmatic scrolling the caller must explicitly call
18805     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18806     *
18807     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18808     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18809     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18810     *
18811     * <p>At each incremental step of the scroll the caller should invoke
18812     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18813     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18814     * parent at least partially consumed the scroll and the caller should adjust the amount it
18815     * scrolls by.</p>
18816     *
18817     * <p>After applying the remainder of the scroll delta the caller should invoke
18818     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18819     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18820     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18821     * </p>
18822     *
18823     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18824     *             {@link #SCROLL_AXIS_VERTICAL}.
18825     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18826     *         the current gesture.
18827     *
18828     * @see #stopNestedScroll()
18829     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18830     * @see #dispatchNestedScroll(int, int, int, int, int[])
18831     */
18832    public boolean startNestedScroll(int axes) {
18833        if (hasNestedScrollingParent()) {
18834            // Already in progress
18835            return true;
18836        }
18837        if (isNestedScrollingEnabled()) {
18838            ViewParent p = getParent();
18839            View child = this;
18840            while (p != null) {
18841                try {
18842                    if (p.onStartNestedScroll(child, this, axes)) {
18843                        mNestedScrollingParent = p;
18844                        p.onNestedScrollAccepted(child, this, axes);
18845                        return true;
18846                    }
18847                } catch (AbstractMethodError e) {
18848                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18849                            "method onStartNestedScroll", e);
18850                    // Allow the search upward to continue
18851                }
18852                if (p instanceof View) {
18853                    child = (View) p;
18854                }
18855                p = p.getParent();
18856            }
18857        }
18858        return false;
18859    }
18860
18861    /**
18862     * Stop a nested scroll in progress.
18863     *
18864     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18865     *
18866     * @see #startNestedScroll(int)
18867     */
18868    public void stopNestedScroll() {
18869        if (mNestedScrollingParent != null) {
18870            mNestedScrollingParent.onStopNestedScroll(this);
18871            mNestedScrollingParent = null;
18872        }
18873    }
18874
18875    /**
18876     * Returns true if this view has a nested scrolling parent.
18877     *
18878     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18879     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18880     *
18881     * @return whether this view has a nested scrolling parent
18882     */
18883    public boolean hasNestedScrollingParent() {
18884        return mNestedScrollingParent != null;
18885    }
18886
18887    /**
18888     * Dispatch one step of a nested scroll in progress.
18889     *
18890     * <p>Implementations of views that support nested scrolling should call this to report
18891     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18892     * is not currently in progress or nested scrolling is not
18893     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18894     *
18895     * <p>Compatible View implementations should also call
18896     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18897     * consuming a component of the scroll event themselves.</p>
18898     *
18899     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18900     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18901     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18902     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18903     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18904     *                       in local view coordinates of this view from before this operation
18905     *                       to after it completes. View implementations may use this to adjust
18906     *                       expected input coordinate tracking.
18907     * @return true if the event was dispatched, false if it could not be dispatched.
18908     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18909     */
18910    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18911            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18912        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18913            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18914                int startX = 0;
18915                int startY = 0;
18916                if (offsetInWindow != null) {
18917                    getLocationInWindow(offsetInWindow);
18918                    startX = offsetInWindow[0];
18919                    startY = offsetInWindow[1];
18920                }
18921
18922                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18923                        dxUnconsumed, dyUnconsumed);
18924
18925                if (offsetInWindow != null) {
18926                    getLocationInWindow(offsetInWindow);
18927                    offsetInWindow[0] -= startX;
18928                    offsetInWindow[1] -= startY;
18929                }
18930                return true;
18931            } else if (offsetInWindow != null) {
18932                // No motion, no dispatch. Keep offsetInWindow up to date.
18933                offsetInWindow[0] = 0;
18934                offsetInWindow[1] = 0;
18935            }
18936        }
18937        return false;
18938    }
18939
18940    /**
18941     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18942     *
18943     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18944     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18945     * scrolling operation to consume some or all of the scroll operation before the child view
18946     * consumes it.</p>
18947     *
18948     * @param dx Horizontal scroll distance in pixels
18949     * @param dy Vertical scroll distance in pixels
18950     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18951     *                 and consumed[1] the consumed dy.
18952     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18953     *                       in local view coordinates of this view from before this operation
18954     *                       to after it completes. View implementations may use this to adjust
18955     *                       expected input coordinate tracking.
18956     * @return true if the parent consumed some or all of the scroll delta
18957     * @see #dispatchNestedScroll(int, int, int, int, int[])
18958     */
18959    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18960        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18961            if (dx != 0 || dy != 0) {
18962                int startX = 0;
18963                int startY = 0;
18964                if (offsetInWindow != null) {
18965                    getLocationInWindow(offsetInWindow);
18966                    startX = offsetInWindow[0];
18967                    startY = offsetInWindow[1];
18968                }
18969
18970                if (consumed == null) {
18971                    if (mTempNestedScrollConsumed == null) {
18972                        mTempNestedScrollConsumed = new int[2];
18973                    }
18974                    consumed = mTempNestedScrollConsumed;
18975                }
18976                consumed[0] = 0;
18977                consumed[1] = 0;
18978                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18979
18980                if (offsetInWindow != null) {
18981                    getLocationInWindow(offsetInWindow);
18982                    offsetInWindow[0] -= startX;
18983                    offsetInWindow[1] -= startY;
18984                }
18985                return consumed[0] != 0 || consumed[1] != 0;
18986            } else if (offsetInWindow != null) {
18987                offsetInWindow[0] = 0;
18988                offsetInWindow[1] = 0;
18989            }
18990        }
18991        return false;
18992    }
18993
18994    /**
18995     * Dispatch a fling to a nested scrolling parent.
18996     *
18997     * <p>This method should be used to indicate that a nested scrolling child has detected
18998     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18999     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
19000     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
19001     * along a scrollable axis.</p>
19002     *
19003     * <p>If a nested scrolling child view would normally fling but it is at the edge of
19004     * its own content, it can use this method to delegate the fling to its nested scrolling
19005     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
19006     *
19007     * @param velocityX Horizontal fling velocity in pixels per second
19008     * @param velocityY Vertical fling velocity in pixels per second
19009     * @param consumed true if the child consumed the fling, false otherwise
19010     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
19011     */
19012    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
19013        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19014            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
19015        }
19016        return false;
19017    }
19018
19019    /**
19020     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
19021     *
19022     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
19023     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
19024     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
19025     * before the child view consumes it. If this method returns <code>true</code>, a nested
19026     * parent view consumed the fling and this view should not scroll as a result.</p>
19027     *
19028     * <p>For a better user experience, only one view in a nested scrolling chain should consume
19029     * the fling at a time. If a parent view consumed the fling this method will return false.
19030     * Custom view implementations should account for this in two ways:</p>
19031     *
19032     * <ul>
19033     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
19034     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
19035     *     position regardless.</li>
19036     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
19037     *     even to settle back to a valid idle position.</li>
19038     * </ul>
19039     *
19040     * <p>Views should also not offer fling velocities to nested parent views along an axis
19041     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
19042     * should not offer a horizontal fling velocity to its parents since scrolling along that
19043     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
19044     *
19045     * @param velocityX Horizontal fling velocity in pixels per second
19046     * @param velocityY Vertical fling velocity in pixels per second
19047     * @return true if a nested scrolling parent consumed the fling
19048     */
19049    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19050        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19051            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19052        }
19053        return false;
19054    }
19055
19056    /**
19057     * Gets a scale factor that determines the distance the view should scroll
19058     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19059     * @return The vertical scroll scale factor.
19060     * @hide
19061     */
19062    protected float getVerticalScrollFactor() {
19063        if (mVerticalScrollFactor == 0) {
19064            TypedValue outValue = new TypedValue();
19065            if (!mContext.getTheme().resolveAttribute(
19066                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19067                throw new IllegalStateException(
19068                        "Expected theme to define listPreferredItemHeight.");
19069            }
19070            mVerticalScrollFactor = outValue.getDimension(
19071                    mContext.getResources().getDisplayMetrics());
19072        }
19073        return mVerticalScrollFactor;
19074    }
19075
19076    /**
19077     * Gets a scale factor that determines the distance the view should scroll
19078     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19079     * @return The horizontal scroll scale factor.
19080     * @hide
19081     */
19082    protected float getHorizontalScrollFactor() {
19083        // TODO: Should use something else.
19084        return getVerticalScrollFactor();
19085    }
19086
19087    /**
19088     * Return the value specifying the text direction or policy that was set with
19089     * {@link #setTextDirection(int)}.
19090     *
19091     * @return the defined text direction. It can be one of:
19092     *
19093     * {@link #TEXT_DIRECTION_INHERIT},
19094     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19095     * {@link #TEXT_DIRECTION_ANY_RTL},
19096     * {@link #TEXT_DIRECTION_LTR},
19097     * {@link #TEXT_DIRECTION_RTL},
19098     * {@link #TEXT_DIRECTION_LOCALE}
19099     *
19100     * @attr ref android.R.styleable#View_textDirection
19101     *
19102     * @hide
19103     */
19104    @ViewDebug.ExportedProperty(category = "text", mapping = {
19105            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19106            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19107            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19108            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19109            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19110            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19111    })
19112    public int getRawTextDirection() {
19113        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19114    }
19115
19116    /**
19117     * Set the text direction.
19118     *
19119     * @param textDirection the direction to set. Should be one of:
19120     *
19121     * {@link #TEXT_DIRECTION_INHERIT},
19122     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19123     * {@link #TEXT_DIRECTION_ANY_RTL},
19124     * {@link #TEXT_DIRECTION_LTR},
19125     * {@link #TEXT_DIRECTION_RTL},
19126     * {@link #TEXT_DIRECTION_LOCALE}
19127     *
19128     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19129     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19130     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19131     *
19132     * @attr ref android.R.styleable#View_textDirection
19133     */
19134    public void setTextDirection(int textDirection) {
19135        if (getRawTextDirection() != textDirection) {
19136            // Reset the current text direction and the resolved one
19137            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19138            resetResolvedTextDirection();
19139            // Set the new text direction
19140            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19141            // Do resolution
19142            resolveTextDirection();
19143            // Notify change
19144            onRtlPropertiesChanged(getLayoutDirection());
19145            // Refresh
19146            requestLayout();
19147            invalidate(true);
19148        }
19149    }
19150
19151    /**
19152     * Return the resolved text direction.
19153     *
19154     * @return the resolved text direction. Returns one of:
19155     *
19156     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19157     * {@link #TEXT_DIRECTION_ANY_RTL},
19158     * {@link #TEXT_DIRECTION_LTR},
19159     * {@link #TEXT_DIRECTION_RTL},
19160     * {@link #TEXT_DIRECTION_LOCALE}
19161     *
19162     * @attr ref android.R.styleable#View_textDirection
19163     */
19164    @ViewDebug.ExportedProperty(category = "text", mapping = {
19165            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19166            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19167            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19168            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19169            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19170            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19171    })
19172    public int getTextDirection() {
19173        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19174    }
19175
19176    /**
19177     * Resolve the text direction.
19178     *
19179     * @return true if resolution has been done, false otherwise.
19180     *
19181     * @hide
19182     */
19183    public boolean resolveTextDirection() {
19184        // Reset any previous text direction resolution
19185        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19186
19187        if (hasRtlSupport()) {
19188            // Set resolved text direction flag depending on text direction flag
19189            final int textDirection = getRawTextDirection();
19190            switch(textDirection) {
19191                case TEXT_DIRECTION_INHERIT:
19192                    if (!canResolveTextDirection()) {
19193                        // We cannot do the resolution if there is no parent, so use the default one
19194                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19195                        // Resolution will need to happen again later
19196                        return false;
19197                    }
19198
19199                    // Parent has not yet resolved, so we still return the default
19200                    try {
19201                        if (!mParent.isTextDirectionResolved()) {
19202                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19203                            // Resolution will need to happen again later
19204                            return false;
19205                        }
19206                    } catch (AbstractMethodError e) {
19207                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19208                                " does not fully implement ViewParent", e);
19209                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19210                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19211                        return true;
19212                    }
19213
19214                    // Set current resolved direction to the same value as the parent's one
19215                    int parentResolvedDirection;
19216                    try {
19217                        parentResolvedDirection = mParent.getTextDirection();
19218                    } catch (AbstractMethodError e) {
19219                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19220                                " does not fully implement ViewParent", e);
19221                        parentResolvedDirection = TEXT_DIRECTION_LTR;
19222                    }
19223                    switch (parentResolvedDirection) {
19224                        case TEXT_DIRECTION_FIRST_STRONG:
19225                        case TEXT_DIRECTION_ANY_RTL:
19226                        case TEXT_DIRECTION_LTR:
19227                        case TEXT_DIRECTION_RTL:
19228                        case TEXT_DIRECTION_LOCALE:
19229                            mPrivateFlags2 |=
19230                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19231                            break;
19232                        default:
19233                            // Default resolved direction is "first strong" heuristic
19234                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19235                    }
19236                    break;
19237                case TEXT_DIRECTION_FIRST_STRONG:
19238                case TEXT_DIRECTION_ANY_RTL:
19239                case TEXT_DIRECTION_LTR:
19240                case TEXT_DIRECTION_RTL:
19241                case TEXT_DIRECTION_LOCALE:
19242                    // Resolved direction is the same as text direction
19243                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19244                    break;
19245                default:
19246                    // Default resolved direction is "first strong" heuristic
19247                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19248            }
19249        } else {
19250            // Default resolved direction is "first strong" heuristic
19251            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19252        }
19253
19254        // Set to resolved
19255        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19256        return true;
19257    }
19258
19259    /**
19260     * Check if text direction resolution can be done.
19261     *
19262     * @return true if text direction resolution can be done otherwise return false.
19263     */
19264    public boolean canResolveTextDirection() {
19265        switch (getRawTextDirection()) {
19266            case TEXT_DIRECTION_INHERIT:
19267                if (mParent != null) {
19268                    try {
19269                        return mParent.canResolveTextDirection();
19270                    } catch (AbstractMethodError e) {
19271                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19272                                " does not fully implement ViewParent", e);
19273                    }
19274                }
19275                return false;
19276
19277            default:
19278                return true;
19279        }
19280    }
19281
19282    /**
19283     * Reset resolved text direction. Text direction will be resolved during a call to
19284     * {@link #onMeasure(int, int)}.
19285     *
19286     * @hide
19287     */
19288    public void resetResolvedTextDirection() {
19289        // Reset any previous text direction resolution
19290        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19291        // Set to default value
19292        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19293    }
19294
19295    /**
19296     * @return true if text direction is inherited.
19297     *
19298     * @hide
19299     */
19300    public boolean isTextDirectionInherited() {
19301        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19302    }
19303
19304    /**
19305     * @return true if text direction is resolved.
19306     */
19307    public boolean isTextDirectionResolved() {
19308        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19309    }
19310
19311    /**
19312     * Return the value specifying the text alignment or policy that was set with
19313     * {@link #setTextAlignment(int)}.
19314     *
19315     * @return the defined text alignment. It can be one of:
19316     *
19317     * {@link #TEXT_ALIGNMENT_INHERIT},
19318     * {@link #TEXT_ALIGNMENT_GRAVITY},
19319     * {@link #TEXT_ALIGNMENT_CENTER},
19320     * {@link #TEXT_ALIGNMENT_TEXT_START},
19321     * {@link #TEXT_ALIGNMENT_TEXT_END},
19322     * {@link #TEXT_ALIGNMENT_VIEW_START},
19323     * {@link #TEXT_ALIGNMENT_VIEW_END}
19324     *
19325     * @attr ref android.R.styleable#View_textAlignment
19326     *
19327     * @hide
19328     */
19329    @ViewDebug.ExportedProperty(category = "text", mapping = {
19330            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19331            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19332            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19333            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19334            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19335            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19336            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19337    })
19338    @TextAlignment
19339    public int getRawTextAlignment() {
19340        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19341    }
19342
19343    /**
19344     * Set the text alignment.
19345     *
19346     * @param textAlignment The text alignment to set. Should be one of
19347     *
19348     * {@link #TEXT_ALIGNMENT_INHERIT},
19349     * {@link #TEXT_ALIGNMENT_GRAVITY},
19350     * {@link #TEXT_ALIGNMENT_CENTER},
19351     * {@link #TEXT_ALIGNMENT_TEXT_START},
19352     * {@link #TEXT_ALIGNMENT_TEXT_END},
19353     * {@link #TEXT_ALIGNMENT_VIEW_START},
19354     * {@link #TEXT_ALIGNMENT_VIEW_END}
19355     *
19356     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19357     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19358     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19359     *
19360     * @attr ref android.R.styleable#View_textAlignment
19361     */
19362    public void setTextAlignment(@TextAlignment int textAlignment) {
19363        if (textAlignment != getRawTextAlignment()) {
19364            // Reset the current and resolved text alignment
19365            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19366            resetResolvedTextAlignment();
19367            // Set the new text alignment
19368            mPrivateFlags2 |=
19369                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
19370            // Do resolution
19371            resolveTextAlignment();
19372            // Notify change
19373            onRtlPropertiesChanged(getLayoutDirection());
19374            // Refresh
19375            requestLayout();
19376            invalidate(true);
19377        }
19378    }
19379
19380    /**
19381     * Return the resolved text alignment.
19382     *
19383     * @return the resolved text alignment. Returns one of:
19384     *
19385     * {@link #TEXT_ALIGNMENT_GRAVITY},
19386     * {@link #TEXT_ALIGNMENT_CENTER},
19387     * {@link #TEXT_ALIGNMENT_TEXT_START},
19388     * {@link #TEXT_ALIGNMENT_TEXT_END},
19389     * {@link #TEXT_ALIGNMENT_VIEW_START},
19390     * {@link #TEXT_ALIGNMENT_VIEW_END}
19391     *
19392     * @attr ref android.R.styleable#View_textAlignment
19393     */
19394    @ViewDebug.ExportedProperty(category = "text", mapping = {
19395            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19396            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19397            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19398            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19399            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19400            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19401            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19402    })
19403    @TextAlignment
19404    public int getTextAlignment() {
19405        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
19406                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
19407    }
19408
19409    /**
19410     * Resolve the text alignment.
19411     *
19412     * @return true if resolution has been done, false otherwise.
19413     *
19414     * @hide
19415     */
19416    public boolean resolveTextAlignment() {
19417        // Reset any previous text alignment resolution
19418        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19419
19420        if (hasRtlSupport()) {
19421            // Set resolved text alignment flag depending on text alignment flag
19422            final int textAlignment = getRawTextAlignment();
19423            switch (textAlignment) {
19424                case TEXT_ALIGNMENT_INHERIT:
19425                    // Check if we can resolve the text alignment
19426                    if (!canResolveTextAlignment()) {
19427                        // We cannot do the resolution if there is no parent so use the default
19428                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19429                        // Resolution will need to happen again later
19430                        return false;
19431                    }
19432
19433                    // Parent has not yet resolved, so we still return the default
19434                    try {
19435                        if (!mParent.isTextAlignmentResolved()) {
19436                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19437                            // Resolution will need to happen again later
19438                            return false;
19439                        }
19440                    } catch (AbstractMethodError e) {
19441                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19442                                " does not fully implement ViewParent", e);
19443                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
19444                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19445                        return true;
19446                    }
19447
19448                    int parentResolvedTextAlignment;
19449                    try {
19450                        parentResolvedTextAlignment = mParent.getTextAlignment();
19451                    } catch (AbstractMethodError e) {
19452                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19453                                " does not fully implement ViewParent", e);
19454                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
19455                    }
19456                    switch (parentResolvedTextAlignment) {
19457                        case TEXT_ALIGNMENT_GRAVITY:
19458                        case TEXT_ALIGNMENT_TEXT_START:
19459                        case TEXT_ALIGNMENT_TEXT_END:
19460                        case TEXT_ALIGNMENT_CENTER:
19461                        case TEXT_ALIGNMENT_VIEW_START:
19462                        case TEXT_ALIGNMENT_VIEW_END:
19463                            // Resolved text alignment is the same as the parent resolved
19464                            // text alignment
19465                            mPrivateFlags2 |=
19466                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19467                            break;
19468                        default:
19469                            // Use default resolved text alignment
19470                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19471                    }
19472                    break;
19473                case TEXT_ALIGNMENT_GRAVITY:
19474                case TEXT_ALIGNMENT_TEXT_START:
19475                case TEXT_ALIGNMENT_TEXT_END:
19476                case TEXT_ALIGNMENT_CENTER:
19477                case TEXT_ALIGNMENT_VIEW_START:
19478                case TEXT_ALIGNMENT_VIEW_END:
19479                    // Resolved text alignment is the same as text alignment
19480                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19481                    break;
19482                default:
19483                    // Use default resolved text alignment
19484                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19485            }
19486        } else {
19487            // Use default resolved text alignment
19488            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19489        }
19490
19491        // Set the resolved
19492        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19493        return true;
19494    }
19495
19496    /**
19497     * Check if text alignment resolution can be done.
19498     *
19499     * @return true if text alignment resolution can be done otherwise return false.
19500     */
19501    public boolean canResolveTextAlignment() {
19502        switch (getRawTextAlignment()) {
19503            case TEXT_DIRECTION_INHERIT:
19504                if (mParent != null) {
19505                    try {
19506                        return mParent.canResolveTextAlignment();
19507                    } catch (AbstractMethodError e) {
19508                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19509                                " does not fully implement ViewParent", e);
19510                    }
19511                }
19512                return false;
19513
19514            default:
19515                return true;
19516        }
19517    }
19518
19519    /**
19520     * Reset resolved text alignment. Text alignment will be resolved during a call to
19521     * {@link #onMeasure(int, int)}.
19522     *
19523     * @hide
19524     */
19525    public void resetResolvedTextAlignment() {
19526        // Reset any previous text alignment resolution
19527        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19528        // Set to default
19529        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19530    }
19531
19532    /**
19533     * @return true if text alignment is inherited.
19534     *
19535     * @hide
19536     */
19537    public boolean isTextAlignmentInherited() {
19538        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
19539    }
19540
19541    /**
19542     * @return true if text alignment is resolved.
19543     */
19544    public boolean isTextAlignmentResolved() {
19545        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19546    }
19547
19548    /**
19549     * Generate a value suitable for use in {@link #setId(int)}.
19550     * This value will not collide with ID values generated at build time by aapt for R.id.
19551     *
19552     * @return a generated ID value
19553     */
19554    public static int generateViewId() {
19555        for (;;) {
19556            final int result = sNextGeneratedId.get();
19557            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
19558            int newValue = result + 1;
19559            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
19560            if (sNextGeneratedId.compareAndSet(result, newValue)) {
19561                return result;
19562            }
19563        }
19564    }
19565
19566    /**
19567     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
19568     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
19569     *                           a normal View or a ViewGroup with
19570     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
19571     * @hide
19572     */
19573    public void captureTransitioningViews(List<View> transitioningViews) {
19574        if (getVisibility() == View.VISIBLE) {
19575            transitioningViews.add(this);
19576        }
19577    }
19578
19579    /**
19580     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19581     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19582     * @hide
19583     */
19584    public void findNamedViews(Map<String, View> namedElements) {
19585        if (getVisibility() == VISIBLE || mGhostView != null) {
19586            String transitionName = getTransitionName();
19587            if (transitionName != null) {
19588                namedElements.put(transitionName, this);
19589            }
19590        }
19591    }
19592
19593    //
19594    // Properties
19595    //
19596    /**
19597     * A Property wrapper around the <code>alpha</code> functionality handled by the
19598     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19599     */
19600    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19601        @Override
19602        public void setValue(View object, float value) {
19603            object.setAlpha(value);
19604        }
19605
19606        @Override
19607        public Float get(View object) {
19608            return object.getAlpha();
19609        }
19610    };
19611
19612    /**
19613     * A Property wrapper around the <code>translationX</code> functionality handled by the
19614     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19615     */
19616    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19617        @Override
19618        public void setValue(View object, float value) {
19619            object.setTranslationX(value);
19620        }
19621
19622                @Override
19623        public Float get(View object) {
19624            return object.getTranslationX();
19625        }
19626    };
19627
19628    /**
19629     * A Property wrapper around the <code>translationY</code> functionality handled by the
19630     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19631     */
19632    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19633        @Override
19634        public void setValue(View object, float value) {
19635            object.setTranslationY(value);
19636        }
19637
19638        @Override
19639        public Float get(View object) {
19640            return object.getTranslationY();
19641        }
19642    };
19643
19644    /**
19645     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19646     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19647     */
19648    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19649        @Override
19650        public void setValue(View object, float value) {
19651            object.setTranslationZ(value);
19652        }
19653
19654        @Override
19655        public Float get(View object) {
19656            return object.getTranslationZ();
19657        }
19658    };
19659
19660    /**
19661     * A Property wrapper around the <code>x</code> functionality handled by the
19662     * {@link View#setX(float)} and {@link View#getX()} methods.
19663     */
19664    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19665        @Override
19666        public void setValue(View object, float value) {
19667            object.setX(value);
19668        }
19669
19670        @Override
19671        public Float get(View object) {
19672            return object.getX();
19673        }
19674    };
19675
19676    /**
19677     * A Property wrapper around the <code>y</code> functionality handled by the
19678     * {@link View#setY(float)} and {@link View#getY()} methods.
19679     */
19680    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19681        @Override
19682        public void setValue(View object, float value) {
19683            object.setY(value);
19684        }
19685
19686        @Override
19687        public Float get(View object) {
19688            return object.getY();
19689        }
19690    };
19691
19692    /**
19693     * A Property wrapper around the <code>z</code> functionality handled by the
19694     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19695     */
19696    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19697        @Override
19698        public void setValue(View object, float value) {
19699            object.setZ(value);
19700        }
19701
19702        @Override
19703        public Float get(View object) {
19704            return object.getZ();
19705        }
19706    };
19707
19708    /**
19709     * A Property wrapper around the <code>rotation</code> functionality handled by the
19710     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19711     */
19712    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19713        @Override
19714        public void setValue(View object, float value) {
19715            object.setRotation(value);
19716        }
19717
19718        @Override
19719        public Float get(View object) {
19720            return object.getRotation();
19721        }
19722    };
19723
19724    /**
19725     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19726     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19727     */
19728    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19729        @Override
19730        public void setValue(View object, float value) {
19731            object.setRotationX(value);
19732        }
19733
19734        @Override
19735        public Float get(View object) {
19736            return object.getRotationX();
19737        }
19738    };
19739
19740    /**
19741     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19742     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19743     */
19744    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19745        @Override
19746        public void setValue(View object, float value) {
19747            object.setRotationY(value);
19748        }
19749
19750        @Override
19751        public Float get(View object) {
19752            return object.getRotationY();
19753        }
19754    };
19755
19756    /**
19757     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19758     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19759     */
19760    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19761        @Override
19762        public void setValue(View object, float value) {
19763            object.setScaleX(value);
19764        }
19765
19766        @Override
19767        public Float get(View object) {
19768            return object.getScaleX();
19769        }
19770    };
19771
19772    /**
19773     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19774     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19775     */
19776    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19777        @Override
19778        public void setValue(View object, float value) {
19779            object.setScaleY(value);
19780        }
19781
19782        @Override
19783        public Float get(View object) {
19784            return object.getScaleY();
19785        }
19786    };
19787
19788    /**
19789     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19790     * Each MeasureSpec represents a requirement for either the width or the height.
19791     * A MeasureSpec is comprised of a size and a mode. There are three possible
19792     * modes:
19793     * <dl>
19794     * <dt>UNSPECIFIED</dt>
19795     * <dd>
19796     * The parent has not imposed any constraint on the child. It can be whatever size
19797     * it wants.
19798     * </dd>
19799     *
19800     * <dt>EXACTLY</dt>
19801     * <dd>
19802     * The parent has determined an exact size for the child. The child is going to be
19803     * given those bounds regardless of how big it wants to be.
19804     * </dd>
19805     *
19806     * <dt>AT_MOST</dt>
19807     * <dd>
19808     * The child can be as large as it wants up to the specified size.
19809     * </dd>
19810     * </dl>
19811     *
19812     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19813     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19814     */
19815    public static class MeasureSpec {
19816        private static final int MODE_SHIFT = 30;
19817        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19818
19819        /**
19820         * Measure specification mode: The parent has not imposed any constraint
19821         * on the child. It can be whatever size it wants.
19822         */
19823        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19824
19825        /**
19826         * Measure specification mode: The parent has determined an exact size
19827         * for the child. The child is going to be given those bounds regardless
19828         * of how big it wants to be.
19829         */
19830        public static final int EXACTLY     = 1 << MODE_SHIFT;
19831
19832        /**
19833         * Measure specification mode: The child can be as large as it wants up
19834         * to the specified size.
19835         */
19836        public static final int AT_MOST     = 2 << MODE_SHIFT;
19837
19838        /**
19839         * Creates a measure specification based on the supplied size and mode.
19840         *
19841         * The mode must always be one of the following:
19842         * <ul>
19843         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19844         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19845         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19846         * </ul>
19847         *
19848         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19849         * implementation was such that the order of arguments did not matter
19850         * and overflow in either value could impact the resulting MeasureSpec.
19851         * {@link android.widget.RelativeLayout} was affected by this bug.
19852         * Apps targeting API levels greater than 17 will get the fixed, more strict
19853         * behavior.</p>
19854         *
19855         * @param size the size of the measure specification
19856         * @param mode the mode of the measure specification
19857         * @return the measure specification based on size and mode
19858         */
19859        public static int makeMeasureSpec(int size, int mode) {
19860            if (sUseBrokenMakeMeasureSpec) {
19861                return size + mode;
19862            } else {
19863                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19864            }
19865        }
19866
19867        /**
19868         * Extracts the mode from the supplied measure specification.
19869         *
19870         * @param measureSpec the measure specification to extract the mode from
19871         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19872         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19873         *         {@link android.view.View.MeasureSpec#EXACTLY}
19874         */
19875        public static int getMode(int measureSpec) {
19876            return (measureSpec & MODE_MASK);
19877        }
19878
19879        /**
19880         * Extracts the size from the supplied measure specification.
19881         *
19882         * @param measureSpec the measure specification to extract the size from
19883         * @return the size in pixels defined in the supplied measure specification
19884         */
19885        public static int getSize(int measureSpec) {
19886            return (measureSpec & ~MODE_MASK);
19887        }
19888
19889        static int adjust(int measureSpec, int delta) {
19890            final int mode = getMode(measureSpec);
19891            if (mode == UNSPECIFIED) {
19892                // No need to adjust size for UNSPECIFIED mode.
19893                return makeMeasureSpec(0, UNSPECIFIED);
19894            }
19895            int size = getSize(measureSpec) + delta;
19896            if (size < 0) {
19897                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19898                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19899                size = 0;
19900            }
19901            return makeMeasureSpec(size, mode);
19902        }
19903
19904        /**
19905         * Returns a String representation of the specified measure
19906         * specification.
19907         *
19908         * @param measureSpec the measure specification to convert to a String
19909         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19910         */
19911        public static String toString(int measureSpec) {
19912            int mode = getMode(measureSpec);
19913            int size = getSize(measureSpec);
19914
19915            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19916
19917            if (mode == UNSPECIFIED)
19918                sb.append("UNSPECIFIED ");
19919            else if (mode == EXACTLY)
19920                sb.append("EXACTLY ");
19921            else if (mode == AT_MOST)
19922                sb.append("AT_MOST ");
19923            else
19924                sb.append(mode).append(" ");
19925
19926            sb.append(size);
19927            return sb.toString();
19928        }
19929    }
19930
19931    private final class CheckForLongPress implements Runnable {
19932        private int mOriginalWindowAttachCount;
19933
19934        @Override
19935        public void run() {
19936            if (isPressed() && (mParent != null)
19937                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19938                if (performLongClick()) {
19939                    mHasPerformedLongPress = true;
19940                }
19941            }
19942        }
19943
19944        public void rememberWindowAttachCount() {
19945            mOriginalWindowAttachCount = mWindowAttachCount;
19946        }
19947    }
19948
19949    private final class CheckForTap implements Runnable {
19950        public float x;
19951        public float y;
19952
19953        @Override
19954        public void run() {
19955            mPrivateFlags &= ~PFLAG_PREPRESSED;
19956            setPressed(true, x, y);
19957            checkForLongClick(ViewConfiguration.getTapTimeout());
19958        }
19959    }
19960
19961    private final class PerformClick implements Runnable {
19962        @Override
19963        public void run() {
19964            performClick();
19965        }
19966    }
19967
19968    /** @hide */
19969    public void hackTurnOffWindowResizeAnim(boolean off) {
19970        mAttachInfo.mTurnOffWindowResizeAnim = off;
19971    }
19972
19973    /**
19974     * This method returns a ViewPropertyAnimator object, which can be used to animate
19975     * specific properties on this View.
19976     *
19977     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19978     */
19979    public ViewPropertyAnimator animate() {
19980        if (mAnimator == null) {
19981            mAnimator = new ViewPropertyAnimator(this);
19982        }
19983        return mAnimator;
19984    }
19985
19986    /**
19987     * Sets the name of the View to be used to identify Views in Transitions.
19988     * Names should be unique in the View hierarchy.
19989     *
19990     * @param transitionName The name of the View to uniquely identify it for Transitions.
19991     */
19992    public final void setTransitionName(String transitionName) {
19993        mTransitionName = transitionName;
19994    }
19995
19996    /**
19997     * Returns the name of the View to be used to identify Views in Transitions.
19998     * Names should be unique in the View hierarchy.
19999     *
20000     * <p>This returns null if the View has not been given a name.</p>
20001     *
20002     * @return The name used of the View to be used to identify Views in Transitions or null
20003     * if no name has been given.
20004     */
20005    @ViewDebug.ExportedProperty
20006    public String getTransitionName() {
20007        return mTransitionName;
20008    }
20009
20010    /**
20011     * Interface definition for a callback to be invoked when a hardware key event is
20012     * dispatched to this view. The callback will be invoked before the key event is
20013     * given to the view. This is only useful for hardware keyboards; a software input
20014     * method has no obligation to trigger this listener.
20015     */
20016    public interface OnKeyListener {
20017        /**
20018         * Called when a hardware key is dispatched to a view. This allows listeners to
20019         * get a chance to respond before the target view.
20020         * <p>Key presses in software keyboards will generally NOT trigger this method,
20021         * although some may elect to do so in some situations. Do not assume a
20022         * software input method has to be key-based; even if it is, it may use key presses
20023         * in a different way than you expect, so there is no way to reliably catch soft
20024         * input key presses.
20025         *
20026         * @param v The view the key has been dispatched to.
20027         * @param keyCode The code for the physical key that was pressed
20028         * @param event The KeyEvent object containing full information about
20029         *        the event.
20030         * @return True if the listener has consumed the event, false otherwise.
20031         */
20032        boolean onKey(View v, int keyCode, KeyEvent event);
20033    }
20034
20035    /**
20036     * Interface definition for a callback to be invoked when a touch event is
20037     * dispatched to this view. The callback will be invoked before the touch
20038     * event is given to the view.
20039     */
20040    public interface OnTouchListener {
20041        /**
20042         * Called when a touch event is dispatched to a view. This allows listeners to
20043         * get a chance to respond before the target view.
20044         *
20045         * @param v The view the touch event has been dispatched to.
20046         * @param event The MotionEvent object containing full information about
20047         *        the event.
20048         * @return True if the listener has consumed the event, false otherwise.
20049         */
20050        boolean onTouch(View v, MotionEvent event);
20051    }
20052
20053    /**
20054     * Interface definition for a callback to be invoked when a hover event is
20055     * dispatched to this view. The callback will be invoked before the hover
20056     * event is given to the view.
20057     */
20058    public interface OnHoverListener {
20059        /**
20060         * Called when a hover event is dispatched to a view. This allows listeners to
20061         * get a chance to respond before the target view.
20062         *
20063         * @param v The view the hover event has been dispatched to.
20064         * @param event The MotionEvent object containing full information about
20065         *        the event.
20066         * @return True if the listener has consumed the event, false otherwise.
20067         */
20068        boolean onHover(View v, MotionEvent event);
20069    }
20070
20071    /**
20072     * Interface definition for a callback to be invoked when a generic motion event is
20073     * dispatched to this view. The callback will be invoked before the generic motion
20074     * event is given to the view.
20075     */
20076    public interface OnGenericMotionListener {
20077        /**
20078         * Called when a generic motion event is dispatched to a view. This allows listeners to
20079         * get a chance to respond before the target view.
20080         *
20081         * @param v The view the generic motion event has been dispatched to.
20082         * @param event The MotionEvent object containing full information about
20083         *        the event.
20084         * @return True if the listener has consumed the event, false otherwise.
20085         */
20086        boolean onGenericMotion(View v, MotionEvent event);
20087    }
20088
20089    /**
20090     * Interface definition for a callback to be invoked when a view has been clicked and held.
20091     */
20092    public interface OnLongClickListener {
20093        /**
20094         * Called when a view has been clicked and held.
20095         *
20096         * @param v The view that was clicked and held.
20097         *
20098         * @return true if the callback consumed the long click, false otherwise.
20099         */
20100        boolean onLongClick(View v);
20101    }
20102
20103    /**
20104     * Interface definition for a callback to be invoked when a drag is being dispatched
20105     * to this view.  The callback will be invoked before the hosting view's own
20106     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20107     * onDrag(event) behavior, it should return 'false' from this callback.
20108     *
20109     * <div class="special reference">
20110     * <h3>Developer Guides</h3>
20111     * <p>For a guide to implementing drag and drop features, read the
20112     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20113     * </div>
20114     */
20115    public interface OnDragListener {
20116        /**
20117         * Called when a drag event is dispatched to a view. This allows listeners
20118         * to get a chance to override base View behavior.
20119         *
20120         * @param v The View that received the drag event.
20121         * @param event The {@link android.view.DragEvent} object for the drag event.
20122         * @return {@code true} if the drag event was handled successfully, or {@code false}
20123         * if the drag event was not handled. Note that {@code false} will trigger the View
20124         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20125         */
20126        boolean onDrag(View v, DragEvent event);
20127    }
20128
20129    /**
20130     * Interface definition for a callback to be invoked when the focus state of
20131     * a view changed.
20132     */
20133    public interface OnFocusChangeListener {
20134        /**
20135         * Called when the focus state of a view has changed.
20136         *
20137         * @param v The view whose state has changed.
20138         * @param hasFocus The new focus state of v.
20139         */
20140        void onFocusChange(View v, boolean hasFocus);
20141    }
20142
20143    /**
20144     * Interface definition for a callback to be invoked when a view is clicked.
20145     */
20146    public interface OnClickListener {
20147        /**
20148         * Called when a view has been clicked.
20149         *
20150         * @param v The view that was clicked.
20151         */
20152        void onClick(View v);
20153    }
20154
20155    /**
20156     * Interface definition for a callback to be invoked when the context menu
20157     * for this view is being built.
20158     */
20159    public interface OnCreateContextMenuListener {
20160        /**
20161         * Called when the context menu for this view is being built. It is not
20162         * safe to hold onto the menu after this method returns.
20163         *
20164         * @param menu The context menu that is being built
20165         * @param v The view for which the context menu is being built
20166         * @param menuInfo Extra information about the item for which the
20167         *            context menu should be shown. This information will vary
20168         *            depending on the class of v.
20169         */
20170        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20171    }
20172
20173    /**
20174     * Interface definition for a callback to be invoked when the status bar changes
20175     * visibility.  This reports <strong>global</strong> changes to the system UI
20176     * state, not what the application is requesting.
20177     *
20178     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20179     */
20180    public interface OnSystemUiVisibilityChangeListener {
20181        /**
20182         * Called when the status bar changes visibility because of a call to
20183         * {@link View#setSystemUiVisibility(int)}.
20184         *
20185         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20186         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20187         * This tells you the <strong>global</strong> state of these UI visibility
20188         * flags, not what your app is currently applying.
20189         */
20190        public void onSystemUiVisibilityChange(int visibility);
20191    }
20192
20193    /**
20194     * Interface definition for a callback to be invoked when this view is attached
20195     * or detached from its window.
20196     */
20197    public interface OnAttachStateChangeListener {
20198        /**
20199         * Called when the view is attached to a window.
20200         * @param v The view that was attached
20201         */
20202        public void onViewAttachedToWindow(View v);
20203        /**
20204         * Called when the view is detached from a window.
20205         * @param v The view that was detached
20206         */
20207        public void onViewDetachedFromWindow(View v);
20208    }
20209
20210    /**
20211     * Listener for applying window insets on a view in a custom way.
20212     *
20213     * <p>Apps may choose to implement this interface if they want to apply custom policy
20214     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
20215     * is set, its
20216     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
20217     * method will be called instead of the View's own
20218     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
20219     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
20220     * the View's normal behavior as part of its own.</p>
20221     */
20222    public interface OnApplyWindowInsetsListener {
20223        /**
20224         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
20225         * on a View, this listener method will be called instead of the view's own
20226         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
20227         *
20228         * @param v The view applying window insets
20229         * @param insets The insets to apply
20230         * @return The insets supplied, minus any insets that were consumed
20231         */
20232        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
20233    }
20234
20235    private final class UnsetPressedState implements Runnable {
20236        @Override
20237        public void run() {
20238            setPressed(false);
20239        }
20240    }
20241
20242    /**
20243     * Base class for derived classes that want to save and restore their own
20244     * state in {@link android.view.View#onSaveInstanceState()}.
20245     */
20246    public static class BaseSavedState extends AbsSavedState {
20247        /**
20248         * Constructor used when reading from a parcel. Reads the state of the superclass.
20249         *
20250         * @param source
20251         */
20252        public BaseSavedState(Parcel source) {
20253            super(source);
20254        }
20255
20256        /**
20257         * Constructor called by derived classes when creating their SavedState objects
20258         *
20259         * @param superState The state of the superclass of this view
20260         */
20261        public BaseSavedState(Parcelable superState) {
20262            super(superState);
20263        }
20264
20265        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20266                new Parcelable.Creator<BaseSavedState>() {
20267            public BaseSavedState createFromParcel(Parcel in) {
20268                return new BaseSavedState(in);
20269            }
20270
20271            public BaseSavedState[] newArray(int size) {
20272                return new BaseSavedState[size];
20273            }
20274        };
20275    }
20276
20277    /**
20278     * A set of information given to a view when it is attached to its parent
20279     * window.
20280     */
20281    final static class AttachInfo {
20282        interface Callbacks {
20283            void playSoundEffect(int effectId);
20284            boolean performHapticFeedback(int effectId, boolean always);
20285        }
20286
20287        /**
20288         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20289         * to a Handler. This class contains the target (View) to invalidate and
20290         * the coordinates of the dirty rectangle.
20291         *
20292         * For performance purposes, this class also implements a pool of up to
20293         * POOL_LIMIT objects that get reused. This reduces memory allocations
20294         * whenever possible.
20295         */
20296        static class InvalidateInfo {
20297            private static final int POOL_LIMIT = 10;
20298
20299            private static final SynchronizedPool<InvalidateInfo> sPool =
20300                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20301
20302            View target;
20303
20304            int left;
20305            int top;
20306            int right;
20307            int bottom;
20308
20309            public static InvalidateInfo obtain() {
20310                InvalidateInfo instance = sPool.acquire();
20311                return (instance != null) ? instance : new InvalidateInfo();
20312            }
20313
20314            public void recycle() {
20315                target = null;
20316                sPool.release(this);
20317            }
20318        }
20319
20320        final IWindowSession mSession;
20321
20322        final IWindow mWindow;
20323
20324        final IBinder mWindowToken;
20325
20326        final Display mDisplay;
20327
20328        final Callbacks mRootCallbacks;
20329
20330        IWindowId mIWindowId;
20331        WindowId mWindowId;
20332
20333        /**
20334         * The top view of the hierarchy.
20335         */
20336        View mRootView;
20337
20338        IBinder mPanelParentWindowToken;
20339
20340        boolean mHardwareAccelerated;
20341        boolean mHardwareAccelerationRequested;
20342        HardwareRenderer mHardwareRenderer;
20343        List<RenderNode> mPendingAnimatingRenderNodes;
20344
20345        /**
20346         * The state of the display to which the window is attached, as reported
20347         * by {@link Display#getState()}.  Note that the display state constants
20348         * declared by {@link Display} do not exactly line up with the screen state
20349         * constants declared by {@link View} (there are more display states than
20350         * screen states).
20351         */
20352        int mDisplayState = Display.STATE_UNKNOWN;
20353
20354        /**
20355         * Scale factor used by the compatibility mode
20356         */
20357        float mApplicationScale;
20358
20359        /**
20360         * Indicates whether the application is in compatibility mode
20361         */
20362        boolean mScalingRequired;
20363
20364        /**
20365         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
20366         */
20367        boolean mTurnOffWindowResizeAnim;
20368
20369        /**
20370         * Left position of this view's window
20371         */
20372        int mWindowLeft;
20373
20374        /**
20375         * Top position of this view's window
20376         */
20377        int mWindowTop;
20378
20379        /**
20380         * Indicates whether views need to use 32-bit drawing caches
20381         */
20382        boolean mUse32BitDrawingCache;
20383
20384        /**
20385         * For windows that are full-screen but using insets to layout inside
20386         * of the screen areas, these are the current insets to appear inside
20387         * the overscan area of the display.
20388         */
20389        final Rect mOverscanInsets = new Rect();
20390
20391        /**
20392         * For windows that are full-screen but using insets to layout inside
20393         * of the screen decorations, these are the current insets for the
20394         * content of the window.
20395         */
20396        final Rect mContentInsets = new Rect();
20397
20398        /**
20399         * For windows that are full-screen but using insets to layout inside
20400         * of the screen decorations, these are the current insets for the
20401         * actual visible parts of the window.
20402         */
20403        final Rect mVisibleInsets = new Rect();
20404
20405        /**
20406         * For windows that are full-screen but using insets to layout inside
20407         * of the screen decorations, these are the current insets for the
20408         * stable system windows.
20409         */
20410        final Rect mStableInsets = new Rect();
20411
20412        /**
20413         * The internal insets given by this window.  This value is
20414         * supplied by the client (through
20415         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
20416         * be given to the window manager when changed to be used in laying
20417         * out windows behind it.
20418         */
20419        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
20420                = new ViewTreeObserver.InternalInsetsInfo();
20421
20422        /**
20423         * Set to true when mGivenInternalInsets is non-empty.
20424         */
20425        boolean mHasNonEmptyGivenInternalInsets;
20426
20427        /**
20428         * All views in the window's hierarchy that serve as scroll containers,
20429         * used to determine if the window can be resized or must be panned
20430         * to adjust for a soft input area.
20431         */
20432        final ArrayList<View> mScrollContainers = new ArrayList<View>();
20433
20434        final KeyEvent.DispatcherState mKeyDispatchState
20435                = new KeyEvent.DispatcherState();
20436
20437        /**
20438         * Indicates whether the view's window currently has the focus.
20439         */
20440        boolean mHasWindowFocus;
20441
20442        /**
20443         * The current visibility of the window.
20444         */
20445        int mWindowVisibility;
20446
20447        /**
20448         * Indicates the time at which drawing started to occur.
20449         */
20450        long mDrawingTime;
20451
20452        /**
20453         * Indicates whether or not ignoring the DIRTY_MASK flags.
20454         */
20455        boolean mIgnoreDirtyState;
20456
20457        /**
20458         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
20459         * to avoid clearing that flag prematurely.
20460         */
20461        boolean mSetIgnoreDirtyState = false;
20462
20463        /**
20464         * Indicates whether the view's window is currently in touch mode.
20465         */
20466        boolean mInTouchMode;
20467
20468        /**
20469         * Indicates whether the view has requested unbuffered input dispatching for the current
20470         * event stream.
20471         */
20472        boolean mUnbufferedDispatchRequested;
20473
20474        /**
20475         * Indicates that ViewAncestor should trigger a global layout change
20476         * the next time it performs a traversal
20477         */
20478        boolean mRecomputeGlobalAttributes;
20479
20480        /**
20481         * Always report new attributes at next traversal.
20482         */
20483        boolean mForceReportNewAttributes;
20484
20485        /**
20486         * Set during a traveral if any views want to keep the screen on.
20487         */
20488        boolean mKeepScreenOn;
20489
20490        /**
20491         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
20492         */
20493        int mSystemUiVisibility;
20494
20495        /**
20496         * Hack to force certain system UI visibility flags to be cleared.
20497         */
20498        int mDisabledSystemUiVisibility;
20499
20500        /**
20501         * Last global system UI visibility reported by the window manager.
20502         */
20503        int mGlobalSystemUiVisibility;
20504
20505        /**
20506         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
20507         * attached.
20508         */
20509        boolean mHasSystemUiListeners;
20510
20511        /**
20512         * Set if the window has requested to extend into the overscan region
20513         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
20514         */
20515        boolean mOverscanRequested;
20516
20517        /**
20518         * Set if the visibility of any views has changed.
20519         */
20520        boolean mViewVisibilityChanged;
20521
20522        /**
20523         * Set to true if a view has been scrolled.
20524         */
20525        boolean mViewScrollChanged;
20526
20527        /**
20528         * Set to true if high contrast mode enabled
20529         */
20530        boolean mHighContrastText;
20531
20532        /**
20533         * Global to the view hierarchy used as a temporary for dealing with
20534         * x/y points in the transparent region computations.
20535         */
20536        final int[] mTransparentLocation = new int[2];
20537
20538        /**
20539         * Global to the view hierarchy used as a temporary for dealing with
20540         * x/y points in the ViewGroup.invalidateChild implementation.
20541         */
20542        final int[] mInvalidateChildLocation = new int[2];
20543
20544        /**
20545         * Global to the view hierarchy used as a temporary for dealng with
20546         * computing absolute on-screen location.
20547         */
20548        final int[] mTmpLocation = new int[2];
20549
20550        /**
20551         * Global to the view hierarchy used as a temporary for dealing with
20552         * x/y location when view is transformed.
20553         */
20554        final float[] mTmpTransformLocation = new float[2];
20555
20556        /**
20557         * The view tree observer used to dispatch global events like
20558         * layout, pre-draw, touch mode change, etc.
20559         */
20560        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
20561
20562        /**
20563         * A Canvas used by the view hierarchy to perform bitmap caching.
20564         */
20565        Canvas mCanvas;
20566
20567        /**
20568         * The view root impl.
20569         */
20570        final ViewRootImpl mViewRootImpl;
20571
20572        /**
20573         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
20574         * handler can be used to pump events in the UI events queue.
20575         */
20576        final Handler mHandler;
20577
20578        /**
20579         * Temporary for use in computing invalidate rectangles while
20580         * calling up the hierarchy.
20581         */
20582        final Rect mTmpInvalRect = new Rect();
20583
20584        /**
20585         * Temporary for use in computing hit areas with transformed views
20586         */
20587        final RectF mTmpTransformRect = new RectF();
20588
20589        /**
20590         * Temporary for use in computing hit areas with transformed views
20591         */
20592        final RectF mTmpTransformRect1 = new RectF();
20593
20594        /**
20595         * Temporary list of rectanges.
20596         */
20597        final List<RectF> mTmpRectList = new ArrayList<>();
20598
20599        /**
20600         * Temporary for use in transforming invalidation rect
20601         */
20602        final Matrix mTmpMatrix = new Matrix();
20603
20604        /**
20605         * Temporary for use in transforming invalidation rect
20606         */
20607        final Transformation mTmpTransformation = new Transformation();
20608
20609        /**
20610         * Temporary for use in querying outlines from OutlineProviders
20611         */
20612        final Outline mTmpOutline = new Outline();
20613
20614        /**
20615         * Temporary list for use in collecting focusable descendents of a view.
20616         */
20617        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20618
20619        /**
20620         * The id of the window for accessibility purposes.
20621         */
20622        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20623
20624        /**
20625         * Flags related to accessibility processing.
20626         *
20627         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20628         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20629         */
20630        int mAccessibilityFetchFlags;
20631
20632        /**
20633         * The drawable for highlighting accessibility focus.
20634         */
20635        Drawable mAccessibilityFocusDrawable;
20636
20637        /**
20638         * Show where the margins, bounds and layout bounds are for each view.
20639         */
20640        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20641
20642        /**
20643         * Point used to compute visible regions.
20644         */
20645        final Point mPoint = new Point();
20646
20647        /**
20648         * Used to track which View originated a requestLayout() call, used when
20649         * requestLayout() is called during layout.
20650         */
20651        View mViewRequestingLayout;
20652
20653        /**
20654         * Creates a new set of attachment information with the specified
20655         * events handler and thread.
20656         *
20657         * @param handler the events handler the view must use
20658         */
20659        AttachInfo(IWindowSession session, IWindow window, Display display,
20660                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20661            mSession = session;
20662            mWindow = window;
20663            mWindowToken = window.asBinder();
20664            mDisplay = display;
20665            mViewRootImpl = viewRootImpl;
20666            mHandler = handler;
20667            mRootCallbacks = effectPlayer;
20668        }
20669    }
20670
20671    /**
20672     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20673     * is supported. This avoids keeping too many unused fields in most
20674     * instances of View.</p>
20675     */
20676    private static class ScrollabilityCache implements Runnable {
20677
20678        /**
20679         * Scrollbars are not visible
20680         */
20681        public static final int OFF = 0;
20682
20683        /**
20684         * Scrollbars are visible
20685         */
20686        public static final int ON = 1;
20687
20688        /**
20689         * Scrollbars are fading away
20690         */
20691        public static final int FADING = 2;
20692
20693        public boolean fadeScrollBars;
20694
20695        public int fadingEdgeLength;
20696        public int scrollBarDefaultDelayBeforeFade;
20697        public int scrollBarFadeDuration;
20698
20699        public int scrollBarSize;
20700        public ScrollBarDrawable scrollBar;
20701        public float[] interpolatorValues;
20702        public View host;
20703
20704        public final Paint paint;
20705        public final Matrix matrix;
20706        public Shader shader;
20707
20708        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20709
20710        private static final float[] OPAQUE = { 255 };
20711        private static final float[] TRANSPARENT = { 0.0f };
20712
20713        /**
20714         * When fading should start. This time moves into the future every time
20715         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20716         */
20717        public long fadeStartTime;
20718
20719
20720        /**
20721         * The current state of the scrollbars: ON, OFF, or FADING
20722         */
20723        public int state = OFF;
20724
20725        private int mLastColor;
20726
20727        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20728            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20729            scrollBarSize = configuration.getScaledScrollBarSize();
20730            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20731            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20732
20733            paint = new Paint();
20734            matrix = new Matrix();
20735            // use use a height of 1, and then wack the matrix each time we
20736            // actually use it.
20737            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20738            paint.setShader(shader);
20739            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20740
20741            this.host = host;
20742        }
20743
20744        public void setFadeColor(int color) {
20745            if (color != mLastColor) {
20746                mLastColor = color;
20747
20748                if (color != 0) {
20749                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20750                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20751                    paint.setShader(shader);
20752                    // Restore the default transfer mode (src_over)
20753                    paint.setXfermode(null);
20754                } else {
20755                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20756                    paint.setShader(shader);
20757                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20758                }
20759            }
20760        }
20761
20762        public void run() {
20763            long now = AnimationUtils.currentAnimationTimeMillis();
20764            if (now >= fadeStartTime) {
20765
20766                // the animation fades the scrollbars out by changing
20767                // the opacity (alpha) from fully opaque to fully
20768                // transparent
20769                int nextFrame = (int) now;
20770                int framesCount = 0;
20771
20772                Interpolator interpolator = scrollBarInterpolator;
20773
20774                // Start opaque
20775                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20776
20777                // End transparent
20778                nextFrame += scrollBarFadeDuration;
20779                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20780
20781                state = FADING;
20782
20783                // Kick off the fade animation
20784                host.invalidate(true);
20785            }
20786        }
20787    }
20788
20789    /**
20790     * Resuable callback for sending
20791     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20792     */
20793    private class SendViewScrolledAccessibilityEvent implements Runnable {
20794        public volatile boolean mIsPending;
20795
20796        public void run() {
20797            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20798            mIsPending = false;
20799        }
20800    }
20801
20802    /**
20803     * <p>
20804     * This class represents a delegate that can be registered in a {@link View}
20805     * to enhance accessibility support via composition rather via inheritance.
20806     * It is specifically targeted to widget developers that extend basic View
20807     * classes i.e. classes in package android.view, that would like their
20808     * applications to be backwards compatible.
20809     * </p>
20810     * <div class="special reference">
20811     * <h3>Developer Guides</h3>
20812     * <p>For more information about making applications accessible, read the
20813     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20814     * developer guide.</p>
20815     * </div>
20816     * <p>
20817     * A scenario in which a developer would like to use an accessibility delegate
20818     * is overriding a method introduced in a later API version then the minimal API
20819     * version supported by the application. For example, the method
20820     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20821     * in API version 4 when the accessibility APIs were first introduced. If a
20822     * developer would like his application to run on API version 4 devices (assuming
20823     * all other APIs used by the application are version 4 or lower) and take advantage
20824     * of this method, instead of overriding the method which would break the application's
20825     * backwards compatibility, he can override the corresponding method in this
20826     * delegate and register the delegate in the target View if the API version of
20827     * the system is high enough i.e. the API version is same or higher to the API
20828     * version that introduced
20829     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20830     * </p>
20831     * <p>
20832     * Here is an example implementation:
20833     * </p>
20834     * <code><pre><p>
20835     * if (Build.VERSION.SDK_INT >= 14) {
20836     *     // If the API version is equal of higher than the version in
20837     *     // which onInitializeAccessibilityNodeInfo was introduced we
20838     *     // register a delegate with a customized implementation.
20839     *     View view = findViewById(R.id.view_id);
20840     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20841     *         public void onInitializeAccessibilityNodeInfo(View host,
20842     *                 AccessibilityNodeInfo info) {
20843     *             // Let the default implementation populate the info.
20844     *             super.onInitializeAccessibilityNodeInfo(host, info);
20845     *             // Set some other information.
20846     *             info.setEnabled(host.isEnabled());
20847     *         }
20848     *     });
20849     * }
20850     * </code></pre></p>
20851     * <p>
20852     * This delegate contains methods that correspond to the accessibility methods
20853     * in View. If a delegate has been specified the implementation in View hands
20854     * off handling to the corresponding method in this delegate. The default
20855     * implementation the delegate methods behaves exactly as the corresponding
20856     * method in View for the case of no accessibility delegate been set. Hence,
20857     * to customize the behavior of a View method, clients can override only the
20858     * corresponding delegate method without altering the behavior of the rest
20859     * accessibility related methods of the host view.
20860     * </p>
20861     */
20862    public static class AccessibilityDelegate {
20863
20864        /**
20865         * Sends an accessibility event of the given type. If accessibility is not
20866         * enabled this method has no effect.
20867         * <p>
20868         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20869         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20870         * been set.
20871         * </p>
20872         *
20873         * @param host The View hosting the delegate.
20874         * @param eventType The type of the event to send.
20875         *
20876         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20877         */
20878        public void sendAccessibilityEvent(View host, int eventType) {
20879            host.sendAccessibilityEventInternal(eventType);
20880        }
20881
20882        /**
20883         * Performs the specified accessibility action on the view. For
20884         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20885         * <p>
20886         * The default implementation behaves as
20887         * {@link View#performAccessibilityAction(int, Bundle)
20888         *  View#performAccessibilityAction(int, Bundle)} for the case of
20889         *  no accessibility delegate been set.
20890         * </p>
20891         *
20892         * @param action The action to perform.
20893         * @return Whether the action was performed.
20894         *
20895         * @see View#performAccessibilityAction(int, Bundle)
20896         *      View#performAccessibilityAction(int, Bundle)
20897         */
20898        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20899            return host.performAccessibilityActionInternal(action, args);
20900        }
20901
20902        /**
20903         * Sends an accessibility event. This method behaves exactly as
20904         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20905         * empty {@link AccessibilityEvent} and does not perform a check whether
20906         * accessibility is enabled.
20907         * <p>
20908         * The default implementation behaves as
20909         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20910         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20911         * the case of no accessibility delegate been set.
20912         * </p>
20913         *
20914         * @param host The View hosting the delegate.
20915         * @param event The event to send.
20916         *
20917         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20918         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20919         */
20920        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20921            host.sendAccessibilityEventUncheckedInternal(event);
20922        }
20923
20924        /**
20925         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20926         * to its children for adding their text content to the event.
20927         * <p>
20928         * The default implementation behaves as
20929         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20930         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20931         * the case of no accessibility delegate been set.
20932         * </p>
20933         *
20934         * @param host The View hosting the delegate.
20935         * @param event The event.
20936         * @return True if the event population was completed.
20937         *
20938         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20939         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20940         */
20941        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20942            return host.dispatchPopulateAccessibilityEventInternal(event);
20943        }
20944
20945        /**
20946         * Gives a chance to the host View to populate the accessibility event with its
20947         * text content.
20948         * <p>
20949         * The default implementation behaves as
20950         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20951         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20952         * the case of no accessibility delegate been set.
20953         * </p>
20954         *
20955         * @param host The View hosting the delegate.
20956         * @param event The accessibility event which to populate.
20957         *
20958         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20959         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20960         */
20961        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20962            host.onPopulateAccessibilityEventInternal(event);
20963        }
20964
20965        /**
20966         * Initializes an {@link AccessibilityEvent} with information about the
20967         * the host View which is the event source.
20968         * <p>
20969         * The default implementation behaves as
20970         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20971         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20972         * the case of no accessibility delegate been set.
20973         * </p>
20974         *
20975         * @param host The View hosting the delegate.
20976         * @param event The event to initialize.
20977         *
20978         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20979         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20980         */
20981        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20982            host.onInitializeAccessibilityEventInternal(event);
20983        }
20984
20985        /**
20986         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20987         * <p>
20988         * The default implementation behaves as
20989         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20990         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20991         * the case of no accessibility delegate been set.
20992         * </p>
20993         *
20994         * @param host The View hosting the delegate.
20995         * @param info The instance to initialize.
20996         *
20997         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20998         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20999         */
21000        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
21001            host.onInitializeAccessibilityNodeInfoInternal(info);
21002        }
21003
21004        /**
21005         * Called when a child of the host View has requested sending an
21006         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
21007         * to augment the event.
21008         * <p>
21009         * The default implementation behaves as
21010         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21011         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
21012         * the case of no accessibility delegate been set.
21013         * </p>
21014         *
21015         * @param host The View hosting the delegate.
21016         * @param child The child which requests sending the event.
21017         * @param event The event to be sent.
21018         * @return True if the event should be sent
21019         *
21020         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21021         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21022         */
21023        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
21024                AccessibilityEvent event) {
21025            return host.onRequestSendAccessibilityEventInternal(child, event);
21026        }
21027
21028        /**
21029         * Gets the provider for managing a virtual view hierarchy rooted at this View
21030         * and reported to {@link android.accessibilityservice.AccessibilityService}s
21031         * that explore the window content.
21032         * <p>
21033         * The default implementation behaves as
21034         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
21035         * the case of no accessibility delegate been set.
21036         * </p>
21037         *
21038         * @return The provider.
21039         *
21040         * @see AccessibilityNodeProvider
21041         */
21042        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
21043            return null;
21044        }
21045
21046        /**
21047         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
21048         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
21049         * This method is responsible for obtaining an accessibility node info from a
21050         * pool of reusable instances and calling
21051         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21052         * view to initialize the former.
21053         * <p>
21054         * <strong>Note:</strong> The client is responsible for recycling the obtained
21055         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21056         * creation.
21057         * </p>
21058         * <p>
21059         * The default implementation behaves as
21060         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21061         * the case of no accessibility delegate been set.
21062         * </p>
21063         * @return A populated {@link AccessibilityNodeInfo}.
21064         *
21065         * @see AccessibilityNodeInfo
21066         *
21067         * @hide
21068         */
21069        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21070            return host.createAccessibilityNodeInfoInternal();
21071        }
21072    }
21073
21074    private class MatchIdPredicate implements Predicate<View> {
21075        public int mId;
21076
21077        @Override
21078        public boolean apply(View view) {
21079            return (view.mID == mId);
21080        }
21081    }
21082
21083    private class MatchLabelForPredicate implements Predicate<View> {
21084        private int mLabeledId;
21085
21086        @Override
21087        public boolean apply(View view) {
21088            return (view.mLabelForId == mLabeledId);
21089        }
21090    }
21091
21092    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21093        private int mChangeTypes = 0;
21094        private boolean mPosted;
21095        private boolean mPostedWithDelay;
21096        private long mLastEventTimeMillis;
21097
21098        @Override
21099        public void run() {
21100            mPosted = false;
21101            mPostedWithDelay = false;
21102            mLastEventTimeMillis = SystemClock.uptimeMillis();
21103            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21104                final AccessibilityEvent event = AccessibilityEvent.obtain();
21105                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21106                event.setContentChangeTypes(mChangeTypes);
21107                sendAccessibilityEventUnchecked(event);
21108            }
21109            mChangeTypes = 0;
21110        }
21111
21112        public void runOrPost(int changeType) {
21113            mChangeTypes |= changeType;
21114
21115            // If this is a live region or the child of a live region, collect
21116            // all events from this frame and send them on the next frame.
21117            if (inLiveRegion()) {
21118                // If we're already posted with a delay, remove that.
21119                if (mPostedWithDelay) {
21120                    removeCallbacks(this);
21121                    mPostedWithDelay = false;
21122                }
21123                // Only post if we're not already posted.
21124                if (!mPosted) {
21125                    post(this);
21126                    mPosted = true;
21127                }
21128                return;
21129            }
21130
21131            if (mPosted) {
21132                return;
21133            }
21134
21135            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21136            final long minEventIntevalMillis =
21137                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21138            if (timeSinceLastMillis >= minEventIntevalMillis) {
21139                removeCallbacks(this);
21140                run();
21141            } else {
21142                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21143                mPostedWithDelay = true;
21144            }
21145        }
21146    }
21147
21148    private boolean inLiveRegion() {
21149        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21150            return true;
21151        }
21152
21153        ViewParent parent = getParent();
21154        while (parent instanceof View) {
21155            if (((View) parent).getAccessibilityLiveRegion()
21156                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21157                return true;
21158            }
21159            parent = parent.getParent();
21160        }
21161
21162        return false;
21163    }
21164
21165    /**
21166     * Dump all private flags in readable format, useful for documentation and
21167     * sanity checking.
21168     */
21169    private static void dumpFlags() {
21170        final HashMap<String, String> found = Maps.newHashMap();
21171        try {
21172            for (Field field : View.class.getDeclaredFields()) {
21173                final int modifiers = field.getModifiers();
21174                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21175                    if (field.getType().equals(int.class)) {
21176                        final int value = field.getInt(null);
21177                        dumpFlag(found, field.getName(), value);
21178                    } else if (field.getType().equals(int[].class)) {
21179                        final int[] values = (int[]) field.get(null);
21180                        for (int i = 0; i < values.length; i++) {
21181                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21182                        }
21183                    }
21184                }
21185            }
21186        } catch (IllegalAccessException e) {
21187            throw new RuntimeException(e);
21188        }
21189
21190        final ArrayList<String> keys = Lists.newArrayList();
21191        keys.addAll(found.keySet());
21192        Collections.sort(keys);
21193        for (String key : keys) {
21194            Log.d(VIEW_LOG_TAG, found.get(key));
21195        }
21196    }
21197
21198    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
21199        // Sort flags by prefix, then by bits, always keeping unique keys
21200        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
21201        final int prefix = name.indexOf('_');
21202        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
21203        final String output = bits + " " + name;
21204        found.put(key, output);
21205    }
21206}
21207