View.java revision c99d3c99f86be8cace507379c0d4f4b7a26fd1e1
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.text.TextUtils;
60import android.util.AttributeSet;
61import android.util.FloatProperty;
62import android.util.LayoutDirection;
63import android.util.Log;
64import android.util.LongSparseLongArray;
65import android.util.Pools.SynchronizedPool;
66import android.util.Property;
67import android.util.SparseArray;
68import android.util.SuperNotCalledException;
69import android.util.TypedValue;
70import android.view.ContextMenu.ContextMenuInfo;
71import android.view.AccessibilityIterators.TextSegmentIterator;
72import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
73import android.view.AccessibilityIterators.WordTextSegmentIterator;
74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
75import android.view.accessibility.AccessibilityEvent;
76import android.view.accessibility.AccessibilityEventSource;
77import android.view.accessibility.AccessibilityManager;
78import android.view.accessibility.AccessibilityNodeInfo;
79import android.view.accessibility.AccessibilityNodeProvider;
80import android.view.animation.Animation;
81import android.view.animation.AnimationUtils;
82import android.view.animation.Transformation;
83import android.view.inputmethod.EditorInfo;
84import android.view.inputmethod.InputConnection;
85import android.view.inputmethod.InputMethodManager;
86import android.widget.ScrollBarDrawable;
87
88import static android.os.Build.VERSION_CODES.*;
89import static java.lang.Math.max;
90
91import com.android.internal.R;
92import com.android.internal.util.Predicate;
93import com.android.internal.view.menu.MenuBuilder;
94import com.google.android.collect.Lists;
95import com.google.android.collect.Maps;
96
97import java.lang.annotation.Retention;
98import java.lang.annotation.RetentionPolicy;
99import java.lang.ref.WeakReference;
100import java.lang.reflect.Field;
101import java.lang.reflect.InvocationTargetException;
102import java.lang.reflect.Method;
103import java.lang.reflect.Modifier;
104import java.util.ArrayList;
105import java.util.Arrays;
106import java.util.Collections;
107import java.util.HashMap;
108import java.util.List;
109import java.util.Locale;
110import java.util.Map;
111import java.util.concurrent.CopyOnWriteArrayList;
112import java.util.concurrent.atomic.AtomicInteger;
113
114/**
115 * <p>
116 * This class represents the basic building block for user interface components. A View
117 * occupies a rectangular area on the screen and is responsible for drawing and
118 * event handling. View is the base class for <em>widgets</em>, which are
119 * used to create interactive UI components (buttons, text fields, etc.). The
120 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
121 * are invisible containers that hold other Views (or other ViewGroups) and define
122 * their layout properties.
123 * </p>
124 *
125 * <div class="special reference">
126 * <h3>Developer Guides</h3>
127 * <p>For information about using this class to develop your application's user interface,
128 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
129 * </div>
130 *
131 * <a name="Using"></a>
132 * <h3>Using Views</h3>
133 * <p>
134 * All of the views in a window are arranged in a single tree. You can add views
135 * either from code or by specifying a tree of views in one or more XML layout
136 * files. There are many specialized subclasses of views that act as controls or
137 * are capable of displaying text, images, or other content.
138 * </p>
139 * <p>
140 * Once you have created a tree of views, there are typically a few types of
141 * common operations you may wish to perform:
142 * <ul>
143 * <li><strong>Set properties:</strong> for example setting the text of a
144 * {@link android.widget.TextView}. The available properties and the methods
145 * that set them will vary among the different subclasses of views. Note that
146 * properties that are known at build time can be set in the XML layout
147 * files.</li>
148 * <li><strong>Set focus:</strong> The framework will handled moving focus in
149 * response to user input. To force focus to a specific view, call
150 * {@link #requestFocus}.</li>
151 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
152 * that will be notified when something interesting happens to the view. For
153 * example, all views will let you set a listener to be notified when the view
154 * gains or loses focus. You can register such a listener using
155 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
156 * Other view subclasses offer more specialized listeners. For example, a Button
157 * exposes a listener to notify clients when the button is clicked.</li>
158 * <li><strong>Set visibility:</strong> You can hide or show views using
159 * {@link #setVisibility(int)}.</li>
160 * </ul>
161 * </p>
162 * <p><em>
163 * Note: The Android framework is responsible for measuring, laying out and
164 * drawing views. You should not call methods that perform these actions on
165 * views yourself unless you are actually implementing a
166 * {@link android.view.ViewGroup}.
167 * </em></p>
168 *
169 * <a name="Lifecycle"></a>
170 * <h3>Implementing a Custom View</h3>
171 *
172 * <p>
173 * To implement a custom view, you will usually begin by providing overrides for
174 * some of the standard methods that the framework calls on all views. You do
175 * not need to override all of these methods. In fact, you can start by just
176 * overriding {@link #onDraw(android.graphics.Canvas)}.
177 * <table border="2" width="85%" align="center" cellpadding="5">
178 *     <thead>
179 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
180 *     </thead>
181 *
182 *     <tbody>
183 *     <tr>
184 *         <td rowspan="2">Creation</td>
185 *         <td>Constructors</td>
186 *         <td>There is a form of the constructor that are called when the view
187 *         is created from code and a form that is called when the view is
188 *         inflated from a layout file. The second form should parse and apply
189 *         any attributes defined in the layout file.
190 *         </td>
191 *     </tr>
192 *     <tr>
193 *         <td><code>{@link #onFinishInflate()}</code></td>
194 *         <td>Called after a view and all of its children has been inflated
195 *         from XML.</td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td rowspan="3">Layout</td>
200 *         <td><code>{@link #onMeasure(int, int)}</code></td>
201 *         <td>Called to determine the size requirements for this view and all
202 *         of its children.
203 *         </td>
204 *     </tr>
205 *     <tr>
206 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
207 *         <td>Called when this view should assign a size and position to all
208 *         of its children.
209 *         </td>
210 *     </tr>
211 *     <tr>
212 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
213 *         <td>Called when the size of this view has changed.
214 *         </td>
215 *     </tr>
216 *
217 *     <tr>
218 *         <td>Drawing</td>
219 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
220 *         <td>Called when the view should render its content.
221 *         </td>
222 *     </tr>
223 *
224 *     <tr>
225 *         <td rowspan="4">Event processing</td>
226 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
227 *         <td>Called when a new hardware key event occurs.
228 *         </td>
229 *     </tr>
230 *     <tr>
231 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
232 *         <td>Called when a hardware key up event occurs.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
237 *         <td>Called when a trackball motion event occurs.
238 *         </td>
239 *     </tr>
240 *     <tr>
241 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
242 *         <td>Called when a touch screen motion event occurs.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td rowspan="2">Focus</td>
248 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
249 *         <td>Called when the view gains or loses focus.
250 *         </td>
251 *     </tr>
252 *
253 *     <tr>
254 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
255 *         <td>Called when the window containing the view gains or loses focus.
256 *         </td>
257 *     </tr>
258 *
259 *     <tr>
260 *         <td rowspan="3">Attaching</td>
261 *         <td><code>{@link #onAttachedToWindow()}</code></td>
262 *         <td>Called when the view is attached to a window.
263 *         </td>
264 *     </tr>
265 *
266 *     <tr>
267 *         <td><code>{@link #onDetachedFromWindow}</code></td>
268 *         <td>Called when the view is detached from its window.
269 *         </td>
270 *     </tr>
271 *
272 *     <tr>
273 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
274 *         <td>Called when the visibility of the window containing the view
275 *         has changed.
276 *         </td>
277 *     </tr>
278 *     </tbody>
279 *
280 * </table>
281 * </p>
282 *
283 * <a name="IDs"></a>
284 * <h3>IDs</h3>
285 * Views may have an integer id associated with them. These ids are typically
286 * assigned in the layout XML files, and are used to find specific views within
287 * the view tree. A common pattern is to:
288 * <ul>
289 * <li>Define a Button in the layout file and assign it a unique ID.
290 * <pre>
291 * &lt;Button
292 *     android:id="@+id/my_button"
293 *     android:layout_width="wrap_content"
294 *     android:layout_height="wrap_content"
295 *     android:text="@string/my_button_text"/&gt;
296 * </pre></li>
297 * <li>From the onCreate method of an Activity, find the Button
298 * <pre class="prettyprint">
299 *      Button myButton = (Button) findViewById(R.id.my_button);
300 * </pre></li>
301 * </ul>
302 * <p>
303 * View IDs need not be unique throughout the tree, but it is good practice to
304 * ensure that they are at least unique within the part of the tree you are
305 * searching.
306 * </p>
307 *
308 * <a name="Position"></a>
309 * <h3>Position</h3>
310 * <p>
311 * The geometry of a view is that of a rectangle. A view has a location,
312 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
313 * two dimensions, expressed as a width and a height. The unit for location
314 * and dimensions is the pixel.
315 * </p>
316 *
317 * <p>
318 * It is possible to retrieve the location of a view by invoking the methods
319 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
320 * coordinate of the rectangle representing the view. The latter returns the
321 * top, or Y, coordinate of the rectangle representing the view. These methods
322 * both return the location of the view relative to its parent. For instance,
323 * when getLeft() returns 20, that means the view is located 20 pixels to the
324 * right of the left edge of its direct parent.
325 * </p>
326 *
327 * <p>
328 * In addition, several convenience methods are offered to avoid unnecessary
329 * computations, namely {@link #getRight()} and {@link #getBottom()}.
330 * These methods return the coordinates of the right and bottom edges of the
331 * rectangle representing the view. For instance, calling {@link #getRight()}
332 * is similar to the following computation: <code>getLeft() + getWidth()</code>
333 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
334 * </p>
335 *
336 * <a name="SizePaddingMargins"></a>
337 * <h3>Size, padding and margins</h3>
338 * <p>
339 * The size of a view is expressed with a width and a height. A view actually
340 * possess two pairs of width and height values.
341 * </p>
342 *
343 * <p>
344 * The first pair is known as <em>measured width</em> and
345 * <em>measured height</em>. These dimensions define how big a view wants to be
346 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
347 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
348 * and {@link #getMeasuredHeight()}.
349 * </p>
350 *
351 * <p>
352 * The second pair is simply known as <em>width</em> and <em>height</em>, or
353 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
354 * dimensions define the actual size of the view on screen, at drawing time and
355 * after layout. These values may, but do not have to, be different from the
356 * measured width and height. The width and height can be obtained by calling
357 * {@link #getWidth()} and {@link #getHeight()}.
358 * </p>
359 *
360 * <p>
361 * To measure its dimensions, a view takes into account its padding. The padding
362 * is expressed in pixels for the left, top, right and bottom parts of the view.
363 * Padding can be used to offset the content of the view by a specific amount of
364 * pixels. For instance, a left padding of 2 will push the view's content by
365 * 2 pixels to the right of the left edge. Padding can be set using the
366 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
367 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
368 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
369 * {@link #getPaddingEnd()}.
370 * </p>
371 *
372 * <p>
373 * Even though a view can define a padding, it does not provide any support for
374 * margins. However, view groups provide such a support. Refer to
375 * {@link android.view.ViewGroup} and
376 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
377 * </p>
378 *
379 * <a name="Layout"></a>
380 * <h3>Layout</h3>
381 * <p>
382 * Layout is a two pass process: a measure pass and a layout pass. The measuring
383 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
384 * of the view tree. Each view pushes dimension specifications down the tree
385 * during the recursion. At the end of the measure pass, every view has stored
386 * its measurements. The second pass happens in
387 * {@link #layout(int,int,int,int)} and is also top-down. During
388 * this pass each parent is responsible for positioning all of its children
389 * using the sizes computed in the measure pass.
390 * </p>
391 *
392 * <p>
393 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
394 * {@link #getMeasuredHeight()} values must be set, along with those for all of
395 * that view's descendants. A view's measured width and measured height values
396 * must respect the constraints imposed by the view's parents. This guarantees
397 * that at the end of the measure pass, all parents accept all of their
398 * children's measurements. A parent view may call measure() more than once on
399 * its children. For example, the parent may measure each child once with
400 * unspecified dimensions to find out how big they want to be, then call
401 * measure() on them again with actual numbers if the sum of all the children's
402 * unconstrained sizes is too big or too small.
403 * </p>
404 *
405 * <p>
406 * The measure pass uses two classes to communicate dimensions. The
407 * {@link MeasureSpec} class is used by views to tell their parents how they
408 * want to be measured and positioned. The base LayoutParams class just
409 * describes how big the view wants to be for both width and height. For each
410 * dimension, it can specify one of:
411 * <ul>
412 * <li> an exact number
413 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
414 * (minus padding)
415 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
416 * enclose its content (plus padding).
417 * </ul>
418 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
419 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
420 * an X and Y value.
421 * </p>
422 *
423 * <p>
424 * MeasureSpecs are used to push requirements down the tree from parent to
425 * child. A MeasureSpec can be in one of three modes:
426 * <ul>
427 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
428 * of a child view. For example, a LinearLayout may call measure() on its child
429 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
430 * tall the child view wants to be given a width of 240 pixels.
431 * <li>EXACTLY: This is used by the parent to impose an exact size on the
432 * child. The child must use this size, and guarantee that all of its
433 * descendants will fit within this size.
434 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
435 * child. The child must guarantee that it and all of its descendants will fit
436 * within this size.
437 * </ul>
438 * </p>
439 *
440 * <p>
441 * To intiate a layout, call {@link #requestLayout}. This method is typically
442 * called by a view on itself when it believes that is can no longer fit within
443 * its current bounds.
444 * </p>
445 *
446 * <a name="Drawing"></a>
447 * <h3>Drawing</h3>
448 * <p>
449 * Drawing is handled by walking the tree and recording the drawing commands of
450 * any View that needs to update. After this, the drawing commands of the
451 * entire tree are issued to screen, clipped to the newly damaged area.
452 * </p>
453 *
454 * <p>
455 * The tree is largely recorded and drawn in order, with parents drawn before
456 * (i.e., behind) their children, with siblings drawn in the order they appear
457 * in the tree. If you set a background drawable for a View, then the View will
458 * draw it before calling back to its <code>onDraw()</code> method. The child
459 * drawing order can be overridden with
460 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
461 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
462 * </p>
463 *
464 * <p>
465 * To force a view to draw, call {@link #invalidate()}.
466 * </p>
467 *
468 * <a name="EventHandlingThreading"></a>
469 * <h3>Event Handling and Threading</h3>
470 * <p>
471 * The basic cycle of a view is as follows:
472 * <ol>
473 * <li>An event comes in and is dispatched to the appropriate view. The view
474 * handles the event and notifies any listeners.</li>
475 * <li>If in the course of processing the event, the view's bounds may need
476 * to be changed, the view will call {@link #requestLayout()}.</li>
477 * <li>Similarly, if in the course of processing the event the view's appearance
478 * may need to be changed, the view will call {@link #invalidate()}.</li>
479 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
480 * the framework will take care of measuring, laying out, and drawing the tree
481 * as appropriate.</li>
482 * </ol>
483 * </p>
484 *
485 * <p><em>Note: The entire view tree is single threaded. You must always be on
486 * the UI thread when calling any method on any view.</em>
487 * If you are doing work on other threads and want to update the state of a view
488 * from that thread, you should use a {@link Handler}.
489 * </p>
490 *
491 * <a name="FocusHandling"></a>
492 * <h3>Focus Handling</h3>
493 * <p>
494 * The framework will handle routine focus movement in response to user input.
495 * This includes changing the focus as views are removed or hidden, or as new
496 * views become available. Views indicate their willingness to take focus
497 * through the {@link #isFocusable} method. To change whether a view can take
498 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
499 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
500 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
501 * </p>
502 * <p>
503 * Focus movement is based on an algorithm which finds the nearest neighbor in a
504 * given direction. In rare cases, the default algorithm may not match the
505 * intended behavior of the developer. In these situations, you can provide
506 * explicit overrides by using these XML attributes in the layout file:
507 * <pre>
508 * nextFocusDown
509 * nextFocusLeft
510 * nextFocusRight
511 * nextFocusUp
512 * </pre>
513 * </p>
514 *
515 *
516 * <p>
517 * To get a particular view to take focus, call {@link #requestFocus()}.
518 * </p>
519 *
520 * <a name="TouchMode"></a>
521 * <h3>Touch Mode</h3>
522 * <p>
523 * When a user is navigating a user interface via directional keys such as a D-pad, it is
524 * necessary to give focus to actionable items such as buttons so the user can see
525 * what will take input.  If the device has touch capabilities, however, and the user
526 * begins interacting with the interface by touching it, it is no longer necessary to
527 * always highlight, or give focus to, a particular view.  This motivates a mode
528 * for interaction named 'touch mode'.
529 * </p>
530 * <p>
531 * For a touch capable device, once the user touches the screen, the device
532 * will enter touch mode.  From this point onward, only views for which
533 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
534 * Other views that are touchable, like buttons, will not take focus when touched; they will
535 * only fire the on click listeners.
536 * </p>
537 * <p>
538 * Any time a user hits a directional key, such as a D-pad direction, the view device will
539 * exit touch mode, and find a view to take focus, so that the user may resume interacting
540 * with the user interface without touching the screen again.
541 * </p>
542 * <p>
543 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
544 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
545 * </p>
546 *
547 * <a name="Scrolling"></a>
548 * <h3>Scrolling</h3>
549 * <p>
550 * The framework provides basic support for views that wish to internally
551 * scroll their content. This includes keeping track of the X and Y scroll
552 * offset as well as mechanisms for drawing scrollbars. See
553 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
554 * {@link #awakenScrollBars()} for more details.
555 * </p>
556 *
557 * <a name="Tags"></a>
558 * <h3>Tags</h3>
559 * <p>
560 * Unlike IDs, tags are not used to identify views. Tags are essentially an
561 * extra piece of information that can be associated with a view. They are most
562 * often used as a convenience to store data related to views in the views
563 * themselves rather than by putting them in a separate structure.
564 * </p>
565 *
566 * <a name="Properties"></a>
567 * <h3>Properties</h3>
568 * <p>
569 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
570 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
571 * available both in the {@link Property} form as well as in similarly-named setter/getter
572 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
573 * be used to set persistent state associated with these rendering-related properties on the view.
574 * The properties and methods can also be used in conjunction with
575 * {@link android.animation.Animator Animator}-based animations, described more in the
576 * <a href="#Animation">Animation</a> section.
577 * </p>
578 *
579 * <a name="Animation"></a>
580 * <h3>Animation</h3>
581 * <p>
582 * Starting with Android 3.0, the preferred way of animating views is to use the
583 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
584 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
585 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
586 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
587 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
588 * makes animating these View properties particularly easy and efficient.
589 * </p>
590 * <p>
591 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
592 * You can attach an {@link Animation} object to a view using
593 * {@link #setAnimation(Animation)} or
594 * {@link #startAnimation(Animation)}. The animation can alter the scale,
595 * rotation, translation and alpha of a view over time. If the animation is
596 * attached to a view that has children, the animation will affect the entire
597 * subtree rooted by that node. When an animation is started, the framework will
598 * take care of redrawing the appropriate views until the animation completes.
599 * </p>
600 *
601 * <a name="Security"></a>
602 * <h3>Security</h3>
603 * <p>
604 * Sometimes it is essential that an application be able to verify that an action
605 * is being performed with the full knowledge and consent of the user, such as
606 * granting a permission request, making a purchase or clicking on an advertisement.
607 * Unfortunately, a malicious application could try to spoof the user into
608 * performing these actions, unaware, by concealing the intended purpose of the view.
609 * As a remedy, the framework offers a touch filtering mechanism that can be used to
610 * improve the security of views that provide access to sensitive functionality.
611 * </p><p>
612 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
613 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
614 * will discard touches that are received whenever the view's window is obscured by
615 * another visible window.  As a result, the view will not receive touches whenever a
616 * toast, dialog or other window appears above the view's window.
617 * </p><p>
618 * For more fine-grained control over security, consider overriding the
619 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
620 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
621 * </p>
622 *
623 * @attr ref android.R.styleable#View_alpha
624 * @attr ref android.R.styleable#View_background
625 * @attr ref android.R.styleable#View_clickable
626 * @attr ref android.R.styleable#View_contentDescription
627 * @attr ref android.R.styleable#View_drawingCacheQuality
628 * @attr ref android.R.styleable#View_duplicateParentState
629 * @attr ref android.R.styleable#View_id
630 * @attr ref android.R.styleable#View_requiresFadingEdge
631 * @attr ref android.R.styleable#View_fadeScrollbars
632 * @attr ref android.R.styleable#View_fadingEdgeLength
633 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
634 * @attr ref android.R.styleable#View_fitsSystemWindows
635 * @attr ref android.R.styleable#View_isScrollContainer
636 * @attr ref android.R.styleable#View_focusable
637 * @attr ref android.R.styleable#View_focusableInTouchMode
638 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
639 * @attr ref android.R.styleable#View_keepScreenOn
640 * @attr ref android.R.styleable#View_layerType
641 * @attr ref android.R.styleable#View_layoutDirection
642 * @attr ref android.R.styleable#View_longClickable
643 * @attr ref android.R.styleable#View_minHeight
644 * @attr ref android.R.styleable#View_minWidth
645 * @attr ref android.R.styleable#View_nextFocusDown
646 * @attr ref android.R.styleable#View_nextFocusLeft
647 * @attr ref android.R.styleable#View_nextFocusRight
648 * @attr ref android.R.styleable#View_nextFocusUp
649 * @attr ref android.R.styleable#View_onClick
650 * @attr ref android.R.styleable#View_padding
651 * @attr ref android.R.styleable#View_paddingBottom
652 * @attr ref android.R.styleable#View_paddingLeft
653 * @attr ref android.R.styleable#View_paddingRight
654 * @attr ref android.R.styleable#View_paddingTop
655 * @attr ref android.R.styleable#View_paddingStart
656 * @attr ref android.R.styleable#View_paddingEnd
657 * @attr ref android.R.styleable#View_saveEnabled
658 * @attr ref android.R.styleable#View_rotation
659 * @attr ref android.R.styleable#View_rotationX
660 * @attr ref android.R.styleable#View_rotationY
661 * @attr ref android.R.styleable#View_scaleX
662 * @attr ref android.R.styleable#View_scaleY
663 * @attr ref android.R.styleable#View_scrollX
664 * @attr ref android.R.styleable#View_scrollY
665 * @attr ref android.R.styleable#View_scrollbarSize
666 * @attr ref android.R.styleable#View_scrollbarStyle
667 * @attr ref android.R.styleable#View_scrollbars
668 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
669 * @attr ref android.R.styleable#View_scrollbarFadeDuration
670 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
671 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
672 * @attr ref android.R.styleable#View_scrollbarThumbVertical
673 * @attr ref android.R.styleable#View_scrollbarTrackVertical
674 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
676 * @attr ref android.R.styleable#View_stateListAnimator
677 * @attr ref android.R.styleable#View_transitionName
678 * @attr ref android.R.styleable#View_soundEffectsEnabled
679 * @attr ref android.R.styleable#View_tag
680 * @attr ref android.R.styleable#View_textAlignment
681 * @attr ref android.R.styleable#View_textDirection
682 * @attr ref android.R.styleable#View_transformPivotX
683 * @attr ref android.R.styleable#View_transformPivotY
684 * @attr ref android.R.styleable#View_translationX
685 * @attr ref android.R.styleable#View_translationY
686 * @attr ref android.R.styleable#View_translationZ
687 * @attr ref android.R.styleable#View_visibility
688 *
689 * @see android.view.ViewGroup
690 */
691public class View implements Drawable.Callback, KeyEvent.Callback,
692        AccessibilityEventSource {
693    private static final boolean DBG = false;
694
695    /**
696     * The logging tag used by this class with android.util.Log.
697     */
698    protected static final String VIEW_LOG_TAG = "View";
699
700    /**
701     * When set to true, apps will draw debugging information about their layouts.
702     *
703     * @hide
704     */
705    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
706
707    /**
708     * When set to true, this view will save its attribute data.
709     *
710     * @hide
711     */
712    public static boolean mDebugViewAttributes = false;
713
714    /**
715     * Used to mark a View that has no ID.
716     */
717    public static final int NO_ID = -1;
718
719    /**
720     * Signals that compatibility booleans have been initialized according to
721     * target SDK versions.
722     */
723    private static boolean sCompatibilityDone = false;
724
725    /**
726     * Use the old (broken) way of building MeasureSpecs.
727     */
728    private static boolean sUseBrokenMakeMeasureSpec = false;
729
730    /**
731     * Ignore any optimizations using the measure cache.
732     */
733    private static boolean sIgnoreMeasureCache = false;
734
735    /**
736     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
737     * calling setFlags.
738     */
739    private static final int NOT_FOCUSABLE = 0x00000000;
740
741    /**
742     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
743     * setFlags.
744     */
745    private static final int FOCUSABLE = 0x00000001;
746
747    /**
748     * Mask for use with setFlags indicating bits used for focus.
749     */
750    private static final int FOCUSABLE_MASK = 0x00000001;
751
752    /**
753     * This view will adjust its padding to fit sytem windows (e.g. status bar)
754     */
755    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
756
757    /** @hide */
758    @IntDef({VISIBLE, INVISIBLE, GONE})
759    @Retention(RetentionPolicy.SOURCE)
760    public @interface Visibility {}
761
762    /**
763     * This view is visible.
764     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
765     * android:visibility}.
766     */
767    public static final int VISIBLE = 0x00000000;
768
769    /**
770     * This view is invisible, but it still takes up space for layout purposes.
771     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
772     * android:visibility}.
773     */
774    public static final int INVISIBLE = 0x00000004;
775
776    /**
777     * This view is invisible, and it doesn't take any space for layout
778     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
779     * android:visibility}.
780     */
781    public static final int GONE = 0x00000008;
782
783    /**
784     * Mask for use with setFlags indicating bits used for visibility.
785     * {@hide}
786     */
787    static final int VISIBILITY_MASK = 0x0000000C;
788
789    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
790
791    /**
792     * This view is enabled. Interpretation varies by subclass.
793     * Use with ENABLED_MASK when calling setFlags.
794     * {@hide}
795     */
796    static final int ENABLED = 0x00000000;
797
798    /**
799     * This view is disabled. Interpretation varies by subclass.
800     * Use with ENABLED_MASK when calling setFlags.
801     * {@hide}
802     */
803    static final int DISABLED = 0x00000020;
804
805   /**
806    * Mask for use with setFlags indicating bits used for indicating whether
807    * this view is enabled
808    * {@hide}
809    */
810    static final int ENABLED_MASK = 0x00000020;
811
812    /**
813     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
814     * called and further optimizations will be performed. It is okay to have
815     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
816     * {@hide}
817     */
818    static final int WILL_NOT_DRAW = 0x00000080;
819
820    /**
821     * Mask for use with setFlags indicating bits used for indicating whether
822     * this view is will draw
823     * {@hide}
824     */
825    static final int DRAW_MASK = 0x00000080;
826
827    /**
828     * <p>This view doesn't show scrollbars.</p>
829     * {@hide}
830     */
831    static final int SCROLLBARS_NONE = 0x00000000;
832
833    /**
834     * <p>This view shows horizontal scrollbars.</p>
835     * {@hide}
836     */
837    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
838
839    /**
840     * <p>This view shows vertical scrollbars.</p>
841     * {@hide}
842     */
843    static final int SCROLLBARS_VERTICAL = 0x00000200;
844
845    /**
846     * <p>Mask for use with setFlags indicating bits used for indicating which
847     * scrollbars are enabled.</p>
848     * {@hide}
849     */
850    static final int SCROLLBARS_MASK = 0x00000300;
851
852    /**
853     * Indicates that the view should filter touches when its window is obscured.
854     * Refer to the class comments for more information about this security feature.
855     * {@hide}
856     */
857    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
858
859    /**
860     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
861     * that they are optional and should be skipped if the window has
862     * requested system UI flags that ignore those insets for layout.
863     */
864    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
865
866    /**
867     * <p>This view doesn't show fading edges.</p>
868     * {@hide}
869     */
870    static final int FADING_EDGE_NONE = 0x00000000;
871
872    /**
873     * <p>This view shows horizontal fading edges.</p>
874     * {@hide}
875     */
876    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
877
878    /**
879     * <p>This view shows vertical fading edges.</p>
880     * {@hide}
881     */
882    static final int FADING_EDGE_VERTICAL = 0x00002000;
883
884    /**
885     * <p>Mask for use with setFlags indicating bits used for indicating which
886     * fading edges are enabled.</p>
887     * {@hide}
888     */
889    static final int FADING_EDGE_MASK = 0x00003000;
890
891    /**
892     * <p>Indicates this view can be clicked. When clickable, a View reacts
893     * to clicks by notifying the OnClickListener.<p>
894     * {@hide}
895     */
896    static final int CLICKABLE = 0x00004000;
897
898    /**
899     * <p>Indicates this view is caching its drawing into a bitmap.</p>
900     * {@hide}
901     */
902    static final int DRAWING_CACHE_ENABLED = 0x00008000;
903
904    /**
905     * <p>Indicates that no icicle should be saved for this view.<p>
906     * {@hide}
907     */
908    static final int SAVE_DISABLED = 0x000010000;
909
910    /**
911     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
912     * property.</p>
913     * {@hide}
914     */
915    static final int SAVE_DISABLED_MASK = 0x000010000;
916
917    /**
918     * <p>Indicates that no drawing cache should ever be created for this view.<p>
919     * {@hide}
920     */
921    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
922
923    /**
924     * <p>Indicates this view can take / keep focus when int touch mode.</p>
925     * {@hide}
926     */
927    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
928
929    /** @hide */
930    @Retention(RetentionPolicy.SOURCE)
931    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
932    public @interface DrawingCacheQuality {}
933
934    /**
935     * <p>Enables low quality mode for the drawing cache.</p>
936     */
937    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
938
939    /**
940     * <p>Enables high quality mode for the drawing cache.</p>
941     */
942    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
943
944    /**
945     * <p>Enables automatic quality mode for the drawing cache.</p>
946     */
947    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
948
949    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
950            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
951    };
952
953    /**
954     * <p>Mask for use with setFlags indicating bits used for the cache
955     * quality property.</p>
956     * {@hide}
957     */
958    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
959
960    /**
961     * <p>
962     * Indicates this view can be long clicked. When long clickable, a View
963     * reacts to long clicks by notifying the OnLongClickListener or showing a
964     * context menu.
965     * </p>
966     * {@hide}
967     */
968    static final int LONG_CLICKABLE = 0x00200000;
969
970    /**
971     * <p>Indicates that this view gets its drawable states from its direct parent
972     * and ignores its original internal states.</p>
973     *
974     * @hide
975     */
976    static final int DUPLICATE_PARENT_STATE = 0x00400000;
977
978    /** @hide */
979    @IntDef({
980        SCROLLBARS_INSIDE_OVERLAY,
981        SCROLLBARS_INSIDE_INSET,
982        SCROLLBARS_OUTSIDE_OVERLAY,
983        SCROLLBARS_OUTSIDE_INSET
984    })
985    @Retention(RetentionPolicy.SOURCE)
986    public @interface ScrollBarStyle {}
987
988    /**
989     * The scrollbar style to display the scrollbars inside the content area,
990     * without increasing the padding. The scrollbars will be overlaid with
991     * translucency on the view's content.
992     */
993    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
994
995    /**
996     * The scrollbar style to display the scrollbars inside the padded area,
997     * increasing the padding of the view. The scrollbars will not overlap the
998     * content area of the view.
999     */
1000    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1001
1002    /**
1003     * The scrollbar style to display the scrollbars at the edge of the view,
1004     * without increasing the padding. The scrollbars will be overlaid with
1005     * translucency.
1006     */
1007    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1008
1009    /**
1010     * The scrollbar style to display the scrollbars at the edge of the view,
1011     * increasing the padding of the view. The scrollbars will only overlap the
1012     * background, if any.
1013     */
1014    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1015
1016    /**
1017     * Mask to check if the scrollbar style is overlay or inset.
1018     * {@hide}
1019     */
1020    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1021
1022    /**
1023     * Mask to check if the scrollbar style is inside or outside.
1024     * {@hide}
1025     */
1026    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1027
1028    /**
1029     * Mask for scrollbar style.
1030     * {@hide}
1031     */
1032    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1033
1034    /**
1035     * View flag indicating that the screen should remain on while the
1036     * window containing this view is visible to the user.  This effectively
1037     * takes care of automatically setting the WindowManager's
1038     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1039     */
1040    public static final int KEEP_SCREEN_ON = 0x04000000;
1041
1042    /**
1043     * View flag indicating whether this view should have sound effects enabled
1044     * for events such as clicking and touching.
1045     */
1046    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1047
1048    /**
1049     * View flag indicating whether this view should have haptic feedback
1050     * enabled for events such as long presses.
1051     */
1052    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1053
1054    /**
1055     * <p>Indicates that the view hierarchy should stop saving state when
1056     * it reaches this view.  If state saving is initiated immediately at
1057     * the view, it will be allowed.
1058     * {@hide}
1059     */
1060    static final int PARENT_SAVE_DISABLED = 0x20000000;
1061
1062    /**
1063     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1064     * {@hide}
1065     */
1066    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1067
1068    /** @hide */
1069    @IntDef(flag = true,
1070            value = {
1071                FOCUSABLES_ALL,
1072                FOCUSABLES_TOUCH_MODE
1073            })
1074    @Retention(RetentionPolicy.SOURCE)
1075    public @interface FocusableMode {}
1076
1077    /**
1078     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1079     * should add all focusable Views regardless if they are focusable in touch mode.
1080     */
1081    public static final int FOCUSABLES_ALL = 0x00000000;
1082
1083    /**
1084     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1085     * should add only Views focusable in touch mode.
1086     */
1087    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1088
1089    /** @hide */
1090    @IntDef({
1091            FOCUS_BACKWARD,
1092            FOCUS_FORWARD,
1093            FOCUS_LEFT,
1094            FOCUS_UP,
1095            FOCUS_RIGHT,
1096            FOCUS_DOWN
1097    })
1098    @Retention(RetentionPolicy.SOURCE)
1099    public @interface FocusDirection {}
1100
1101    /** @hide */
1102    @IntDef({
1103            FOCUS_LEFT,
1104            FOCUS_UP,
1105            FOCUS_RIGHT,
1106            FOCUS_DOWN
1107    })
1108    @Retention(RetentionPolicy.SOURCE)
1109    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1110
1111    /**
1112     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1113     * item.
1114     */
1115    public static final int FOCUS_BACKWARD = 0x00000001;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1119     * item.
1120     */
1121    public static final int FOCUS_FORWARD = 0x00000002;
1122
1123    /**
1124     * Use with {@link #focusSearch(int)}. Move focus to the left.
1125     */
1126    public static final int FOCUS_LEFT = 0x00000011;
1127
1128    /**
1129     * Use with {@link #focusSearch(int)}. Move focus up.
1130     */
1131    public static final int FOCUS_UP = 0x00000021;
1132
1133    /**
1134     * Use with {@link #focusSearch(int)}. Move focus to the right.
1135     */
1136    public static final int FOCUS_RIGHT = 0x00000042;
1137
1138    /**
1139     * Use with {@link #focusSearch(int)}. Move focus down.
1140     */
1141    public static final int FOCUS_DOWN = 0x00000082;
1142
1143    /**
1144     * Bits of {@link #getMeasuredWidthAndState()} and
1145     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1146     */
1147    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1148
1149    /**
1150     * Bits of {@link #getMeasuredWidthAndState()} and
1151     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1152     */
1153    public static final int MEASURED_STATE_MASK = 0xff000000;
1154
1155    /**
1156     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1157     * for functions that combine both width and height into a single int,
1158     * such as {@link #getMeasuredState()} and the childState argument of
1159     * {@link #resolveSizeAndState(int, int, int)}.
1160     */
1161    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1162
1163    /**
1164     * Bit of {@link #getMeasuredWidthAndState()} and
1165     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1166     * is smaller that the space the view would like to have.
1167     */
1168    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1169
1170    /**
1171     * Base View state sets
1172     */
1173    // Singles
1174    /**
1175     * Indicates the view has no states set. States are used with
1176     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1177     * view depending on its state.
1178     *
1179     * @see android.graphics.drawable.Drawable
1180     * @see #getDrawableState()
1181     */
1182    protected static final int[] EMPTY_STATE_SET;
1183    /**
1184     * Indicates the view is enabled. States are used with
1185     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1186     * view depending on its state.
1187     *
1188     * @see android.graphics.drawable.Drawable
1189     * @see #getDrawableState()
1190     */
1191    protected static final int[] ENABLED_STATE_SET;
1192    /**
1193     * Indicates the view is focused. States are used with
1194     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1195     * view depending on its state.
1196     *
1197     * @see android.graphics.drawable.Drawable
1198     * @see #getDrawableState()
1199     */
1200    protected static final int[] FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is selected. States are used with
1203     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1204     * view depending on its state.
1205     *
1206     * @see android.graphics.drawable.Drawable
1207     * @see #getDrawableState()
1208     */
1209    protected static final int[] SELECTED_STATE_SET;
1210    /**
1211     * Indicates the view is pressed. States are used with
1212     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1213     * view depending on its state.
1214     *
1215     * @see android.graphics.drawable.Drawable
1216     * @see #getDrawableState()
1217     */
1218    protected static final int[] PRESSED_STATE_SET;
1219    /**
1220     * Indicates the view's window has focus. States are used with
1221     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1222     * view depending on its state.
1223     *
1224     * @see android.graphics.drawable.Drawable
1225     * @see #getDrawableState()
1226     */
1227    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1228    // Doubles
1229    /**
1230     * Indicates the view is enabled and has the focus.
1231     *
1232     * @see #ENABLED_STATE_SET
1233     * @see #FOCUSED_STATE_SET
1234     */
1235    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1236    /**
1237     * Indicates the view is enabled and selected.
1238     *
1239     * @see #ENABLED_STATE_SET
1240     * @see #SELECTED_STATE_SET
1241     */
1242    protected static final int[] ENABLED_SELECTED_STATE_SET;
1243    /**
1244     * Indicates the view is enabled and that its window has focus.
1245     *
1246     * @see #ENABLED_STATE_SET
1247     * @see #WINDOW_FOCUSED_STATE_SET
1248     */
1249    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is focused and selected.
1252     *
1253     * @see #FOCUSED_STATE_SET
1254     * @see #SELECTED_STATE_SET
1255     */
1256    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1257    /**
1258     * Indicates the view has the focus and that its window has the focus.
1259     *
1260     * @see #FOCUSED_STATE_SET
1261     * @see #WINDOW_FOCUSED_STATE_SET
1262     */
1263    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1264    /**
1265     * Indicates the view is selected and that its window has the focus.
1266     *
1267     * @see #SELECTED_STATE_SET
1268     * @see #WINDOW_FOCUSED_STATE_SET
1269     */
1270    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1271    // Triples
1272    /**
1273     * Indicates the view is enabled, focused and selected.
1274     *
1275     * @see #ENABLED_STATE_SET
1276     * @see #FOCUSED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     */
1279    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1280    /**
1281     * Indicates the view is enabled, focused and its window has the focus.
1282     *
1283     * @see #ENABLED_STATE_SET
1284     * @see #FOCUSED_STATE_SET
1285     * @see #WINDOW_FOCUSED_STATE_SET
1286     */
1287    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is enabled, selected and its window has the focus.
1290     *
1291     * @see #ENABLED_STATE_SET
1292     * @see #SELECTED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is focused, selected and its window has the focus.
1298     *
1299     * @see #FOCUSED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #WINDOW_FOCUSED_STATE_SET
1302     */
1303    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1304    /**
1305     * Indicates the view is enabled, focused, selected and its window
1306     * has the focus.
1307     *
1308     * @see #ENABLED_STATE_SET
1309     * @see #FOCUSED_STATE_SET
1310     * @see #SELECTED_STATE_SET
1311     * @see #WINDOW_FOCUSED_STATE_SET
1312     */
1313    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed and its window has the focus.
1316     *
1317     * @see #PRESSED_STATE_SET
1318     * @see #WINDOW_FOCUSED_STATE_SET
1319     */
1320    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1321    /**
1322     * Indicates the view is pressed and selected.
1323     *
1324     * @see #PRESSED_STATE_SET
1325     * @see #SELECTED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_SELECTED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, selected and its window has the focus.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #SELECTED_STATE_SET
1333     * @see #WINDOW_FOCUSED_STATE_SET
1334     */
1335    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1336    /**
1337     * Indicates the view is pressed and focused.
1338     *
1339     * @see #PRESSED_STATE_SET
1340     * @see #FOCUSED_STATE_SET
1341     */
1342    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1343    /**
1344     * Indicates the view is pressed, focused and its window has the focus.
1345     *
1346     * @see #PRESSED_STATE_SET
1347     * @see #FOCUSED_STATE_SET
1348     * @see #WINDOW_FOCUSED_STATE_SET
1349     */
1350    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1351    /**
1352     * Indicates the view is pressed, focused and selected.
1353     *
1354     * @see #PRESSED_STATE_SET
1355     * @see #SELECTED_STATE_SET
1356     * @see #FOCUSED_STATE_SET
1357     */
1358    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1359    /**
1360     * Indicates the view is pressed, focused, selected and its window has the focus.
1361     *
1362     * @see #PRESSED_STATE_SET
1363     * @see #FOCUSED_STATE_SET
1364     * @see #SELECTED_STATE_SET
1365     * @see #WINDOW_FOCUSED_STATE_SET
1366     */
1367    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1368    /**
1369     * Indicates the view is pressed and enabled.
1370     *
1371     * @see #PRESSED_STATE_SET
1372     * @see #ENABLED_STATE_SET
1373     */
1374    protected static final int[] PRESSED_ENABLED_STATE_SET;
1375    /**
1376     * Indicates the view is pressed, enabled and its window has the focus.
1377     *
1378     * @see #PRESSED_STATE_SET
1379     * @see #ENABLED_STATE_SET
1380     * @see #WINDOW_FOCUSED_STATE_SET
1381     */
1382    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1383    /**
1384     * Indicates the view is pressed, enabled and selected.
1385     *
1386     * @see #PRESSED_STATE_SET
1387     * @see #ENABLED_STATE_SET
1388     * @see #SELECTED_STATE_SET
1389     */
1390    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1391    /**
1392     * Indicates the view is pressed, enabled, selected and its window has the
1393     * focus.
1394     *
1395     * @see #PRESSED_STATE_SET
1396     * @see #ENABLED_STATE_SET
1397     * @see #SELECTED_STATE_SET
1398     * @see #WINDOW_FOCUSED_STATE_SET
1399     */
1400    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1401    /**
1402     * Indicates the view is pressed, enabled and focused.
1403     *
1404     * @see #PRESSED_STATE_SET
1405     * @see #ENABLED_STATE_SET
1406     * @see #FOCUSED_STATE_SET
1407     */
1408    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1409    /**
1410     * Indicates the view is pressed, enabled, focused and its window has the
1411     * focus.
1412     *
1413     * @see #PRESSED_STATE_SET
1414     * @see #ENABLED_STATE_SET
1415     * @see #FOCUSED_STATE_SET
1416     * @see #WINDOW_FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1419    /**
1420     * Indicates the view is pressed, enabled, focused and selected.
1421     *
1422     * @see #PRESSED_STATE_SET
1423     * @see #ENABLED_STATE_SET
1424     * @see #SELECTED_STATE_SET
1425     * @see #FOCUSED_STATE_SET
1426     */
1427    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1428    /**
1429     * Indicates the view is pressed, enabled, focused, selected and its window
1430     * has the focus.
1431     *
1432     * @see #PRESSED_STATE_SET
1433     * @see #ENABLED_STATE_SET
1434     * @see #SELECTED_STATE_SET
1435     * @see #FOCUSED_STATE_SET
1436     * @see #WINDOW_FOCUSED_STATE_SET
1437     */
1438    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1439
1440    /**
1441     * The order here is very important to {@link #getDrawableState()}
1442     */
1443    private static final int[][] VIEW_STATE_SETS;
1444
1445    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1446    static final int VIEW_STATE_SELECTED = 1 << 1;
1447    static final int VIEW_STATE_FOCUSED = 1 << 2;
1448    static final int VIEW_STATE_ENABLED = 1 << 3;
1449    static final int VIEW_STATE_PRESSED = 1 << 4;
1450    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1451    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1452    static final int VIEW_STATE_HOVERED = 1 << 7;
1453    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1454    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1455
1456    static final int[] VIEW_STATE_IDS = new int[] {
1457        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1458        R.attr.state_selected,          VIEW_STATE_SELECTED,
1459        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1460        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1461        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1462        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1463        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1464        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1465        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1466        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1467    };
1468
1469    static {
1470        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1471            throw new IllegalStateException(
1472                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1473        }
1474        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1475        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1476            int viewState = R.styleable.ViewDrawableStates[i];
1477            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1478                if (VIEW_STATE_IDS[j] == viewState) {
1479                    orderedIds[i * 2] = viewState;
1480                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1481                }
1482            }
1483        }
1484        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1485        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1486        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1487            int numBits = Integer.bitCount(i);
1488            int[] set = new int[numBits];
1489            int pos = 0;
1490            for (int j = 0; j < orderedIds.length; j += 2) {
1491                if ((i & orderedIds[j+1]) != 0) {
1492                    set[pos++] = orderedIds[j];
1493                }
1494            }
1495            VIEW_STATE_SETS[i] = set;
1496        }
1497
1498        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1499        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1500        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1501        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1503        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1504        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1505                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1506        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1508        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1510                | VIEW_STATE_FOCUSED];
1511        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1512        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1514        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1515                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1516        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1518                | VIEW_STATE_ENABLED];
1519        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1520                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1521        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1523                | VIEW_STATE_ENABLED];
1524        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1525                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1526                | VIEW_STATE_ENABLED];
1527        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1528                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1529                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1530
1531        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1532        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1533                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1534        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1535                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1536        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1538                | VIEW_STATE_PRESSED];
1539        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1540                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1541        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1543                | VIEW_STATE_PRESSED];
1544        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1546                | VIEW_STATE_PRESSED];
1547        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1549                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1552        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1553                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1554                | VIEW_STATE_PRESSED];
1555        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1556                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1557                | VIEW_STATE_PRESSED];
1558        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1559                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1560                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1561        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1562                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1563                | VIEW_STATE_PRESSED];
1564        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1565                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1566                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1567        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1568                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1569                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1570        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1571                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1572                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1573                | VIEW_STATE_PRESSED];
1574    }
1575
1576    /**
1577     * Accessibility event types that are dispatched for text population.
1578     */
1579    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1580            AccessibilityEvent.TYPE_VIEW_CLICKED
1581            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1582            | AccessibilityEvent.TYPE_VIEW_SELECTED
1583            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1584            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1585            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1586            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1587            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1588            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1589            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1590            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1591
1592    /**
1593     * Temporary Rect currently for use in setBackground().  This will probably
1594     * be extended in the future to hold our own class with more than just
1595     * a Rect. :)
1596     */
1597    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1598
1599    /**
1600     * Map used to store views' tags.
1601     */
1602    private SparseArray<Object> mKeyedTags;
1603
1604    /**
1605     * The next available accessibility id.
1606     */
1607    private static int sNextAccessibilityViewId;
1608
1609    /**
1610     * The animation currently associated with this view.
1611     * @hide
1612     */
1613    protected Animation mCurrentAnimation = null;
1614
1615    /**
1616     * Width as measured during measure pass.
1617     * {@hide}
1618     */
1619    @ViewDebug.ExportedProperty(category = "measurement")
1620    int mMeasuredWidth;
1621
1622    /**
1623     * Height as measured during measure pass.
1624     * {@hide}
1625     */
1626    @ViewDebug.ExportedProperty(category = "measurement")
1627    int mMeasuredHeight;
1628
1629    /**
1630     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1631     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1632     * its display list. This flag, used only when hw accelerated, allows us to clear the
1633     * flag while retaining this information until it's needed (at getDisplayList() time and
1634     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1635     *
1636     * {@hide}
1637     */
1638    boolean mRecreateDisplayList = false;
1639
1640    /**
1641     * The view's identifier.
1642     * {@hide}
1643     *
1644     * @see #setId(int)
1645     * @see #getId()
1646     */
1647    @ViewDebug.ExportedProperty(resolveId = true)
1648    int mID = NO_ID;
1649
1650    /**
1651     * The stable ID of this view for accessibility purposes.
1652     */
1653    int mAccessibilityViewId = NO_ID;
1654
1655    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1656
1657    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1658
1659    /**
1660     * The view's tag.
1661     * {@hide}
1662     *
1663     * @see #setTag(Object)
1664     * @see #getTag()
1665     */
1666    protected Object mTag = null;
1667
1668    // for mPrivateFlags:
1669    /** {@hide} */
1670    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1671    /** {@hide} */
1672    static final int PFLAG_FOCUSED                     = 0x00000002;
1673    /** {@hide} */
1674    static final int PFLAG_SELECTED                    = 0x00000004;
1675    /** {@hide} */
1676    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1677    /** {@hide} */
1678    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1679    /** {@hide} */
1680    static final int PFLAG_DRAWN                       = 0x00000020;
1681    /**
1682     * When this flag is set, this view is running an animation on behalf of its
1683     * children and should therefore not cancel invalidate requests, even if they
1684     * lie outside of this view's bounds.
1685     *
1686     * {@hide}
1687     */
1688    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1689    /** {@hide} */
1690    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1691    /** {@hide} */
1692    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1693    /** {@hide} */
1694    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1695    /** {@hide} */
1696    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1697    /** {@hide} */
1698    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1699    /** {@hide} */
1700    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1701    /** {@hide} */
1702    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1703
1704    private static final int PFLAG_PRESSED             = 0x00004000;
1705
1706    /** {@hide} */
1707    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1708    /**
1709     * Flag used to indicate that this view should be drawn once more (and only once
1710     * more) after its animation has completed.
1711     * {@hide}
1712     */
1713    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1714
1715    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1716
1717    /**
1718     * Indicates that the View returned true when onSetAlpha() was called and that
1719     * the alpha must be restored.
1720     * {@hide}
1721     */
1722    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1723
1724    /**
1725     * Set by {@link #setScrollContainer(boolean)}.
1726     */
1727    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1728
1729    /**
1730     * Set by {@link #setScrollContainer(boolean)}.
1731     */
1732    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1733
1734    /**
1735     * View flag indicating whether this view was invalidated (fully or partially.)
1736     *
1737     * @hide
1738     */
1739    static final int PFLAG_DIRTY                       = 0x00200000;
1740
1741    /**
1742     * View flag indicating whether this view was invalidated by an opaque
1743     * invalidate request.
1744     *
1745     * @hide
1746     */
1747    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1748
1749    /**
1750     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1751     *
1752     * @hide
1753     */
1754    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1755
1756    /**
1757     * Indicates whether the background is opaque.
1758     *
1759     * @hide
1760     */
1761    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1762
1763    /**
1764     * Indicates whether the scrollbars are opaque.
1765     *
1766     * @hide
1767     */
1768    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1769
1770    /**
1771     * Indicates whether the view is opaque.
1772     *
1773     * @hide
1774     */
1775    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1776
1777    /**
1778     * Indicates a prepressed state;
1779     * the short time between ACTION_DOWN and recognizing
1780     * a 'real' press. Prepressed is used to recognize quick taps
1781     * even when they are shorter than ViewConfiguration.getTapTimeout().
1782     *
1783     * @hide
1784     */
1785    private static final int PFLAG_PREPRESSED          = 0x02000000;
1786
1787    /**
1788     * Indicates whether the view is temporarily detached.
1789     *
1790     * @hide
1791     */
1792    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1793
1794    /**
1795     * Indicates that we should awaken scroll bars once attached
1796     *
1797     * @hide
1798     */
1799    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1800
1801    /**
1802     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1803     * @hide
1804     */
1805    private static final int PFLAG_HOVERED             = 0x10000000;
1806
1807    /**
1808     * no longer needed, should be reused
1809     */
1810    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1811
1812    /** {@hide} */
1813    static final int PFLAG_ACTIVATED                   = 0x40000000;
1814
1815    /**
1816     * Indicates that this view was specifically invalidated, not just dirtied because some
1817     * child view was invalidated. The flag is used to determine when we need to recreate
1818     * a view's display list (as opposed to just returning a reference to its existing
1819     * display list).
1820     *
1821     * @hide
1822     */
1823    static final int PFLAG_INVALIDATED                 = 0x80000000;
1824
1825    /**
1826     * Masks for mPrivateFlags2, as generated by dumpFlags():
1827     *
1828     * |-------|-------|-------|-------|
1829     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1830     *                                1  PFLAG2_DRAG_HOVERED
1831     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1832     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1833     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1834     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1835     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1836     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1837     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1838     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1839     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1840     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1841     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1842     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1843     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1844     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1845     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1846     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1847     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1848     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1849     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1850     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1851     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1852     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1853     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1854     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1855     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1856     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1857     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1858     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1859     *    1                              PFLAG2_PADDING_RESOLVED
1860     *   1                               PFLAG2_DRAWABLE_RESOLVED
1861     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1862     * |-------|-------|-------|-------|
1863     */
1864
1865    /**
1866     * Indicates that this view has reported that it can accept the current drag's content.
1867     * Cleared when the drag operation concludes.
1868     * @hide
1869     */
1870    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1871
1872    /**
1873     * Indicates that this view is currently directly under the drag location in a
1874     * drag-and-drop operation involving content that it can accept.  Cleared when
1875     * the drag exits the view, or when the drag operation concludes.
1876     * @hide
1877     */
1878    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1879
1880    /** @hide */
1881    @IntDef({
1882        LAYOUT_DIRECTION_LTR,
1883        LAYOUT_DIRECTION_RTL,
1884        LAYOUT_DIRECTION_INHERIT,
1885        LAYOUT_DIRECTION_LOCALE
1886    })
1887    @Retention(RetentionPolicy.SOURCE)
1888    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1889    public @interface LayoutDir {}
1890
1891    /** @hide */
1892    @IntDef({
1893        LAYOUT_DIRECTION_LTR,
1894        LAYOUT_DIRECTION_RTL
1895    })
1896    @Retention(RetentionPolicy.SOURCE)
1897    public @interface ResolvedLayoutDir {}
1898
1899    /**
1900     * Horizontal layout direction of this view is from Left to Right.
1901     * Use with {@link #setLayoutDirection}.
1902     */
1903    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1904
1905    /**
1906     * Horizontal layout direction of this view is from Right to Left.
1907     * Use with {@link #setLayoutDirection}.
1908     */
1909    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1910
1911    /**
1912     * Horizontal layout direction of this view is inherited from its parent.
1913     * Use with {@link #setLayoutDirection}.
1914     */
1915    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1916
1917    /**
1918     * Horizontal layout direction of this view is from deduced from the default language
1919     * script for the locale. Use with {@link #setLayoutDirection}.
1920     */
1921    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1922
1923    /**
1924     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1925     * @hide
1926     */
1927    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1928
1929    /**
1930     * Mask for use with private flags indicating bits used for horizontal layout direction.
1931     * @hide
1932     */
1933    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1934
1935    /**
1936     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1937     * right-to-left direction.
1938     * @hide
1939     */
1940    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1941
1942    /**
1943     * Indicates whether the view horizontal layout direction has been resolved.
1944     * @hide
1945     */
1946    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1947
1948    /**
1949     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1950     * @hide
1951     */
1952    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1953            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1954
1955    /*
1956     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1957     * flag value.
1958     * @hide
1959     */
1960    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1961            LAYOUT_DIRECTION_LTR,
1962            LAYOUT_DIRECTION_RTL,
1963            LAYOUT_DIRECTION_INHERIT,
1964            LAYOUT_DIRECTION_LOCALE
1965    };
1966
1967    /**
1968     * Default horizontal layout direction.
1969     */
1970    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1971
1972    /**
1973     * Default horizontal layout direction.
1974     * @hide
1975     */
1976    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1977
1978    /**
1979     * Text direction is inherited thru {@link ViewGroup}
1980     */
1981    public static final int TEXT_DIRECTION_INHERIT = 0;
1982
1983    /**
1984     * Text direction is using "first strong algorithm". The first strong directional character
1985     * determines the paragraph direction. If there is no strong directional character, the
1986     * paragraph direction is the view's resolved layout direction.
1987     */
1988    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1989
1990    /**
1991     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1992     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1993     * If there are neither, the paragraph direction is the view's resolved layout direction.
1994     */
1995    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1996
1997    /**
1998     * Text direction is forced to LTR.
1999     */
2000    public static final int TEXT_DIRECTION_LTR = 3;
2001
2002    /**
2003     * Text direction is forced to RTL.
2004     */
2005    public static final int TEXT_DIRECTION_RTL = 4;
2006
2007    /**
2008     * Text direction is coming from the system Locale.
2009     */
2010    public static final int TEXT_DIRECTION_LOCALE = 5;
2011
2012    /**
2013     * Default text direction is inherited
2014     */
2015    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2016
2017    /**
2018     * Default resolved text direction
2019     * @hide
2020     */
2021    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2022
2023    /**
2024     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2025     * @hide
2026     */
2027    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2028
2029    /**
2030     * Mask for use with private flags indicating bits used for text direction.
2031     * @hide
2032     */
2033    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2034            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2035
2036    /**
2037     * Array of text direction flags for mapping attribute "textDirection" to correct
2038     * flag value.
2039     * @hide
2040     */
2041    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2042            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2043            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2044            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2045            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2046            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2047            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2048    };
2049
2050    /**
2051     * Indicates whether the view text direction has been resolved.
2052     * @hide
2053     */
2054    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2055            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2056
2057    /**
2058     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2059     * @hide
2060     */
2061    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2062
2063    /**
2064     * Mask for use with private flags indicating bits used for resolved text direction.
2065     * @hide
2066     */
2067    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2068            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2069
2070    /**
2071     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2072     * @hide
2073     */
2074    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2075            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2076
2077    /** @hide */
2078    @IntDef({
2079        TEXT_ALIGNMENT_INHERIT,
2080        TEXT_ALIGNMENT_GRAVITY,
2081        TEXT_ALIGNMENT_CENTER,
2082        TEXT_ALIGNMENT_TEXT_START,
2083        TEXT_ALIGNMENT_TEXT_END,
2084        TEXT_ALIGNMENT_VIEW_START,
2085        TEXT_ALIGNMENT_VIEW_END
2086    })
2087    @Retention(RetentionPolicy.SOURCE)
2088    public @interface TextAlignment {}
2089
2090    /**
2091     * Default text alignment. The text alignment of this View is inherited from its parent.
2092     * Use with {@link #setTextAlignment(int)}
2093     */
2094    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2095
2096    /**
2097     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2098     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2099     *
2100     * Use with {@link #setTextAlignment(int)}
2101     */
2102    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2103
2104    /**
2105     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2106     *
2107     * Use with {@link #setTextAlignment(int)}
2108     */
2109    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2110
2111    /**
2112     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2113     *
2114     * Use with {@link #setTextAlignment(int)}
2115     */
2116    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2117
2118    /**
2119     * Center the paragraph, e.g. ALIGN_CENTER.
2120     *
2121     * Use with {@link #setTextAlignment(int)}
2122     */
2123    public static final int TEXT_ALIGNMENT_CENTER = 4;
2124
2125    /**
2126     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2127     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2128     *
2129     * Use with {@link #setTextAlignment(int)}
2130     */
2131    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2132
2133    /**
2134     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2135     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2136     *
2137     * Use with {@link #setTextAlignment(int)}
2138     */
2139    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2140
2141    /**
2142     * Default text alignment is inherited
2143     */
2144    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2145
2146    /**
2147     * Default resolved text alignment
2148     * @hide
2149     */
2150    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2151
2152    /**
2153      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2154      * @hide
2155      */
2156    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2157
2158    /**
2159      * Mask for use with private flags indicating bits used for text alignment.
2160      * @hide
2161      */
2162    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2163
2164    /**
2165     * Array of text direction flags for mapping attribute "textAlignment" to correct
2166     * flag value.
2167     * @hide
2168     */
2169    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2170            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2171            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2172            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2173            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2174            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2175            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2176            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2177    };
2178
2179    /**
2180     * Indicates whether the view text alignment has been resolved.
2181     * @hide
2182     */
2183    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2184
2185    /**
2186     * Bit shift to get the resolved text alignment.
2187     * @hide
2188     */
2189    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2190
2191    /**
2192     * Mask for use with private flags indicating bits used for text alignment.
2193     * @hide
2194     */
2195    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2196            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2197
2198    /**
2199     * Indicates whether if the view text alignment has been resolved to gravity
2200     */
2201    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2202            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2203
2204    // Accessiblity constants for mPrivateFlags2
2205
2206    /**
2207     * Shift for the bits in {@link #mPrivateFlags2} related to the
2208     * "importantForAccessibility" attribute.
2209     */
2210    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2211
2212    /**
2213     * Automatically determine whether a view is important for accessibility.
2214     */
2215    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2216
2217    /**
2218     * The view is important for accessibility.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2221
2222    /**
2223     * The view is not important for accessibility.
2224     */
2225    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2226
2227    /**
2228     * The view is not important for accessibility, nor are any of its
2229     * descendant views.
2230     */
2231    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2232
2233    /**
2234     * The default whether the view is important for accessibility.
2235     */
2236    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2237
2238    /**
2239     * Mask for obtainig the bits which specify how to determine
2240     * whether a view is important for accessibility.
2241     */
2242    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2243        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2244        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2245        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2246
2247    /**
2248     * Shift for the bits in {@link #mPrivateFlags2} related to the
2249     * "accessibilityLiveRegion" attribute.
2250     */
2251    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2252
2253    /**
2254     * Live region mode specifying that accessibility services should not
2255     * automatically announce changes to this view. This is the default live
2256     * region mode for most views.
2257     * <p>
2258     * Use with {@link #setAccessibilityLiveRegion(int)}.
2259     */
2260    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2261
2262    /**
2263     * Live region mode specifying that accessibility services should announce
2264     * changes to this view.
2265     * <p>
2266     * Use with {@link #setAccessibilityLiveRegion(int)}.
2267     */
2268    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2269
2270    /**
2271     * Live region mode specifying that accessibility services should interrupt
2272     * ongoing speech to immediately announce changes to this view.
2273     * <p>
2274     * Use with {@link #setAccessibilityLiveRegion(int)}.
2275     */
2276    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2277
2278    /**
2279     * The default whether the view is important for accessibility.
2280     */
2281    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2282
2283    /**
2284     * Mask for obtaining the bits which specify a view's accessibility live
2285     * region mode.
2286     */
2287    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2288            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2289            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2290
2291    /**
2292     * Flag indicating whether a view has accessibility focus.
2293     */
2294    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2295
2296    /**
2297     * Flag whether the accessibility state of the subtree rooted at this view changed.
2298     */
2299    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2300
2301    /**
2302     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2303     * is used to check whether later changes to the view's transform should invalidate the
2304     * view to force the quickReject test to run again.
2305     */
2306    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2307
2308    /**
2309     * Flag indicating that start/end padding has been resolved into left/right padding
2310     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2311     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2312     * during measurement. In some special cases this is required such as when an adapter-based
2313     * view measures prospective children without attaching them to a window.
2314     */
2315    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2316
2317    /**
2318     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2319     */
2320    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2321
2322    /**
2323     * Indicates that the view is tracking some sort of transient state
2324     * that the app should not need to be aware of, but that the framework
2325     * should take special care to preserve.
2326     */
2327    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2328
2329    /**
2330     * Group of bits indicating that RTL properties resolution is done.
2331     */
2332    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2333            PFLAG2_TEXT_DIRECTION_RESOLVED |
2334            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2335            PFLAG2_PADDING_RESOLVED |
2336            PFLAG2_DRAWABLE_RESOLVED;
2337
2338    // There are a couple of flags left in mPrivateFlags2
2339
2340    /* End of masks for mPrivateFlags2 */
2341
2342    /**
2343     * Masks for mPrivateFlags3, as generated by dumpFlags():
2344     *
2345     * |-------|-------|-------|-------|
2346     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2347     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2348     *                               1   PFLAG3_IS_LAID_OUT
2349     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2350     *                             1     PFLAG3_CALLED_SUPER
2351     * |-------|-------|-------|-------|
2352     */
2353
2354    /**
2355     * Flag indicating that view has a transform animation set on it. This is used to track whether
2356     * an animation is cleared between successive frames, in order to tell the associated
2357     * DisplayList to clear its animation matrix.
2358     */
2359    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2360
2361    /**
2362     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2363     * animation is cleared between successive frames, in order to tell the associated
2364     * DisplayList to restore its alpha value.
2365     */
2366    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2367
2368    /**
2369     * Flag indicating that the view has been through at least one layout since it
2370     * was last attached to a window.
2371     */
2372    static final int PFLAG3_IS_LAID_OUT = 0x4;
2373
2374    /**
2375     * Flag indicating that a call to measure() was skipped and should be done
2376     * instead when layout() is invoked.
2377     */
2378    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2379
2380    /**
2381     * Flag indicating that an overridden method correctly called down to
2382     * the superclass implementation as required by the API spec.
2383     */
2384    static final int PFLAG3_CALLED_SUPER = 0x10;
2385
2386    /**
2387     * Flag indicating that we're in the process of applying window insets.
2388     */
2389    static final int PFLAG3_APPLYING_INSETS = 0x20;
2390
2391    /**
2392     * Flag indicating that we're in the process of fitting system windows using the old method.
2393     */
2394    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2395
2396    /**
2397     * Flag indicating that nested scrolling is enabled for this view.
2398     * The view will optionally cooperate with views up its parent chain to allow for
2399     * integrated nested scrolling along the same axis.
2400     */
2401    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2402
2403    /* End of masks for mPrivateFlags3 */
2404
2405    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2406
2407    /**
2408     * Always allow a user to over-scroll this view, provided it is a
2409     * view that can scroll.
2410     *
2411     * @see #getOverScrollMode()
2412     * @see #setOverScrollMode(int)
2413     */
2414    public static final int OVER_SCROLL_ALWAYS = 0;
2415
2416    /**
2417     * Allow a user to over-scroll this view only if the content is large
2418     * enough to meaningfully scroll, provided it is a view that can scroll.
2419     *
2420     * @see #getOverScrollMode()
2421     * @see #setOverScrollMode(int)
2422     */
2423    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2424
2425    /**
2426     * Never allow a user to over-scroll this view.
2427     *
2428     * @see #getOverScrollMode()
2429     * @see #setOverScrollMode(int)
2430     */
2431    public static final int OVER_SCROLL_NEVER = 2;
2432
2433    /**
2434     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2435     * requested the system UI (status bar) to be visible (the default).
2436     *
2437     * @see #setSystemUiVisibility(int)
2438     */
2439    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2440
2441    /**
2442     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2443     * system UI to enter an unobtrusive "low profile" mode.
2444     *
2445     * <p>This is for use in games, book readers, video players, or any other
2446     * "immersive" application where the usual system chrome is deemed too distracting.
2447     *
2448     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2449     *
2450     * @see #setSystemUiVisibility(int)
2451     */
2452    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2453
2454    /**
2455     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2456     * system navigation be temporarily hidden.
2457     *
2458     * <p>This is an even less obtrusive state than that called for by
2459     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2460     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2461     * those to disappear. This is useful (in conjunction with the
2462     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2463     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2464     * window flags) for displaying content using every last pixel on the display.
2465     *
2466     * <p>There is a limitation: because navigation controls are so important, the least user
2467     * interaction will cause them to reappear immediately.  When this happens, both
2468     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2469     * so that both elements reappear at the same time.
2470     *
2471     * @see #setSystemUiVisibility(int)
2472     */
2473    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2474
2475    /**
2476     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2477     * into the normal fullscreen mode so that its content can take over the screen
2478     * while still allowing the user to interact with the application.
2479     *
2480     * <p>This has the same visual effect as
2481     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2482     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2483     * meaning that non-critical screen decorations (such as the status bar) will be
2484     * hidden while the user is in the View's window, focusing the experience on
2485     * that content.  Unlike the window flag, if you are using ActionBar in
2486     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2487     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2488     * hide the action bar.
2489     *
2490     * <p>This approach to going fullscreen is best used over the window flag when
2491     * it is a transient state -- that is, the application does this at certain
2492     * points in its user interaction where it wants to allow the user to focus
2493     * on content, but not as a continuous state.  For situations where the application
2494     * would like to simply stay full screen the entire time (such as a game that
2495     * wants to take over the screen), the
2496     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2497     * is usually a better approach.  The state set here will be removed by the system
2498     * in various situations (such as the user moving to another application) like
2499     * the other system UI states.
2500     *
2501     * <p>When using this flag, the application should provide some easy facility
2502     * for the user to go out of it.  A common example would be in an e-book
2503     * reader, where tapping on the screen brings back whatever screen and UI
2504     * decorations that had been hidden while the user was immersed in reading
2505     * the book.
2506     *
2507     * @see #setSystemUiVisibility(int)
2508     */
2509    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2510
2511    /**
2512     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2513     * flags, we would like a stable view of the content insets given to
2514     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2515     * will always represent the worst case that the application can expect
2516     * as a continuous state.  In the stock Android UI this is the space for
2517     * the system bar, nav bar, and status bar, but not more transient elements
2518     * such as an input method.
2519     *
2520     * The stable layout your UI sees is based on the system UI modes you can
2521     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2522     * then you will get a stable layout for changes of the
2523     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2524     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2525     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2526     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2527     * with a stable layout.  (Note that you should avoid using
2528     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2529     *
2530     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2531     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2532     * then a hidden status bar will be considered a "stable" state for purposes
2533     * here.  This allows your UI to continually hide the status bar, while still
2534     * using the system UI flags to hide the action bar while still retaining
2535     * a stable layout.  Note that changing the window fullscreen flag will never
2536     * provide a stable layout for a clean transition.
2537     *
2538     * <p>If you are using ActionBar in
2539     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2540     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2541     * insets it adds to those given to the application.
2542     */
2543    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2544
2545    /**
2546     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2547     * to be layed out as if it has requested
2548     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2549     * allows it to avoid artifacts when switching in and out of that mode, at
2550     * the expense that some of its user interface may be covered by screen
2551     * decorations when they are shown.  You can perform layout of your inner
2552     * UI elements to account for the navigation system UI through the
2553     * {@link #fitSystemWindows(Rect)} method.
2554     */
2555    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2556
2557    /**
2558     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2559     * to be layed out as if it has requested
2560     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2561     * allows it to avoid artifacts when switching in and out of that mode, at
2562     * the expense that some of its user interface may be covered by screen
2563     * decorations when they are shown.  You can perform layout of your inner
2564     * UI elements to account for non-fullscreen system UI through the
2565     * {@link #fitSystemWindows(Rect)} method.
2566     */
2567    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2568
2569    /**
2570     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2571     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2572     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2573     * user interaction.
2574     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2575     * has an effect when used in combination with that flag.</p>
2576     */
2577    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2578
2579    /**
2580     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2581     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2582     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2583     * experience while also hiding the system bars.  If this flag is not set,
2584     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2585     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2586     * if the user swipes from the top of the screen.
2587     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2588     * system gestures, such as swiping from the top of the screen.  These transient system bars
2589     * will overlay app’s content, may have some degree of transparency, and will automatically
2590     * hide after a short timeout.
2591     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2592     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2593     * with one or both of those flags.</p>
2594     */
2595    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2596
2597    /**
2598     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2599     */
2600    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2601
2602    /**
2603     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2604     */
2605    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2606
2607    /**
2608     * @hide
2609     *
2610     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2611     * out of the public fields to keep the undefined bits out of the developer's way.
2612     *
2613     * Flag to make the status bar not expandable.  Unless you also
2614     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2615     */
2616    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2617
2618    /**
2619     * @hide
2620     *
2621     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2622     * out of the public fields to keep the undefined bits out of the developer's way.
2623     *
2624     * Flag to hide notification icons and scrolling ticker text.
2625     */
2626    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2627
2628    /**
2629     * @hide
2630     *
2631     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2632     * out of the public fields to keep the undefined bits out of the developer's way.
2633     *
2634     * Flag to disable incoming notification alerts.  This will not block
2635     * icons, but it will block sound, vibrating and other visual or aural notifications.
2636     */
2637    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2638
2639    /**
2640     * @hide
2641     *
2642     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2643     * out of the public fields to keep the undefined bits out of the developer's way.
2644     *
2645     * Flag to hide only the scrolling ticker.  Note that
2646     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2647     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2648     */
2649    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2650
2651    /**
2652     * @hide
2653     *
2654     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2655     * out of the public fields to keep the undefined bits out of the developer's way.
2656     *
2657     * Flag to hide the center system info area.
2658     */
2659    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2660
2661    /**
2662     * @hide
2663     *
2664     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2665     * out of the public fields to keep the undefined bits out of the developer's way.
2666     *
2667     * Flag to hide only the home button.  Don't use this
2668     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2669     */
2670    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2671
2672    /**
2673     * @hide
2674     *
2675     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2676     * out of the public fields to keep the undefined bits out of the developer's way.
2677     *
2678     * Flag to hide only the back button. Don't use this
2679     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2680     */
2681    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2682
2683    /**
2684     * @hide
2685     *
2686     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2687     * out of the public fields to keep the undefined bits out of the developer's way.
2688     *
2689     * Flag to hide only the clock.  You might use this if your activity has
2690     * its own clock making the status bar's clock redundant.
2691     */
2692    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2693
2694    /**
2695     * @hide
2696     *
2697     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2698     * out of the public fields to keep the undefined bits out of the developer's way.
2699     *
2700     * Flag to hide only the recent apps button. Don't use this
2701     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2702     */
2703    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
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 disable the global search gesture. Don't use this
2712     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2713     */
2714    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2715
2716    /**
2717     * @hide
2718     *
2719     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2720     * out of the public fields to keep the undefined bits out of the developer's way.
2721     *
2722     * Flag to specify that the status bar is displayed in transient mode.
2723     */
2724    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2725
2726    /**
2727     * @hide
2728     *
2729     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2730     * out of the public fields to keep the undefined bits out of the developer's way.
2731     *
2732     * Flag to specify that the navigation bar is displayed in transient mode.
2733     */
2734    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2735
2736    /**
2737     * @hide
2738     *
2739     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2740     * out of the public fields to keep the undefined bits out of the developer's way.
2741     *
2742     * Flag to specify that the hidden status bar would like to be shown.
2743     */
2744    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2745
2746    /**
2747     * @hide
2748     *
2749     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2750     * out of the public fields to keep the undefined bits out of the developer's way.
2751     *
2752     * Flag to specify that the hidden navigation bar would like to be shown.
2753     */
2754    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2755
2756    /**
2757     * @hide
2758     *
2759     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2760     * out of the public fields to keep the undefined bits out of the developer's way.
2761     *
2762     * Flag to specify that the status bar is displayed in translucent mode.
2763     */
2764    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2765
2766    /**
2767     * @hide
2768     *
2769     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2770     * out of the public fields to keep the undefined bits out of the developer's way.
2771     *
2772     * Flag to specify that the navigation bar is displayed in translucent mode.
2773     */
2774    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2775
2776    /**
2777     * @hide
2778     *
2779     * Whether Recents is visible or not.
2780     */
2781    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2782
2783    /**
2784     * @hide
2785     *
2786     * Makes system ui transparent.
2787     */
2788    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2789
2790    /**
2791     * @hide
2792     */
2793    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2794
2795    /**
2796     * These are the system UI flags that can be cleared by events outside
2797     * of an application.  Currently this is just the ability to tap on the
2798     * screen while hiding the navigation bar to have it return.
2799     * @hide
2800     */
2801    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2802            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2803            | SYSTEM_UI_FLAG_FULLSCREEN;
2804
2805    /**
2806     * Flags that can impact the layout in relation to system UI.
2807     */
2808    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2809            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2810            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2811
2812    /** @hide */
2813    @IntDef(flag = true,
2814            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2815    @Retention(RetentionPolicy.SOURCE)
2816    public @interface FindViewFlags {}
2817
2818    /**
2819     * Find views that render the specified text.
2820     *
2821     * @see #findViewsWithText(ArrayList, CharSequence, int)
2822     */
2823    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2824
2825    /**
2826     * Find find views that contain the specified content description.
2827     *
2828     * @see #findViewsWithText(ArrayList, CharSequence, int)
2829     */
2830    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2831
2832    /**
2833     * Find views that contain {@link AccessibilityNodeProvider}. Such
2834     * a View is a root of virtual view hierarchy and may contain the searched
2835     * text. If this flag is set Views with providers are automatically
2836     * added and it is a responsibility of the client to call the APIs of
2837     * the provider to determine whether the virtual tree rooted at this View
2838     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2839     * representing the virtual views with this text.
2840     *
2841     * @see #findViewsWithText(ArrayList, CharSequence, int)
2842     *
2843     * @hide
2844     */
2845    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2846
2847    /**
2848     * The undefined cursor position.
2849     *
2850     * @hide
2851     */
2852    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2853
2854    /**
2855     * Indicates that the screen has changed state and is now off.
2856     *
2857     * @see #onScreenStateChanged(int)
2858     */
2859    public static final int SCREEN_STATE_OFF = 0x0;
2860
2861    /**
2862     * Indicates that the screen has changed state and is now on.
2863     *
2864     * @see #onScreenStateChanged(int)
2865     */
2866    public static final int SCREEN_STATE_ON = 0x1;
2867
2868    /**
2869     * Indicates no axis of view scrolling.
2870     */
2871    public static final int SCROLL_AXIS_NONE = 0;
2872
2873    /**
2874     * Indicates scrolling along the horizontal axis.
2875     */
2876    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2877
2878    /**
2879     * Indicates scrolling along the vertical axis.
2880     */
2881    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2882
2883    /**
2884     * Controls the over-scroll mode for this view.
2885     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2886     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2887     * and {@link #OVER_SCROLL_NEVER}.
2888     */
2889    private int mOverScrollMode;
2890
2891    /**
2892     * The parent this view is attached to.
2893     * {@hide}
2894     *
2895     * @see #getParent()
2896     */
2897    protected ViewParent mParent;
2898
2899    /**
2900     * {@hide}
2901     */
2902    AttachInfo mAttachInfo;
2903
2904    /**
2905     * {@hide}
2906     */
2907    @ViewDebug.ExportedProperty(flagMapping = {
2908        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2909                name = "FORCE_LAYOUT"),
2910        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2911                name = "LAYOUT_REQUIRED"),
2912        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2913            name = "DRAWING_CACHE_INVALID", outputIf = false),
2914        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2915        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2916        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2917        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2918    }, formatToHexString = true)
2919    int mPrivateFlags;
2920    int mPrivateFlags2;
2921    int mPrivateFlags3;
2922
2923    /**
2924     * This view's request for the visibility of the status bar.
2925     * @hide
2926     */
2927    @ViewDebug.ExportedProperty(flagMapping = {
2928        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2929                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2930                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2931        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2932                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2933                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2934        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2935                                equals = SYSTEM_UI_FLAG_VISIBLE,
2936                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2937    }, formatToHexString = true)
2938    int mSystemUiVisibility;
2939
2940    /**
2941     * Reference count for transient state.
2942     * @see #setHasTransientState(boolean)
2943     */
2944    int mTransientStateCount = 0;
2945
2946    /**
2947     * Count of how many windows this view has been attached to.
2948     */
2949    int mWindowAttachCount;
2950
2951    /**
2952     * The layout parameters associated with this view and used by the parent
2953     * {@link android.view.ViewGroup} to determine how this view should be
2954     * laid out.
2955     * {@hide}
2956     */
2957    protected ViewGroup.LayoutParams mLayoutParams;
2958
2959    /**
2960     * The view flags hold various views states.
2961     * {@hide}
2962     */
2963    @ViewDebug.ExportedProperty(formatToHexString = true)
2964    int mViewFlags;
2965
2966    static class TransformationInfo {
2967        /**
2968         * The transform matrix for the View. This transform is calculated internally
2969         * based on the translation, rotation, and scale properties.
2970         *
2971         * Do *not* use this variable directly; instead call getMatrix(), which will
2972         * load the value from the View's RenderNode.
2973         */
2974        private final Matrix mMatrix = new Matrix();
2975
2976        /**
2977         * The inverse transform matrix for the View. This transform is calculated
2978         * internally based on the translation, rotation, and scale properties.
2979         *
2980         * Do *not* use this variable directly; instead call getInverseMatrix(),
2981         * which will load the value from the View's RenderNode.
2982         */
2983        private Matrix mInverseMatrix;
2984
2985        /**
2986         * The opacity of the View. This is a value from 0 to 1, where 0 means
2987         * completely transparent and 1 means completely opaque.
2988         */
2989        @ViewDebug.ExportedProperty
2990        float mAlpha = 1f;
2991
2992        /**
2993         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2994         * property only used by transitions, which is composited with the other alpha
2995         * values to calculate the final visual alpha value.
2996         */
2997        float mTransitionAlpha = 1f;
2998    }
2999
3000    TransformationInfo mTransformationInfo;
3001
3002    /**
3003     * Current clip bounds. to which all drawing of this view are constrained.
3004     */
3005    Rect mClipBounds = null;
3006
3007    private boolean mLastIsOpaque;
3008
3009    /**
3010     * The distance in pixels from the left edge of this view's parent
3011     * to the left edge of this view.
3012     * {@hide}
3013     */
3014    @ViewDebug.ExportedProperty(category = "layout")
3015    protected int mLeft;
3016    /**
3017     * The distance in pixels from the left edge of this view's parent
3018     * to the right edge of this view.
3019     * {@hide}
3020     */
3021    @ViewDebug.ExportedProperty(category = "layout")
3022    protected int mRight;
3023    /**
3024     * The distance in pixels from the top edge of this view's parent
3025     * to the top edge of this view.
3026     * {@hide}
3027     */
3028    @ViewDebug.ExportedProperty(category = "layout")
3029    protected int mTop;
3030    /**
3031     * The distance in pixels from the top edge of this view's parent
3032     * to the bottom edge of this view.
3033     * {@hide}
3034     */
3035    @ViewDebug.ExportedProperty(category = "layout")
3036    protected int mBottom;
3037
3038    /**
3039     * The offset, in pixels, by which the content of this view is scrolled
3040     * horizontally.
3041     * {@hide}
3042     */
3043    @ViewDebug.ExportedProperty(category = "scrolling")
3044    protected int mScrollX;
3045    /**
3046     * The offset, in pixels, by which the content of this view is scrolled
3047     * vertically.
3048     * {@hide}
3049     */
3050    @ViewDebug.ExportedProperty(category = "scrolling")
3051    protected int mScrollY;
3052
3053    /**
3054     * The left padding in pixels, that is the distance in pixels between the
3055     * left edge of this view and the left edge of its content.
3056     * {@hide}
3057     */
3058    @ViewDebug.ExportedProperty(category = "padding")
3059    protected int mPaddingLeft = 0;
3060    /**
3061     * The right padding in pixels, that is the distance in pixels between the
3062     * right edge of this view and the right edge of its content.
3063     * {@hide}
3064     */
3065    @ViewDebug.ExportedProperty(category = "padding")
3066    protected int mPaddingRight = 0;
3067    /**
3068     * The top padding in pixels, that is the distance in pixels between the
3069     * top edge of this view and the top edge of its content.
3070     * {@hide}
3071     */
3072    @ViewDebug.ExportedProperty(category = "padding")
3073    protected int mPaddingTop;
3074    /**
3075     * The bottom padding in pixels, that is the distance in pixels between the
3076     * bottom edge of this view and the bottom edge of its content.
3077     * {@hide}
3078     */
3079    @ViewDebug.ExportedProperty(category = "padding")
3080    protected int mPaddingBottom;
3081
3082    /**
3083     * The layout insets in pixels, that is the distance in pixels between the
3084     * visible edges of this view its bounds.
3085     */
3086    private Insets mLayoutInsets;
3087
3088    /**
3089     * Briefly describes the view and is primarily used for accessibility support.
3090     */
3091    private CharSequence mContentDescription;
3092
3093    /**
3094     * Specifies the id of a view for which this view serves as a label for
3095     * accessibility purposes.
3096     */
3097    private int mLabelForId = View.NO_ID;
3098
3099    /**
3100     * Predicate for matching labeled view id with its label for
3101     * accessibility purposes.
3102     */
3103    private MatchLabelForPredicate mMatchLabelForPredicate;
3104
3105    /**
3106     * Specifies a view before which this one is visited in accessibility traversal.
3107     */
3108    private int mAccessibilityTraversalBeforeId = NO_ID;
3109
3110    /**
3111     * Specifies a view after which this one is visited in accessibility traversal.
3112     */
3113    private int mAccessibilityTraversalAfterId = NO_ID;
3114
3115    /**
3116     * Predicate for matching a view by its id.
3117     */
3118    private MatchIdPredicate mMatchIdPredicate;
3119
3120    /**
3121     * Cache the paddingRight set by the user to append to the scrollbar's size.
3122     *
3123     * @hide
3124     */
3125    @ViewDebug.ExportedProperty(category = "padding")
3126    protected int mUserPaddingRight;
3127
3128    /**
3129     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3130     *
3131     * @hide
3132     */
3133    @ViewDebug.ExportedProperty(category = "padding")
3134    protected int mUserPaddingBottom;
3135
3136    /**
3137     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3138     *
3139     * @hide
3140     */
3141    @ViewDebug.ExportedProperty(category = "padding")
3142    protected int mUserPaddingLeft;
3143
3144    /**
3145     * Cache the paddingStart set by the user to append to the scrollbar's size.
3146     *
3147     */
3148    @ViewDebug.ExportedProperty(category = "padding")
3149    int mUserPaddingStart;
3150
3151    /**
3152     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3153     *
3154     */
3155    @ViewDebug.ExportedProperty(category = "padding")
3156    int mUserPaddingEnd;
3157
3158    /**
3159     * Cache initial left padding.
3160     *
3161     * @hide
3162     */
3163    int mUserPaddingLeftInitial;
3164
3165    /**
3166     * Cache initial right padding.
3167     *
3168     * @hide
3169     */
3170    int mUserPaddingRightInitial;
3171
3172    /**
3173     * Default undefined padding
3174     */
3175    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3176
3177    /**
3178     * Cache if a left padding has been defined
3179     */
3180    private boolean mLeftPaddingDefined = false;
3181
3182    /**
3183     * Cache if a right padding has been defined
3184     */
3185    private boolean mRightPaddingDefined = false;
3186
3187    /**
3188     * @hide
3189     */
3190    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3191    /**
3192     * @hide
3193     */
3194    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3195
3196    private LongSparseLongArray mMeasureCache;
3197
3198    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3199    private Drawable mBackground;
3200    private TintInfo mBackgroundTint;
3201
3202    /**
3203     * RenderNode used for backgrounds.
3204     * <p>
3205     * When non-null and valid, this is expected to contain an up-to-date copy
3206     * of the background drawable. It is cleared on temporary detach, and reset
3207     * on cleanup.
3208     */
3209    private RenderNode mBackgroundRenderNode;
3210
3211    private int mBackgroundResource;
3212    private boolean mBackgroundSizeChanged;
3213
3214    private String mTransitionName;
3215
3216    private static class TintInfo {
3217        ColorStateList mTintList;
3218        PorterDuff.Mode mTintMode;
3219        boolean mHasTintMode;
3220        boolean mHasTintList;
3221    }
3222
3223    static class ListenerInfo {
3224        /**
3225         * Listener used to dispatch focus change events.
3226         * This field should be made private, so it is hidden from the SDK.
3227         * {@hide}
3228         */
3229        protected OnFocusChangeListener mOnFocusChangeListener;
3230
3231        /**
3232         * Listeners for layout change events.
3233         */
3234        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3235
3236        protected OnScrollChangeListener mOnScrollChangeListener;
3237
3238        /**
3239         * Listeners for attach events.
3240         */
3241        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3242
3243        /**
3244         * Listener used to dispatch click events.
3245         * This field should be made private, so it is hidden from the SDK.
3246         * {@hide}
3247         */
3248        public OnClickListener mOnClickListener;
3249
3250        /**
3251         * Listener used to dispatch long click events.
3252         * This field should be made private, so it is hidden from the SDK.
3253         * {@hide}
3254         */
3255        protected OnLongClickListener mOnLongClickListener;
3256
3257        /**
3258         * Listener used to build the context menu.
3259         * This field should be made private, so it is hidden from the SDK.
3260         * {@hide}
3261         */
3262        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3263
3264        private OnKeyListener mOnKeyListener;
3265
3266        private OnTouchListener mOnTouchListener;
3267
3268        private OnHoverListener mOnHoverListener;
3269
3270        private OnGenericMotionListener mOnGenericMotionListener;
3271
3272        private OnDragListener mOnDragListener;
3273
3274        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3275
3276        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3277    }
3278
3279    ListenerInfo mListenerInfo;
3280
3281    /**
3282     * The application environment this view lives in.
3283     * This field should be made private, so it is hidden from the SDK.
3284     * {@hide}
3285     */
3286    @ViewDebug.ExportedProperty(deepExport = true)
3287    protected Context mContext;
3288
3289    private final Resources mResources;
3290
3291    private ScrollabilityCache mScrollCache;
3292
3293    private int[] mDrawableState = null;
3294
3295    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3296
3297    /**
3298     * Animator that automatically runs based on state changes.
3299     */
3300    private StateListAnimator mStateListAnimator;
3301
3302    /**
3303     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3304     * the user may specify which view to go to next.
3305     */
3306    private int mNextFocusLeftId = View.NO_ID;
3307
3308    /**
3309     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3310     * the user may specify which view to go to next.
3311     */
3312    private int mNextFocusRightId = View.NO_ID;
3313
3314    /**
3315     * When this view has focus and the next focus is {@link #FOCUS_UP},
3316     * the user may specify which view to go to next.
3317     */
3318    private int mNextFocusUpId = View.NO_ID;
3319
3320    /**
3321     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3322     * the user may specify which view to go to next.
3323     */
3324    private int mNextFocusDownId = View.NO_ID;
3325
3326    /**
3327     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3328     * the user may specify which view to go to next.
3329     */
3330    int mNextFocusForwardId = View.NO_ID;
3331
3332    private CheckForLongPress mPendingCheckForLongPress;
3333    private CheckForTap mPendingCheckForTap = null;
3334    private PerformClick mPerformClick;
3335    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3336
3337    private UnsetPressedState mUnsetPressedState;
3338
3339    /**
3340     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3341     * up event while a long press is invoked as soon as the long press duration is reached, so
3342     * a long press could be performed before the tap is checked, in which case the tap's action
3343     * should not be invoked.
3344     */
3345    private boolean mHasPerformedLongPress;
3346
3347    /**
3348     * The minimum height of the view. We'll try our best to have the height
3349     * of this view to at least this amount.
3350     */
3351    @ViewDebug.ExportedProperty(category = "measurement")
3352    private int mMinHeight;
3353
3354    /**
3355     * The minimum width of the view. We'll try our best to have the width
3356     * of this view to at least this amount.
3357     */
3358    @ViewDebug.ExportedProperty(category = "measurement")
3359    private int mMinWidth;
3360
3361    /**
3362     * The delegate to handle touch events that are physically in this view
3363     * but should be handled by another view.
3364     */
3365    private TouchDelegate mTouchDelegate = null;
3366
3367    /**
3368     * Solid color to use as a background when creating the drawing cache. Enables
3369     * the cache to use 16 bit bitmaps instead of 32 bit.
3370     */
3371    private int mDrawingCacheBackgroundColor = 0;
3372
3373    /**
3374     * Special tree observer used when mAttachInfo is null.
3375     */
3376    private ViewTreeObserver mFloatingTreeObserver;
3377
3378    /**
3379     * Cache the touch slop from the context that created the view.
3380     */
3381    private int mTouchSlop;
3382
3383    /**
3384     * Object that handles automatic animation of view properties.
3385     */
3386    private ViewPropertyAnimator mAnimator = null;
3387
3388    /**
3389     * Flag indicating that a drag can cross window boundaries.  When
3390     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3391     * with this flag set, all visible applications will be able to participate
3392     * in the drag operation and receive the dragged content.
3393     *
3394     * @hide
3395     */
3396    public static final int DRAG_FLAG_GLOBAL = 1;
3397
3398    /**
3399     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3400     */
3401    private float mVerticalScrollFactor;
3402
3403    /**
3404     * Position of the vertical scroll bar.
3405     */
3406    private int mVerticalScrollbarPosition;
3407
3408    /**
3409     * Position the scroll bar at the default position as determined by the system.
3410     */
3411    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3412
3413    /**
3414     * Position the scroll bar along the left edge.
3415     */
3416    public static final int SCROLLBAR_POSITION_LEFT = 1;
3417
3418    /**
3419     * Position the scroll bar along the right edge.
3420     */
3421    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3422
3423    /**
3424     * Indicates that the view does not have a layer.
3425     *
3426     * @see #getLayerType()
3427     * @see #setLayerType(int, android.graphics.Paint)
3428     * @see #LAYER_TYPE_SOFTWARE
3429     * @see #LAYER_TYPE_HARDWARE
3430     */
3431    public static final int LAYER_TYPE_NONE = 0;
3432
3433    /**
3434     * <p>Indicates that the view has a software layer. A software layer is backed
3435     * by a bitmap and causes the view to be rendered using Android's software
3436     * rendering pipeline, even if hardware acceleration is enabled.</p>
3437     *
3438     * <p>Software layers have various usages:</p>
3439     * <p>When the application is not using hardware acceleration, a software layer
3440     * is useful to apply a specific color filter and/or blending mode and/or
3441     * translucency to a view and all its children.</p>
3442     * <p>When the application is using hardware acceleration, a software layer
3443     * is useful to render drawing primitives not supported by the hardware
3444     * accelerated pipeline. It can also be used to cache a complex view tree
3445     * into a texture and reduce the complexity of drawing operations. For instance,
3446     * when animating a complex view tree with a translation, a software layer can
3447     * be used to render the view tree only once.</p>
3448     * <p>Software layers should be avoided when the affected view tree updates
3449     * often. Every update will require to re-render the software layer, which can
3450     * potentially be slow (particularly when hardware acceleration is turned on
3451     * since the layer will have to be uploaded into a hardware texture after every
3452     * update.)</p>
3453     *
3454     * @see #getLayerType()
3455     * @see #setLayerType(int, android.graphics.Paint)
3456     * @see #LAYER_TYPE_NONE
3457     * @see #LAYER_TYPE_HARDWARE
3458     */
3459    public static final int LAYER_TYPE_SOFTWARE = 1;
3460
3461    /**
3462     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3463     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3464     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3465     * rendering pipeline, but only if hardware acceleration is turned on for the
3466     * view hierarchy. When hardware acceleration is turned off, hardware layers
3467     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3468     *
3469     * <p>A hardware layer is useful to apply a specific color filter and/or
3470     * blending mode and/or translucency to a view and all its children.</p>
3471     * <p>A hardware layer can be used to cache a complex view tree into a
3472     * texture and reduce the complexity of drawing operations. For instance,
3473     * when animating a complex view tree with a translation, a hardware layer can
3474     * be used to render the view tree only once.</p>
3475     * <p>A hardware layer can also be used to increase the rendering quality when
3476     * rotation transformations are applied on a view. It can also be used to
3477     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3478     *
3479     * @see #getLayerType()
3480     * @see #setLayerType(int, android.graphics.Paint)
3481     * @see #LAYER_TYPE_NONE
3482     * @see #LAYER_TYPE_SOFTWARE
3483     */
3484    public static final int LAYER_TYPE_HARDWARE = 2;
3485
3486    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3487            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3488            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3489            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3490    })
3491    int mLayerType = LAYER_TYPE_NONE;
3492    Paint mLayerPaint;
3493
3494    /**
3495     * Set to true when drawing cache is enabled and cannot be created.
3496     *
3497     * @hide
3498     */
3499    public boolean mCachingFailed;
3500    private Bitmap mDrawingCache;
3501    private Bitmap mUnscaledDrawingCache;
3502
3503    /**
3504     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3505     * <p>
3506     * When non-null and valid, this is expected to contain an up-to-date copy
3507     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3508     * cleanup.
3509     */
3510    final RenderNode mRenderNode;
3511
3512    /**
3513     * Set to true when the view is sending hover accessibility events because it
3514     * is the innermost hovered view.
3515     */
3516    private boolean mSendingHoverAccessibilityEvents;
3517
3518    /**
3519     * Delegate for injecting accessibility functionality.
3520     */
3521    AccessibilityDelegate mAccessibilityDelegate;
3522
3523    /**
3524     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3525     * and add/remove objects to/from the overlay directly through the Overlay methods.
3526     */
3527    ViewOverlay mOverlay;
3528
3529    /**
3530     * The currently active parent view for receiving delegated nested scrolling events.
3531     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3532     * by {@link #stopNestedScroll()} at the same point where we clear
3533     * requestDisallowInterceptTouchEvent.
3534     */
3535    private ViewParent mNestedScrollingParent;
3536
3537    /**
3538     * Consistency verifier for debugging purposes.
3539     * @hide
3540     */
3541    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3542            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3543                    new InputEventConsistencyVerifier(this, 0) : null;
3544
3545    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3546
3547    private int[] mTempNestedScrollConsumed;
3548
3549    /**
3550     * An overlay is going to draw this View instead of being drawn as part of this
3551     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3552     * when this view is invalidated.
3553     */
3554    GhostView mGhostView;
3555
3556    /**
3557     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3558     * @hide
3559     */
3560    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3561    public String[] mAttributes;
3562
3563    /**
3564     * Maps a Resource id to its name.
3565     */
3566    private static SparseArray<String> mAttributeMap;
3567
3568    /**
3569     * Simple constructor to use when creating a view from code.
3570     *
3571     * @param context The Context the view is running in, through which it can
3572     *        access the current theme, resources, etc.
3573     */
3574    public View(Context context) {
3575        mContext = context;
3576        mResources = context != null ? context.getResources() : null;
3577        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3578        // Set some flags defaults
3579        mPrivateFlags2 =
3580                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3581                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3582                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3583                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3584                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3585                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3586        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3587        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3588        mUserPaddingStart = UNDEFINED_PADDING;
3589        mUserPaddingEnd = UNDEFINED_PADDING;
3590        mRenderNode = RenderNode.create(getClass().getName(), this);
3591
3592        if (!sCompatibilityDone && context != null) {
3593            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3594
3595            // Older apps may need this compatibility hack for measurement.
3596            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3597
3598            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3599            // of whether a layout was requested on that View.
3600            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3601
3602            sCompatibilityDone = true;
3603        }
3604    }
3605
3606    /**
3607     * Constructor that is called when inflating a view from XML. This is called
3608     * when a view is being constructed from an XML file, supplying attributes
3609     * that were specified in the XML file. This version uses a default style of
3610     * 0, so the only attribute values applied are those in the Context's Theme
3611     * and the given AttributeSet.
3612     *
3613     * <p>
3614     * The method onFinishInflate() will be called after all children have been
3615     * added.
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     * @see #View(Context, AttributeSet, int)
3621     */
3622    public View(Context context, AttributeSet attrs) {
3623        this(context, attrs, 0);
3624    }
3625
3626    /**
3627     * Perform inflation from XML and apply a class-specific base style from a
3628     * theme attribute. This constructor of View allows subclasses to use their
3629     * own base style when they are inflating. For example, a Button class's
3630     * constructor would call this version of the super class constructor and
3631     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3632     * allows the theme's button style to modify all of the base view attributes
3633     * (in particular its background) as well as the Button class's attributes.
3634     *
3635     * @param context The Context the view is running in, through which it can
3636     *        access the current theme, resources, etc.
3637     * @param attrs The attributes of the XML tag that is inflating the view.
3638     * @param defStyleAttr An attribute in the current theme that contains a
3639     *        reference to a style resource that supplies default values for
3640     *        the view. Can be 0 to not look for defaults.
3641     * @see #View(Context, AttributeSet)
3642     */
3643    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3644        this(context, attrs, defStyleAttr, 0);
3645    }
3646
3647    /**
3648     * Perform inflation from XML and apply a class-specific base style from a
3649     * theme attribute or style resource. This constructor of View allows
3650     * subclasses to use their own base style when they are inflating.
3651     * <p>
3652     * When determining the final value of a particular attribute, there are
3653     * four inputs that come into play:
3654     * <ol>
3655     * <li>Any attribute values in the given AttributeSet.
3656     * <li>The style resource specified in the AttributeSet (named "style").
3657     * <li>The default style specified by <var>defStyleAttr</var>.
3658     * <li>The default style specified by <var>defStyleRes</var>.
3659     * <li>The base values in this theme.
3660     * </ol>
3661     * <p>
3662     * Each of these inputs is considered in-order, with the first listed taking
3663     * precedence over the following ones. In other words, if in the
3664     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3665     * , then the button's text will <em>always</em> be black, regardless of
3666     * what is specified in any of the styles.
3667     *
3668     * @param context The Context the view is running in, through which it can
3669     *        access the current theme, resources, etc.
3670     * @param attrs The attributes of the XML tag that is inflating the view.
3671     * @param defStyleAttr An attribute in the current theme that contains a
3672     *        reference to a style resource that supplies default values for
3673     *        the view. Can be 0 to not look for defaults.
3674     * @param defStyleRes A resource identifier of a style resource that
3675     *        supplies default values for the view, used only if
3676     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3677     *        to not look for defaults.
3678     * @see #View(Context, AttributeSet, int)
3679     */
3680    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3681        this(context);
3682
3683        final TypedArray a = context.obtainStyledAttributes(
3684                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3685
3686        if (mDebugViewAttributes) {
3687            saveAttributeData(attrs, a);
3688        }
3689
3690        Drawable background = null;
3691
3692        int leftPadding = -1;
3693        int topPadding = -1;
3694        int rightPadding = -1;
3695        int bottomPadding = -1;
3696        int startPadding = UNDEFINED_PADDING;
3697        int endPadding = UNDEFINED_PADDING;
3698
3699        int padding = -1;
3700
3701        int viewFlagValues = 0;
3702        int viewFlagMasks = 0;
3703
3704        boolean setScrollContainer = false;
3705
3706        int x = 0;
3707        int y = 0;
3708
3709        float tx = 0;
3710        float ty = 0;
3711        float tz = 0;
3712        float elevation = 0;
3713        float rotation = 0;
3714        float rotationX = 0;
3715        float rotationY = 0;
3716        float sx = 1f;
3717        float sy = 1f;
3718        boolean transformSet = false;
3719
3720        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3721        int overScrollMode = mOverScrollMode;
3722        boolean initializeScrollbars = false;
3723
3724        boolean startPaddingDefined = false;
3725        boolean endPaddingDefined = false;
3726        boolean leftPaddingDefined = false;
3727        boolean rightPaddingDefined = false;
3728
3729        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3730
3731        final int N = a.getIndexCount();
3732        for (int i = 0; i < N; i++) {
3733            int attr = a.getIndex(i);
3734            switch (attr) {
3735                case com.android.internal.R.styleable.View_background:
3736                    background = a.getDrawable(attr);
3737                    break;
3738                case com.android.internal.R.styleable.View_padding:
3739                    padding = a.getDimensionPixelSize(attr, -1);
3740                    mUserPaddingLeftInitial = padding;
3741                    mUserPaddingRightInitial = padding;
3742                    leftPaddingDefined = true;
3743                    rightPaddingDefined = true;
3744                    break;
3745                 case com.android.internal.R.styleable.View_paddingLeft:
3746                    leftPadding = a.getDimensionPixelSize(attr, -1);
3747                    mUserPaddingLeftInitial = leftPadding;
3748                    leftPaddingDefined = true;
3749                    break;
3750                case com.android.internal.R.styleable.View_paddingTop:
3751                    topPadding = a.getDimensionPixelSize(attr, -1);
3752                    break;
3753                case com.android.internal.R.styleable.View_paddingRight:
3754                    rightPadding = a.getDimensionPixelSize(attr, -1);
3755                    mUserPaddingRightInitial = rightPadding;
3756                    rightPaddingDefined = true;
3757                    break;
3758                case com.android.internal.R.styleable.View_paddingBottom:
3759                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3760                    break;
3761                case com.android.internal.R.styleable.View_paddingStart:
3762                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3763                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3764                    break;
3765                case com.android.internal.R.styleable.View_paddingEnd:
3766                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3767                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3768                    break;
3769                case com.android.internal.R.styleable.View_scrollX:
3770                    x = a.getDimensionPixelOffset(attr, 0);
3771                    break;
3772                case com.android.internal.R.styleable.View_scrollY:
3773                    y = a.getDimensionPixelOffset(attr, 0);
3774                    break;
3775                case com.android.internal.R.styleable.View_alpha:
3776                    setAlpha(a.getFloat(attr, 1f));
3777                    break;
3778                case com.android.internal.R.styleable.View_transformPivotX:
3779                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3780                    break;
3781                case com.android.internal.R.styleable.View_transformPivotY:
3782                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3783                    break;
3784                case com.android.internal.R.styleable.View_translationX:
3785                    tx = a.getDimensionPixelOffset(attr, 0);
3786                    transformSet = true;
3787                    break;
3788                case com.android.internal.R.styleable.View_translationY:
3789                    ty = a.getDimensionPixelOffset(attr, 0);
3790                    transformSet = true;
3791                    break;
3792                case com.android.internal.R.styleable.View_translationZ:
3793                    tz = a.getDimensionPixelOffset(attr, 0);
3794                    transformSet = true;
3795                    break;
3796                case com.android.internal.R.styleable.View_elevation:
3797                    elevation = a.getDimensionPixelOffset(attr, 0);
3798                    transformSet = true;
3799                    break;
3800                case com.android.internal.R.styleable.View_rotation:
3801                    rotation = a.getFloat(attr, 0);
3802                    transformSet = true;
3803                    break;
3804                case com.android.internal.R.styleable.View_rotationX:
3805                    rotationX = a.getFloat(attr, 0);
3806                    transformSet = true;
3807                    break;
3808                case com.android.internal.R.styleable.View_rotationY:
3809                    rotationY = a.getFloat(attr, 0);
3810                    transformSet = true;
3811                    break;
3812                case com.android.internal.R.styleable.View_scaleX:
3813                    sx = a.getFloat(attr, 1f);
3814                    transformSet = true;
3815                    break;
3816                case com.android.internal.R.styleable.View_scaleY:
3817                    sy = a.getFloat(attr, 1f);
3818                    transformSet = true;
3819                    break;
3820                case com.android.internal.R.styleable.View_id:
3821                    mID = a.getResourceId(attr, NO_ID);
3822                    break;
3823                case com.android.internal.R.styleable.View_tag:
3824                    mTag = a.getText(attr);
3825                    break;
3826                case com.android.internal.R.styleable.View_fitsSystemWindows:
3827                    if (a.getBoolean(attr, false)) {
3828                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3829                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3830                    }
3831                    break;
3832                case com.android.internal.R.styleable.View_focusable:
3833                    if (a.getBoolean(attr, false)) {
3834                        viewFlagValues |= FOCUSABLE;
3835                        viewFlagMasks |= FOCUSABLE_MASK;
3836                    }
3837                    break;
3838                case com.android.internal.R.styleable.View_focusableInTouchMode:
3839                    if (a.getBoolean(attr, false)) {
3840                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3841                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3842                    }
3843                    break;
3844                case com.android.internal.R.styleable.View_clickable:
3845                    if (a.getBoolean(attr, false)) {
3846                        viewFlagValues |= CLICKABLE;
3847                        viewFlagMasks |= CLICKABLE;
3848                    }
3849                    break;
3850                case com.android.internal.R.styleable.View_longClickable:
3851                    if (a.getBoolean(attr, false)) {
3852                        viewFlagValues |= LONG_CLICKABLE;
3853                        viewFlagMasks |= LONG_CLICKABLE;
3854                    }
3855                    break;
3856                case com.android.internal.R.styleable.View_saveEnabled:
3857                    if (!a.getBoolean(attr, true)) {
3858                        viewFlagValues |= SAVE_DISABLED;
3859                        viewFlagMasks |= SAVE_DISABLED_MASK;
3860                    }
3861                    break;
3862                case com.android.internal.R.styleable.View_duplicateParentState:
3863                    if (a.getBoolean(attr, false)) {
3864                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3865                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3866                    }
3867                    break;
3868                case com.android.internal.R.styleable.View_visibility:
3869                    final int visibility = a.getInt(attr, 0);
3870                    if (visibility != 0) {
3871                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3872                        viewFlagMasks |= VISIBILITY_MASK;
3873                    }
3874                    break;
3875                case com.android.internal.R.styleable.View_layoutDirection:
3876                    // Clear any layout direction flags (included resolved bits) already set
3877                    mPrivateFlags2 &=
3878                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3879                    // Set the layout direction flags depending on the value of the attribute
3880                    final int layoutDirection = a.getInt(attr, -1);
3881                    final int value = (layoutDirection != -1) ?
3882                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3883                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3884                    break;
3885                case com.android.internal.R.styleable.View_drawingCacheQuality:
3886                    final int cacheQuality = a.getInt(attr, 0);
3887                    if (cacheQuality != 0) {
3888                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3889                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3890                    }
3891                    break;
3892                case com.android.internal.R.styleable.View_contentDescription:
3893                    setContentDescription(a.getString(attr));
3894                    break;
3895                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3896                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3897                    break;
3898                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3899                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3900                    break;
3901                case com.android.internal.R.styleable.View_labelFor:
3902                    setLabelFor(a.getResourceId(attr, NO_ID));
3903                    break;
3904                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3905                    if (!a.getBoolean(attr, true)) {
3906                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3907                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3908                    }
3909                    break;
3910                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3911                    if (!a.getBoolean(attr, true)) {
3912                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3913                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3914                    }
3915                    break;
3916                case R.styleable.View_scrollbars:
3917                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3918                    if (scrollbars != SCROLLBARS_NONE) {
3919                        viewFlagValues |= scrollbars;
3920                        viewFlagMasks |= SCROLLBARS_MASK;
3921                        initializeScrollbars = true;
3922                    }
3923                    break;
3924                //noinspection deprecation
3925                case R.styleable.View_fadingEdge:
3926                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3927                        // Ignore the attribute starting with ICS
3928                        break;
3929                    }
3930                    // With builds < ICS, fall through and apply fading edges
3931                case R.styleable.View_requiresFadingEdge:
3932                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3933                    if (fadingEdge != FADING_EDGE_NONE) {
3934                        viewFlagValues |= fadingEdge;
3935                        viewFlagMasks |= FADING_EDGE_MASK;
3936                        initializeFadingEdgeInternal(a);
3937                    }
3938                    break;
3939                case R.styleable.View_scrollbarStyle:
3940                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3941                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3942                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3943                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3944                    }
3945                    break;
3946                case R.styleable.View_isScrollContainer:
3947                    setScrollContainer = true;
3948                    if (a.getBoolean(attr, false)) {
3949                        setScrollContainer(true);
3950                    }
3951                    break;
3952                case com.android.internal.R.styleable.View_keepScreenOn:
3953                    if (a.getBoolean(attr, false)) {
3954                        viewFlagValues |= KEEP_SCREEN_ON;
3955                        viewFlagMasks |= KEEP_SCREEN_ON;
3956                    }
3957                    break;
3958                case R.styleable.View_filterTouchesWhenObscured:
3959                    if (a.getBoolean(attr, false)) {
3960                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3961                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3962                    }
3963                    break;
3964                case R.styleable.View_nextFocusLeft:
3965                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3966                    break;
3967                case R.styleable.View_nextFocusRight:
3968                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3969                    break;
3970                case R.styleable.View_nextFocusUp:
3971                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3972                    break;
3973                case R.styleable.View_nextFocusDown:
3974                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3975                    break;
3976                case R.styleable.View_nextFocusForward:
3977                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3978                    break;
3979                case R.styleable.View_minWidth:
3980                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3981                    break;
3982                case R.styleable.View_minHeight:
3983                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3984                    break;
3985                case R.styleable.View_onClick:
3986                    if (context.isRestricted()) {
3987                        throw new IllegalStateException("The android:onClick attribute cannot "
3988                                + "be used within a restricted context");
3989                    }
3990
3991                    final String handlerName = a.getString(attr);
3992                    if (handlerName != null) {
3993                        setOnClickListener(new OnClickListener() {
3994                            private Method mHandler;
3995
3996                            public void onClick(View v) {
3997                                if (mHandler == null) {
3998                                    try {
3999                                        mHandler = getContext().getClass().getMethod(handlerName,
4000                                                View.class);
4001                                    } catch (NoSuchMethodException e) {
4002                                        int id = getId();
4003                                        String idText = id == NO_ID ? "" : " with id '"
4004                                                + getContext().getResources().getResourceEntryName(
4005                                                    id) + "'";
4006                                        throw new IllegalStateException("Could not find a method " +
4007                                                handlerName + "(View) in the activity "
4008                                                + getContext().getClass() + " for onClick handler"
4009                                                + " on view " + View.this.getClass() + idText, e);
4010                                    }
4011                                }
4012
4013                                try {
4014                                    mHandler.invoke(getContext(), View.this);
4015                                } catch (IllegalAccessException e) {
4016                                    throw new IllegalStateException("Could not execute non "
4017                                            + "public method of the activity", e);
4018                                } catch (InvocationTargetException e) {
4019                                    throw new IllegalStateException("Could not execute "
4020                                            + "method of the activity", e);
4021                                }
4022                            }
4023                        });
4024                    }
4025                    break;
4026                case R.styleable.View_overScrollMode:
4027                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4028                    break;
4029                case R.styleable.View_verticalScrollbarPosition:
4030                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4031                    break;
4032                case R.styleable.View_layerType:
4033                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4034                    break;
4035                case R.styleable.View_textDirection:
4036                    // Clear any text direction flag already set
4037                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4038                    // Set the text direction flags depending on the value of the attribute
4039                    final int textDirection = a.getInt(attr, -1);
4040                    if (textDirection != -1) {
4041                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4042                    }
4043                    break;
4044                case R.styleable.View_textAlignment:
4045                    // Clear any text alignment flag already set
4046                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4047                    // Set the text alignment flag depending on the value of the attribute
4048                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4049                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4050                    break;
4051                case R.styleable.View_importantForAccessibility:
4052                    setImportantForAccessibility(a.getInt(attr,
4053                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4054                    break;
4055                case R.styleable.View_accessibilityLiveRegion:
4056                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4057                    break;
4058                case R.styleable.View_transitionName:
4059                    setTransitionName(a.getString(attr));
4060                    break;
4061                case R.styleable.View_nestedScrollingEnabled:
4062                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4063                    break;
4064                case R.styleable.View_stateListAnimator:
4065                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4066                            a.getResourceId(attr, 0)));
4067                    break;
4068                case R.styleable.View_backgroundTint:
4069                    // This will get applied later during setBackground().
4070                    if (mBackgroundTint == null) {
4071                        mBackgroundTint = new TintInfo();
4072                    }
4073                    mBackgroundTint.mTintList = a.getColorStateList(
4074                            R.styleable.View_backgroundTint);
4075                    mBackgroundTint.mHasTintList = true;
4076                    break;
4077                case R.styleable.View_backgroundTintMode:
4078                    // This will get applied later during setBackground().
4079                    if (mBackgroundTint == null) {
4080                        mBackgroundTint = new TintInfo();
4081                    }
4082                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4083                            R.styleable.View_backgroundTintMode, -1), null);
4084                    mBackgroundTint.mHasTintMode = true;
4085                    break;
4086                case R.styleable.View_outlineProvider:
4087                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4088                            PROVIDER_BACKGROUND));
4089                    break;
4090            }
4091        }
4092
4093        setOverScrollMode(overScrollMode);
4094
4095        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4096        // the resolved layout direction). Those cached values will be used later during padding
4097        // resolution.
4098        mUserPaddingStart = startPadding;
4099        mUserPaddingEnd = endPadding;
4100
4101        if (background != null) {
4102            setBackground(background);
4103        }
4104
4105        // setBackground above will record that padding is currently provided by the background.
4106        // If we have padding specified via xml, record that here instead and use it.
4107        mLeftPaddingDefined = leftPaddingDefined;
4108        mRightPaddingDefined = rightPaddingDefined;
4109
4110        if (padding >= 0) {
4111            leftPadding = padding;
4112            topPadding = padding;
4113            rightPadding = padding;
4114            bottomPadding = padding;
4115            mUserPaddingLeftInitial = padding;
4116            mUserPaddingRightInitial = padding;
4117        }
4118
4119        if (isRtlCompatibilityMode()) {
4120            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4121            // left / right padding are used if defined (meaning here nothing to do). If they are not
4122            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4123            // start / end and resolve them as left / right (layout direction is not taken into account).
4124            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4125            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4126            // defined.
4127            if (!mLeftPaddingDefined && startPaddingDefined) {
4128                leftPadding = startPadding;
4129            }
4130            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4131            if (!mRightPaddingDefined && endPaddingDefined) {
4132                rightPadding = endPadding;
4133            }
4134            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4135        } else {
4136            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4137            // values defined. Otherwise, left /right values are used.
4138            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4139            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4140            // defined.
4141            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4142
4143            if (mLeftPaddingDefined && !hasRelativePadding) {
4144                mUserPaddingLeftInitial = leftPadding;
4145            }
4146            if (mRightPaddingDefined && !hasRelativePadding) {
4147                mUserPaddingRightInitial = rightPadding;
4148            }
4149        }
4150
4151        internalSetPadding(
4152                mUserPaddingLeftInitial,
4153                topPadding >= 0 ? topPadding : mPaddingTop,
4154                mUserPaddingRightInitial,
4155                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4156
4157        if (viewFlagMasks != 0) {
4158            setFlags(viewFlagValues, viewFlagMasks);
4159        }
4160
4161        if (initializeScrollbars) {
4162            initializeScrollbarsInternal(a);
4163        }
4164
4165        a.recycle();
4166
4167        // Needs to be called after mViewFlags is set
4168        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4169            recomputePadding();
4170        }
4171
4172        if (x != 0 || y != 0) {
4173            scrollTo(x, y);
4174        }
4175
4176        if (transformSet) {
4177            setTranslationX(tx);
4178            setTranslationY(ty);
4179            setTranslationZ(tz);
4180            setElevation(elevation);
4181            setRotation(rotation);
4182            setRotationX(rotationX);
4183            setRotationY(rotationY);
4184            setScaleX(sx);
4185            setScaleY(sy);
4186        }
4187
4188        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4189            setScrollContainer(true);
4190        }
4191
4192        computeOpaqueFlags();
4193    }
4194
4195    /**
4196     * Non-public constructor for use in testing
4197     */
4198    View() {
4199        mResources = null;
4200        mRenderNode = RenderNode.create(getClass().getName(), this);
4201    }
4202
4203    private static SparseArray<String> getAttributeMap() {
4204        if (mAttributeMap == null) {
4205            mAttributeMap = new SparseArray<String>();
4206        }
4207        return mAttributeMap;
4208    }
4209
4210    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4211        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4212        mAttributes = new String[length];
4213
4214        int i = 0;
4215        if (attrs != null) {
4216            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4217                mAttributes[i] = attrs.getAttributeName(i);
4218                mAttributes[i + 1] = attrs.getAttributeValue(i);
4219            }
4220
4221        }
4222
4223        SparseArray<String> attributeMap = getAttributeMap();
4224        for (int j = 0; j < a.length(); ++j) {
4225            if (a.hasValue(j)) {
4226                try {
4227                    int resourceId = a.getResourceId(j, 0);
4228                    if (resourceId == 0) {
4229                        continue;
4230                    }
4231
4232                    String resourceName = attributeMap.get(resourceId);
4233                    if (resourceName == null) {
4234                        resourceName = a.getResources().getResourceName(resourceId);
4235                        attributeMap.put(resourceId, resourceName);
4236                    }
4237
4238                    mAttributes[i] = resourceName;
4239                    mAttributes[i + 1] = a.getText(j).toString();
4240                    i += 2;
4241                } catch (Resources.NotFoundException e) {
4242                    // if we can't get the resource name, we just ignore it
4243                }
4244            }
4245        }
4246    }
4247
4248    public String toString() {
4249        StringBuilder out = new StringBuilder(128);
4250        out.append(getClass().getName());
4251        out.append('{');
4252        out.append(Integer.toHexString(System.identityHashCode(this)));
4253        out.append(' ');
4254        switch (mViewFlags&VISIBILITY_MASK) {
4255            case VISIBLE: out.append('V'); break;
4256            case INVISIBLE: out.append('I'); break;
4257            case GONE: out.append('G'); break;
4258            default: out.append('.'); break;
4259        }
4260        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4261        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4262        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4263        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4264        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4265        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4266        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4267        out.append(' ');
4268        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4269        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4270        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4271        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4272            out.append('p');
4273        } else {
4274            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4275        }
4276        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4277        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4278        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4279        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4280        out.append(' ');
4281        out.append(mLeft);
4282        out.append(',');
4283        out.append(mTop);
4284        out.append('-');
4285        out.append(mRight);
4286        out.append(',');
4287        out.append(mBottom);
4288        final int id = getId();
4289        if (id != NO_ID) {
4290            out.append(" #");
4291            out.append(Integer.toHexString(id));
4292            final Resources r = mResources;
4293            if (Resources.resourceHasPackage(id) && r != null) {
4294                try {
4295                    String pkgname;
4296                    switch (id&0xff000000) {
4297                        case 0x7f000000:
4298                            pkgname="app";
4299                            break;
4300                        case 0x01000000:
4301                            pkgname="android";
4302                            break;
4303                        default:
4304                            pkgname = r.getResourcePackageName(id);
4305                            break;
4306                    }
4307                    String typename = r.getResourceTypeName(id);
4308                    String entryname = r.getResourceEntryName(id);
4309                    out.append(" ");
4310                    out.append(pkgname);
4311                    out.append(":");
4312                    out.append(typename);
4313                    out.append("/");
4314                    out.append(entryname);
4315                } catch (Resources.NotFoundException e) {
4316                }
4317            }
4318        }
4319        out.append("}");
4320        return out.toString();
4321    }
4322
4323    /**
4324     * <p>
4325     * Initializes the fading edges from a given set of styled attributes. This
4326     * method should be called by subclasses that need fading edges and when an
4327     * instance of these subclasses is created programmatically rather than
4328     * being inflated from XML. This method is automatically called when the XML
4329     * is inflated.
4330     * </p>
4331     *
4332     * @param a the styled attributes set to initialize the fading edges from
4333     *
4334     * @removed
4335     */
4336    protected void initializeFadingEdge(TypedArray a) {
4337        // This method probably shouldn't have been included in the SDK to begin with.
4338        // It relies on 'a' having been initialized using an attribute filter array that is
4339        // not publicly available to the SDK. The old method has been renamed
4340        // to initializeFadingEdgeInternal and hidden for framework use only;
4341        // this one initializes using defaults to make it safe to call for apps.
4342
4343        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4344
4345        initializeFadingEdgeInternal(arr);
4346
4347        arr.recycle();
4348    }
4349
4350    /**
4351     * <p>
4352     * Initializes the fading edges from a given set of styled attributes. This
4353     * method should be called by subclasses that need fading edges and when an
4354     * instance of these subclasses is created programmatically rather than
4355     * being inflated from XML. This method is automatically called when the XML
4356     * is inflated.
4357     * </p>
4358     *
4359     * @param a the styled attributes set to initialize the fading edges from
4360     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4361     */
4362    protected void initializeFadingEdgeInternal(TypedArray a) {
4363        initScrollCache();
4364
4365        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4366                R.styleable.View_fadingEdgeLength,
4367                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4368    }
4369
4370    /**
4371     * Returns the size of the vertical faded edges used to indicate that more
4372     * content in this view is visible.
4373     *
4374     * @return The size in pixels of the vertical faded edge or 0 if vertical
4375     *         faded edges are not enabled for this view.
4376     * @attr ref android.R.styleable#View_fadingEdgeLength
4377     */
4378    public int getVerticalFadingEdgeLength() {
4379        if (isVerticalFadingEdgeEnabled()) {
4380            ScrollabilityCache cache = mScrollCache;
4381            if (cache != null) {
4382                return cache.fadingEdgeLength;
4383            }
4384        }
4385        return 0;
4386    }
4387
4388    /**
4389     * Set the size of the faded edge used to indicate that more content in this
4390     * view is available.  Will not change whether the fading edge is enabled; use
4391     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4392     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4393     * for the vertical or horizontal fading edges.
4394     *
4395     * @param length The size in pixels of the faded edge used to indicate that more
4396     *        content in this view is visible.
4397     */
4398    public void setFadingEdgeLength(int length) {
4399        initScrollCache();
4400        mScrollCache.fadingEdgeLength = length;
4401    }
4402
4403    /**
4404     * Returns the size of the horizontal faded edges used to indicate that more
4405     * content in this view is visible.
4406     *
4407     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4408     *         faded edges are not enabled for this view.
4409     * @attr ref android.R.styleable#View_fadingEdgeLength
4410     */
4411    public int getHorizontalFadingEdgeLength() {
4412        if (isHorizontalFadingEdgeEnabled()) {
4413            ScrollabilityCache cache = mScrollCache;
4414            if (cache != null) {
4415                return cache.fadingEdgeLength;
4416            }
4417        }
4418        return 0;
4419    }
4420
4421    /**
4422     * Returns the width of the vertical scrollbar.
4423     *
4424     * @return The width in pixels of the vertical scrollbar or 0 if there
4425     *         is no vertical scrollbar.
4426     */
4427    public int getVerticalScrollbarWidth() {
4428        ScrollabilityCache cache = mScrollCache;
4429        if (cache != null) {
4430            ScrollBarDrawable scrollBar = cache.scrollBar;
4431            if (scrollBar != null) {
4432                int size = scrollBar.getSize(true);
4433                if (size <= 0) {
4434                    size = cache.scrollBarSize;
4435                }
4436                return size;
4437            }
4438            return 0;
4439        }
4440        return 0;
4441    }
4442
4443    /**
4444     * Returns the height of the horizontal scrollbar.
4445     *
4446     * @return The height in pixels of the horizontal scrollbar or 0 if
4447     *         there is no horizontal scrollbar.
4448     */
4449    protected int getHorizontalScrollbarHeight() {
4450        ScrollabilityCache cache = mScrollCache;
4451        if (cache != null) {
4452            ScrollBarDrawable scrollBar = cache.scrollBar;
4453            if (scrollBar != null) {
4454                int size = scrollBar.getSize(false);
4455                if (size <= 0) {
4456                    size = cache.scrollBarSize;
4457                }
4458                return size;
4459            }
4460            return 0;
4461        }
4462        return 0;
4463    }
4464
4465    /**
4466     * <p>
4467     * Initializes the scrollbars from a given set of styled attributes. This
4468     * method should be called by subclasses that need scrollbars and when an
4469     * instance of these subclasses is created programmatically rather than
4470     * being inflated from XML. This method is automatically called when the XML
4471     * is inflated.
4472     * </p>
4473     *
4474     * @param a the styled attributes set to initialize the scrollbars from
4475     *
4476     * @removed
4477     */
4478    protected void initializeScrollbars(TypedArray a) {
4479        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4480        // using the View filter array which is not available to the SDK. As such, internal
4481        // framework usage now uses initializeScrollbarsInternal and we grab a default
4482        // TypedArray with the right filter instead here.
4483        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4484
4485        initializeScrollbarsInternal(arr);
4486
4487        // We ignored the method parameter. Recycle the one we actually did use.
4488        arr.recycle();
4489    }
4490
4491    /**
4492     * <p>
4493     * Initializes the scrollbars from a given set of styled attributes. This
4494     * method should be called by subclasses that need scrollbars and when an
4495     * instance of these subclasses is created programmatically rather than
4496     * being inflated from XML. This method is automatically called when the XML
4497     * is inflated.
4498     * </p>
4499     *
4500     * @param a the styled attributes set to initialize the scrollbars from
4501     * @hide
4502     */
4503    protected void initializeScrollbarsInternal(TypedArray a) {
4504        initScrollCache();
4505
4506        final ScrollabilityCache scrollabilityCache = mScrollCache;
4507
4508        if (scrollabilityCache.scrollBar == null) {
4509            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4510        }
4511
4512        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4513
4514        if (!fadeScrollbars) {
4515            scrollabilityCache.state = ScrollabilityCache.ON;
4516        }
4517        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4518
4519
4520        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4521                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4522                        .getScrollBarFadeDuration());
4523        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4524                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4525                ViewConfiguration.getScrollDefaultDelay());
4526
4527
4528        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4529                com.android.internal.R.styleable.View_scrollbarSize,
4530                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4531
4532        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4533        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4534
4535        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4536        if (thumb != null) {
4537            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4538        }
4539
4540        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4541                false);
4542        if (alwaysDraw) {
4543            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4544        }
4545
4546        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4547        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4548
4549        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4550        if (thumb != null) {
4551            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4552        }
4553
4554        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4555                false);
4556        if (alwaysDraw) {
4557            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4558        }
4559
4560        // Apply layout direction to the new Drawables if needed
4561        final int layoutDirection = getLayoutDirection();
4562        if (track != null) {
4563            track.setLayoutDirection(layoutDirection);
4564        }
4565        if (thumb != null) {
4566            thumb.setLayoutDirection(layoutDirection);
4567        }
4568
4569        // Re-apply user/background padding so that scrollbar(s) get added
4570        resolvePadding();
4571    }
4572
4573    /**
4574     * <p>
4575     * Initalizes the scrollability cache if necessary.
4576     * </p>
4577     */
4578    private void initScrollCache() {
4579        if (mScrollCache == null) {
4580            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4581        }
4582    }
4583
4584    private ScrollabilityCache getScrollCache() {
4585        initScrollCache();
4586        return mScrollCache;
4587    }
4588
4589    /**
4590     * Set the position of the vertical scroll bar. Should be one of
4591     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4592     * {@link #SCROLLBAR_POSITION_RIGHT}.
4593     *
4594     * @param position Where the vertical scroll bar should be positioned.
4595     */
4596    public void setVerticalScrollbarPosition(int position) {
4597        if (mVerticalScrollbarPosition != position) {
4598            mVerticalScrollbarPosition = position;
4599            computeOpaqueFlags();
4600            resolvePadding();
4601        }
4602    }
4603
4604    /**
4605     * @return The position where the vertical scroll bar will show, if applicable.
4606     * @see #setVerticalScrollbarPosition(int)
4607     */
4608    public int getVerticalScrollbarPosition() {
4609        return mVerticalScrollbarPosition;
4610    }
4611
4612    ListenerInfo getListenerInfo() {
4613        if (mListenerInfo != null) {
4614            return mListenerInfo;
4615        }
4616        mListenerInfo = new ListenerInfo();
4617        return mListenerInfo;
4618    }
4619
4620    /**
4621     * Register a callback to be invoked when the scroll position of this view
4622     * changed.
4623     *
4624     * @param l The callback that will run.
4625     * @hide Only used internally.
4626     */
4627    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4628        getListenerInfo().mOnScrollChangeListener = l;
4629    }
4630
4631    /**
4632     * Register a callback to be invoked when focus of this view changed.
4633     *
4634     * @param l The callback that will run.
4635     */
4636    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4637        getListenerInfo().mOnFocusChangeListener = l;
4638    }
4639
4640    /**
4641     * Add a listener that will be called when the bounds of the view change due to
4642     * layout processing.
4643     *
4644     * @param listener The listener that will be called when layout bounds change.
4645     */
4646    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4647        ListenerInfo li = getListenerInfo();
4648        if (li.mOnLayoutChangeListeners == null) {
4649            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4650        }
4651        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4652            li.mOnLayoutChangeListeners.add(listener);
4653        }
4654    }
4655
4656    /**
4657     * Remove a listener for layout changes.
4658     *
4659     * @param listener The listener for layout bounds change.
4660     */
4661    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4662        ListenerInfo li = mListenerInfo;
4663        if (li == null || li.mOnLayoutChangeListeners == null) {
4664            return;
4665        }
4666        li.mOnLayoutChangeListeners.remove(listener);
4667    }
4668
4669    /**
4670     * Add a listener for attach state changes.
4671     *
4672     * This listener will be called whenever this view is attached or detached
4673     * from a window. Remove the listener using
4674     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4675     *
4676     * @param listener Listener to attach
4677     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4678     */
4679    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4680        ListenerInfo li = getListenerInfo();
4681        if (li.mOnAttachStateChangeListeners == null) {
4682            li.mOnAttachStateChangeListeners
4683                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4684        }
4685        li.mOnAttachStateChangeListeners.add(listener);
4686    }
4687
4688    /**
4689     * Remove a listener for attach state changes. The listener will receive no further
4690     * notification of window attach/detach events.
4691     *
4692     * @param listener Listener to remove
4693     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4694     */
4695    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4696        ListenerInfo li = mListenerInfo;
4697        if (li == null || li.mOnAttachStateChangeListeners == null) {
4698            return;
4699        }
4700        li.mOnAttachStateChangeListeners.remove(listener);
4701    }
4702
4703    /**
4704     * Returns the focus-change callback registered for this view.
4705     *
4706     * @return The callback, or null if one is not registered.
4707     */
4708    public OnFocusChangeListener getOnFocusChangeListener() {
4709        ListenerInfo li = mListenerInfo;
4710        return li != null ? li.mOnFocusChangeListener : null;
4711    }
4712
4713    /**
4714     * Register a callback to be invoked when this view is clicked. If this view is not
4715     * clickable, it becomes clickable.
4716     *
4717     * @param l The callback that will run
4718     *
4719     * @see #setClickable(boolean)
4720     */
4721    public void setOnClickListener(OnClickListener l) {
4722        if (!isClickable()) {
4723            setClickable(true);
4724        }
4725        getListenerInfo().mOnClickListener = l;
4726    }
4727
4728    /**
4729     * Return whether this view has an attached OnClickListener.  Returns
4730     * true if there is a listener, false if there is none.
4731     */
4732    public boolean hasOnClickListeners() {
4733        ListenerInfo li = mListenerInfo;
4734        return (li != null && li.mOnClickListener != null);
4735    }
4736
4737    /**
4738     * Register a callback to be invoked when this view is clicked and held. If this view is not
4739     * long clickable, it becomes long clickable.
4740     *
4741     * @param l The callback that will run
4742     *
4743     * @see #setLongClickable(boolean)
4744     */
4745    public void setOnLongClickListener(OnLongClickListener l) {
4746        if (!isLongClickable()) {
4747            setLongClickable(true);
4748        }
4749        getListenerInfo().mOnLongClickListener = l;
4750    }
4751
4752    /**
4753     * Register a callback to be invoked when the context menu for this view is
4754     * being built. If this view is not long clickable, it becomes long clickable.
4755     *
4756     * @param l The callback that will run
4757     *
4758     */
4759    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4760        if (!isLongClickable()) {
4761            setLongClickable(true);
4762        }
4763        getListenerInfo().mOnCreateContextMenuListener = l;
4764    }
4765
4766    /**
4767     * Call this view's OnClickListener, if it is defined.  Performs all normal
4768     * actions associated with clicking: reporting accessibility event, playing
4769     * a sound, etc.
4770     *
4771     * @return True there was an assigned OnClickListener that was called, false
4772     *         otherwise is returned.
4773     */
4774    public boolean performClick() {
4775        final boolean result;
4776        final ListenerInfo li = mListenerInfo;
4777        if (li != null && li.mOnClickListener != null) {
4778            playSoundEffect(SoundEffectConstants.CLICK);
4779            li.mOnClickListener.onClick(this);
4780            result = true;
4781        } else {
4782            result = false;
4783        }
4784
4785        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4786        return result;
4787    }
4788
4789    /**
4790     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4791     * this only calls the listener, and does not do any associated clicking
4792     * actions like reporting an accessibility event.
4793     *
4794     * @return True there was an assigned OnClickListener that was called, false
4795     *         otherwise is returned.
4796     */
4797    public boolean callOnClick() {
4798        ListenerInfo li = mListenerInfo;
4799        if (li != null && li.mOnClickListener != null) {
4800            li.mOnClickListener.onClick(this);
4801            return true;
4802        }
4803        return false;
4804    }
4805
4806    /**
4807     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4808     * OnLongClickListener did not consume the event.
4809     *
4810     * @return True if one of the above receivers consumed the event, false otherwise.
4811     */
4812    public boolean performLongClick() {
4813        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4814
4815        boolean handled = false;
4816        ListenerInfo li = mListenerInfo;
4817        if (li != null && li.mOnLongClickListener != null) {
4818            handled = li.mOnLongClickListener.onLongClick(View.this);
4819        }
4820        if (!handled) {
4821            handled = showContextMenu();
4822        }
4823        if (handled) {
4824            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4825        }
4826        return handled;
4827    }
4828
4829    /**
4830     * Performs button-related actions during a touch down event.
4831     *
4832     * @param event The event.
4833     * @return True if the down was consumed.
4834     *
4835     * @hide
4836     */
4837    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4838        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4839            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4840                return true;
4841            }
4842        }
4843        return false;
4844    }
4845
4846    /**
4847     * Bring up the context menu for this view.
4848     *
4849     * @return Whether a context menu was displayed.
4850     */
4851    public boolean showContextMenu() {
4852        return getParent().showContextMenuForChild(this);
4853    }
4854
4855    /**
4856     * Bring up the context menu for this view, referring to the item under the specified point.
4857     *
4858     * @param x The referenced x coordinate.
4859     * @param y The referenced y coordinate.
4860     * @param metaState The keyboard modifiers that were pressed.
4861     * @return Whether a context menu was displayed.
4862     *
4863     * @hide
4864     */
4865    public boolean showContextMenu(float x, float y, int metaState) {
4866        return showContextMenu();
4867    }
4868
4869    /**
4870     * Start an action mode.
4871     *
4872     * @param callback Callback that will control the lifecycle of the action mode
4873     * @return The new action mode if it is started, null otherwise
4874     *
4875     * @see ActionMode
4876     */
4877    public ActionMode startActionMode(ActionMode.Callback callback) {
4878        ViewParent parent = getParent();
4879        if (parent == null) return null;
4880        return parent.startActionModeForChild(this, callback);
4881    }
4882
4883    /**
4884     * Register a callback to be invoked when a hardware key is pressed in this view.
4885     * Key presses in software input methods will generally not trigger the methods of
4886     * this listener.
4887     * @param l the key listener to attach to this view
4888     */
4889    public void setOnKeyListener(OnKeyListener l) {
4890        getListenerInfo().mOnKeyListener = l;
4891    }
4892
4893    /**
4894     * Register a callback to be invoked when a touch event is sent to this view.
4895     * @param l the touch listener to attach to this view
4896     */
4897    public void setOnTouchListener(OnTouchListener l) {
4898        getListenerInfo().mOnTouchListener = l;
4899    }
4900
4901    /**
4902     * Register a callback to be invoked when a generic motion event is sent to this view.
4903     * @param l the generic motion listener to attach to this view
4904     */
4905    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4906        getListenerInfo().mOnGenericMotionListener = l;
4907    }
4908
4909    /**
4910     * Register a callback to be invoked when a hover event is sent to this view.
4911     * @param l the hover listener to attach to this view
4912     */
4913    public void setOnHoverListener(OnHoverListener l) {
4914        getListenerInfo().mOnHoverListener = l;
4915    }
4916
4917    /**
4918     * Register a drag event listener callback object for this View. The parameter is
4919     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4920     * View, the system calls the
4921     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4922     * @param l An implementation of {@link android.view.View.OnDragListener}.
4923     */
4924    public void setOnDragListener(OnDragListener l) {
4925        getListenerInfo().mOnDragListener = l;
4926    }
4927
4928    /**
4929     * Give this view focus. This will cause
4930     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4931     *
4932     * Note: this does not check whether this {@link View} should get focus, it just
4933     * gives it focus no matter what.  It should only be called internally by framework
4934     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4935     *
4936     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4937     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4938     *        focus moved when requestFocus() is called. It may not always
4939     *        apply, in which case use the default View.FOCUS_DOWN.
4940     * @param previouslyFocusedRect The rectangle of the view that had focus
4941     *        prior in this View's coordinate system.
4942     */
4943    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4944        if (DBG) {
4945            System.out.println(this + " requestFocus()");
4946        }
4947
4948        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4949            mPrivateFlags |= PFLAG_FOCUSED;
4950
4951            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4952
4953            if (mParent != null) {
4954                mParent.requestChildFocus(this, this);
4955            }
4956
4957            if (mAttachInfo != null) {
4958                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4959            }
4960
4961            onFocusChanged(true, direction, previouslyFocusedRect);
4962            refreshDrawableState();
4963        }
4964    }
4965
4966    /**
4967     * Populates <code>outRect</code> with the hotspot bounds. By default,
4968     * the hotspot bounds are identical to the screen bounds.
4969     *
4970     * @param outRect rect to populate with hotspot bounds
4971     * @hide Only for internal use by views and widgets.
4972     */
4973    public void getHotspotBounds(Rect outRect) {
4974        final Drawable background = getBackground();
4975        if (background != null) {
4976            background.getHotspotBounds(outRect);
4977        } else {
4978            getBoundsOnScreen(outRect);
4979        }
4980    }
4981
4982    /**
4983     * Request that a rectangle of this view be visible on the screen,
4984     * scrolling if necessary just enough.
4985     *
4986     * <p>A View should call this if it maintains some notion of which part
4987     * of its content is interesting.  For example, a text editing view
4988     * should call this when its cursor moves.
4989     *
4990     * @param rectangle The rectangle.
4991     * @return Whether any parent scrolled.
4992     */
4993    public boolean requestRectangleOnScreen(Rect rectangle) {
4994        return requestRectangleOnScreen(rectangle, false);
4995    }
4996
4997    /**
4998     * Request that a rectangle of this view be visible on the screen,
4999     * scrolling if necessary just enough.
5000     *
5001     * <p>A View should call this if it maintains some notion of which part
5002     * of its content is interesting.  For example, a text editing view
5003     * should call this when its cursor moves.
5004     *
5005     * <p>When <code>immediate</code> is set to true, scrolling will not be
5006     * animated.
5007     *
5008     * @param rectangle The rectangle.
5009     * @param immediate True to forbid animated scrolling, false otherwise
5010     * @return Whether any parent scrolled.
5011     */
5012    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5013        if (mParent == null) {
5014            return false;
5015        }
5016
5017        View child = this;
5018
5019        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5020        position.set(rectangle);
5021
5022        ViewParent parent = mParent;
5023        boolean scrolled = false;
5024        while (parent != null) {
5025            rectangle.set((int) position.left, (int) position.top,
5026                    (int) position.right, (int) position.bottom);
5027
5028            scrolled |= parent.requestChildRectangleOnScreen(child,
5029                    rectangle, immediate);
5030
5031            if (!child.hasIdentityMatrix()) {
5032                child.getMatrix().mapRect(position);
5033            }
5034
5035            position.offset(child.mLeft, child.mTop);
5036
5037            if (!(parent instanceof View)) {
5038                break;
5039            }
5040
5041            View parentView = (View) parent;
5042
5043            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5044
5045            child = parentView;
5046            parent = child.getParent();
5047        }
5048
5049        return scrolled;
5050    }
5051
5052    /**
5053     * Called when this view wants to give up focus. If focus is cleared
5054     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5055     * <p>
5056     * <strong>Note:</strong> When a View clears focus the framework is trying
5057     * to give focus to the first focusable View from the top. Hence, if this
5058     * View is the first from the top that can take focus, then all callbacks
5059     * related to clearing focus will be invoked after which the framework will
5060     * give focus to this view.
5061     * </p>
5062     */
5063    public void clearFocus() {
5064        if (DBG) {
5065            System.out.println(this + " clearFocus()");
5066        }
5067
5068        clearFocusInternal(null, true, true);
5069    }
5070
5071    /**
5072     * Clears focus from the view, optionally propagating the change up through
5073     * the parent hierarchy and requesting that the root view place new focus.
5074     *
5075     * @param propagate whether to propagate the change up through the parent
5076     *            hierarchy
5077     * @param refocus when propagate is true, specifies whether to request the
5078     *            root view place new focus
5079     */
5080    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5081        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5082            mPrivateFlags &= ~PFLAG_FOCUSED;
5083
5084            if (propagate && mParent != null) {
5085                mParent.clearChildFocus(this);
5086            }
5087
5088            onFocusChanged(false, 0, null);
5089            refreshDrawableState();
5090
5091            if (propagate && (!refocus || !rootViewRequestFocus())) {
5092                notifyGlobalFocusCleared(this);
5093            }
5094        }
5095    }
5096
5097    void notifyGlobalFocusCleared(View oldFocus) {
5098        if (oldFocus != null && mAttachInfo != null) {
5099            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5100        }
5101    }
5102
5103    boolean rootViewRequestFocus() {
5104        final View root = getRootView();
5105        return root != null && root.requestFocus();
5106    }
5107
5108    /**
5109     * Called internally by the view system when a new view is getting focus.
5110     * This is what clears the old focus.
5111     * <p>
5112     * <b>NOTE:</b> The parent view's focused child must be updated manually
5113     * after calling this method. Otherwise, the view hierarchy may be left in
5114     * an inconstent state.
5115     */
5116    void unFocus(View focused) {
5117        if (DBG) {
5118            System.out.println(this + " unFocus()");
5119        }
5120
5121        clearFocusInternal(focused, false, false);
5122    }
5123
5124    /**
5125     * Returns true if this view has focus iteself, or is the ancestor of the
5126     * view that has focus.
5127     *
5128     * @return True if this view has or contains focus, false otherwise.
5129     */
5130    @ViewDebug.ExportedProperty(category = "focus")
5131    public boolean hasFocus() {
5132        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5133    }
5134
5135    /**
5136     * Returns true if this view is focusable or if it contains a reachable View
5137     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5138     * is a View whose parents do not block descendants focus.
5139     *
5140     * Only {@link #VISIBLE} views are considered focusable.
5141     *
5142     * @return True if the view is focusable or if the view contains a focusable
5143     *         View, false otherwise.
5144     *
5145     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5146     * @see ViewGroup#getTouchscreenBlocksFocus()
5147     */
5148    public boolean hasFocusable() {
5149        if (!isFocusableInTouchMode()) {
5150            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5151                final ViewGroup g = (ViewGroup) p;
5152                if (g.shouldBlockFocusForTouchscreen()) {
5153                    return false;
5154                }
5155            }
5156        }
5157        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5158    }
5159
5160    /**
5161     * Called by the view system when the focus state of this view changes.
5162     * When the focus change event is caused by directional navigation, direction
5163     * and previouslyFocusedRect provide insight into where the focus is coming from.
5164     * When overriding, be sure to call up through to the super class so that
5165     * the standard focus handling will occur.
5166     *
5167     * @param gainFocus True if the View has focus; false otherwise.
5168     * @param direction The direction focus has moved when requestFocus()
5169     *                  is called to give this view focus. Values are
5170     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5171     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5172     *                  It may not always apply, in which case use the default.
5173     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5174     *        system, of the previously focused view.  If applicable, this will be
5175     *        passed in as finer grained information about where the focus is coming
5176     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5177     */
5178    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5179            @Nullable Rect previouslyFocusedRect) {
5180        if (gainFocus) {
5181            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5182        } else {
5183            notifyViewAccessibilityStateChangedIfNeeded(
5184                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5185        }
5186
5187        InputMethodManager imm = InputMethodManager.peekInstance();
5188        if (!gainFocus) {
5189            if (isPressed()) {
5190                setPressed(false);
5191            }
5192            if (imm != null && mAttachInfo != null
5193                    && mAttachInfo.mHasWindowFocus) {
5194                imm.focusOut(this);
5195            }
5196            onFocusLost();
5197        } else if (imm != null && mAttachInfo != null
5198                && mAttachInfo.mHasWindowFocus) {
5199            imm.focusIn(this);
5200        }
5201
5202        invalidate(true);
5203        ListenerInfo li = mListenerInfo;
5204        if (li != null && li.mOnFocusChangeListener != null) {
5205            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5206        }
5207
5208        if (mAttachInfo != null) {
5209            mAttachInfo.mKeyDispatchState.reset(this);
5210        }
5211    }
5212
5213    /**
5214     * Sends an accessibility event of the given type. If accessibility is
5215     * not enabled this method has no effect. The default implementation calls
5216     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5217     * to populate information about the event source (this View), then calls
5218     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5219     * populate the text content of the event source including its descendants,
5220     * and last calls
5221     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5222     * on its parent to resuest sending of the event to interested parties.
5223     * <p>
5224     * If an {@link AccessibilityDelegate} has been specified via calling
5225     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5226     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5227     * responsible for handling this call.
5228     * </p>
5229     *
5230     * @param eventType The type of the event to send, as defined by several types from
5231     * {@link android.view.accessibility.AccessibilityEvent}, such as
5232     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5233     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5234     *
5235     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5236     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5237     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5238     * @see AccessibilityDelegate
5239     */
5240    public void sendAccessibilityEvent(int eventType) {
5241        if (mAccessibilityDelegate != null) {
5242            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5243        } else {
5244            sendAccessibilityEventInternal(eventType);
5245        }
5246    }
5247
5248    /**
5249     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5250     * {@link AccessibilityEvent} to make an announcement which is related to some
5251     * sort of a context change for which none of the events representing UI transitions
5252     * is a good fit. For example, announcing a new page in a book. If accessibility
5253     * is not enabled this method does nothing.
5254     *
5255     * @param text The announcement text.
5256     */
5257    public void announceForAccessibility(CharSequence text) {
5258        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5259            AccessibilityEvent event = AccessibilityEvent.obtain(
5260                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5261            onInitializeAccessibilityEvent(event);
5262            event.getText().add(text);
5263            event.setContentDescription(null);
5264            mParent.requestSendAccessibilityEvent(this, event);
5265        }
5266    }
5267
5268    /**
5269     * @see #sendAccessibilityEvent(int)
5270     *
5271     * Note: Called from the default {@link AccessibilityDelegate}.
5272     */
5273    void sendAccessibilityEventInternal(int eventType) {
5274        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5275            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5276        }
5277    }
5278
5279    /**
5280     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5281     * takes as an argument an empty {@link AccessibilityEvent} and does not
5282     * perform a check whether accessibility is enabled.
5283     * <p>
5284     * If an {@link AccessibilityDelegate} has been specified via calling
5285     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5286     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5287     * is responsible for handling this call.
5288     * </p>
5289     *
5290     * @param event The event to send.
5291     *
5292     * @see #sendAccessibilityEvent(int)
5293     */
5294    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5295        if (mAccessibilityDelegate != null) {
5296            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5297        } else {
5298            sendAccessibilityEventUncheckedInternal(event);
5299        }
5300    }
5301
5302    /**
5303     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5304     *
5305     * Note: Called from the default {@link AccessibilityDelegate}.
5306     */
5307    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5308        if (!isShown()) {
5309            return;
5310        }
5311        onInitializeAccessibilityEvent(event);
5312        // Only a subset of accessibility events populates text content.
5313        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5314            dispatchPopulateAccessibilityEvent(event);
5315        }
5316        // In the beginning we called #isShown(), so we know that getParent() is not null.
5317        getParent().requestSendAccessibilityEvent(this, event);
5318    }
5319
5320    /**
5321     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5322     * to its children for adding their text content to the event. Note that the
5323     * event text is populated in a separate dispatch path since we add to the
5324     * event not only the text of the source but also the text of all its descendants.
5325     * A typical implementation will call
5326     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5327     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5328     * on each child. Override this method if custom population of the event text
5329     * content is required.
5330     * <p>
5331     * If an {@link AccessibilityDelegate} has been specified via calling
5332     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5333     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5334     * is responsible for handling this call.
5335     * </p>
5336     * <p>
5337     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5338     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5339     * </p>
5340     *
5341     * @param event The event.
5342     *
5343     * @return True if the event population was completed.
5344     */
5345    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5346        if (mAccessibilityDelegate != null) {
5347            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5348        } else {
5349            return dispatchPopulateAccessibilityEventInternal(event);
5350        }
5351    }
5352
5353    /**
5354     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5355     *
5356     * Note: Called from the default {@link AccessibilityDelegate}.
5357     */
5358    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5359        onPopulateAccessibilityEvent(event);
5360        return false;
5361    }
5362
5363    /**
5364     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5365     * giving a chance to this View to populate the accessibility event with its
5366     * text content. While this method is free to modify event
5367     * attributes other than text content, doing so should normally be performed in
5368     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5369     * <p>
5370     * Example: Adding formatted date string to an accessibility event in addition
5371     *          to the text added by the super implementation:
5372     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5373     *     super.onPopulateAccessibilityEvent(event);
5374     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5375     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5376     *         mCurrentDate.getTimeInMillis(), flags);
5377     *     event.getText().add(selectedDateUtterance);
5378     * }</pre>
5379     * <p>
5380     * If an {@link AccessibilityDelegate} has been specified via calling
5381     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5382     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(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     *
5389     * @param event The accessibility event which to populate.
5390     *
5391     * @see #sendAccessibilityEvent(int)
5392     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5393     */
5394    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5395        if (mAccessibilityDelegate != null) {
5396            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5397        } else {
5398            onPopulateAccessibilityEventInternal(event);
5399        }
5400    }
5401
5402    /**
5403     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5404     *
5405     * Note: Called from the default {@link AccessibilityDelegate}.
5406     */
5407    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5408    }
5409
5410    /**
5411     * Initializes an {@link AccessibilityEvent} with information about
5412     * this View which is the event source. In other words, the source of
5413     * an accessibility event is the view whose state change triggered firing
5414     * the event.
5415     * <p>
5416     * Example: Setting the password property of an event in addition
5417     *          to properties set by the super implementation:
5418     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5419     *     super.onInitializeAccessibilityEvent(event);
5420     *     event.setPassword(true);
5421     * }</pre>
5422     * <p>
5423     * If an {@link AccessibilityDelegate} has been specified via calling
5424     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5425     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5426     * is responsible for handling this call.
5427     * </p>
5428     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5429     * information to the event, in case the default implementation has basic information to add.
5430     * </p>
5431     * @param event The event to initialize.
5432     *
5433     * @see #sendAccessibilityEvent(int)
5434     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5435     */
5436    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5437        if (mAccessibilityDelegate != null) {
5438            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5439        } else {
5440            onInitializeAccessibilityEventInternal(event);
5441        }
5442    }
5443
5444    /**
5445     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5446     *
5447     * Note: Called from the default {@link AccessibilityDelegate}.
5448     */
5449    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5450        event.setSource(this);
5451        event.setClassName(View.class.getName());
5452        event.setPackageName(getContext().getPackageName());
5453        event.setEnabled(isEnabled());
5454        event.setContentDescription(mContentDescription);
5455
5456        switch (event.getEventType()) {
5457            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5458                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5459                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5460                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5461                event.setItemCount(focusablesTempList.size());
5462                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5463                if (mAttachInfo != null) {
5464                    focusablesTempList.clear();
5465                }
5466            } break;
5467            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5468                CharSequence text = getIterableTextForAccessibility();
5469                if (text != null && text.length() > 0) {
5470                    event.setFromIndex(getAccessibilitySelectionStart());
5471                    event.setToIndex(getAccessibilitySelectionEnd());
5472                    event.setItemCount(text.length());
5473                }
5474            } break;
5475        }
5476    }
5477
5478    /**
5479     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5480     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5481     * This method is responsible for obtaining an accessibility node info from a
5482     * pool of reusable instances and calling
5483     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5484     * initialize the former.
5485     * <p>
5486     * Note: The client is responsible for recycling the obtained instance by calling
5487     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5488     * </p>
5489     *
5490     * @return A populated {@link AccessibilityNodeInfo}.
5491     *
5492     * @see AccessibilityNodeInfo
5493     */
5494    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5495        if (mAccessibilityDelegate != null) {
5496            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5497        } else {
5498            return createAccessibilityNodeInfoInternal();
5499        }
5500    }
5501
5502    /**
5503     * @see #createAccessibilityNodeInfo()
5504     */
5505    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5506        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5507        if (provider != null) {
5508            return provider.createAccessibilityNodeInfo(View.NO_ID);
5509        } else {
5510            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5511            onInitializeAccessibilityNodeInfo(info);
5512            return info;
5513        }
5514    }
5515
5516    /**
5517     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5518     * The base implementation sets:
5519     * <ul>
5520     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5521     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5522     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5523     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5524     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5525     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5526     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5527     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5528     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5529     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5530     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5531     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5532     * </ul>
5533     * <p>
5534     * Subclasses should override this method, call the super implementation,
5535     * and set additional attributes.
5536     * </p>
5537     * <p>
5538     * If an {@link AccessibilityDelegate} has been specified via calling
5539     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5540     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5541     * is responsible for handling this call.
5542     * </p>
5543     *
5544     * @param info The instance to initialize.
5545     */
5546    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5547        if (mAccessibilityDelegate != null) {
5548            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5549        } else {
5550            onInitializeAccessibilityNodeInfoInternal(info);
5551        }
5552    }
5553
5554    /**
5555     * Gets the location of this view in screen coordintates.
5556     *
5557     * @param outRect The output location
5558     * @hide
5559     */
5560    public void getBoundsOnScreen(Rect outRect) {
5561        if (mAttachInfo == null) {
5562            return;
5563        }
5564
5565        RectF position = mAttachInfo.mTmpTransformRect;
5566        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5567
5568        if (!hasIdentityMatrix()) {
5569            getMatrix().mapRect(position);
5570        }
5571
5572        position.offset(mLeft, mTop);
5573
5574        ViewParent parent = mParent;
5575        while (parent instanceof View) {
5576            View parentView = (View) parent;
5577
5578            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5579
5580            if (!parentView.hasIdentityMatrix()) {
5581                parentView.getMatrix().mapRect(position);
5582            }
5583
5584            position.offset(parentView.mLeft, parentView.mTop);
5585
5586            parent = parentView.mParent;
5587        }
5588
5589        if (parent instanceof ViewRootImpl) {
5590            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5591            position.offset(0, -viewRootImpl.mCurScrollY);
5592        }
5593
5594        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5595
5596        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5597                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5598    }
5599
5600    /**
5601     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5602     *
5603     * Note: Called from the default {@link AccessibilityDelegate}.
5604     */
5605    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5606        Rect bounds = mAttachInfo.mTmpInvalRect;
5607
5608        getDrawingRect(bounds);
5609        info.setBoundsInParent(bounds);
5610
5611        getBoundsOnScreen(bounds);
5612        info.setBoundsInScreen(bounds);
5613
5614        ViewParent parent = getParentForAccessibility();
5615        if (parent instanceof View) {
5616            info.setParent((View) parent);
5617        }
5618
5619        if (mID != View.NO_ID) {
5620            View rootView = getRootView();
5621            if (rootView == null) {
5622                rootView = this;
5623            }
5624
5625            View label = rootView.findLabelForView(this, mID);
5626            if (label != null) {
5627                info.setLabeledBy(label);
5628            }
5629
5630            if ((mAttachInfo.mAccessibilityFetchFlags
5631                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5632                    && Resources.resourceHasPackage(mID)) {
5633                try {
5634                    String viewId = getResources().getResourceName(mID);
5635                    info.setViewIdResourceName(viewId);
5636                } catch (Resources.NotFoundException nfe) {
5637                    /* ignore */
5638                }
5639            }
5640        }
5641
5642        if (mLabelForId != View.NO_ID) {
5643            View rootView = getRootView();
5644            if (rootView == null) {
5645                rootView = this;
5646            }
5647            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5648            if (labeled != null) {
5649                info.setLabelFor(labeled);
5650            }
5651        }
5652
5653        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
5654            View rootView = getRootView();
5655            if (rootView == null) {
5656                rootView = this;
5657            }
5658            View next = rootView.findViewInsideOutShouldExist(this,
5659                    mAccessibilityTraversalBeforeId);
5660            if (next != null) {
5661                info.setTraversalBefore(next);
5662            }
5663        }
5664
5665        if (mAccessibilityTraversalAfterId != View.NO_ID) {
5666            View rootView = getRootView();
5667            if (rootView == null) {
5668                rootView = this;
5669            }
5670            View next = rootView.findViewInsideOutShouldExist(this,
5671                    mAccessibilityTraversalAfterId);
5672            if (next != null) {
5673                info.setTraversalAfter(next);
5674            }
5675        }
5676
5677        info.setVisibleToUser(isVisibleToUser());
5678
5679        info.setPackageName(mContext.getPackageName());
5680        info.setClassName(View.class.getName());
5681        info.setContentDescription(getContentDescription());
5682
5683        info.setEnabled(isEnabled());
5684        info.setClickable(isClickable());
5685        info.setFocusable(isFocusable());
5686        info.setFocused(isFocused());
5687        info.setAccessibilityFocused(isAccessibilityFocused());
5688        info.setSelected(isSelected());
5689        info.setLongClickable(isLongClickable());
5690        info.setLiveRegion(getAccessibilityLiveRegion());
5691
5692        // TODO: These make sense only if we are in an AdapterView but all
5693        // views can be selected. Maybe from accessibility perspective
5694        // we should report as selectable view in an AdapterView.
5695        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5696        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5697
5698        if (isFocusable()) {
5699            if (isFocused()) {
5700                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5701            } else {
5702                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5703            }
5704        }
5705
5706        if (!isAccessibilityFocused()) {
5707            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5708        } else {
5709            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5710        }
5711
5712        if (isClickable() && isEnabled()) {
5713            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5714        }
5715
5716        if (isLongClickable() && isEnabled()) {
5717            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5718        }
5719
5720        CharSequence text = getIterableTextForAccessibility();
5721        if (text != null && text.length() > 0) {
5722            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5723
5724            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5725            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5726            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5727            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5728                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5729                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5730        }
5731    }
5732
5733    private View findLabelForView(View view, int labeledId) {
5734        if (mMatchLabelForPredicate == null) {
5735            mMatchLabelForPredicate = new MatchLabelForPredicate();
5736        }
5737        mMatchLabelForPredicate.mLabeledId = labeledId;
5738        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5739    }
5740
5741    /**
5742     * Computes whether this view is visible to the user. Such a view is
5743     * attached, visible, all its predecessors are visible, it is not clipped
5744     * entirely by its predecessors, and has an alpha greater than zero.
5745     *
5746     * @return Whether the view is visible on the screen.
5747     *
5748     * @hide
5749     */
5750    protected boolean isVisibleToUser() {
5751        return isVisibleToUser(null);
5752    }
5753
5754    /**
5755     * Computes whether the given portion of this view is visible to the user.
5756     * Such a view is attached, visible, all its predecessors are visible,
5757     * has an alpha greater than zero, and the specified portion is not
5758     * clipped entirely by its predecessors.
5759     *
5760     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5761     *                    <code>null</code>, and the entire view will be tested in this case.
5762     *                    When <code>true</code> is returned by the function, the actual visible
5763     *                    region will be stored in this parameter; that is, if boundInView is fully
5764     *                    contained within the view, no modification will be made, otherwise regions
5765     *                    outside of the visible area of the view will be clipped.
5766     *
5767     * @return Whether the specified portion of the view is visible on the screen.
5768     *
5769     * @hide
5770     */
5771    protected boolean isVisibleToUser(Rect boundInView) {
5772        if (mAttachInfo != null) {
5773            // Attached to invisible window means this view is not visible.
5774            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5775                return false;
5776            }
5777            // An invisible predecessor or one with alpha zero means
5778            // that this view is not visible to the user.
5779            Object current = this;
5780            while (current instanceof View) {
5781                View view = (View) current;
5782                // We have attach info so this view is attached and there is no
5783                // need to check whether we reach to ViewRootImpl on the way up.
5784                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5785                        view.getVisibility() != VISIBLE) {
5786                    return false;
5787                }
5788                current = view.mParent;
5789            }
5790            // Check if the view is entirely covered by its predecessors.
5791            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5792            Point offset = mAttachInfo.mPoint;
5793            if (!getGlobalVisibleRect(visibleRect, offset)) {
5794                return false;
5795            }
5796            // Check if the visible portion intersects the rectangle of interest.
5797            if (boundInView != null) {
5798                visibleRect.offset(-offset.x, -offset.y);
5799                return boundInView.intersect(visibleRect);
5800            }
5801            return true;
5802        }
5803        return false;
5804    }
5805
5806    /**
5807     * Computes a point on which a sequence of a down/up event can be sent to
5808     * trigger clicking this view. This method is for the exclusive use by the
5809     * accessibility layer to determine where to send a click event in explore
5810     * by touch mode.
5811     *
5812     * @param interactiveRegion The interactive portion of this window.
5813     * @param outPoint The point to populate.
5814     * @return True of such a point exists.
5815     */
5816    boolean computeClickPointInScreenForAccessibility(Region interactiveRegion,
5817            Point outPoint) {
5818        // Since the interactive portion of the view is a region but as a view
5819        // may have a transformation matrix which cannot be applied to a
5820        // region we compute the view bounds rectangle and all interactive
5821        // predecessor's and sibling's (siblings of predecessors included)
5822        // rectangles that intersect the view bounds. At the
5823        // end if the view was partially covered by another interactive
5824        // view we compute the view's interactive region and pick a point
5825        // on its boundary path as regions do not offer APIs to get inner
5826        // points. Note that the the code is optimized to fail early and
5827        // avoid unnecessary allocations plus computations.
5828
5829        // The current approach has edge cases that may produce false
5830        // positives or false negatives. For example, a portion of the
5831        // view may be covered by an interactive descendant of a
5832        // predecessor, which we do not compute. Also a view may be handling
5833        // raw touch events instead registering click listeners, which
5834        // we cannot compute. Despite these limitations this approach will
5835        // work most of the time and it is a huge improvement over just
5836        // blindly sending the down and up events in the center of the
5837        // view.
5838
5839        // Cannot click on an unattached view.
5840        if (mAttachInfo == null) {
5841            return false;
5842        }
5843
5844        // Attached to an invisible window means this view is not visible.
5845        if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5846            return false;
5847        }
5848
5849        RectF bounds = mAttachInfo.mTmpTransformRect;
5850        bounds.set(0, 0, getWidth(), getHeight());
5851        List<RectF> intersections = mAttachInfo.mTmpRectList;
5852        intersections.clear();
5853
5854        if (mParent instanceof ViewGroup) {
5855            ViewGroup parentGroup = (ViewGroup) mParent;
5856            if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates(
5857                    this, bounds, intersections)) {
5858                intersections.clear();
5859                return false;
5860            }
5861        }
5862
5863        // Take into account the window location.
5864        final int dx = mAttachInfo.mWindowLeft;
5865        final int dy = mAttachInfo.mWindowTop;
5866        bounds.offset(dx, dy);
5867        offsetRects(intersections, dx, dy);
5868
5869        if (intersections.isEmpty() && interactiveRegion == null) {
5870            outPoint.set((int) bounds.centerX(), (int) bounds.centerY());
5871        } else {
5872            // This view is partially covered by other views, then compute
5873            // the not covered region and pick a point on its boundary.
5874            Region region = new Region();
5875            region.set((int) bounds.left, (int) bounds.top,
5876                    (int) bounds.right, (int) bounds.bottom);
5877
5878            final int intersectionCount = intersections.size();
5879            for (int i = intersectionCount - 1; i >= 0; i--) {
5880                RectF intersection = intersections.remove(i);
5881                region.op((int) intersection.left, (int) intersection.top,
5882                        (int) intersection.right, (int) intersection.bottom,
5883                        Region.Op.DIFFERENCE);
5884            }
5885
5886            // If the view is completely covered, done.
5887            if (region.isEmpty()) {
5888                return false;
5889            }
5890
5891            // Take into account the interactive portion of the window
5892            // as the rest is covered by other windows. If no such a region
5893            // then the whole window is interactive.
5894            if (interactiveRegion != null) {
5895                region.op(interactiveRegion, Region.Op.INTERSECT);
5896            }
5897
5898            // Take into account the window bounds.
5899            final View root = getRootView();
5900            if (root != null) {
5901                region.op(dx, dy, root.getWidth() + dx, root.getHeight() + dy, Region.Op.INTERSECT);
5902            }
5903
5904            // If the view is completely covered, done.
5905            if (region.isEmpty()) {
5906                return false;
5907            }
5908
5909            // Try a shortcut here.
5910            if (region.isRect()) {
5911                Rect regionBounds = mAttachInfo.mTmpInvalRect;
5912                region.getBounds(regionBounds);
5913                outPoint.set(regionBounds.centerX(), regionBounds.centerY());
5914                return true;
5915            }
5916
5917            // Get the a point on the region boundary path.
5918            Path path = region.getBoundaryPath();
5919            PathMeasure pathMeasure = new PathMeasure(path, false);
5920            final float[] coordinates = mAttachInfo.mTmpTransformLocation;
5921
5922            // Without loss of generality pick a point.
5923            final float point = pathMeasure.getLength() * 0.01f;
5924            if (!pathMeasure.getPosTan(point, coordinates, null)) {
5925                return false;
5926            }
5927
5928            outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1]));
5929        }
5930
5931        return true;
5932    }
5933
5934    /**
5935     * Adds the clickable rectangles withing the bounds of this view. They
5936     * may overlap. This method is intended for use only by the accessibility
5937     * layer.
5938     *
5939     * @param outRects List to which to add clickable areas.
5940     */
5941    void addClickableRectsForAccessibility(List<RectF> outRects) {
5942        if (isClickable() || isLongClickable()) {
5943            RectF bounds = new RectF();
5944            bounds.set(0, 0, getWidth(), getHeight());
5945            outRects.add(bounds);
5946        }
5947    }
5948
5949    static void offsetRects(List<RectF> rects, float offsetX, float offsetY) {
5950        final int rectCount = rects.size();
5951        for (int i = 0; i < rectCount; i++) {
5952            RectF intersection = rects.get(i);
5953            intersection.offset(offsetX, offsetY);
5954        }
5955    }
5956
5957    /**
5958     * Returns the delegate for implementing accessibility support via
5959     * composition. For more details see {@link AccessibilityDelegate}.
5960     *
5961     * @return The delegate, or null if none set.
5962     *
5963     * @hide
5964     */
5965    public AccessibilityDelegate getAccessibilityDelegate() {
5966        return mAccessibilityDelegate;
5967    }
5968
5969    /**
5970     * Sets a delegate for implementing accessibility support via composition as
5971     * opposed to inheritance. The delegate's primary use is for implementing
5972     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5973     *
5974     * @param delegate The delegate instance.
5975     *
5976     * @see AccessibilityDelegate
5977     */
5978    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5979        mAccessibilityDelegate = delegate;
5980    }
5981
5982    /**
5983     * Gets the provider for managing a virtual view hierarchy rooted at this View
5984     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5985     * that explore the window content.
5986     * <p>
5987     * If this method returns an instance, this instance is responsible for managing
5988     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5989     * View including the one representing the View itself. Similarly the returned
5990     * instance is responsible for performing accessibility actions on any virtual
5991     * view or the root view itself.
5992     * </p>
5993     * <p>
5994     * If an {@link AccessibilityDelegate} has been specified via calling
5995     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5996     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5997     * is responsible for handling this call.
5998     * </p>
5999     *
6000     * @return The provider.
6001     *
6002     * @see AccessibilityNodeProvider
6003     */
6004    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6005        if (mAccessibilityDelegate != null) {
6006            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6007        } else {
6008            return null;
6009        }
6010    }
6011
6012    /**
6013     * Gets the unique identifier of this view on the screen for accessibility purposes.
6014     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6015     *
6016     * @return The view accessibility id.
6017     *
6018     * @hide
6019     */
6020    public int getAccessibilityViewId() {
6021        if (mAccessibilityViewId == NO_ID) {
6022            mAccessibilityViewId = sNextAccessibilityViewId++;
6023        }
6024        return mAccessibilityViewId;
6025    }
6026
6027    /**
6028     * Gets the unique identifier of the window in which this View reseides.
6029     *
6030     * @return The window accessibility id.
6031     *
6032     * @hide
6033     */
6034    public int getAccessibilityWindowId() {
6035        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6036                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6037    }
6038
6039    /**
6040     * Gets the {@link View} description. It briefly describes the view and is
6041     * primarily used for accessibility support. Set this property to enable
6042     * better accessibility support for your application. This is especially
6043     * true for views that do not have textual representation (For example,
6044     * ImageButton).
6045     *
6046     * @return The content description.
6047     *
6048     * @attr ref android.R.styleable#View_contentDescription
6049     */
6050    @ViewDebug.ExportedProperty(category = "accessibility")
6051    public CharSequence getContentDescription() {
6052        return mContentDescription;
6053    }
6054
6055    /**
6056     * Sets the {@link View} description. It briefly describes the view and is
6057     * primarily used for accessibility support. Set this property to enable
6058     * better accessibility support for your application. This is especially
6059     * true for views that do not have textual representation (For example,
6060     * ImageButton).
6061     *
6062     * @param contentDescription The content description.
6063     *
6064     * @attr ref android.R.styleable#View_contentDescription
6065     */
6066    @RemotableViewMethod
6067    public void setContentDescription(CharSequence contentDescription) {
6068        if (mContentDescription == null) {
6069            if (contentDescription == null) {
6070                return;
6071            }
6072        } else if (mContentDescription.equals(contentDescription)) {
6073            return;
6074        }
6075        mContentDescription = contentDescription;
6076        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6077        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6078            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6079            notifySubtreeAccessibilityStateChangedIfNeeded();
6080        } else {
6081            notifyViewAccessibilityStateChangedIfNeeded(
6082                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6083        }
6084    }
6085
6086    /**
6087     * Sets the id of a view before which this one is visited in accessibility traversal.
6088     * A screen-reader must visit the content of this view before the content of the one
6089     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6090     * will traverse the entire content of B before traversing the entire content of A,
6091     * regardles of what traversal strategy it is using.
6092     * <p>
6093     * Views that do not have specified before/after relationships are traversed in order
6094     * determined by the screen-reader.
6095     * </p>
6096     * <p>
6097     * Setting that this view is before a view that is not important for accessibility
6098     * or if this view is not important for accessibility will have no effect as the
6099     * screen-reader is not aware of unimportant views.
6100     * </p>
6101     *
6102     * @param beforeId The id of a view this one precedes in accessibility traversal.
6103     *
6104     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6105     *
6106     * @see #setImportantForAccessibility(int)
6107     */
6108    @RemotableViewMethod
6109    public void setAccessibilityTraversalBefore(int beforeId) {
6110        if (mAccessibilityTraversalBeforeId == beforeId) {
6111            return;
6112        }
6113        mAccessibilityTraversalBeforeId = beforeId;
6114        notifyViewAccessibilityStateChangedIfNeeded(
6115                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6116    }
6117
6118    /**
6119     * Gets the id of a view before which this one is visited in accessibility traversal.
6120     *
6121     * @return The id of a view this one precedes in accessibility traversal if
6122     *         specified, otherwise {@link #NO_ID}.
6123     *
6124     * @see #setAccessibilityTraversalBefore(int)
6125     */
6126    public int getAccessibilityTraversalBefore() {
6127        return mAccessibilityTraversalBeforeId;
6128    }
6129
6130    /**
6131     * Sets the id of a view after which this one is visited in accessibility traversal.
6132     * A screen-reader must visit the content of the other view before the content of this
6133     * one. For example, if view B is set to be after view A, then a screen-reader
6134     * will traverse the entire content of A before traversing the entire content of B,
6135     * regardles of what traversal strategy it is using.
6136     * <p>
6137     * Views that do not have specified before/after relationships are traversed in order
6138     * determined by the screen-reader.
6139     * </p>
6140     * <p>
6141     * Setting that this view is after a view that is not important for accessibility
6142     * or if this view is not important for accessibility will have no effect as the
6143     * screen-reader is not aware of unimportant views.
6144     * </p>
6145     *
6146     * @param afterId The id of a view this one succedees in accessibility traversal.
6147     *
6148     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6149     *
6150     * @see #setImportantForAccessibility(int)
6151     */
6152    @RemotableViewMethod
6153    public void setAccessibilityTraversalAfter(int afterId) {
6154        if (mAccessibilityTraversalAfterId == afterId) {
6155            return;
6156        }
6157        mAccessibilityTraversalAfterId = afterId;
6158        notifyViewAccessibilityStateChangedIfNeeded(
6159                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6160    }
6161
6162    /**
6163     * Gets the id of a view after which this one is visited in accessibility traversal.
6164     *
6165     * @return The id of a view this one succeedes in accessibility traversal if
6166     *         specified, otherwise {@link #NO_ID}.
6167     *
6168     * @see #setAccessibilityTraversalAfter(int)
6169     */
6170    public int getAccessibilityTraversalAfter() {
6171        return mAccessibilityTraversalAfterId;
6172    }
6173
6174    /**
6175     * Gets the id of a view for which this view serves as a label for
6176     * accessibility purposes.
6177     *
6178     * @return The labeled view id.
6179     */
6180    @ViewDebug.ExportedProperty(category = "accessibility")
6181    public int getLabelFor() {
6182        return mLabelForId;
6183    }
6184
6185    /**
6186     * Sets the id of a view for which this view serves as a label for
6187     * accessibility purposes.
6188     *
6189     * @param id The labeled view id.
6190     */
6191    @RemotableViewMethod
6192    public void setLabelFor(int id) {
6193        if (mLabelForId == id) {
6194            return;
6195        }
6196        mLabelForId = id;
6197        if (mLabelForId != View.NO_ID
6198                && mID == View.NO_ID) {
6199            mID = generateViewId();
6200        }
6201        notifyViewAccessibilityStateChangedIfNeeded(
6202                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6203    }
6204
6205    /**
6206     * Invoked whenever this view loses focus, either by losing window focus or by losing
6207     * focus within its window. This method can be used to clear any state tied to the
6208     * focus. For instance, if a button is held pressed with the trackball and the window
6209     * loses focus, this method can be used to cancel the press.
6210     *
6211     * Subclasses of View overriding this method should always call super.onFocusLost().
6212     *
6213     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6214     * @see #onWindowFocusChanged(boolean)
6215     *
6216     * @hide pending API council approval
6217     */
6218    protected void onFocusLost() {
6219        resetPressedState();
6220    }
6221
6222    private void resetPressedState() {
6223        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6224            return;
6225        }
6226
6227        if (isPressed()) {
6228            setPressed(false);
6229
6230            if (!mHasPerformedLongPress) {
6231                removeLongPressCallback();
6232            }
6233        }
6234    }
6235
6236    /**
6237     * Returns true if this view has focus
6238     *
6239     * @return True if this view has focus, false otherwise.
6240     */
6241    @ViewDebug.ExportedProperty(category = "focus")
6242    public boolean isFocused() {
6243        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6244    }
6245
6246    /**
6247     * Find the view in the hierarchy rooted at this view that currently has
6248     * focus.
6249     *
6250     * @return The view that currently has focus, or null if no focused view can
6251     *         be found.
6252     */
6253    public View findFocus() {
6254        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6255    }
6256
6257    /**
6258     * Indicates whether this view is one of the set of scrollable containers in
6259     * its window.
6260     *
6261     * @return whether this view is one of the set of scrollable containers in
6262     * its window
6263     *
6264     * @attr ref android.R.styleable#View_isScrollContainer
6265     */
6266    public boolean isScrollContainer() {
6267        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6268    }
6269
6270    /**
6271     * Change whether this view is one of the set of scrollable containers in
6272     * its window.  This will be used to determine whether the window can
6273     * resize or must pan when a soft input area is open -- scrollable
6274     * containers allow the window to use resize mode since the container
6275     * will appropriately shrink.
6276     *
6277     * @attr ref android.R.styleable#View_isScrollContainer
6278     */
6279    public void setScrollContainer(boolean isScrollContainer) {
6280        if (isScrollContainer) {
6281            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6282                mAttachInfo.mScrollContainers.add(this);
6283                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6284            }
6285            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6286        } else {
6287            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6288                mAttachInfo.mScrollContainers.remove(this);
6289            }
6290            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6291        }
6292    }
6293
6294    /**
6295     * Returns the quality of the drawing cache.
6296     *
6297     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6298     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6299     *
6300     * @see #setDrawingCacheQuality(int)
6301     * @see #setDrawingCacheEnabled(boolean)
6302     * @see #isDrawingCacheEnabled()
6303     *
6304     * @attr ref android.R.styleable#View_drawingCacheQuality
6305     */
6306    @DrawingCacheQuality
6307    public int getDrawingCacheQuality() {
6308        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6309    }
6310
6311    /**
6312     * Set the drawing cache quality of this view. This value is used only when the
6313     * drawing cache is enabled
6314     *
6315     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6316     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6317     *
6318     * @see #getDrawingCacheQuality()
6319     * @see #setDrawingCacheEnabled(boolean)
6320     * @see #isDrawingCacheEnabled()
6321     *
6322     * @attr ref android.R.styleable#View_drawingCacheQuality
6323     */
6324    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6325        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6326    }
6327
6328    /**
6329     * Returns whether the screen should remain on, corresponding to the current
6330     * value of {@link #KEEP_SCREEN_ON}.
6331     *
6332     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6333     *
6334     * @see #setKeepScreenOn(boolean)
6335     *
6336     * @attr ref android.R.styleable#View_keepScreenOn
6337     */
6338    public boolean getKeepScreenOn() {
6339        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6340    }
6341
6342    /**
6343     * Controls whether the screen should remain on, modifying the
6344     * value of {@link #KEEP_SCREEN_ON}.
6345     *
6346     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6347     *
6348     * @see #getKeepScreenOn()
6349     *
6350     * @attr ref android.R.styleable#View_keepScreenOn
6351     */
6352    public void setKeepScreenOn(boolean keepScreenOn) {
6353        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6354    }
6355
6356    /**
6357     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6358     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6359     *
6360     * @attr ref android.R.styleable#View_nextFocusLeft
6361     */
6362    public int getNextFocusLeftId() {
6363        return mNextFocusLeftId;
6364    }
6365
6366    /**
6367     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6368     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6369     * decide automatically.
6370     *
6371     * @attr ref android.R.styleable#View_nextFocusLeft
6372     */
6373    public void setNextFocusLeftId(int nextFocusLeftId) {
6374        mNextFocusLeftId = nextFocusLeftId;
6375    }
6376
6377    /**
6378     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6379     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6380     *
6381     * @attr ref android.R.styleable#View_nextFocusRight
6382     */
6383    public int getNextFocusRightId() {
6384        return mNextFocusRightId;
6385    }
6386
6387    /**
6388     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6389     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6390     * decide automatically.
6391     *
6392     * @attr ref android.R.styleable#View_nextFocusRight
6393     */
6394    public void setNextFocusRightId(int nextFocusRightId) {
6395        mNextFocusRightId = nextFocusRightId;
6396    }
6397
6398    /**
6399     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6400     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6401     *
6402     * @attr ref android.R.styleable#View_nextFocusUp
6403     */
6404    public int getNextFocusUpId() {
6405        return mNextFocusUpId;
6406    }
6407
6408    /**
6409     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6410     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6411     * decide automatically.
6412     *
6413     * @attr ref android.R.styleable#View_nextFocusUp
6414     */
6415    public void setNextFocusUpId(int nextFocusUpId) {
6416        mNextFocusUpId = nextFocusUpId;
6417    }
6418
6419    /**
6420     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6421     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6422     *
6423     * @attr ref android.R.styleable#View_nextFocusDown
6424     */
6425    public int getNextFocusDownId() {
6426        return mNextFocusDownId;
6427    }
6428
6429    /**
6430     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6431     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6432     * decide automatically.
6433     *
6434     * @attr ref android.R.styleable#View_nextFocusDown
6435     */
6436    public void setNextFocusDownId(int nextFocusDownId) {
6437        mNextFocusDownId = nextFocusDownId;
6438    }
6439
6440    /**
6441     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6442     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6443     *
6444     * @attr ref android.R.styleable#View_nextFocusForward
6445     */
6446    public int getNextFocusForwardId() {
6447        return mNextFocusForwardId;
6448    }
6449
6450    /**
6451     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6452     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6453     * decide automatically.
6454     *
6455     * @attr ref android.R.styleable#View_nextFocusForward
6456     */
6457    public void setNextFocusForwardId(int nextFocusForwardId) {
6458        mNextFocusForwardId = nextFocusForwardId;
6459    }
6460
6461    /**
6462     * Returns the visibility of this view and all of its ancestors
6463     *
6464     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6465     */
6466    public boolean isShown() {
6467        View current = this;
6468        //noinspection ConstantConditions
6469        do {
6470            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6471                return false;
6472            }
6473            ViewParent parent = current.mParent;
6474            if (parent == null) {
6475                return false; // We are not attached to the view root
6476            }
6477            if (!(parent instanceof View)) {
6478                return true;
6479            }
6480            current = (View) parent;
6481        } while (current != null);
6482
6483        return false;
6484    }
6485
6486    /**
6487     * Called by the view hierarchy when the content insets for a window have
6488     * changed, to allow it to adjust its content to fit within those windows.
6489     * The content insets tell you the space that the status bar, input method,
6490     * and other system windows infringe on the application's window.
6491     *
6492     * <p>You do not normally need to deal with this function, since the default
6493     * window decoration given to applications takes care of applying it to the
6494     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6495     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6496     * and your content can be placed under those system elements.  You can then
6497     * use this method within your view hierarchy if you have parts of your UI
6498     * which you would like to ensure are not being covered.
6499     *
6500     * <p>The default implementation of this method simply applies the content
6501     * insets to the view's padding, consuming that content (modifying the
6502     * insets to be 0), and returning true.  This behavior is off by default, but can
6503     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6504     *
6505     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6506     * insets object is propagated down the hierarchy, so any changes made to it will
6507     * be seen by all following views (including potentially ones above in
6508     * the hierarchy since this is a depth-first traversal).  The first view
6509     * that returns true will abort the entire traversal.
6510     *
6511     * <p>The default implementation works well for a situation where it is
6512     * used with a container that covers the entire window, allowing it to
6513     * apply the appropriate insets to its content on all edges.  If you need
6514     * a more complicated layout (such as two different views fitting system
6515     * windows, one on the top of the window, and one on the bottom),
6516     * you can override the method and handle the insets however you would like.
6517     * Note that the insets provided by the framework are always relative to the
6518     * far edges of the window, not accounting for the location of the called view
6519     * within that window.  (In fact when this method is called you do not yet know
6520     * where the layout will place the view, as it is done before layout happens.)
6521     *
6522     * <p>Note: unlike many View methods, there is no dispatch phase to this
6523     * call.  If you are overriding it in a ViewGroup and want to allow the
6524     * call to continue to your children, you must be sure to call the super
6525     * implementation.
6526     *
6527     * <p>Here is a sample layout that makes use of fitting system windows
6528     * to have controls for a video view placed inside of the window decorations
6529     * that it hides and shows.  This can be used with code like the second
6530     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6531     *
6532     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6533     *
6534     * @param insets Current content insets of the window.  Prior to
6535     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6536     * the insets or else you and Android will be unhappy.
6537     *
6538     * @return {@code true} if this view applied the insets and it should not
6539     * continue propagating further down the hierarchy, {@code false} otherwise.
6540     * @see #getFitsSystemWindows()
6541     * @see #setFitsSystemWindows(boolean)
6542     * @see #setSystemUiVisibility(int)
6543     *
6544     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6545     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6546     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6547     * to implement handling their own insets.
6548     */
6549    protected boolean fitSystemWindows(Rect insets) {
6550        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6551            if (insets == null) {
6552                // Null insets by definition have already been consumed.
6553                // This call cannot apply insets since there are none to apply,
6554                // so return false.
6555                return false;
6556            }
6557            // If we're not in the process of dispatching the newer apply insets call,
6558            // that means we're not in the compatibility path. Dispatch into the newer
6559            // apply insets path and take things from there.
6560            try {
6561                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6562                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6563            } finally {
6564                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6565            }
6566        } else {
6567            // We're being called from the newer apply insets path.
6568            // Perform the standard fallback behavior.
6569            return fitSystemWindowsInt(insets);
6570        }
6571    }
6572
6573    private boolean fitSystemWindowsInt(Rect insets) {
6574        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6575            mUserPaddingStart = UNDEFINED_PADDING;
6576            mUserPaddingEnd = UNDEFINED_PADDING;
6577            Rect localInsets = sThreadLocal.get();
6578            if (localInsets == null) {
6579                localInsets = new Rect();
6580                sThreadLocal.set(localInsets);
6581            }
6582            boolean res = computeFitSystemWindows(insets, localInsets);
6583            mUserPaddingLeftInitial = localInsets.left;
6584            mUserPaddingRightInitial = localInsets.right;
6585            internalSetPadding(localInsets.left, localInsets.top,
6586                    localInsets.right, localInsets.bottom);
6587            return res;
6588        }
6589        return false;
6590    }
6591
6592    /**
6593     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6594     *
6595     * <p>This method should be overridden by views that wish to apply a policy different from or
6596     * in addition to the default behavior. Clients that wish to force a view subtree
6597     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6598     *
6599     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6600     * it will be called during dispatch instead of this method. The listener may optionally
6601     * call this method from its own implementation if it wishes to apply the view's default
6602     * insets policy in addition to its own.</p>
6603     *
6604     * <p>Implementations of this method should either return the insets parameter unchanged
6605     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6606     * that this view applied itself. This allows new inset types added in future platform
6607     * versions to pass through existing implementations unchanged without being erroneously
6608     * consumed.</p>
6609     *
6610     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6611     * property is set then the view will consume the system window insets and apply them
6612     * as padding for the view.</p>
6613     *
6614     * @param insets Insets to apply
6615     * @return The supplied insets with any applied insets consumed
6616     */
6617    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6618        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6619            // We weren't called from within a direct call to fitSystemWindows,
6620            // call into it as a fallback in case we're in a class that overrides it
6621            // and has logic to perform.
6622            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6623                return insets.consumeSystemWindowInsets();
6624            }
6625        } else {
6626            // We were called from within a direct call to fitSystemWindows.
6627            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6628                return insets.consumeSystemWindowInsets();
6629            }
6630        }
6631        return insets;
6632    }
6633
6634    /**
6635     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6636     * window insets to this view. The listener's
6637     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6638     * method will be called instead of the view's
6639     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6640     *
6641     * @param listener Listener to set
6642     *
6643     * @see #onApplyWindowInsets(WindowInsets)
6644     */
6645    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6646        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6647    }
6648
6649    /**
6650     * Request to apply the given window insets to this view or another view in its subtree.
6651     *
6652     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6653     * obscured by window decorations or overlays. This can include the status and navigation bars,
6654     * action bars, input methods and more. New inset categories may be added in the future.
6655     * The method returns the insets provided minus any that were applied by this view or its
6656     * children.</p>
6657     *
6658     * <p>Clients wishing to provide custom behavior should override the
6659     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6660     * {@link OnApplyWindowInsetsListener} via the
6661     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6662     * method.</p>
6663     *
6664     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6665     * </p>
6666     *
6667     * @param insets Insets to apply
6668     * @return The provided insets minus the insets that were consumed
6669     */
6670    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6671        try {
6672            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6673            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6674                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6675            } else {
6676                return onApplyWindowInsets(insets);
6677            }
6678        } finally {
6679            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6680        }
6681    }
6682
6683    /**
6684     * @hide Compute the insets that should be consumed by this view and the ones
6685     * that should propagate to those under it.
6686     */
6687    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6688        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6689                || mAttachInfo == null
6690                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6691                        && !mAttachInfo.mOverscanRequested)) {
6692            outLocalInsets.set(inoutInsets);
6693            inoutInsets.set(0, 0, 0, 0);
6694            return true;
6695        } else {
6696            // The application wants to take care of fitting system window for
6697            // the content...  however we still need to take care of any overscan here.
6698            final Rect overscan = mAttachInfo.mOverscanInsets;
6699            outLocalInsets.set(overscan);
6700            inoutInsets.left -= overscan.left;
6701            inoutInsets.top -= overscan.top;
6702            inoutInsets.right -= overscan.right;
6703            inoutInsets.bottom -= overscan.bottom;
6704            return false;
6705        }
6706    }
6707
6708    /**
6709     * Compute insets that should be consumed by this view and the ones that should propagate
6710     * to those under it.
6711     *
6712     * @param in Insets currently being processed by this View, likely received as a parameter
6713     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6714     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6715     *                       by this view
6716     * @return Insets that should be passed along to views under this one
6717     */
6718    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6719        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6720                || mAttachInfo == null
6721                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6722            outLocalInsets.set(in.getSystemWindowInsets());
6723            return in.consumeSystemWindowInsets();
6724        } else {
6725            outLocalInsets.set(0, 0, 0, 0);
6726            return in;
6727        }
6728    }
6729
6730    /**
6731     * Sets whether or not this view should account for system screen decorations
6732     * such as the status bar and inset its content; that is, controlling whether
6733     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6734     * executed.  See that method for more details.
6735     *
6736     * <p>Note that if you are providing your own implementation of
6737     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6738     * flag to true -- your implementation will be overriding the default
6739     * implementation that checks this flag.
6740     *
6741     * @param fitSystemWindows If true, then the default implementation of
6742     * {@link #fitSystemWindows(Rect)} will be executed.
6743     *
6744     * @attr ref android.R.styleable#View_fitsSystemWindows
6745     * @see #getFitsSystemWindows()
6746     * @see #fitSystemWindows(Rect)
6747     * @see #setSystemUiVisibility(int)
6748     */
6749    public void setFitsSystemWindows(boolean fitSystemWindows) {
6750        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6751    }
6752
6753    /**
6754     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6755     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6756     * will be executed.
6757     *
6758     * @return {@code true} if the default implementation of
6759     * {@link #fitSystemWindows(Rect)} will be executed.
6760     *
6761     * @attr ref android.R.styleable#View_fitsSystemWindows
6762     * @see #setFitsSystemWindows(boolean)
6763     * @see #fitSystemWindows(Rect)
6764     * @see #setSystemUiVisibility(int)
6765     */
6766    @ViewDebug.ExportedProperty
6767    public boolean getFitsSystemWindows() {
6768        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6769    }
6770
6771    /** @hide */
6772    public boolean fitsSystemWindows() {
6773        return getFitsSystemWindows();
6774    }
6775
6776    /**
6777     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6778     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6779     */
6780    public void requestFitSystemWindows() {
6781        if (mParent != null) {
6782            mParent.requestFitSystemWindows();
6783        }
6784    }
6785
6786    /**
6787     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6788     */
6789    public void requestApplyInsets() {
6790        requestFitSystemWindows();
6791    }
6792
6793    /**
6794     * For use by PhoneWindow to make its own system window fitting optional.
6795     * @hide
6796     */
6797    public void makeOptionalFitsSystemWindows() {
6798        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6799    }
6800
6801    /**
6802     * Returns the visibility status for this view.
6803     *
6804     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6805     * @attr ref android.R.styleable#View_visibility
6806     */
6807    @ViewDebug.ExportedProperty(mapping = {
6808        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6809        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6810        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6811    })
6812    @Visibility
6813    public int getVisibility() {
6814        return mViewFlags & VISIBILITY_MASK;
6815    }
6816
6817    /**
6818     * Set the enabled state of this view.
6819     *
6820     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6821     * @attr ref android.R.styleable#View_visibility
6822     */
6823    @RemotableViewMethod
6824    public void setVisibility(@Visibility int visibility) {
6825        setFlags(visibility, VISIBILITY_MASK);
6826        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6827    }
6828
6829    /**
6830     * Returns the enabled status for this view. The interpretation of the
6831     * enabled state varies by subclass.
6832     *
6833     * @return True if this view is enabled, false otherwise.
6834     */
6835    @ViewDebug.ExportedProperty
6836    public boolean isEnabled() {
6837        return (mViewFlags & ENABLED_MASK) == ENABLED;
6838    }
6839
6840    /**
6841     * Set the enabled state of this view. The interpretation of the enabled
6842     * state varies by subclass.
6843     *
6844     * @param enabled True if this view is enabled, false otherwise.
6845     */
6846    @RemotableViewMethod
6847    public void setEnabled(boolean enabled) {
6848        if (enabled == isEnabled()) return;
6849
6850        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6851
6852        /*
6853         * The View most likely has to change its appearance, so refresh
6854         * the drawable state.
6855         */
6856        refreshDrawableState();
6857
6858        // Invalidate too, since the default behavior for views is to be
6859        // be drawn at 50% alpha rather than to change the drawable.
6860        invalidate(true);
6861
6862        if (!enabled) {
6863            cancelPendingInputEvents();
6864        }
6865    }
6866
6867    /**
6868     * Set whether this view can receive the focus.
6869     *
6870     * Setting this to false will also ensure that this view is not focusable
6871     * in touch mode.
6872     *
6873     * @param focusable If true, this view can receive the focus.
6874     *
6875     * @see #setFocusableInTouchMode(boolean)
6876     * @attr ref android.R.styleable#View_focusable
6877     */
6878    public void setFocusable(boolean focusable) {
6879        if (!focusable) {
6880            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6881        }
6882        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6883    }
6884
6885    /**
6886     * Set whether this view can receive focus while in touch mode.
6887     *
6888     * Setting this to true will also ensure that this view is focusable.
6889     *
6890     * @param focusableInTouchMode If true, this view can receive the focus while
6891     *   in touch mode.
6892     *
6893     * @see #setFocusable(boolean)
6894     * @attr ref android.R.styleable#View_focusableInTouchMode
6895     */
6896    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6897        // Focusable in touch mode should always be set before the focusable flag
6898        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6899        // which, in touch mode, will not successfully request focus on this view
6900        // because the focusable in touch mode flag is not set
6901        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6902        if (focusableInTouchMode) {
6903            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6904        }
6905    }
6906
6907    /**
6908     * Set whether this view should have sound effects enabled for events such as
6909     * clicking and touching.
6910     *
6911     * <p>You may wish to disable sound effects for a view if you already play sounds,
6912     * for instance, a dial key that plays dtmf tones.
6913     *
6914     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6915     * @see #isSoundEffectsEnabled()
6916     * @see #playSoundEffect(int)
6917     * @attr ref android.R.styleable#View_soundEffectsEnabled
6918     */
6919    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6920        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6921    }
6922
6923    /**
6924     * @return whether this view should have sound effects enabled for events such as
6925     *     clicking and touching.
6926     *
6927     * @see #setSoundEffectsEnabled(boolean)
6928     * @see #playSoundEffect(int)
6929     * @attr ref android.R.styleable#View_soundEffectsEnabled
6930     */
6931    @ViewDebug.ExportedProperty
6932    public boolean isSoundEffectsEnabled() {
6933        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6934    }
6935
6936    /**
6937     * Set whether this view should have haptic feedback for events such as
6938     * long presses.
6939     *
6940     * <p>You may wish to disable haptic feedback if your view already controls
6941     * its own haptic feedback.
6942     *
6943     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6944     * @see #isHapticFeedbackEnabled()
6945     * @see #performHapticFeedback(int)
6946     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6947     */
6948    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6949        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6950    }
6951
6952    /**
6953     * @return whether this view should have haptic feedback enabled for events
6954     * long presses.
6955     *
6956     * @see #setHapticFeedbackEnabled(boolean)
6957     * @see #performHapticFeedback(int)
6958     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6959     */
6960    @ViewDebug.ExportedProperty
6961    public boolean isHapticFeedbackEnabled() {
6962        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6963    }
6964
6965    /**
6966     * Returns the layout direction for this view.
6967     *
6968     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6969     *   {@link #LAYOUT_DIRECTION_RTL},
6970     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6971     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6972     *
6973     * @attr ref android.R.styleable#View_layoutDirection
6974     *
6975     * @hide
6976     */
6977    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6978        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6979        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6980        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6981        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6982    })
6983    @LayoutDir
6984    public int getRawLayoutDirection() {
6985        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6986    }
6987
6988    /**
6989     * Set the layout direction for this view. This will propagate a reset of layout direction
6990     * resolution to the view's children and resolve layout direction for this view.
6991     *
6992     * @param layoutDirection the layout direction to set. Should be one of:
6993     *
6994     * {@link #LAYOUT_DIRECTION_LTR},
6995     * {@link #LAYOUT_DIRECTION_RTL},
6996     * {@link #LAYOUT_DIRECTION_INHERIT},
6997     * {@link #LAYOUT_DIRECTION_LOCALE}.
6998     *
6999     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7000     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7001     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7002     *
7003     * @attr ref android.R.styleable#View_layoutDirection
7004     */
7005    @RemotableViewMethod
7006    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7007        if (getRawLayoutDirection() != layoutDirection) {
7008            // Reset the current layout direction and the resolved one
7009            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7010            resetRtlProperties();
7011            // Set the new layout direction (filtered)
7012            mPrivateFlags2 |=
7013                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7014            // We need to resolve all RTL properties as they all depend on layout direction
7015            resolveRtlPropertiesIfNeeded();
7016            requestLayout();
7017            invalidate(true);
7018        }
7019    }
7020
7021    /**
7022     * Returns the resolved layout direction for this view.
7023     *
7024     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7025     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7026     *
7027     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7028     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7029     *
7030     * @attr ref android.R.styleable#View_layoutDirection
7031     */
7032    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7033        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7034        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7035    })
7036    @ResolvedLayoutDir
7037    public int getLayoutDirection() {
7038        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7039        if (targetSdkVersion < JELLY_BEAN_MR1) {
7040            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7041            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7042        }
7043        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7044                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7045    }
7046
7047    /**
7048     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7049     * layout attribute and/or the inherited value from the parent
7050     *
7051     * @return true if the layout is right-to-left.
7052     *
7053     * @hide
7054     */
7055    @ViewDebug.ExportedProperty(category = "layout")
7056    public boolean isLayoutRtl() {
7057        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7058    }
7059
7060    /**
7061     * Indicates whether the view is currently tracking transient state that the
7062     * app should not need to concern itself with saving and restoring, but that
7063     * the framework should take special note to preserve when possible.
7064     *
7065     * <p>A view with transient state cannot be trivially rebound from an external
7066     * data source, such as an adapter binding item views in a list. This may be
7067     * because the view is performing an animation, tracking user selection
7068     * of content, or similar.</p>
7069     *
7070     * @return true if the view has transient state
7071     */
7072    @ViewDebug.ExportedProperty(category = "layout")
7073    public boolean hasTransientState() {
7074        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7075    }
7076
7077    /**
7078     * Set whether this view is currently tracking transient state that the
7079     * framework should attempt to preserve when possible. This flag is reference counted,
7080     * so every call to setHasTransientState(true) should be paired with a later call
7081     * to setHasTransientState(false).
7082     *
7083     * <p>A view with transient state cannot be trivially rebound from an external
7084     * data source, such as an adapter binding item views in a list. This may be
7085     * because the view is performing an animation, tracking user selection
7086     * of content, or similar.</p>
7087     *
7088     * @param hasTransientState true if this view has transient state
7089     */
7090    public void setHasTransientState(boolean hasTransientState) {
7091        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7092                mTransientStateCount - 1;
7093        if (mTransientStateCount < 0) {
7094            mTransientStateCount = 0;
7095            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7096                    "unmatched pair of setHasTransientState calls");
7097        } else if ((hasTransientState && mTransientStateCount == 1) ||
7098                (!hasTransientState && mTransientStateCount == 0)) {
7099            // update flag if we've just incremented up from 0 or decremented down to 0
7100            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7101                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7102            if (mParent != null) {
7103                try {
7104                    mParent.childHasTransientStateChanged(this, hasTransientState);
7105                } catch (AbstractMethodError e) {
7106                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7107                            " does not fully implement ViewParent", e);
7108                }
7109            }
7110        }
7111    }
7112
7113    /**
7114     * Returns true if this view is currently attached to a window.
7115     */
7116    public boolean isAttachedToWindow() {
7117        return mAttachInfo != null;
7118    }
7119
7120    /**
7121     * Returns true if this view has been through at least one layout since it
7122     * was last attached to or detached from a window.
7123     */
7124    public boolean isLaidOut() {
7125        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7126    }
7127
7128    /**
7129     * If this view doesn't do any drawing on its own, set this flag to
7130     * allow further optimizations. By default, this flag is not set on
7131     * View, but could be set on some View subclasses such as ViewGroup.
7132     *
7133     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7134     * you should clear this flag.
7135     *
7136     * @param willNotDraw whether or not this View draw on its own
7137     */
7138    public void setWillNotDraw(boolean willNotDraw) {
7139        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7140    }
7141
7142    /**
7143     * Returns whether or not this View draws on its own.
7144     *
7145     * @return true if this view has nothing to draw, false otherwise
7146     */
7147    @ViewDebug.ExportedProperty(category = "drawing")
7148    public boolean willNotDraw() {
7149        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7150    }
7151
7152    /**
7153     * When a View's drawing cache is enabled, drawing is redirected to an
7154     * offscreen bitmap. Some views, like an ImageView, must be able to
7155     * bypass this mechanism if they already draw a single bitmap, to avoid
7156     * unnecessary usage of the memory.
7157     *
7158     * @param willNotCacheDrawing true if this view does not cache its
7159     *        drawing, false otherwise
7160     */
7161    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7162        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7163    }
7164
7165    /**
7166     * Returns whether or not this View can cache its drawing or not.
7167     *
7168     * @return true if this view does not cache its drawing, false otherwise
7169     */
7170    @ViewDebug.ExportedProperty(category = "drawing")
7171    public boolean willNotCacheDrawing() {
7172        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7173    }
7174
7175    /**
7176     * Indicates whether this view reacts to click events or not.
7177     *
7178     * @return true if the view is clickable, false otherwise
7179     *
7180     * @see #setClickable(boolean)
7181     * @attr ref android.R.styleable#View_clickable
7182     */
7183    @ViewDebug.ExportedProperty
7184    public boolean isClickable() {
7185        return (mViewFlags & CLICKABLE) == CLICKABLE;
7186    }
7187
7188    /**
7189     * Enables or disables click events for this view. When a view
7190     * is clickable it will change its state to "pressed" on every click.
7191     * Subclasses should set the view clickable to visually react to
7192     * user's clicks.
7193     *
7194     * @param clickable true to make the view clickable, false otherwise
7195     *
7196     * @see #isClickable()
7197     * @attr ref android.R.styleable#View_clickable
7198     */
7199    public void setClickable(boolean clickable) {
7200        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7201    }
7202
7203    /**
7204     * Indicates whether this view reacts to long click events or not.
7205     *
7206     * @return true if the view is long clickable, false otherwise
7207     *
7208     * @see #setLongClickable(boolean)
7209     * @attr ref android.R.styleable#View_longClickable
7210     */
7211    public boolean isLongClickable() {
7212        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7213    }
7214
7215    /**
7216     * Enables or disables long click events for this view. When a view is long
7217     * clickable it reacts to the user holding down the button for a longer
7218     * duration than a tap. This event can either launch the listener or a
7219     * context menu.
7220     *
7221     * @param longClickable true to make the view long clickable, false otherwise
7222     * @see #isLongClickable()
7223     * @attr ref android.R.styleable#View_longClickable
7224     */
7225    public void setLongClickable(boolean longClickable) {
7226        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7227    }
7228
7229    /**
7230     * Sets the pressed state for this view and provides a touch coordinate for
7231     * animation hinting.
7232     *
7233     * @param pressed Pass true to set the View's internal state to "pressed",
7234     *            or false to reverts the View's internal state from a
7235     *            previously set "pressed" state.
7236     * @param x The x coordinate of the touch that caused the press
7237     * @param y The y coordinate of the touch that caused the press
7238     */
7239    private void setPressed(boolean pressed, float x, float y) {
7240        if (pressed) {
7241            drawableHotspotChanged(x, y);
7242        }
7243
7244        setPressed(pressed);
7245    }
7246
7247    /**
7248     * Sets the pressed state for this view.
7249     *
7250     * @see #isClickable()
7251     * @see #setClickable(boolean)
7252     *
7253     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7254     *        the View's internal state from a previously set "pressed" state.
7255     */
7256    public void setPressed(boolean pressed) {
7257        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7258
7259        if (pressed) {
7260            mPrivateFlags |= PFLAG_PRESSED;
7261        } else {
7262            mPrivateFlags &= ~PFLAG_PRESSED;
7263        }
7264
7265        if (needsRefresh) {
7266            refreshDrawableState();
7267        }
7268        dispatchSetPressed(pressed);
7269    }
7270
7271    /**
7272     * Dispatch setPressed to all of this View's children.
7273     *
7274     * @see #setPressed(boolean)
7275     *
7276     * @param pressed The new pressed state
7277     */
7278    protected void dispatchSetPressed(boolean pressed) {
7279    }
7280
7281    /**
7282     * Indicates whether the view is currently in pressed state. Unless
7283     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7284     * the pressed state.
7285     *
7286     * @see #setPressed(boolean)
7287     * @see #isClickable()
7288     * @see #setClickable(boolean)
7289     *
7290     * @return true if the view is currently pressed, false otherwise
7291     */
7292    @ViewDebug.ExportedProperty
7293    public boolean isPressed() {
7294        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7295    }
7296
7297    /**
7298     * Indicates whether this view will save its state (that is,
7299     * whether its {@link #onSaveInstanceState} method will be called).
7300     *
7301     * @return Returns true if the view state saving is enabled, else false.
7302     *
7303     * @see #setSaveEnabled(boolean)
7304     * @attr ref android.R.styleable#View_saveEnabled
7305     */
7306    public boolean isSaveEnabled() {
7307        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7308    }
7309
7310    /**
7311     * Controls whether the saving of this view's state is
7312     * enabled (that is, whether its {@link #onSaveInstanceState} method
7313     * will be called).  Note that even if freezing is enabled, the
7314     * view still must have an id assigned to it (via {@link #setId(int)})
7315     * for its state to be saved.  This flag can only disable the
7316     * saving of this view; any child views may still have their state saved.
7317     *
7318     * @param enabled Set to false to <em>disable</em> state saving, or true
7319     * (the default) to allow it.
7320     *
7321     * @see #isSaveEnabled()
7322     * @see #setId(int)
7323     * @see #onSaveInstanceState()
7324     * @attr ref android.R.styleable#View_saveEnabled
7325     */
7326    public void setSaveEnabled(boolean enabled) {
7327        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7328    }
7329
7330    /**
7331     * Gets whether the framework should discard touches when the view's
7332     * window is obscured by another visible window.
7333     * Refer to the {@link View} security documentation for more details.
7334     *
7335     * @return True if touch filtering is enabled.
7336     *
7337     * @see #setFilterTouchesWhenObscured(boolean)
7338     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7339     */
7340    @ViewDebug.ExportedProperty
7341    public boolean getFilterTouchesWhenObscured() {
7342        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7343    }
7344
7345    /**
7346     * Sets whether the framework should discard touches when the view's
7347     * window is obscured by another visible window.
7348     * Refer to the {@link View} security documentation for more details.
7349     *
7350     * @param enabled True if touch filtering should be enabled.
7351     *
7352     * @see #getFilterTouchesWhenObscured
7353     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7354     */
7355    public void setFilterTouchesWhenObscured(boolean enabled) {
7356        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7357                FILTER_TOUCHES_WHEN_OBSCURED);
7358    }
7359
7360    /**
7361     * Indicates whether the entire hierarchy under this view will save its
7362     * state when a state saving traversal occurs from its parent.  The default
7363     * is true; if false, these views will not be saved unless
7364     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7365     *
7366     * @return Returns true if the view state saving from parent is enabled, else false.
7367     *
7368     * @see #setSaveFromParentEnabled(boolean)
7369     */
7370    public boolean isSaveFromParentEnabled() {
7371        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7372    }
7373
7374    /**
7375     * Controls whether the entire hierarchy under this view will save its
7376     * state when a state saving traversal occurs from its parent.  The default
7377     * is true; if false, these views will not be saved unless
7378     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7379     *
7380     * @param enabled Set to false to <em>disable</em> state saving, or true
7381     * (the default) to allow it.
7382     *
7383     * @see #isSaveFromParentEnabled()
7384     * @see #setId(int)
7385     * @see #onSaveInstanceState()
7386     */
7387    public void setSaveFromParentEnabled(boolean enabled) {
7388        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7389    }
7390
7391
7392    /**
7393     * Returns whether this View is able to take focus.
7394     *
7395     * @return True if this view can take focus, or false otherwise.
7396     * @attr ref android.R.styleable#View_focusable
7397     */
7398    @ViewDebug.ExportedProperty(category = "focus")
7399    public final boolean isFocusable() {
7400        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7401    }
7402
7403    /**
7404     * When a view is focusable, it may not want to take focus when in touch mode.
7405     * For example, a button would like focus when the user is navigating via a D-pad
7406     * so that the user can click on it, but once the user starts touching the screen,
7407     * the button shouldn't take focus
7408     * @return Whether the view is focusable in touch mode.
7409     * @attr ref android.R.styleable#View_focusableInTouchMode
7410     */
7411    @ViewDebug.ExportedProperty
7412    public final boolean isFocusableInTouchMode() {
7413        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7414    }
7415
7416    /**
7417     * Find the nearest view in the specified direction that can take focus.
7418     * This does not actually give focus to that view.
7419     *
7420     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7421     *
7422     * @return The nearest focusable in the specified direction, or null if none
7423     *         can be found.
7424     */
7425    public View focusSearch(@FocusRealDirection int direction) {
7426        if (mParent != null) {
7427            return mParent.focusSearch(this, direction);
7428        } else {
7429            return null;
7430        }
7431    }
7432
7433    /**
7434     * This method is the last chance for the focused view and its ancestors to
7435     * respond to an arrow key. This is called when the focused view did not
7436     * consume the key internally, nor could the view system find a new view in
7437     * the requested direction to give focus to.
7438     *
7439     * @param focused The currently focused view.
7440     * @param direction The direction focus wants to move. One of FOCUS_UP,
7441     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7442     * @return True if the this view consumed this unhandled move.
7443     */
7444    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7445        return false;
7446    }
7447
7448    /**
7449     * If a user manually specified the next view id for a particular direction,
7450     * use the root to look up the view.
7451     * @param root The root view of the hierarchy containing this view.
7452     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7453     * or FOCUS_BACKWARD.
7454     * @return The user specified next view, or null if there is none.
7455     */
7456    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7457        switch (direction) {
7458            case FOCUS_LEFT:
7459                if (mNextFocusLeftId == View.NO_ID) return null;
7460                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7461            case FOCUS_RIGHT:
7462                if (mNextFocusRightId == View.NO_ID) return null;
7463                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7464            case FOCUS_UP:
7465                if (mNextFocusUpId == View.NO_ID) return null;
7466                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7467            case FOCUS_DOWN:
7468                if (mNextFocusDownId == View.NO_ID) return null;
7469                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7470            case FOCUS_FORWARD:
7471                if (mNextFocusForwardId == View.NO_ID) return null;
7472                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7473            case FOCUS_BACKWARD: {
7474                if (mID == View.NO_ID) return null;
7475                final int id = mID;
7476                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7477                    @Override
7478                    public boolean apply(View t) {
7479                        return t.mNextFocusForwardId == id;
7480                    }
7481                });
7482            }
7483        }
7484        return null;
7485    }
7486
7487    private View findViewInsideOutShouldExist(View root, int id) {
7488        if (mMatchIdPredicate == null) {
7489            mMatchIdPredicate = new MatchIdPredicate();
7490        }
7491        mMatchIdPredicate.mId = id;
7492        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7493        if (result == null) {
7494            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7495        }
7496        return result;
7497    }
7498
7499    /**
7500     * Find and return all focusable views that are descendants of this view,
7501     * possibly including this view if it is focusable itself.
7502     *
7503     * @param direction The direction of the focus
7504     * @return A list of focusable views
7505     */
7506    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7507        ArrayList<View> result = new ArrayList<View>(24);
7508        addFocusables(result, direction);
7509        return result;
7510    }
7511
7512    /**
7513     * Add any focusable views that are descendants of this view (possibly
7514     * including this view if it is focusable itself) to views.  If we are in touch mode,
7515     * only add views that are also focusable in touch mode.
7516     *
7517     * @param views Focusable views found so far
7518     * @param direction The direction of the focus
7519     */
7520    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7521        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7522    }
7523
7524    /**
7525     * Adds any focusable views that are descendants of this view (possibly
7526     * including this view if it is focusable itself) to views. This method
7527     * adds all focusable views regardless if we are in touch mode or
7528     * only views focusable in touch mode if we are in touch mode or
7529     * only views that can take accessibility focus if accessibility is enabeld
7530     * depending on the focusable mode paramater.
7531     *
7532     * @param views Focusable views found so far or null if all we are interested is
7533     *        the number of focusables.
7534     * @param direction The direction of the focus.
7535     * @param focusableMode The type of focusables to be added.
7536     *
7537     * @see #FOCUSABLES_ALL
7538     * @see #FOCUSABLES_TOUCH_MODE
7539     */
7540    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7541            @FocusableMode int focusableMode) {
7542        if (views == null) {
7543            return;
7544        }
7545        if (!isFocusable()) {
7546            return;
7547        }
7548        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7549                && isInTouchMode() && !isFocusableInTouchMode()) {
7550            return;
7551        }
7552        views.add(this);
7553    }
7554
7555    /**
7556     * Finds the Views that contain given text. The containment is case insensitive.
7557     * The search is performed by either the text that the View renders or the content
7558     * description that describes the view for accessibility purposes and the view does
7559     * not render or both. Clients can specify how the search is to be performed via
7560     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7561     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7562     *
7563     * @param outViews The output list of matching Views.
7564     * @param searched The text to match against.
7565     *
7566     * @see #FIND_VIEWS_WITH_TEXT
7567     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7568     * @see #setContentDescription(CharSequence)
7569     */
7570    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7571            @FindViewFlags int flags) {
7572        if (getAccessibilityNodeProvider() != null) {
7573            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7574                outViews.add(this);
7575            }
7576        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7577                && (searched != null && searched.length() > 0)
7578                && (mContentDescription != null && mContentDescription.length() > 0)) {
7579            String searchedLowerCase = searched.toString().toLowerCase();
7580            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7581            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7582                outViews.add(this);
7583            }
7584        }
7585    }
7586
7587    /**
7588     * Find and return all touchable views that are descendants of this view,
7589     * possibly including this view if it is touchable itself.
7590     *
7591     * @return A list of touchable views
7592     */
7593    public ArrayList<View> getTouchables() {
7594        ArrayList<View> result = new ArrayList<View>();
7595        addTouchables(result);
7596        return result;
7597    }
7598
7599    /**
7600     * Add any touchable views that are descendants of this view (possibly
7601     * including this view if it is touchable itself) to views.
7602     *
7603     * @param views Touchable views found so far
7604     */
7605    public void addTouchables(ArrayList<View> views) {
7606        final int viewFlags = mViewFlags;
7607
7608        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7609                && (viewFlags & ENABLED_MASK) == ENABLED) {
7610            views.add(this);
7611        }
7612    }
7613
7614    /**
7615     * Returns whether this View is accessibility focused.
7616     *
7617     * @return True if this View is accessibility focused.
7618     */
7619    public boolean isAccessibilityFocused() {
7620        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7621    }
7622
7623    /**
7624     * Call this to try to give accessibility focus to this view.
7625     *
7626     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7627     * returns false or the view is no visible or the view already has accessibility
7628     * focus.
7629     *
7630     * See also {@link #focusSearch(int)}, which is what you call to say that you
7631     * have focus, and you want your parent to look for the next one.
7632     *
7633     * @return Whether this view actually took accessibility focus.
7634     *
7635     * @hide
7636     */
7637    public boolean requestAccessibilityFocus() {
7638        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7639        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7640            return false;
7641        }
7642        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7643            return false;
7644        }
7645        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7646            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7647            ViewRootImpl viewRootImpl = getViewRootImpl();
7648            if (viewRootImpl != null) {
7649                viewRootImpl.setAccessibilityFocus(this, null);
7650            }
7651            invalidate();
7652            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7653            return true;
7654        }
7655        return false;
7656    }
7657
7658    /**
7659     * Call this to try to clear accessibility focus of this view.
7660     *
7661     * See also {@link #focusSearch(int)}, which is what you call to say that you
7662     * have focus, and you want your parent to look for the next one.
7663     *
7664     * @hide
7665     */
7666    public void clearAccessibilityFocus() {
7667        clearAccessibilityFocusNoCallbacks();
7668        // Clear the global reference of accessibility focus if this
7669        // view or any of its descendants had accessibility focus.
7670        ViewRootImpl viewRootImpl = getViewRootImpl();
7671        if (viewRootImpl != null) {
7672            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7673            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7674                viewRootImpl.setAccessibilityFocus(null, null);
7675            }
7676        }
7677    }
7678
7679    private void sendAccessibilityHoverEvent(int eventType) {
7680        // Since we are not delivering to a client accessibility events from not
7681        // important views (unless the clinet request that) we need to fire the
7682        // event from the deepest view exposed to the client. As a consequence if
7683        // the user crosses a not exposed view the client will see enter and exit
7684        // of the exposed predecessor followed by and enter and exit of that same
7685        // predecessor when entering and exiting the not exposed descendant. This
7686        // is fine since the client has a clear idea which view is hovered at the
7687        // price of a couple more events being sent. This is a simple and
7688        // working solution.
7689        View source = this;
7690        while (true) {
7691            if (source.includeForAccessibility()) {
7692                source.sendAccessibilityEvent(eventType);
7693                return;
7694            }
7695            ViewParent parent = source.getParent();
7696            if (parent instanceof View) {
7697                source = (View) parent;
7698            } else {
7699                return;
7700            }
7701        }
7702    }
7703
7704    /**
7705     * Clears accessibility focus without calling any callback methods
7706     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7707     * is used for clearing accessibility focus when giving this focus to
7708     * another view.
7709     */
7710    void clearAccessibilityFocusNoCallbacks() {
7711        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7712            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7713            invalidate();
7714            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7715        }
7716    }
7717
7718    /**
7719     * Call this to try to give focus to a specific view or to one of its
7720     * descendants.
7721     *
7722     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7723     * false), or if it is focusable and it is not focusable in touch mode
7724     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7725     *
7726     * See also {@link #focusSearch(int)}, which is what you call to say that you
7727     * have focus, and you want your parent to look for the next one.
7728     *
7729     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7730     * {@link #FOCUS_DOWN} and <code>null</code>.
7731     *
7732     * @return Whether this view or one of its descendants actually took focus.
7733     */
7734    public final boolean requestFocus() {
7735        return requestFocus(View.FOCUS_DOWN);
7736    }
7737
7738    /**
7739     * Call this to try to give focus to a specific view or to one of its
7740     * descendants and give it a hint about what direction focus is heading.
7741     *
7742     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7743     * false), or if it is focusable and it is not focusable in touch mode
7744     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7745     *
7746     * See also {@link #focusSearch(int)}, which is what you call to say that you
7747     * have focus, and you want your parent to look for the next one.
7748     *
7749     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7750     * <code>null</code> set for the previously focused rectangle.
7751     *
7752     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7753     * @return Whether this view or one of its descendants actually took focus.
7754     */
7755    public final boolean requestFocus(int direction) {
7756        return requestFocus(direction, null);
7757    }
7758
7759    /**
7760     * Call this to try to give focus to a specific view or to one of its descendants
7761     * and give it hints about the direction and a specific rectangle that the focus
7762     * is coming from.  The rectangle can help give larger views a finer grained hint
7763     * about where focus is coming from, and therefore, where to show selection, or
7764     * forward focus change internally.
7765     *
7766     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7767     * false), or if it is focusable and it is not focusable in touch mode
7768     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7769     *
7770     * A View will not take focus if it is not visible.
7771     *
7772     * A View will not take focus if one of its parents has
7773     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7774     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7775     *
7776     * See also {@link #focusSearch(int)}, which is what you call to say that you
7777     * have focus, and you want your parent to look for the next one.
7778     *
7779     * You may wish to override this method if your custom {@link View} has an internal
7780     * {@link View} that it wishes to forward the request to.
7781     *
7782     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7783     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7784     *        to give a finer grained hint about where focus is coming from.  May be null
7785     *        if there is no hint.
7786     * @return Whether this view or one of its descendants actually took focus.
7787     */
7788    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7789        return requestFocusNoSearch(direction, previouslyFocusedRect);
7790    }
7791
7792    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7793        // need to be focusable
7794        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7795                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7796            return false;
7797        }
7798
7799        // need to be focusable in touch mode if in touch mode
7800        if (isInTouchMode() &&
7801            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7802               return false;
7803        }
7804
7805        // need to not have any parents blocking us
7806        if (hasAncestorThatBlocksDescendantFocus()) {
7807            return false;
7808        }
7809
7810        handleFocusGainInternal(direction, previouslyFocusedRect);
7811        return true;
7812    }
7813
7814    /**
7815     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7816     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7817     * touch mode to request focus when they are touched.
7818     *
7819     * @return Whether this view or one of its descendants actually took focus.
7820     *
7821     * @see #isInTouchMode()
7822     *
7823     */
7824    public final boolean requestFocusFromTouch() {
7825        // Leave touch mode if we need to
7826        if (isInTouchMode()) {
7827            ViewRootImpl viewRoot = getViewRootImpl();
7828            if (viewRoot != null) {
7829                viewRoot.ensureTouchMode(false);
7830            }
7831        }
7832        return requestFocus(View.FOCUS_DOWN);
7833    }
7834
7835    /**
7836     * @return Whether any ancestor of this view blocks descendant focus.
7837     */
7838    private boolean hasAncestorThatBlocksDescendantFocus() {
7839        final boolean focusableInTouchMode = isFocusableInTouchMode();
7840        ViewParent ancestor = mParent;
7841        while (ancestor instanceof ViewGroup) {
7842            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7843            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7844                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7845                return true;
7846            } else {
7847                ancestor = vgAncestor.getParent();
7848            }
7849        }
7850        return false;
7851    }
7852
7853    /**
7854     * Gets the mode for determining whether this View is important for accessibility
7855     * which is if it fires accessibility events and if it is reported to
7856     * accessibility services that query the screen.
7857     *
7858     * @return The mode for determining whether a View is important for accessibility.
7859     *
7860     * @attr ref android.R.styleable#View_importantForAccessibility
7861     *
7862     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7863     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7864     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7865     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7866     */
7867    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7868            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7869            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7870            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7871            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7872                    to = "noHideDescendants")
7873        })
7874    public int getImportantForAccessibility() {
7875        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7876                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7877    }
7878
7879    /**
7880     * Sets the live region mode for this view. This indicates to accessibility
7881     * services whether they should automatically notify the user about changes
7882     * to the view's content description or text, or to the content descriptions
7883     * or text of the view's children (where applicable).
7884     * <p>
7885     * For example, in a login screen with a TextView that displays an "incorrect
7886     * password" notification, that view should be marked as a live region with
7887     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7888     * <p>
7889     * To disable change notifications for this view, use
7890     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7891     * mode for most views.
7892     * <p>
7893     * To indicate that the user should be notified of changes, use
7894     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7895     * <p>
7896     * If the view's changes should interrupt ongoing speech and notify the user
7897     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7898     *
7899     * @param mode The live region mode for this view, one of:
7900     *        <ul>
7901     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7902     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7903     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7904     *        </ul>
7905     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7906     */
7907    public void setAccessibilityLiveRegion(int mode) {
7908        if (mode != getAccessibilityLiveRegion()) {
7909            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7910            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7911                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7912            notifyViewAccessibilityStateChangedIfNeeded(
7913                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7914        }
7915    }
7916
7917    /**
7918     * Gets the live region mode for this View.
7919     *
7920     * @return The live region mode for the view.
7921     *
7922     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7923     *
7924     * @see #setAccessibilityLiveRegion(int)
7925     */
7926    public int getAccessibilityLiveRegion() {
7927        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7928                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7929    }
7930
7931    /**
7932     * Sets how to determine whether this view is important for accessibility
7933     * which is if it fires accessibility events and if it is reported to
7934     * accessibility services that query the screen.
7935     *
7936     * @param mode How to determine whether this view is important for accessibility.
7937     *
7938     * @attr ref android.R.styleable#View_importantForAccessibility
7939     *
7940     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7941     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7942     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7943     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7944     */
7945    public void setImportantForAccessibility(int mode) {
7946        final int oldMode = getImportantForAccessibility();
7947        if (mode != oldMode) {
7948            // If we're moving between AUTO and another state, we might not need
7949            // to send a subtree changed notification. We'll store the computed
7950            // importance, since we'll need to check it later to make sure.
7951            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7952                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7953            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7954            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7955            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7956                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7957            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7958                notifySubtreeAccessibilityStateChangedIfNeeded();
7959            } else {
7960                notifyViewAccessibilityStateChangedIfNeeded(
7961                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7962            }
7963        }
7964    }
7965
7966    /**
7967     * Computes whether this view should be exposed for accessibility. In
7968     * general, views that are interactive or provide information are exposed
7969     * while views that serve only as containers are hidden.
7970     * <p>
7971     * If an ancestor of this view has importance
7972     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7973     * returns <code>false</code>.
7974     * <p>
7975     * Otherwise, the value is computed according to the view's
7976     * {@link #getImportantForAccessibility()} value:
7977     * <ol>
7978     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7979     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7980     * </code>
7981     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7982     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7983     * view satisfies any of the following:
7984     * <ul>
7985     * <li>Is actionable, e.g. {@link #isClickable()},
7986     * {@link #isLongClickable()}, or {@link #isFocusable()}
7987     * <li>Has an {@link AccessibilityDelegate}
7988     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7989     * {@link OnKeyListener}, etc.
7990     * <li>Is an accessibility live region, e.g.
7991     * {@link #getAccessibilityLiveRegion()} is not
7992     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7993     * </ul>
7994     * </ol>
7995     *
7996     * @return Whether the view is exposed for accessibility.
7997     * @see #setImportantForAccessibility(int)
7998     * @see #getImportantForAccessibility()
7999     */
8000    public boolean isImportantForAccessibility() {
8001        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8002                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8003        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8004                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8005            return false;
8006        }
8007
8008        // Check parent mode to ensure we're not hidden.
8009        ViewParent parent = mParent;
8010        while (parent instanceof View) {
8011            if (((View) parent).getImportantForAccessibility()
8012                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8013                return false;
8014            }
8015            parent = parent.getParent();
8016        }
8017
8018        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8019                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8020                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8021    }
8022
8023    /**
8024     * Gets the parent for accessibility purposes. Note that the parent for
8025     * accessibility is not necessary the immediate parent. It is the first
8026     * predecessor that is important for accessibility.
8027     *
8028     * @return The parent for accessibility purposes.
8029     */
8030    public ViewParent getParentForAccessibility() {
8031        if (mParent instanceof View) {
8032            View parentView = (View) mParent;
8033            if (parentView.includeForAccessibility()) {
8034                return mParent;
8035            } else {
8036                return mParent.getParentForAccessibility();
8037            }
8038        }
8039        return null;
8040    }
8041
8042    /**
8043     * Adds the children of a given View for accessibility. Since some Views are
8044     * not important for accessibility the children for accessibility are not
8045     * necessarily direct children of the view, rather they are the first level of
8046     * descendants important for accessibility.
8047     *
8048     * @param children The list of children for accessibility.
8049     */
8050    public void addChildrenForAccessibility(ArrayList<View> children) {
8051
8052    }
8053
8054    /**
8055     * Whether to regard this view for accessibility. A view is regarded for
8056     * accessibility if it is important for accessibility or the querying
8057     * accessibility service has explicitly requested that view not
8058     * important for accessibility are regarded.
8059     *
8060     * @return Whether to regard the view for accessibility.
8061     *
8062     * @hide
8063     */
8064    public boolean includeForAccessibility() {
8065        if (mAttachInfo != null) {
8066            return (mAttachInfo.mAccessibilityFetchFlags
8067                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8068                    || isImportantForAccessibility();
8069        }
8070        return false;
8071    }
8072
8073    /**
8074     * Returns whether the View is considered actionable from
8075     * accessibility perspective. Such view are important for
8076     * accessibility.
8077     *
8078     * @return True if the view is actionable for accessibility.
8079     *
8080     * @hide
8081     */
8082    public boolean isActionableForAccessibility() {
8083        return (isClickable() || isLongClickable() || isFocusable());
8084    }
8085
8086    /**
8087     * Returns whether the View has registered callbacks which makes it
8088     * important for accessibility.
8089     *
8090     * @return True if the view is actionable for accessibility.
8091     */
8092    private boolean hasListenersForAccessibility() {
8093        ListenerInfo info = getListenerInfo();
8094        return mTouchDelegate != null || info.mOnKeyListener != null
8095                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8096                || info.mOnHoverListener != null || info.mOnDragListener != null;
8097    }
8098
8099    /**
8100     * Notifies that the accessibility state of this view changed. The change
8101     * is local to this view and does not represent structural changes such
8102     * as children and parent. For example, the view became focusable. The
8103     * notification is at at most once every
8104     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8105     * to avoid unnecessary load to the system. Also once a view has a pending
8106     * notification this method is a NOP until the notification has been sent.
8107     *
8108     * @hide
8109     */
8110    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8111        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8112            return;
8113        }
8114        if (mSendViewStateChangedAccessibilityEvent == null) {
8115            mSendViewStateChangedAccessibilityEvent =
8116                    new SendViewStateChangedAccessibilityEvent();
8117        }
8118        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8119    }
8120
8121    /**
8122     * Notifies that the accessibility state of this view changed. The change
8123     * is *not* local to this view and does represent structural changes such
8124     * as children and parent. For example, the view size changed. The
8125     * notification is at at most once every
8126     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8127     * to avoid unnecessary load to the system. Also once a view has a pending
8128     * notification this method is a NOP until the notification has been sent.
8129     *
8130     * @hide
8131     */
8132    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8133        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8134            return;
8135        }
8136        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8137            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8138            if (mParent != null) {
8139                try {
8140                    mParent.notifySubtreeAccessibilityStateChanged(
8141                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8142                } catch (AbstractMethodError e) {
8143                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8144                            " does not fully implement ViewParent", e);
8145                }
8146            }
8147        }
8148    }
8149
8150    /**
8151     * Reset the flag indicating the accessibility state of the subtree rooted
8152     * at this view changed.
8153     */
8154    void resetSubtreeAccessibilityStateChanged() {
8155        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8156    }
8157
8158    /**
8159     * Performs the specified accessibility action on the view. For
8160     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8161     * <p>
8162     * If an {@link AccessibilityDelegate} has been specified via calling
8163     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8164     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8165     * is responsible for handling this call.
8166     * </p>
8167     *
8168     * @param action The action to perform.
8169     * @param arguments Optional action arguments.
8170     * @return Whether the action was performed.
8171     */
8172    public boolean performAccessibilityAction(int action, Bundle arguments) {
8173      if (mAccessibilityDelegate != null) {
8174          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8175      } else {
8176          return performAccessibilityActionInternal(action, arguments);
8177      }
8178    }
8179
8180   /**
8181    * @see #performAccessibilityAction(int, Bundle)
8182    *
8183    * Note: Called from the default {@link AccessibilityDelegate}.
8184    */
8185    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8186        switch (action) {
8187            case AccessibilityNodeInfo.ACTION_CLICK: {
8188                if (isClickable()) {
8189                    performClick();
8190                    return true;
8191                }
8192            } break;
8193            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8194                if (isLongClickable()) {
8195                    performLongClick();
8196                    return true;
8197                }
8198            } break;
8199            case AccessibilityNodeInfo.ACTION_FOCUS: {
8200                if (!hasFocus()) {
8201                    // Get out of touch mode since accessibility
8202                    // wants to move focus around.
8203                    getViewRootImpl().ensureTouchMode(false);
8204                    return requestFocus();
8205                }
8206            } break;
8207            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8208                if (hasFocus()) {
8209                    clearFocus();
8210                    return !isFocused();
8211                }
8212            } break;
8213            case AccessibilityNodeInfo.ACTION_SELECT: {
8214                if (!isSelected()) {
8215                    setSelected(true);
8216                    return isSelected();
8217                }
8218            } break;
8219            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8220                if (isSelected()) {
8221                    setSelected(false);
8222                    return !isSelected();
8223                }
8224            } break;
8225            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8226                if (!isAccessibilityFocused()) {
8227                    return requestAccessibilityFocus();
8228                }
8229            } break;
8230            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8231                if (isAccessibilityFocused()) {
8232                    clearAccessibilityFocus();
8233                    return true;
8234                }
8235            } break;
8236            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8237                if (arguments != null) {
8238                    final int granularity = arguments.getInt(
8239                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8240                    final boolean extendSelection = arguments.getBoolean(
8241                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8242                    return traverseAtGranularity(granularity, true, extendSelection);
8243                }
8244            } break;
8245            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8246                if (arguments != null) {
8247                    final int granularity = arguments.getInt(
8248                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8249                    final boolean extendSelection = arguments.getBoolean(
8250                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8251                    return traverseAtGranularity(granularity, false, extendSelection);
8252                }
8253            } break;
8254            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8255                CharSequence text = getIterableTextForAccessibility();
8256                if (text == null) {
8257                    return false;
8258                }
8259                final int start = (arguments != null) ? arguments.getInt(
8260                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8261                final int end = (arguments != null) ? arguments.getInt(
8262                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8263                // Only cursor position can be specified (selection length == 0)
8264                if ((getAccessibilitySelectionStart() != start
8265                        || getAccessibilitySelectionEnd() != end)
8266                        && (start == end)) {
8267                    setAccessibilitySelection(start, end);
8268                    notifyViewAccessibilityStateChangedIfNeeded(
8269                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8270                    return true;
8271                }
8272            } break;
8273        }
8274        return false;
8275    }
8276
8277    private boolean traverseAtGranularity(int granularity, boolean forward,
8278            boolean extendSelection) {
8279        CharSequence text = getIterableTextForAccessibility();
8280        if (text == null || text.length() == 0) {
8281            return false;
8282        }
8283        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8284        if (iterator == null) {
8285            return false;
8286        }
8287        int current = getAccessibilitySelectionEnd();
8288        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8289            current = forward ? 0 : text.length();
8290        }
8291        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8292        if (range == null) {
8293            return false;
8294        }
8295        final int segmentStart = range[0];
8296        final int segmentEnd = range[1];
8297        int selectionStart;
8298        int selectionEnd;
8299        if (extendSelection && isAccessibilitySelectionExtendable()) {
8300            selectionStart = getAccessibilitySelectionStart();
8301            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8302                selectionStart = forward ? segmentStart : segmentEnd;
8303            }
8304            selectionEnd = forward ? segmentEnd : segmentStart;
8305        } else {
8306            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8307        }
8308        setAccessibilitySelection(selectionStart, selectionEnd);
8309        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8310                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8311        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8312        return true;
8313    }
8314
8315    /**
8316     * Gets the text reported for accessibility purposes.
8317     *
8318     * @return The accessibility text.
8319     *
8320     * @hide
8321     */
8322    public CharSequence getIterableTextForAccessibility() {
8323        return getContentDescription();
8324    }
8325
8326    /**
8327     * Gets whether accessibility selection can be extended.
8328     *
8329     * @return If selection is extensible.
8330     *
8331     * @hide
8332     */
8333    public boolean isAccessibilitySelectionExtendable() {
8334        return false;
8335    }
8336
8337    /**
8338     * @hide
8339     */
8340    public int getAccessibilitySelectionStart() {
8341        return mAccessibilityCursorPosition;
8342    }
8343
8344    /**
8345     * @hide
8346     */
8347    public int getAccessibilitySelectionEnd() {
8348        return getAccessibilitySelectionStart();
8349    }
8350
8351    /**
8352     * @hide
8353     */
8354    public void setAccessibilitySelection(int start, int end) {
8355        if (start ==  end && end == mAccessibilityCursorPosition) {
8356            return;
8357        }
8358        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8359            mAccessibilityCursorPosition = start;
8360        } else {
8361            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8362        }
8363        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8364    }
8365
8366    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8367            int fromIndex, int toIndex) {
8368        if (mParent == null) {
8369            return;
8370        }
8371        AccessibilityEvent event = AccessibilityEvent.obtain(
8372                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8373        onInitializeAccessibilityEvent(event);
8374        onPopulateAccessibilityEvent(event);
8375        event.setFromIndex(fromIndex);
8376        event.setToIndex(toIndex);
8377        event.setAction(action);
8378        event.setMovementGranularity(granularity);
8379        mParent.requestSendAccessibilityEvent(this, event);
8380    }
8381
8382    /**
8383     * @hide
8384     */
8385    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8386        switch (granularity) {
8387            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8388                CharSequence text = getIterableTextForAccessibility();
8389                if (text != null && text.length() > 0) {
8390                    CharacterTextSegmentIterator iterator =
8391                        CharacterTextSegmentIterator.getInstance(
8392                                mContext.getResources().getConfiguration().locale);
8393                    iterator.initialize(text.toString());
8394                    return iterator;
8395                }
8396            } break;
8397            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8398                CharSequence text = getIterableTextForAccessibility();
8399                if (text != null && text.length() > 0) {
8400                    WordTextSegmentIterator iterator =
8401                        WordTextSegmentIterator.getInstance(
8402                                mContext.getResources().getConfiguration().locale);
8403                    iterator.initialize(text.toString());
8404                    return iterator;
8405                }
8406            } break;
8407            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8408                CharSequence text = getIterableTextForAccessibility();
8409                if (text != null && text.length() > 0) {
8410                    ParagraphTextSegmentIterator iterator =
8411                        ParagraphTextSegmentIterator.getInstance();
8412                    iterator.initialize(text.toString());
8413                    return iterator;
8414                }
8415            } break;
8416        }
8417        return null;
8418    }
8419
8420    /**
8421     * @hide
8422     */
8423    public void dispatchStartTemporaryDetach() {
8424        onStartTemporaryDetach();
8425    }
8426
8427    /**
8428     * This is called when a container is going to temporarily detach a child, with
8429     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8430     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8431     * {@link #onDetachedFromWindow()} when the container is done.
8432     */
8433    public void onStartTemporaryDetach() {
8434        removeUnsetPressCallback();
8435        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8436    }
8437
8438    /**
8439     * @hide
8440     */
8441    public void dispatchFinishTemporaryDetach() {
8442        onFinishTemporaryDetach();
8443    }
8444
8445    /**
8446     * Called after {@link #onStartTemporaryDetach} when the container is done
8447     * changing the view.
8448     */
8449    public void onFinishTemporaryDetach() {
8450    }
8451
8452    /**
8453     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8454     * for this view's window.  Returns null if the view is not currently attached
8455     * to the window.  Normally you will not need to use this directly, but
8456     * just use the standard high-level event callbacks like
8457     * {@link #onKeyDown(int, KeyEvent)}.
8458     */
8459    public KeyEvent.DispatcherState getKeyDispatcherState() {
8460        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8461    }
8462
8463    /**
8464     * Dispatch a key event before it is processed by any input method
8465     * associated with the view hierarchy.  This can be used to intercept
8466     * key events in special situations before the IME consumes them; a
8467     * typical example would be handling the BACK key to update the application's
8468     * UI instead of allowing the IME to see it and close itself.
8469     *
8470     * @param event The key event to be dispatched.
8471     * @return True if the event was handled, false otherwise.
8472     */
8473    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8474        return onKeyPreIme(event.getKeyCode(), event);
8475    }
8476
8477    /**
8478     * Dispatch a key event to the next view on the focus path. This path runs
8479     * from the top of the view tree down to the currently focused view. If this
8480     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8481     * the next node down the focus path. This method also fires any key
8482     * listeners.
8483     *
8484     * @param event The key event to be dispatched.
8485     * @return True if the event was handled, false otherwise.
8486     */
8487    public boolean dispatchKeyEvent(KeyEvent event) {
8488        if (mInputEventConsistencyVerifier != null) {
8489            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8490        }
8491
8492        // Give any attached key listener a first crack at the event.
8493        //noinspection SimplifiableIfStatement
8494        ListenerInfo li = mListenerInfo;
8495        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8496                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8497            return true;
8498        }
8499
8500        if (event.dispatch(this, mAttachInfo != null
8501                ? mAttachInfo.mKeyDispatchState : null, this)) {
8502            return true;
8503        }
8504
8505        if (mInputEventConsistencyVerifier != null) {
8506            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8507        }
8508        return false;
8509    }
8510
8511    /**
8512     * Dispatches a key shortcut event.
8513     *
8514     * @param event The key event to be dispatched.
8515     * @return True if the event was handled by the view, false otherwise.
8516     */
8517    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8518        return onKeyShortcut(event.getKeyCode(), event);
8519    }
8520
8521    /**
8522     * Pass the touch screen motion event down to the target view, or this
8523     * view if it is the target.
8524     *
8525     * @param event The motion event to be dispatched.
8526     * @return True if the event was handled by the view, false otherwise.
8527     */
8528    public boolean dispatchTouchEvent(MotionEvent event) {
8529        boolean result = false;
8530
8531        if (mInputEventConsistencyVerifier != null) {
8532            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8533        }
8534
8535        final int actionMasked = event.getActionMasked();
8536        if (actionMasked == MotionEvent.ACTION_DOWN) {
8537            // Defensive cleanup for new gesture
8538            stopNestedScroll();
8539        }
8540
8541        if (onFilterTouchEventForSecurity(event)) {
8542            //noinspection SimplifiableIfStatement
8543            ListenerInfo li = mListenerInfo;
8544            if (li != null && li.mOnTouchListener != null
8545                    && (mViewFlags & ENABLED_MASK) == ENABLED
8546                    && li.mOnTouchListener.onTouch(this, event)) {
8547                result = true;
8548            }
8549
8550            if (!result && onTouchEvent(event)) {
8551                result = true;
8552            }
8553        }
8554
8555        if (!result && mInputEventConsistencyVerifier != null) {
8556            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8557        }
8558
8559        // Clean up after nested scrolls if this is the end of a gesture;
8560        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8561        // of the gesture.
8562        if (actionMasked == MotionEvent.ACTION_UP ||
8563                actionMasked == MotionEvent.ACTION_CANCEL ||
8564                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8565            stopNestedScroll();
8566        }
8567
8568        return result;
8569    }
8570
8571    /**
8572     * Filter the touch event to apply security policies.
8573     *
8574     * @param event The motion event to be filtered.
8575     * @return True if the event should be dispatched, false if the event should be dropped.
8576     *
8577     * @see #getFilterTouchesWhenObscured
8578     */
8579    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8580        //noinspection RedundantIfStatement
8581        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8582                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8583            // Window is obscured, drop this touch.
8584            return false;
8585        }
8586        return true;
8587    }
8588
8589    /**
8590     * Pass a trackball motion event down to the focused view.
8591     *
8592     * @param event The motion event to be dispatched.
8593     * @return True if the event was handled by the view, false otherwise.
8594     */
8595    public boolean dispatchTrackballEvent(MotionEvent event) {
8596        if (mInputEventConsistencyVerifier != null) {
8597            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8598        }
8599
8600        return onTrackballEvent(event);
8601    }
8602
8603    /**
8604     * Dispatch a generic motion event.
8605     * <p>
8606     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8607     * are delivered to the view under the pointer.  All other generic motion events are
8608     * delivered to the focused view.  Hover events are handled specially and are delivered
8609     * to {@link #onHoverEvent(MotionEvent)}.
8610     * </p>
8611     *
8612     * @param event The motion event to be dispatched.
8613     * @return True if the event was handled by the view, false otherwise.
8614     */
8615    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8616        if (mInputEventConsistencyVerifier != null) {
8617            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8618        }
8619
8620        final int source = event.getSource();
8621        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8622            final int action = event.getAction();
8623            if (action == MotionEvent.ACTION_HOVER_ENTER
8624                    || action == MotionEvent.ACTION_HOVER_MOVE
8625                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8626                if (dispatchHoverEvent(event)) {
8627                    return true;
8628                }
8629            } else if (dispatchGenericPointerEvent(event)) {
8630                return true;
8631            }
8632        } else if (dispatchGenericFocusedEvent(event)) {
8633            return true;
8634        }
8635
8636        if (dispatchGenericMotionEventInternal(event)) {
8637            return true;
8638        }
8639
8640        if (mInputEventConsistencyVerifier != null) {
8641            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8642        }
8643        return false;
8644    }
8645
8646    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8647        //noinspection SimplifiableIfStatement
8648        ListenerInfo li = mListenerInfo;
8649        if (li != null && li.mOnGenericMotionListener != null
8650                && (mViewFlags & ENABLED_MASK) == ENABLED
8651                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8652            return true;
8653        }
8654
8655        if (onGenericMotionEvent(event)) {
8656            return true;
8657        }
8658
8659        if (mInputEventConsistencyVerifier != null) {
8660            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8661        }
8662        return false;
8663    }
8664
8665    /**
8666     * Dispatch a hover event.
8667     * <p>
8668     * Do not call this method directly.
8669     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8670     * </p>
8671     *
8672     * @param event The motion event to be dispatched.
8673     * @return True if the event was handled by the view, false otherwise.
8674     */
8675    protected boolean dispatchHoverEvent(MotionEvent event) {
8676        ListenerInfo li = mListenerInfo;
8677        //noinspection SimplifiableIfStatement
8678        if (li != null && li.mOnHoverListener != null
8679                && (mViewFlags & ENABLED_MASK) == ENABLED
8680                && li.mOnHoverListener.onHover(this, event)) {
8681            return true;
8682        }
8683
8684        return onHoverEvent(event);
8685    }
8686
8687    /**
8688     * Returns true if the view has a child to which it has recently sent
8689     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8690     * it does not have a hovered child, then it must be the innermost hovered view.
8691     * @hide
8692     */
8693    protected boolean hasHoveredChild() {
8694        return false;
8695    }
8696
8697    /**
8698     * Dispatch a generic motion event to the view under the first pointer.
8699     * <p>
8700     * Do not call this method directly.
8701     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8702     * </p>
8703     *
8704     * @param event The motion event to be dispatched.
8705     * @return True if the event was handled by the view, false otherwise.
8706     */
8707    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8708        return false;
8709    }
8710
8711    /**
8712     * Dispatch a generic motion event to the currently focused view.
8713     * <p>
8714     * Do not call this method directly.
8715     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8716     * </p>
8717     *
8718     * @param event The motion event to be dispatched.
8719     * @return True if the event was handled by the view, false otherwise.
8720     */
8721    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8722        return false;
8723    }
8724
8725    /**
8726     * Dispatch a pointer event.
8727     * <p>
8728     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8729     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8730     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8731     * and should not be expected to handle other pointing device features.
8732     * </p>
8733     *
8734     * @param event The motion event to be dispatched.
8735     * @return True if the event was handled by the view, false otherwise.
8736     * @hide
8737     */
8738    public final boolean dispatchPointerEvent(MotionEvent event) {
8739        if (event.isTouchEvent()) {
8740            return dispatchTouchEvent(event);
8741        } else {
8742            return dispatchGenericMotionEvent(event);
8743        }
8744    }
8745
8746    /**
8747     * Called when the window containing this view gains or loses window focus.
8748     * ViewGroups should override to route to their children.
8749     *
8750     * @param hasFocus True if the window containing this view now has focus,
8751     *        false otherwise.
8752     */
8753    public void dispatchWindowFocusChanged(boolean hasFocus) {
8754        onWindowFocusChanged(hasFocus);
8755    }
8756
8757    /**
8758     * Called when the window containing this view gains or loses focus.  Note
8759     * that this is separate from view focus: to receive key events, both
8760     * your view and its window must have focus.  If a window is displayed
8761     * on top of yours that takes input focus, then your own window will lose
8762     * focus but the view focus will remain unchanged.
8763     *
8764     * @param hasWindowFocus True if the window containing this view now has
8765     *        focus, false otherwise.
8766     */
8767    public void onWindowFocusChanged(boolean hasWindowFocus) {
8768        InputMethodManager imm = InputMethodManager.peekInstance();
8769        if (!hasWindowFocus) {
8770            if (isPressed()) {
8771                setPressed(false);
8772            }
8773            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8774                imm.focusOut(this);
8775            }
8776            removeLongPressCallback();
8777            removeTapCallback();
8778            onFocusLost();
8779        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8780            imm.focusIn(this);
8781        }
8782        refreshDrawableState();
8783    }
8784
8785    /**
8786     * Returns true if this view is in a window that currently has window focus.
8787     * Note that this is not the same as the view itself having focus.
8788     *
8789     * @return True if this view is in a window that currently has window focus.
8790     */
8791    public boolean hasWindowFocus() {
8792        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8793    }
8794
8795    /**
8796     * Dispatch a view visibility change down the view hierarchy.
8797     * ViewGroups should override to route to their children.
8798     * @param changedView The view whose visibility changed. Could be 'this' or
8799     * an ancestor view.
8800     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8801     * {@link #INVISIBLE} or {@link #GONE}.
8802     */
8803    protected void dispatchVisibilityChanged(@NonNull View changedView,
8804            @Visibility int visibility) {
8805        onVisibilityChanged(changedView, visibility);
8806    }
8807
8808    /**
8809     * Called when the visibility of the view or an ancestor of the view is changed.
8810     * @param changedView The view whose visibility changed. Could be 'this' or
8811     * an ancestor view.
8812     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8813     * {@link #INVISIBLE} or {@link #GONE}.
8814     */
8815    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8816        if (visibility == VISIBLE) {
8817            if (mAttachInfo != null) {
8818                initialAwakenScrollBars();
8819            } else {
8820                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8821            }
8822        }
8823    }
8824
8825    /**
8826     * Dispatch a hint about whether this view is displayed. For instance, when
8827     * a View moves out of the screen, it might receives a display hint indicating
8828     * the view is not displayed. Applications should not <em>rely</em> on this hint
8829     * as there is no guarantee that they will receive one.
8830     *
8831     * @param hint A hint about whether or not this view is displayed:
8832     * {@link #VISIBLE} or {@link #INVISIBLE}.
8833     */
8834    public void dispatchDisplayHint(@Visibility int hint) {
8835        onDisplayHint(hint);
8836    }
8837
8838    /**
8839     * Gives this view a hint about whether is displayed or not. For instance, when
8840     * a View moves out of the screen, it might receives a display hint indicating
8841     * the view is not displayed. Applications should not <em>rely</em> on this hint
8842     * as there is no guarantee that they will receive one.
8843     *
8844     * @param hint A hint about whether or not this view is displayed:
8845     * {@link #VISIBLE} or {@link #INVISIBLE}.
8846     */
8847    protected void onDisplayHint(@Visibility int hint) {
8848    }
8849
8850    /**
8851     * Dispatch a window visibility change down the view hierarchy.
8852     * ViewGroups should override to route to their children.
8853     *
8854     * @param visibility The new visibility of the window.
8855     *
8856     * @see #onWindowVisibilityChanged(int)
8857     */
8858    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8859        onWindowVisibilityChanged(visibility);
8860    }
8861
8862    /**
8863     * Called when the window containing has change its visibility
8864     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8865     * that this tells you whether or not your window is being made visible
8866     * to the window manager; this does <em>not</em> tell you whether or not
8867     * your window is obscured by other windows on the screen, even if it
8868     * is itself visible.
8869     *
8870     * @param visibility The new visibility of the window.
8871     */
8872    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8873        if (visibility == VISIBLE) {
8874            initialAwakenScrollBars();
8875        }
8876    }
8877
8878    /**
8879     * Returns the current visibility of the window this view is attached to
8880     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8881     *
8882     * @return Returns the current visibility of the view's window.
8883     */
8884    @Visibility
8885    public int getWindowVisibility() {
8886        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8887    }
8888
8889    /**
8890     * Retrieve the overall visible display size in which the window this view is
8891     * attached to has been positioned in.  This takes into account screen
8892     * decorations above the window, for both cases where the window itself
8893     * is being position inside of them or the window is being placed under
8894     * then and covered insets are used for the window to position its content
8895     * inside.  In effect, this tells you the available area where content can
8896     * be placed and remain visible to users.
8897     *
8898     * <p>This function requires an IPC back to the window manager to retrieve
8899     * the requested information, so should not be used in performance critical
8900     * code like drawing.
8901     *
8902     * @param outRect Filled in with the visible display frame.  If the view
8903     * is not attached to a window, this is simply the raw display size.
8904     */
8905    public void getWindowVisibleDisplayFrame(Rect outRect) {
8906        if (mAttachInfo != null) {
8907            try {
8908                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8909            } catch (RemoteException e) {
8910                return;
8911            }
8912            // XXX This is really broken, and probably all needs to be done
8913            // in the window manager, and we need to know more about whether
8914            // we want the area behind or in front of the IME.
8915            final Rect insets = mAttachInfo.mVisibleInsets;
8916            outRect.left += insets.left;
8917            outRect.top += insets.top;
8918            outRect.right -= insets.right;
8919            outRect.bottom -= insets.bottom;
8920            return;
8921        }
8922        // The view is not attached to a display so we don't have a context.
8923        // Make a best guess about the display size.
8924        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8925        d.getRectSize(outRect);
8926    }
8927
8928    /**
8929     * Dispatch a notification about a resource configuration change down
8930     * the view hierarchy.
8931     * ViewGroups should override to route to their children.
8932     *
8933     * @param newConfig The new resource configuration.
8934     *
8935     * @see #onConfigurationChanged(android.content.res.Configuration)
8936     */
8937    public void dispatchConfigurationChanged(Configuration newConfig) {
8938        onConfigurationChanged(newConfig);
8939    }
8940
8941    /**
8942     * Called when the current configuration of the resources being used
8943     * by the application have changed.  You can use this to decide when
8944     * to reload resources that can changed based on orientation and other
8945     * configuration characterstics.  You only need to use this if you are
8946     * not relying on the normal {@link android.app.Activity} mechanism of
8947     * recreating the activity instance upon a configuration change.
8948     *
8949     * @param newConfig The new resource configuration.
8950     */
8951    protected void onConfigurationChanged(Configuration newConfig) {
8952    }
8953
8954    /**
8955     * Private function to aggregate all per-view attributes in to the view
8956     * root.
8957     */
8958    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8959        performCollectViewAttributes(attachInfo, visibility);
8960    }
8961
8962    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8963        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8964            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8965                attachInfo.mKeepScreenOn = true;
8966            }
8967            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8968            ListenerInfo li = mListenerInfo;
8969            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8970                attachInfo.mHasSystemUiListeners = true;
8971            }
8972        }
8973    }
8974
8975    void needGlobalAttributesUpdate(boolean force) {
8976        final AttachInfo ai = mAttachInfo;
8977        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8978            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8979                    || ai.mHasSystemUiListeners) {
8980                ai.mRecomputeGlobalAttributes = true;
8981            }
8982        }
8983    }
8984
8985    /**
8986     * Returns whether the device is currently in touch mode.  Touch mode is entered
8987     * once the user begins interacting with the device by touch, and affects various
8988     * things like whether focus is always visible to the user.
8989     *
8990     * @return Whether the device is in touch mode.
8991     */
8992    @ViewDebug.ExportedProperty
8993    public boolean isInTouchMode() {
8994        if (mAttachInfo != null) {
8995            return mAttachInfo.mInTouchMode;
8996        } else {
8997            return ViewRootImpl.isInTouchMode();
8998        }
8999    }
9000
9001    /**
9002     * Returns the context the view is running in, through which it can
9003     * access the current theme, resources, etc.
9004     *
9005     * @return The view's Context.
9006     */
9007    @ViewDebug.CapturedViewProperty
9008    public final Context getContext() {
9009        return mContext;
9010    }
9011
9012    /**
9013     * Handle a key event before it is processed by any input method
9014     * associated with the view hierarchy.  This can be used to intercept
9015     * key events in special situations before the IME consumes them; a
9016     * typical example would be handling the BACK key to update the application's
9017     * UI instead of allowing the IME to see it and close itself.
9018     *
9019     * @param keyCode The value in event.getKeyCode().
9020     * @param event Description of the key event.
9021     * @return If you handled the event, return true. If you want to allow the
9022     *         event to be handled by the next receiver, return false.
9023     */
9024    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9025        return false;
9026    }
9027
9028    /**
9029     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9030     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9031     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9032     * is released, if the view is enabled and clickable.
9033     *
9034     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9035     * although some may elect to do so in some situations. Do not rely on this to
9036     * catch software key presses.
9037     *
9038     * @param keyCode A key code that represents the button pressed, from
9039     *                {@link android.view.KeyEvent}.
9040     * @param event   The KeyEvent object that defines the button action.
9041     */
9042    public boolean onKeyDown(int keyCode, KeyEvent event) {
9043        boolean result = false;
9044
9045        if (KeyEvent.isConfirmKey(keyCode)) {
9046            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9047                return true;
9048            }
9049            // Long clickable items don't necessarily have to be clickable
9050            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9051                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9052                    (event.getRepeatCount() == 0)) {
9053                setPressed(true);
9054                checkForLongClick(0);
9055                return true;
9056            }
9057        }
9058        return result;
9059    }
9060
9061    /**
9062     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9063     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9064     * the event).
9065     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9066     * although some may elect to do so in some situations. Do not rely on this to
9067     * catch software key presses.
9068     */
9069    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9070        return false;
9071    }
9072
9073    /**
9074     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9075     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9076     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9077     * {@link KeyEvent#KEYCODE_ENTER} is released.
9078     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9079     * although some may elect to do so in some situations. Do not rely on this to
9080     * catch software key presses.
9081     *
9082     * @param keyCode A key code that represents the button pressed, from
9083     *                {@link android.view.KeyEvent}.
9084     * @param event   The KeyEvent object that defines the button action.
9085     */
9086    public boolean onKeyUp(int keyCode, KeyEvent event) {
9087        if (KeyEvent.isConfirmKey(keyCode)) {
9088            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9089                return true;
9090            }
9091            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9092                setPressed(false);
9093
9094                if (!mHasPerformedLongPress) {
9095                    // This is a tap, so remove the longpress check
9096                    removeLongPressCallback();
9097                    return performClick();
9098                }
9099            }
9100        }
9101        return false;
9102    }
9103
9104    /**
9105     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9106     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9107     * the event).
9108     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9109     * although some may elect to do so in some situations. Do not rely on this to
9110     * catch software key presses.
9111     *
9112     * @param keyCode     A key code that represents the button pressed, from
9113     *                    {@link android.view.KeyEvent}.
9114     * @param repeatCount The number of times the action was made.
9115     * @param event       The KeyEvent object that defines the button action.
9116     */
9117    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9118        return false;
9119    }
9120
9121    /**
9122     * Called on the focused view when a key shortcut event is not handled.
9123     * Override this method to implement local key shortcuts for the View.
9124     * Key shortcuts can also be implemented by setting the
9125     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9126     *
9127     * @param keyCode The value in event.getKeyCode().
9128     * @param event Description of the key event.
9129     * @return If you handled the event, return true. If you want to allow the
9130     *         event to be handled by the next receiver, return false.
9131     */
9132    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9133        return false;
9134    }
9135
9136    /**
9137     * Check whether the called view is a text editor, in which case it
9138     * would make sense to automatically display a soft input window for
9139     * it.  Subclasses should override this if they implement
9140     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9141     * a call on that method would return a non-null InputConnection, and
9142     * they are really a first-class editor that the user would normally
9143     * start typing on when the go into a window containing your view.
9144     *
9145     * <p>The default implementation always returns false.  This does
9146     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9147     * will not be called or the user can not otherwise perform edits on your
9148     * view; it is just a hint to the system that this is not the primary
9149     * purpose of this view.
9150     *
9151     * @return Returns true if this view is a text editor, else false.
9152     */
9153    public boolean onCheckIsTextEditor() {
9154        return false;
9155    }
9156
9157    /**
9158     * Create a new InputConnection for an InputMethod to interact
9159     * with the view.  The default implementation returns null, since it doesn't
9160     * support input methods.  You can override this to implement such support.
9161     * This is only needed for views that take focus and text input.
9162     *
9163     * <p>When implementing this, you probably also want to implement
9164     * {@link #onCheckIsTextEditor()} to indicate you will return a
9165     * non-null InputConnection.</p>
9166     *
9167     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9168     * object correctly and in its entirety, so that the connected IME can rely
9169     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9170     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9171     * must be filled in with the correct cursor position for IMEs to work correctly
9172     * with your application.</p>
9173     *
9174     * @param outAttrs Fill in with attribute information about the connection.
9175     */
9176    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9177        return null;
9178    }
9179
9180    /**
9181     * Called by the {@link android.view.inputmethod.InputMethodManager}
9182     * when a view who is not the current
9183     * input connection target is trying to make a call on the manager.  The
9184     * default implementation returns false; you can override this to return
9185     * true for certain views if you are performing InputConnection proxying
9186     * to them.
9187     * @param view The View that is making the InputMethodManager call.
9188     * @return Return true to allow the call, false to reject.
9189     */
9190    public boolean checkInputConnectionProxy(View view) {
9191        return false;
9192    }
9193
9194    /**
9195     * Show the context menu for this view. It is not safe to hold on to the
9196     * menu after returning from this method.
9197     *
9198     * You should normally not overload this method. Overload
9199     * {@link #onCreateContextMenu(ContextMenu)} or define an
9200     * {@link OnCreateContextMenuListener} to add items to the context menu.
9201     *
9202     * @param menu The context menu to populate
9203     */
9204    public void createContextMenu(ContextMenu menu) {
9205        ContextMenuInfo menuInfo = getContextMenuInfo();
9206
9207        // Sets the current menu info so all items added to menu will have
9208        // my extra info set.
9209        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9210
9211        onCreateContextMenu(menu);
9212        ListenerInfo li = mListenerInfo;
9213        if (li != null && li.mOnCreateContextMenuListener != null) {
9214            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9215        }
9216
9217        // Clear the extra information so subsequent items that aren't mine don't
9218        // have my extra info.
9219        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9220
9221        if (mParent != null) {
9222            mParent.createContextMenu(menu);
9223        }
9224    }
9225
9226    /**
9227     * Views should implement this if they have extra information to associate
9228     * with the context menu. The return result is supplied as a parameter to
9229     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9230     * callback.
9231     *
9232     * @return Extra information about the item for which the context menu
9233     *         should be shown. This information will vary across different
9234     *         subclasses of View.
9235     */
9236    protected ContextMenuInfo getContextMenuInfo() {
9237        return null;
9238    }
9239
9240    /**
9241     * Views should implement this if the view itself is going to add items to
9242     * the context menu.
9243     *
9244     * @param menu the context menu to populate
9245     */
9246    protected void onCreateContextMenu(ContextMenu menu) {
9247    }
9248
9249    /**
9250     * Implement this method to handle trackball motion events.  The
9251     * <em>relative</em> movement of the trackball since the last event
9252     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9253     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9254     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9255     * they will often be fractional values, representing the more fine-grained
9256     * movement information available from a trackball).
9257     *
9258     * @param event The motion event.
9259     * @return True if the event was handled, false otherwise.
9260     */
9261    public boolean onTrackballEvent(MotionEvent event) {
9262        return false;
9263    }
9264
9265    /**
9266     * Implement this method to handle generic motion events.
9267     * <p>
9268     * Generic motion events describe joystick movements, mouse hovers, track pad
9269     * touches, scroll wheel movements and other input events.  The
9270     * {@link MotionEvent#getSource() source} of the motion event specifies
9271     * the class of input that was received.  Implementations of this method
9272     * must examine the bits in the source before processing the event.
9273     * The following code example shows how this is done.
9274     * </p><p>
9275     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9276     * are delivered to the view under the pointer.  All other generic motion events are
9277     * delivered to the focused view.
9278     * </p>
9279     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9280     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9281     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9282     *             // process the joystick movement...
9283     *             return true;
9284     *         }
9285     *     }
9286     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9287     *         switch (event.getAction()) {
9288     *             case MotionEvent.ACTION_HOVER_MOVE:
9289     *                 // process the mouse hover movement...
9290     *                 return true;
9291     *             case MotionEvent.ACTION_SCROLL:
9292     *                 // process the scroll wheel movement...
9293     *                 return true;
9294     *         }
9295     *     }
9296     *     return super.onGenericMotionEvent(event);
9297     * }</pre>
9298     *
9299     * @param event The generic motion event being processed.
9300     * @return True if the event was handled, false otherwise.
9301     */
9302    public boolean onGenericMotionEvent(MotionEvent event) {
9303        return false;
9304    }
9305
9306    /**
9307     * Implement this method to handle hover events.
9308     * <p>
9309     * This method is called whenever a pointer is hovering into, over, or out of the
9310     * bounds of a view and the view is not currently being touched.
9311     * Hover events are represented as pointer events with action
9312     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9313     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9314     * </p>
9315     * <ul>
9316     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9317     * when the pointer enters the bounds of the view.</li>
9318     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9319     * when the pointer has already entered the bounds of the view and has moved.</li>
9320     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9321     * when the pointer has exited the bounds of the view or when the pointer is
9322     * about to go down due to a button click, tap, or similar user action that
9323     * causes the view to be touched.</li>
9324     * </ul>
9325     * <p>
9326     * The view should implement this method to return true to indicate that it is
9327     * handling the hover event, such as by changing its drawable state.
9328     * </p><p>
9329     * The default implementation calls {@link #setHovered} to update the hovered state
9330     * of the view when a hover enter or hover exit event is received, if the view
9331     * is enabled and is clickable.  The default implementation also sends hover
9332     * accessibility events.
9333     * </p>
9334     *
9335     * @param event The motion event that describes the hover.
9336     * @return True if the view handled the hover event.
9337     *
9338     * @see #isHovered
9339     * @see #setHovered
9340     * @see #onHoverChanged
9341     */
9342    public boolean onHoverEvent(MotionEvent event) {
9343        // The root view may receive hover (or touch) events that are outside the bounds of
9344        // the window.  This code ensures that we only send accessibility events for
9345        // hovers that are actually within the bounds of the root view.
9346        final int action = event.getActionMasked();
9347        if (!mSendingHoverAccessibilityEvents) {
9348            if ((action == MotionEvent.ACTION_HOVER_ENTER
9349                    || action == MotionEvent.ACTION_HOVER_MOVE)
9350                    && !hasHoveredChild()
9351                    && pointInView(event.getX(), event.getY())) {
9352                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9353                mSendingHoverAccessibilityEvents = true;
9354            }
9355        } else {
9356            if (action == MotionEvent.ACTION_HOVER_EXIT
9357                    || (action == MotionEvent.ACTION_MOVE
9358                            && !pointInView(event.getX(), event.getY()))) {
9359                mSendingHoverAccessibilityEvents = false;
9360                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9361            }
9362        }
9363
9364        if (isHoverable()) {
9365            switch (action) {
9366                case MotionEvent.ACTION_HOVER_ENTER:
9367                    setHovered(true);
9368                    break;
9369                case MotionEvent.ACTION_HOVER_EXIT:
9370                    setHovered(false);
9371                    break;
9372            }
9373
9374            // Dispatch the event to onGenericMotionEvent before returning true.
9375            // This is to provide compatibility with existing applications that
9376            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9377            // break because of the new default handling for hoverable views
9378            // in onHoverEvent.
9379            // Note that onGenericMotionEvent will be called by default when
9380            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9381            dispatchGenericMotionEventInternal(event);
9382            // The event was already handled by calling setHovered(), so always
9383            // return true.
9384            return true;
9385        }
9386
9387        return false;
9388    }
9389
9390    /**
9391     * Returns true if the view should handle {@link #onHoverEvent}
9392     * by calling {@link #setHovered} to change its hovered state.
9393     *
9394     * @return True if the view is hoverable.
9395     */
9396    private boolean isHoverable() {
9397        final int viewFlags = mViewFlags;
9398        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9399            return false;
9400        }
9401
9402        return (viewFlags & CLICKABLE) == CLICKABLE
9403                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9404    }
9405
9406    /**
9407     * Returns true if the view is currently hovered.
9408     *
9409     * @return True if the view is currently hovered.
9410     *
9411     * @see #setHovered
9412     * @see #onHoverChanged
9413     */
9414    @ViewDebug.ExportedProperty
9415    public boolean isHovered() {
9416        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9417    }
9418
9419    /**
9420     * Sets whether the view is currently hovered.
9421     * <p>
9422     * Calling this method also changes the drawable state of the view.  This
9423     * enables the view to react to hover by using different drawable resources
9424     * to change its appearance.
9425     * </p><p>
9426     * The {@link #onHoverChanged} method is called when the hovered state changes.
9427     * </p>
9428     *
9429     * @param hovered True if the view is hovered.
9430     *
9431     * @see #isHovered
9432     * @see #onHoverChanged
9433     */
9434    public void setHovered(boolean hovered) {
9435        if (hovered) {
9436            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9437                mPrivateFlags |= PFLAG_HOVERED;
9438                refreshDrawableState();
9439                onHoverChanged(true);
9440            }
9441        } else {
9442            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9443                mPrivateFlags &= ~PFLAG_HOVERED;
9444                refreshDrawableState();
9445                onHoverChanged(false);
9446            }
9447        }
9448    }
9449
9450    /**
9451     * Implement this method to handle hover state changes.
9452     * <p>
9453     * This method is called whenever the hover state changes as a result of a
9454     * call to {@link #setHovered}.
9455     * </p>
9456     *
9457     * @param hovered The current hover state, as returned by {@link #isHovered}.
9458     *
9459     * @see #isHovered
9460     * @see #setHovered
9461     */
9462    public void onHoverChanged(boolean hovered) {
9463    }
9464
9465    /**
9466     * Implement this method to handle touch screen motion events.
9467     * <p>
9468     * If this method is used to detect click actions, it is recommended that
9469     * the actions be performed by implementing and calling
9470     * {@link #performClick()}. This will ensure consistent system behavior,
9471     * including:
9472     * <ul>
9473     * <li>obeying click sound preferences
9474     * <li>dispatching OnClickListener calls
9475     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9476     * accessibility features are enabled
9477     * </ul>
9478     *
9479     * @param event The motion event.
9480     * @return True if the event was handled, false otherwise.
9481     */
9482    public boolean onTouchEvent(MotionEvent event) {
9483        final float x = event.getX();
9484        final float y = event.getY();
9485        final int viewFlags = mViewFlags;
9486
9487        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9488            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9489                setPressed(false);
9490            }
9491            // A disabled view that is clickable still consumes the touch
9492            // events, it just doesn't respond to them.
9493            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9494                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9495        }
9496
9497        if (mTouchDelegate != null) {
9498            if (mTouchDelegate.onTouchEvent(event)) {
9499                return true;
9500            }
9501        }
9502
9503        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9504                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9505            switch (event.getAction()) {
9506                case MotionEvent.ACTION_UP:
9507                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9508                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9509                        // take focus if we don't have it already and we should in
9510                        // touch mode.
9511                        boolean focusTaken = false;
9512                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9513                            focusTaken = requestFocus();
9514                        }
9515
9516                        if (prepressed) {
9517                            // The button is being released before we actually
9518                            // showed it as pressed.  Make it show the pressed
9519                            // state now (before scheduling the click) to ensure
9520                            // the user sees it.
9521                            setPressed(true, x, y);
9522                       }
9523
9524                        if (!mHasPerformedLongPress) {
9525                            // This is a tap, so remove the longpress check
9526                            removeLongPressCallback();
9527
9528                            // Only perform take click actions if we were in the pressed state
9529                            if (!focusTaken) {
9530                                // Use a Runnable and post this rather than calling
9531                                // performClick directly. This lets other visual state
9532                                // of the view update before click actions start.
9533                                if (mPerformClick == null) {
9534                                    mPerformClick = new PerformClick();
9535                                }
9536                                if (!post(mPerformClick)) {
9537                                    performClick();
9538                                }
9539                            }
9540                        }
9541
9542                        if (mUnsetPressedState == null) {
9543                            mUnsetPressedState = new UnsetPressedState();
9544                        }
9545
9546                        if (prepressed) {
9547                            postDelayed(mUnsetPressedState,
9548                                    ViewConfiguration.getPressedStateDuration());
9549                        } else if (!post(mUnsetPressedState)) {
9550                            // If the post failed, unpress right now
9551                            mUnsetPressedState.run();
9552                        }
9553
9554                        removeTapCallback();
9555                    }
9556                    break;
9557
9558                case MotionEvent.ACTION_DOWN:
9559                    mHasPerformedLongPress = false;
9560
9561                    if (performButtonActionOnTouchDown(event)) {
9562                        break;
9563                    }
9564
9565                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9566                    boolean isInScrollingContainer = isInScrollingContainer();
9567
9568                    // For views inside a scrolling container, delay the pressed feedback for
9569                    // a short period in case this is a scroll.
9570                    if (isInScrollingContainer) {
9571                        mPrivateFlags |= PFLAG_PREPRESSED;
9572                        if (mPendingCheckForTap == null) {
9573                            mPendingCheckForTap = new CheckForTap();
9574                        }
9575                        mPendingCheckForTap.x = event.getX();
9576                        mPendingCheckForTap.y = event.getY();
9577                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9578                    } else {
9579                        // Not inside a scrolling container, so show the feedback right away
9580                        setPressed(true, x, y);
9581                        checkForLongClick(0);
9582                    }
9583                    break;
9584
9585                case MotionEvent.ACTION_CANCEL:
9586                    setPressed(false);
9587                    removeTapCallback();
9588                    removeLongPressCallback();
9589                    break;
9590
9591                case MotionEvent.ACTION_MOVE:
9592                    drawableHotspotChanged(x, y);
9593
9594                    // Be lenient about moving outside of buttons
9595                    if (!pointInView(x, y, mTouchSlop)) {
9596                        // Outside button
9597                        removeTapCallback();
9598                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9599                            // Remove any future long press/tap checks
9600                            removeLongPressCallback();
9601
9602                            setPressed(false);
9603                        }
9604                    }
9605                    break;
9606            }
9607
9608            return true;
9609        }
9610
9611        return false;
9612    }
9613
9614    /**
9615     * @hide
9616     */
9617    public boolean isInScrollingContainer() {
9618        ViewParent p = getParent();
9619        while (p != null && p instanceof ViewGroup) {
9620            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9621                return true;
9622            }
9623            p = p.getParent();
9624        }
9625        return false;
9626    }
9627
9628    /**
9629     * Remove the longpress detection timer.
9630     */
9631    private void removeLongPressCallback() {
9632        if (mPendingCheckForLongPress != null) {
9633          removeCallbacks(mPendingCheckForLongPress);
9634        }
9635    }
9636
9637    /**
9638     * Remove the pending click action
9639     */
9640    private void removePerformClickCallback() {
9641        if (mPerformClick != null) {
9642            removeCallbacks(mPerformClick);
9643        }
9644    }
9645
9646    /**
9647     * Remove the prepress detection timer.
9648     */
9649    private void removeUnsetPressCallback() {
9650        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9651            setPressed(false);
9652            removeCallbacks(mUnsetPressedState);
9653        }
9654    }
9655
9656    /**
9657     * Remove the tap detection timer.
9658     */
9659    private void removeTapCallback() {
9660        if (mPendingCheckForTap != null) {
9661            mPrivateFlags &= ~PFLAG_PREPRESSED;
9662            removeCallbacks(mPendingCheckForTap);
9663        }
9664    }
9665
9666    /**
9667     * Cancels a pending long press.  Your subclass can use this if you
9668     * want the context menu to come up if the user presses and holds
9669     * at the same place, but you don't want it to come up if they press
9670     * and then move around enough to cause scrolling.
9671     */
9672    public void cancelLongPress() {
9673        removeLongPressCallback();
9674
9675        /*
9676         * The prepressed state handled by the tap callback is a display
9677         * construct, but the tap callback will post a long press callback
9678         * less its own timeout. Remove it here.
9679         */
9680        removeTapCallback();
9681    }
9682
9683    /**
9684     * Remove the pending callback for sending a
9685     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9686     */
9687    private void removeSendViewScrolledAccessibilityEventCallback() {
9688        if (mSendViewScrolledAccessibilityEvent != null) {
9689            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9690            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9691        }
9692    }
9693
9694    /**
9695     * Sets the TouchDelegate for this View.
9696     */
9697    public void setTouchDelegate(TouchDelegate delegate) {
9698        mTouchDelegate = delegate;
9699    }
9700
9701    /**
9702     * Gets the TouchDelegate for this View.
9703     */
9704    public TouchDelegate getTouchDelegate() {
9705        return mTouchDelegate;
9706    }
9707
9708    /**
9709     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9710     *
9711     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9712     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9713     * available. This method should only be called for touch events.
9714     *
9715     * <p class="note">This api is not intended for most applications. Buffered dispatch
9716     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9717     * streams will not improve your input latency. Side effects include: increased latency,
9718     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9719     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9720     * you.</p>
9721     */
9722    public final void requestUnbufferedDispatch(MotionEvent event) {
9723        final int action = event.getAction();
9724        if (mAttachInfo == null
9725                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9726                || !event.isTouchEvent()) {
9727            return;
9728        }
9729        mAttachInfo.mUnbufferedDispatchRequested = true;
9730    }
9731
9732    /**
9733     * Set flags controlling behavior of this view.
9734     *
9735     * @param flags Constant indicating the value which should be set
9736     * @param mask Constant indicating the bit range that should be changed
9737     */
9738    void setFlags(int flags, int mask) {
9739        final boolean accessibilityEnabled =
9740                AccessibilityManager.getInstance(mContext).isEnabled();
9741        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9742
9743        int old = mViewFlags;
9744        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9745
9746        int changed = mViewFlags ^ old;
9747        if (changed == 0) {
9748            return;
9749        }
9750        int privateFlags = mPrivateFlags;
9751
9752        /* Check if the FOCUSABLE bit has changed */
9753        if (((changed & FOCUSABLE_MASK) != 0) &&
9754                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9755            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9756                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9757                /* Give up focus if we are no longer focusable */
9758                clearFocus();
9759            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9760                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9761                /*
9762                 * Tell the view system that we are now available to take focus
9763                 * if no one else already has it.
9764                 */
9765                if (mParent != null) mParent.focusableViewAvailable(this);
9766            }
9767        }
9768
9769        final int newVisibility = flags & VISIBILITY_MASK;
9770        if (newVisibility == VISIBLE) {
9771            if ((changed & VISIBILITY_MASK) != 0) {
9772                /*
9773                 * If this view is becoming visible, invalidate it in case it changed while
9774                 * it was not visible. Marking it drawn ensures that the invalidation will
9775                 * go through.
9776                 */
9777                mPrivateFlags |= PFLAG_DRAWN;
9778                invalidate(true);
9779
9780                needGlobalAttributesUpdate(true);
9781
9782                // a view becoming visible is worth notifying the parent
9783                // about in case nothing has focus.  even if this specific view
9784                // isn't focusable, it may contain something that is, so let
9785                // the root view try to give this focus if nothing else does.
9786                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9787                    mParent.focusableViewAvailable(this);
9788                }
9789            }
9790        }
9791
9792        /* Check if the GONE bit has changed */
9793        if ((changed & GONE) != 0) {
9794            needGlobalAttributesUpdate(false);
9795            requestLayout();
9796
9797            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9798                if (hasFocus()) clearFocus();
9799                clearAccessibilityFocus();
9800                destroyDrawingCache();
9801                if (mParent instanceof View) {
9802                    // GONE views noop invalidation, so invalidate the parent
9803                    ((View) mParent).invalidate(true);
9804                }
9805                // Mark the view drawn to ensure that it gets invalidated properly the next
9806                // time it is visible and gets invalidated
9807                mPrivateFlags |= PFLAG_DRAWN;
9808            }
9809            if (mAttachInfo != null) {
9810                mAttachInfo.mViewVisibilityChanged = true;
9811            }
9812        }
9813
9814        /* Check if the VISIBLE bit has changed */
9815        if ((changed & INVISIBLE) != 0) {
9816            needGlobalAttributesUpdate(false);
9817            /*
9818             * If this view is becoming invisible, set the DRAWN flag so that
9819             * the next invalidate() will not be skipped.
9820             */
9821            mPrivateFlags |= PFLAG_DRAWN;
9822
9823            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9824                // root view becoming invisible shouldn't clear focus and accessibility focus
9825                if (getRootView() != this) {
9826                    if (hasFocus()) clearFocus();
9827                    clearAccessibilityFocus();
9828                }
9829            }
9830            if (mAttachInfo != null) {
9831                mAttachInfo.mViewVisibilityChanged = true;
9832            }
9833        }
9834
9835        if ((changed & VISIBILITY_MASK) != 0) {
9836            // If the view is invisible, cleanup its display list to free up resources
9837            if (newVisibility != VISIBLE && mAttachInfo != null) {
9838                cleanupDraw();
9839            }
9840
9841            if (mParent instanceof ViewGroup) {
9842                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9843                        (changed & VISIBILITY_MASK), newVisibility);
9844                ((View) mParent).invalidate(true);
9845            } else if (mParent != null) {
9846                mParent.invalidateChild(this, null);
9847            }
9848            dispatchVisibilityChanged(this, newVisibility);
9849
9850            notifySubtreeAccessibilityStateChangedIfNeeded();
9851        }
9852
9853        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9854            destroyDrawingCache();
9855        }
9856
9857        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9858            destroyDrawingCache();
9859            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9860            invalidateParentCaches();
9861        }
9862
9863        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9864            destroyDrawingCache();
9865            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9866        }
9867
9868        if ((changed & DRAW_MASK) != 0) {
9869            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9870                if (mBackground != null) {
9871                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9872                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9873                } else {
9874                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9875                }
9876            } else {
9877                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9878            }
9879            requestLayout();
9880            invalidate(true);
9881        }
9882
9883        if ((changed & KEEP_SCREEN_ON) != 0) {
9884            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9885                mParent.recomputeViewAttributes(this);
9886            }
9887        }
9888
9889        if (accessibilityEnabled) {
9890            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9891                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9892                if (oldIncludeForAccessibility != includeForAccessibility()) {
9893                    notifySubtreeAccessibilityStateChangedIfNeeded();
9894                } else {
9895                    notifyViewAccessibilityStateChangedIfNeeded(
9896                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9897                }
9898            } else if ((changed & ENABLED_MASK) != 0) {
9899                notifyViewAccessibilityStateChangedIfNeeded(
9900                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9901            }
9902        }
9903    }
9904
9905    /**
9906     * Change the view's z order in the tree, so it's on top of other sibling
9907     * views. This ordering change may affect layout, if the parent container
9908     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9909     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9910     * method should be followed by calls to {@link #requestLayout()} and
9911     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9912     * with the new child ordering.
9913     *
9914     * @see ViewGroup#bringChildToFront(View)
9915     */
9916    public void bringToFront() {
9917        if (mParent != null) {
9918            mParent.bringChildToFront(this);
9919        }
9920    }
9921
9922    /**
9923     * This is called in response to an internal scroll in this view (i.e., the
9924     * view scrolled its own contents). This is typically as a result of
9925     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9926     * called.
9927     *
9928     * @param l Current horizontal scroll origin.
9929     * @param t Current vertical scroll origin.
9930     * @param oldl Previous horizontal scroll origin.
9931     * @param oldt Previous vertical scroll origin.
9932     */
9933    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9934        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9935            postSendViewScrolledAccessibilityEventCallback();
9936        }
9937
9938        mBackgroundSizeChanged = true;
9939
9940        final AttachInfo ai = mAttachInfo;
9941        if (ai != null) {
9942            ai.mViewScrollChanged = true;
9943        }
9944
9945        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
9946            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
9947        }
9948    }
9949
9950    /**
9951     * Interface definition for a callback to be invoked when the scroll
9952     * position of a view changes.
9953     *
9954     * @hide Only used internally.
9955     */
9956    public interface OnScrollChangeListener {
9957        /**
9958         * Called when the scroll position of a view changes.
9959         *
9960         * @param v The view whose scroll position has changed.
9961         * @param scrollX Current horizontal scroll origin.
9962         * @param scrollY Current vertical scroll origin.
9963         * @param oldScrollX Previous horizontal scroll origin.
9964         * @param oldScrollY Previous vertical scroll origin.
9965         */
9966        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
9967    }
9968
9969    /**
9970     * Interface definition for a callback to be invoked when the layout bounds of a view
9971     * changes due to layout processing.
9972     */
9973    public interface OnLayoutChangeListener {
9974        /**
9975         * Called when the layout bounds of a view changes due to layout processing.
9976         *
9977         * @param v The view whose bounds have changed.
9978         * @param left The new value of the view's left property.
9979         * @param top The new value of the view's top property.
9980         * @param right The new value of the view's right property.
9981         * @param bottom The new value of the view's bottom property.
9982         * @param oldLeft The previous value of the view's left property.
9983         * @param oldTop The previous value of the view's top property.
9984         * @param oldRight The previous value of the view's right property.
9985         * @param oldBottom The previous value of the view's bottom property.
9986         */
9987        void onLayoutChange(View v, int left, int top, int right, int bottom,
9988            int oldLeft, int oldTop, int oldRight, int oldBottom);
9989    }
9990
9991    /**
9992     * This is called during layout when the size of this view has changed. If
9993     * you were just added to the view hierarchy, you're called with the old
9994     * values of 0.
9995     *
9996     * @param w Current width of this view.
9997     * @param h Current height of this view.
9998     * @param oldw Old width of this view.
9999     * @param oldh Old height of this view.
10000     */
10001    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10002    }
10003
10004    /**
10005     * Called by draw to draw the child views. This may be overridden
10006     * by derived classes to gain control just before its children are drawn
10007     * (but after its own view has been drawn).
10008     * @param canvas the canvas on which to draw the view
10009     */
10010    protected void dispatchDraw(Canvas canvas) {
10011
10012    }
10013
10014    /**
10015     * Gets the parent of this view. Note that the parent is a
10016     * ViewParent and not necessarily a View.
10017     *
10018     * @return Parent of this view.
10019     */
10020    public final ViewParent getParent() {
10021        return mParent;
10022    }
10023
10024    /**
10025     * Set the horizontal scrolled position of your view. This will cause a call to
10026     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10027     * invalidated.
10028     * @param value the x position to scroll to
10029     */
10030    public void setScrollX(int value) {
10031        scrollTo(value, mScrollY);
10032    }
10033
10034    /**
10035     * Set the vertical scrolled position of your view. This will cause a call to
10036     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10037     * invalidated.
10038     * @param value the y position to scroll to
10039     */
10040    public void setScrollY(int value) {
10041        scrollTo(mScrollX, value);
10042    }
10043
10044    /**
10045     * Return the scrolled left position of this view. This is the left edge of
10046     * the displayed part of your view. You do not need to draw any pixels
10047     * farther left, since those are outside of the frame of your view on
10048     * screen.
10049     *
10050     * @return The left edge of the displayed part of your view, in pixels.
10051     */
10052    public final int getScrollX() {
10053        return mScrollX;
10054    }
10055
10056    /**
10057     * Return the scrolled top position of this view. This is the top edge of
10058     * the displayed part of your view. You do not need to draw any pixels above
10059     * it, since those are outside of the frame of your view on screen.
10060     *
10061     * @return The top edge of the displayed part of your view, in pixels.
10062     */
10063    public final int getScrollY() {
10064        return mScrollY;
10065    }
10066
10067    /**
10068     * Return the width of the your view.
10069     *
10070     * @return The width of your view, in pixels.
10071     */
10072    @ViewDebug.ExportedProperty(category = "layout")
10073    public final int getWidth() {
10074        return mRight - mLeft;
10075    }
10076
10077    /**
10078     * Return the height of your view.
10079     *
10080     * @return The height of your view, in pixels.
10081     */
10082    @ViewDebug.ExportedProperty(category = "layout")
10083    public final int getHeight() {
10084        return mBottom - mTop;
10085    }
10086
10087    /**
10088     * Return the visible drawing bounds of your view. Fills in the output
10089     * rectangle with the values from getScrollX(), getScrollY(),
10090     * getWidth(), and getHeight(). These bounds do not account for any
10091     * transformation properties currently set on the view, such as
10092     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10093     *
10094     * @param outRect The (scrolled) drawing bounds of the view.
10095     */
10096    public void getDrawingRect(Rect outRect) {
10097        outRect.left = mScrollX;
10098        outRect.top = mScrollY;
10099        outRect.right = mScrollX + (mRight - mLeft);
10100        outRect.bottom = mScrollY + (mBottom - mTop);
10101    }
10102
10103    /**
10104     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10105     * raw width component (that is the result is masked by
10106     * {@link #MEASURED_SIZE_MASK}).
10107     *
10108     * @return The raw measured width of this view.
10109     */
10110    public final int getMeasuredWidth() {
10111        return mMeasuredWidth & MEASURED_SIZE_MASK;
10112    }
10113
10114    /**
10115     * Return the full width measurement information for this view as computed
10116     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10117     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10118     * This should be used during measurement and layout calculations only. Use
10119     * {@link #getWidth()} to see how wide a view is after layout.
10120     *
10121     * @return The measured width of this view as a bit mask.
10122     */
10123    public final int getMeasuredWidthAndState() {
10124        return mMeasuredWidth;
10125    }
10126
10127    /**
10128     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10129     * raw width component (that is the result is masked by
10130     * {@link #MEASURED_SIZE_MASK}).
10131     *
10132     * @return The raw measured height of this view.
10133     */
10134    public final int getMeasuredHeight() {
10135        return mMeasuredHeight & MEASURED_SIZE_MASK;
10136    }
10137
10138    /**
10139     * Return the full height measurement information for this view as computed
10140     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10141     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10142     * This should be used during measurement and layout calculations only. Use
10143     * {@link #getHeight()} to see how wide a view is after layout.
10144     *
10145     * @return The measured width of this view as a bit mask.
10146     */
10147    public final int getMeasuredHeightAndState() {
10148        return mMeasuredHeight;
10149    }
10150
10151    /**
10152     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10153     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10154     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10155     * and the height component is at the shifted bits
10156     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10157     */
10158    public final int getMeasuredState() {
10159        return (mMeasuredWidth&MEASURED_STATE_MASK)
10160                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10161                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10162    }
10163
10164    /**
10165     * The transform matrix of this view, which is calculated based on the current
10166     * rotation, scale, and pivot properties.
10167     *
10168     * @see #getRotation()
10169     * @see #getScaleX()
10170     * @see #getScaleY()
10171     * @see #getPivotX()
10172     * @see #getPivotY()
10173     * @return The current transform matrix for the view
10174     */
10175    public Matrix getMatrix() {
10176        ensureTransformationInfo();
10177        final Matrix matrix = mTransformationInfo.mMatrix;
10178        mRenderNode.getMatrix(matrix);
10179        return matrix;
10180    }
10181
10182    /**
10183     * Returns true if the transform matrix is the identity matrix.
10184     * Recomputes the matrix if necessary.
10185     *
10186     * @return True if the transform matrix is the identity matrix, false otherwise.
10187     */
10188    final boolean hasIdentityMatrix() {
10189        return mRenderNode.hasIdentityMatrix();
10190    }
10191
10192    void ensureTransformationInfo() {
10193        if (mTransformationInfo == null) {
10194            mTransformationInfo = new TransformationInfo();
10195        }
10196    }
10197
10198   /**
10199     * Utility method to retrieve the inverse of the current mMatrix property.
10200     * We cache the matrix to avoid recalculating it when transform properties
10201     * have not changed.
10202     *
10203     * @return The inverse of the current matrix of this view.
10204     * @hide
10205     */
10206    public final Matrix getInverseMatrix() {
10207        ensureTransformationInfo();
10208        if (mTransformationInfo.mInverseMatrix == null) {
10209            mTransformationInfo.mInverseMatrix = new Matrix();
10210        }
10211        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10212        mRenderNode.getInverseMatrix(matrix);
10213        return matrix;
10214    }
10215
10216    /**
10217     * Gets the distance along the Z axis from the camera to this view.
10218     *
10219     * @see #setCameraDistance(float)
10220     *
10221     * @return The distance along the Z axis.
10222     */
10223    public float getCameraDistance() {
10224        final float dpi = mResources.getDisplayMetrics().densityDpi;
10225        return -(mRenderNode.getCameraDistance() * dpi);
10226    }
10227
10228    /**
10229     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10230     * views are drawn) from the camera to this view. The camera's distance
10231     * affects 3D transformations, for instance rotations around the X and Y
10232     * axis. If the rotationX or rotationY properties are changed and this view is
10233     * large (more than half the size of the screen), it is recommended to always
10234     * use a camera distance that's greater than the height (X axis rotation) or
10235     * the width (Y axis rotation) of this view.</p>
10236     *
10237     * <p>The distance of the camera from the view plane can have an affect on the
10238     * perspective distortion of the view when it is rotated around the x or y axis.
10239     * For example, a large distance will result in a large viewing angle, and there
10240     * will not be much perspective distortion of the view as it rotates. A short
10241     * distance may cause much more perspective distortion upon rotation, and can
10242     * also result in some drawing artifacts if the rotated view ends up partially
10243     * behind the camera (which is why the recommendation is to use a distance at
10244     * least as far as the size of the view, if the view is to be rotated.)</p>
10245     *
10246     * <p>The distance is expressed in "depth pixels." The default distance depends
10247     * on the screen density. For instance, on a medium density display, the
10248     * default distance is 1280. On a high density display, the default distance
10249     * is 1920.</p>
10250     *
10251     * <p>If you want to specify a distance that leads to visually consistent
10252     * results across various densities, use the following formula:</p>
10253     * <pre>
10254     * float scale = context.getResources().getDisplayMetrics().density;
10255     * view.setCameraDistance(distance * scale);
10256     * </pre>
10257     *
10258     * <p>The density scale factor of a high density display is 1.5,
10259     * and 1920 = 1280 * 1.5.</p>
10260     *
10261     * @param distance The distance in "depth pixels", if negative the opposite
10262     *        value is used
10263     *
10264     * @see #setRotationX(float)
10265     * @see #setRotationY(float)
10266     */
10267    public void setCameraDistance(float distance) {
10268        final float dpi = mResources.getDisplayMetrics().densityDpi;
10269
10270        invalidateViewProperty(true, false);
10271        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10272        invalidateViewProperty(false, false);
10273
10274        invalidateParentIfNeededAndWasQuickRejected();
10275    }
10276
10277    /**
10278     * The degrees that the view is rotated around the pivot point.
10279     *
10280     * @see #setRotation(float)
10281     * @see #getPivotX()
10282     * @see #getPivotY()
10283     *
10284     * @return The degrees of rotation.
10285     */
10286    @ViewDebug.ExportedProperty(category = "drawing")
10287    public float getRotation() {
10288        return mRenderNode.getRotation();
10289    }
10290
10291    /**
10292     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10293     * result in clockwise rotation.
10294     *
10295     * @param rotation The degrees of rotation.
10296     *
10297     * @see #getRotation()
10298     * @see #getPivotX()
10299     * @see #getPivotY()
10300     * @see #setRotationX(float)
10301     * @see #setRotationY(float)
10302     *
10303     * @attr ref android.R.styleable#View_rotation
10304     */
10305    public void setRotation(float rotation) {
10306        if (rotation != getRotation()) {
10307            // Double-invalidation is necessary to capture view's old and new areas
10308            invalidateViewProperty(true, false);
10309            mRenderNode.setRotation(rotation);
10310            invalidateViewProperty(false, true);
10311
10312            invalidateParentIfNeededAndWasQuickRejected();
10313            notifySubtreeAccessibilityStateChangedIfNeeded();
10314        }
10315    }
10316
10317    /**
10318     * The degrees that the view is rotated around the vertical axis through the pivot point.
10319     *
10320     * @see #getPivotX()
10321     * @see #getPivotY()
10322     * @see #setRotationY(float)
10323     *
10324     * @return The degrees of Y rotation.
10325     */
10326    @ViewDebug.ExportedProperty(category = "drawing")
10327    public float getRotationY() {
10328        return mRenderNode.getRotationY();
10329    }
10330
10331    /**
10332     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10333     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10334     * down the y axis.
10335     *
10336     * When rotating large views, it is recommended to adjust the camera distance
10337     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10338     *
10339     * @param rotationY The degrees of Y rotation.
10340     *
10341     * @see #getRotationY()
10342     * @see #getPivotX()
10343     * @see #getPivotY()
10344     * @see #setRotation(float)
10345     * @see #setRotationX(float)
10346     * @see #setCameraDistance(float)
10347     *
10348     * @attr ref android.R.styleable#View_rotationY
10349     */
10350    public void setRotationY(float rotationY) {
10351        if (rotationY != getRotationY()) {
10352            invalidateViewProperty(true, false);
10353            mRenderNode.setRotationY(rotationY);
10354            invalidateViewProperty(false, true);
10355
10356            invalidateParentIfNeededAndWasQuickRejected();
10357            notifySubtreeAccessibilityStateChangedIfNeeded();
10358        }
10359    }
10360
10361    /**
10362     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10363     *
10364     * @see #getPivotX()
10365     * @see #getPivotY()
10366     * @see #setRotationX(float)
10367     *
10368     * @return The degrees of X rotation.
10369     */
10370    @ViewDebug.ExportedProperty(category = "drawing")
10371    public float getRotationX() {
10372        return mRenderNode.getRotationX();
10373    }
10374
10375    /**
10376     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10377     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10378     * x axis.
10379     *
10380     * When rotating large views, it is recommended to adjust the camera distance
10381     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10382     *
10383     * @param rotationX The degrees of X rotation.
10384     *
10385     * @see #getRotationX()
10386     * @see #getPivotX()
10387     * @see #getPivotY()
10388     * @see #setRotation(float)
10389     * @see #setRotationY(float)
10390     * @see #setCameraDistance(float)
10391     *
10392     * @attr ref android.R.styleable#View_rotationX
10393     */
10394    public void setRotationX(float rotationX) {
10395        if (rotationX != getRotationX()) {
10396            invalidateViewProperty(true, false);
10397            mRenderNode.setRotationX(rotationX);
10398            invalidateViewProperty(false, true);
10399
10400            invalidateParentIfNeededAndWasQuickRejected();
10401            notifySubtreeAccessibilityStateChangedIfNeeded();
10402        }
10403    }
10404
10405    /**
10406     * The amount that the view is scaled in x around the pivot point, as a proportion of
10407     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10408     *
10409     * <p>By default, this is 1.0f.
10410     *
10411     * @see #getPivotX()
10412     * @see #getPivotY()
10413     * @return The scaling factor.
10414     */
10415    @ViewDebug.ExportedProperty(category = "drawing")
10416    public float getScaleX() {
10417        return mRenderNode.getScaleX();
10418    }
10419
10420    /**
10421     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10422     * the view's unscaled width. A value of 1 means that no scaling is applied.
10423     *
10424     * @param scaleX The scaling factor.
10425     * @see #getPivotX()
10426     * @see #getPivotY()
10427     *
10428     * @attr ref android.R.styleable#View_scaleX
10429     */
10430    public void setScaleX(float scaleX) {
10431        if (scaleX != getScaleX()) {
10432            invalidateViewProperty(true, false);
10433            mRenderNode.setScaleX(scaleX);
10434            invalidateViewProperty(false, true);
10435
10436            invalidateParentIfNeededAndWasQuickRejected();
10437            notifySubtreeAccessibilityStateChangedIfNeeded();
10438        }
10439    }
10440
10441    /**
10442     * The amount that the view is scaled in y around the pivot point, as a proportion of
10443     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10444     *
10445     * <p>By default, this is 1.0f.
10446     *
10447     * @see #getPivotX()
10448     * @see #getPivotY()
10449     * @return The scaling factor.
10450     */
10451    @ViewDebug.ExportedProperty(category = "drawing")
10452    public float getScaleY() {
10453        return mRenderNode.getScaleY();
10454    }
10455
10456    /**
10457     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10458     * the view's unscaled width. A value of 1 means that no scaling is applied.
10459     *
10460     * @param scaleY The scaling factor.
10461     * @see #getPivotX()
10462     * @see #getPivotY()
10463     *
10464     * @attr ref android.R.styleable#View_scaleY
10465     */
10466    public void setScaleY(float scaleY) {
10467        if (scaleY != getScaleY()) {
10468            invalidateViewProperty(true, false);
10469            mRenderNode.setScaleY(scaleY);
10470            invalidateViewProperty(false, true);
10471
10472            invalidateParentIfNeededAndWasQuickRejected();
10473            notifySubtreeAccessibilityStateChangedIfNeeded();
10474        }
10475    }
10476
10477    /**
10478     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10479     * and {@link #setScaleX(float) scaled}.
10480     *
10481     * @see #getRotation()
10482     * @see #getScaleX()
10483     * @see #getScaleY()
10484     * @see #getPivotY()
10485     * @return The x location of the pivot point.
10486     *
10487     * @attr ref android.R.styleable#View_transformPivotX
10488     */
10489    @ViewDebug.ExportedProperty(category = "drawing")
10490    public float getPivotX() {
10491        return mRenderNode.getPivotX();
10492    }
10493
10494    /**
10495     * Sets the x location of the point around which the view is
10496     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10497     * By default, the pivot point is centered on the object.
10498     * Setting this property disables this behavior and causes the view to use only the
10499     * explicitly set pivotX and pivotY values.
10500     *
10501     * @param pivotX The x location of the pivot point.
10502     * @see #getRotation()
10503     * @see #getScaleX()
10504     * @see #getScaleY()
10505     * @see #getPivotY()
10506     *
10507     * @attr ref android.R.styleable#View_transformPivotX
10508     */
10509    public void setPivotX(float pivotX) {
10510        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10511            invalidateViewProperty(true, false);
10512            mRenderNode.setPivotX(pivotX);
10513            invalidateViewProperty(false, true);
10514
10515            invalidateParentIfNeededAndWasQuickRejected();
10516        }
10517    }
10518
10519    /**
10520     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10521     * and {@link #setScaleY(float) scaled}.
10522     *
10523     * @see #getRotation()
10524     * @see #getScaleX()
10525     * @see #getScaleY()
10526     * @see #getPivotY()
10527     * @return The y location of the pivot point.
10528     *
10529     * @attr ref android.R.styleable#View_transformPivotY
10530     */
10531    @ViewDebug.ExportedProperty(category = "drawing")
10532    public float getPivotY() {
10533        return mRenderNode.getPivotY();
10534    }
10535
10536    /**
10537     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10538     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10539     * Setting this property disables this behavior and causes the view to use only the
10540     * explicitly set pivotX and pivotY values.
10541     *
10542     * @param pivotY The y location of the pivot point.
10543     * @see #getRotation()
10544     * @see #getScaleX()
10545     * @see #getScaleY()
10546     * @see #getPivotY()
10547     *
10548     * @attr ref android.R.styleable#View_transformPivotY
10549     */
10550    public void setPivotY(float pivotY) {
10551        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10552            invalidateViewProperty(true, false);
10553            mRenderNode.setPivotY(pivotY);
10554            invalidateViewProperty(false, true);
10555
10556            invalidateParentIfNeededAndWasQuickRejected();
10557        }
10558    }
10559
10560    /**
10561     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10562     * completely transparent and 1 means the view is completely opaque.
10563     *
10564     * <p>By default this is 1.0f.
10565     * @return The opacity of the view.
10566     */
10567    @ViewDebug.ExportedProperty(category = "drawing")
10568    public float getAlpha() {
10569        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10570    }
10571
10572    /**
10573     * Returns whether this View has content which overlaps.
10574     *
10575     * <p>This function, intended to be overridden by specific View types, is an optimization when
10576     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10577     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10578     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10579     * directly. An example of overlapping rendering is a TextView with a background image, such as
10580     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10581     * ImageView with only the foreground image. The default implementation returns true; subclasses
10582     * should override if they have cases which can be optimized.</p>
10583     *
10584     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10585     * necessitates that a View return true if it uses the methods internally without passing the
10586     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10587     *
10588     * @return true if the content in this view might overlap, false otherwise.
10589     */
10590    @ViewDebug.ExportedProperty(category = "drawing")
10591    public boolean hasOverlappingRendering() {
10592        return true;
10593    }
10594
10595    /**
10596     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10597     * completely transparent and 1 means the view is completely opaque.</p>
10598     *
10599     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10600     * performance implications, especially for large views. It is best to use the alpha property
10601     * sparingly and transiently, as in the case of fading animations.</p>
10602     *
10603     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10604     * strongly recommended for performance reasons to either override
10605     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10606     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10607     *
10608     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10609     * responsible for applying the opacity itself.</p>
10610     *
10611     * <p>Note that if the view is backed by a
10612     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10613     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10614     * 1.0 will supercede the alpha of the layer paint.</p>
10615     *
10616     * @param alpha The opacity of the view.
10617     *
10618     * @see #hasOverlappingRendering()
10619     * @see #setLayerType(int, android.graphics.Paint)
10620     *
10621     * @attr ref android.R.styleable#View_alpha
10622     */
10623    public void setAlpha(float alpha) {
10624        ensureTransformationInfo();
10625        if (mTransformationInfo.mAlpha != alpha) {
10626            mTransformationInfo.mAlpha = alpha;
10627            if (onSetAlpha((int) (alpha * 255))) {
10628                mPrivateFlags |= PFLAG_ALPHA_SET;
10629                // subclass is handling alpha - don't optimize rendering cache invalidation
10630                invalidateParentCaches();
10631                invalidate(true);
10632            } else {
10633                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10634                invalidateViewProperty(true, false);
10635                mRenderNode.setAlpha(getFinalAlpha());
10636                notifyViewAccessibilityStateChangedIfNeeded(
10637                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10638            }
10639        }
10640    }
10641
10642    /**
10643     * Faster version of setAlpha() which performs the same steps except there are
10644     * no calls to invalidate(). The caller of this function should perform proper invalidation
10645     * on the parent and this object. The return value indicates whether the subclass handles
10646     * alpha (the return value for onSetAlpha()).
10647     *
10648     * @param alpha The new value for the alpha property
10649     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10650     *         the new value for the alpha property is different from the old value
10651     */
10652    boolean setAlphaNoInvalidation(float alpha) {
10653        ensureTransformationInfo();
10654        if (mTransformationInfo.mAlpha != alpha) {
10655            mTransformationInfo.mAlpha = alpha;
10656            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10657            if (subclassHandlesAlpha) {
10658                mPrivateFlags |= PFLAG_ALPHA_SET;
10659                return true;
10660            } else {
10661                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10662                mRenderNode.setAlpha(getFinalAlpha());
10663            }
10664        }
10665        return false;
10666    }
10667
10668    /**
10669     * This property is hidden and intended only for use by the Fade transition, which
10670     * animates it to produce a visual translucency that does not side-effect (or get
10671     * affected by) the real alpha property. This value is composited with the other
10672     * alpha value (and the AlphaAnimation value, when that is present) to produce
10673     * a final visual translucency result, which is what is passed into the DisplayList.
10674     *
10675     * @hide
10676     */
10677    public void setTransitionAlpha(float alpha) {
10678        ensureTransformationInfo();
10679        if (mTransformationInfo.mTransitionAlpha != alpha) {
10680            mTransformationInfo.mTransitionAlpha = alpha;
10681            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10682            invalidateViewProperty(true, false);
10683            mRenderNode.setAlpha(getFinalAlpha());
10684        }
10685    }
10686
10687    /**
10688     * Calculates the visual alpha of this view, which is a combination of the actual
10689     * alpha value and the transitionAlpha value (if set).
10690     */
10691    private float getFinalAlpha() {
10692        if (mTransformationInfo != null) {
10693            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10694        }
10695        return 1;
10696    }
10697
10698    /**
10699     * This property is hidden and intended only for use by the Fade transition, which
10700     * animates it to produce a visual translucency that does not side-effect (or get
10701     * affected by) the real alpha property. This value is composited with the other
10702     * alpha value (and the AlphaAnimation value, when that is present) to produce
10703     * a final visual translucency result, which is what is passed into the DisplayList.
10704     *
10705     * @hide
10706     */
10707    @ViewDebug.ExportedProperty(category = "drawing")
10708    public float getTransitionAlpha() {
10709        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10710    }
10711
10712    /**
10713     * Top position of this view relative to its parent.
10714     *
10715     * @return The top of this view, in pixels.
10716     */
10717    @ViewDebug.CapturedViewProperty
10718    public final int getTop() {
10719        return mTop;
10720    }
10721
10722    /**
10723     * Sets the top position of this view relative to its parent. This method is meant to be called
10724     * by the layout system and should not generally be called otherwise, because the property
10725     * may be changed at any time by the layout.
10726     *
10727     * @param top The top of this view, in pixels.
10728     */
10729    public final void setTop(int top) {
10730        if (top != mTop) {
10731            final boolean matrixIsIdentity = hasIdentityMatrix();
10732            if (matrixIsIdentity) {
10733                if (mAttachInfo != null) {
10734                    int minTop;
10735                    int yLoc;
10736                    if (top < mTop) {
10737                        minTop = top;
10738                        yLoc = top - mTop;
10739                    } else {
10740                        minTop = mTop;
10741                        yLoc = 0;
10742                    }
10743                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10744                }
10745            } else {
10746                // Double-invalidation is necessary to capture view's old and new areas
10747                invalidate(true);
10748            }
10749
10750            int width = mRight - mLeft;
10751            int oldHeight = mBottom - mTop;
10752
10753            mTop = top;
10754            mRenderNode.setTop(mTop);
10755
10756            sizeChange(width, mBottom - mTop, width, oldHeight);
10757
10758            if (!matrixIsIdentity) {
10759                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10760                invalidate(true);
10761            }
10762            mBackgroundSizeChanged = true;
10763            invalidateParentIfNeeded();
10764            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10765                // View was rejected last time it was drawn by its parent; this may have changed
10766                invalidateParentIfNeeded();
10767            }
10768        }
10769    }
10770
10771    /**
10772     * Bottom position of this view relative to its parent.
10773     *
10774     * @return The bottom of this view, in pixels.
10775     */
10776    @ViewDebug.CapturedViewProperty
10777    public final int getBottom() {
10778        return mBottom;
10779    }
10780
10781    /**
10782     * True if this view has changed since the last time being drawn.
10783     *
10784     * @return The dirty state of this view.
10785     */
10786    public boolean isDirty() {
10787        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10788    }
10789
10790    /**
10791     * Sets the bottom position of this view relative to its parent. This method is meant to be
10792     * called by the layout system and should not generally be called otherwise, because the
10793     * property may be changed at any time by the layout.
10794     *
10795     * @param bottom The bottom of this view, in pixels.
10796     */
10797    public final void setBottom(int bottom) {
10798        if (bottom != mBottom) {
10799            final boolean matrixIsIdentity = hasIdentityMatrix();
10800            if (matrixIsIdentity) {
10801                if (mAttachInfo != null) {
10802                    int maxBottom;
10803                    if (bottom < mBottom) {
10804                        maxBottom = mBottom;
10805                    } else {
10806                        maxBottom = bottom;
10807                    }
10808                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10809                }
10810            } else {
10811                // Double-invalidation is necessary to capture view's old and new areas
10812                invalidate(true);
10813            }
10814
10815            int width = mRight - mLeft;
10816            int oldHeight = mBottom - mTop;
10817
10818            mBottom = bottom;
10819            mRenderNode.setBottom(mBottom);
10820
10821            sizeChange(width, mBottom - mTop, width, oldHeight);
10822
10823            if (!matrixIsIdentity) {
10824                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10825                invalidate(true);
10826            }
10827            mBackgroundSizeChanged = true;
10828            invalidateParentIfNeeded();
10829            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10830                // View was rejected last time it was drawn by its parent; this may have changed
10831                invalidateParentIfNeeded();
10832            }
10833        }
10834    }
10835
10836    /**
10837     * Left position of this view relative to its parent.
10838     *
10839     * @return The left edge of this view, in pixels.
10840     */
10841    @ViewDebug.CapturedViewProperty
10842    public final int getLeft() {
10843        return mLeft;
10844    }
10845
10846    /**
10847     * Sets the left position of this view relative to its parent. This method is meant to be called
10848     * by the layout system and should not generally be called otherwise, because the property
10849     * may be changed at any time by the layout.
10850     *
10851     * @param left The left of this view, in pixels.
10852     */
10853    public final void setLeft(int left) {
10854        if (left != mLeft) {
10855            final boolean matrixIsIdentity = hasIdentityMatrix();
10856            if (matrixIsIdentity) {
10857                if (mAttachInfo != null) {
10858                    int minLeft;
10859                    int xLoc;
10860                    if (left < mLeft) {
10861                        minLeft = left;
10862                        xLoc = left - mLeft;
10863                    } else {
10864                        minLeft = mLeft;
10865                        xLoc = 0;
10866                    }
10867                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10868                }
10869            } else {
10870                // Double-invalidation is necessary to capture view's old and new areas
10871                invalidate(true);
10872            }
10873
10874            int oldWidth = mRight - mLeft;
10875            int height = mBottom - mTop;
10876
10877            mLeft = left;
10878            mRenderNode.setLeft(left);
10879
10880            sizeChange(mRight - mLeft, height, oldWidth, height);
10881
10882            if (!matrixIsIdentity) {
10883                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10884                invalidate(true);
10885            }
10886            mBackgroundSizeChanged = true;
10887            invalidateParentIfNeeded();
10888            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10889                // View was rejected last time it was drawn by its parent; this may have changed
10890                invalidateParentIfNeeded();
10891            }
10892        }
10893    }
10894
10895    /**
10896     * Right position of this view relative to its parent.
10897     *
10898     * @return The right edge of this view, in pixels.
10899     */
10900    @ViewDebug.CapturedViewProperty
10901    public final int getRight() {
10902        return mRight;
10903    }
10904
10905    /**
10906     * Sets the right position of this view relative to its parent. This method is meant to be called
10907     * by the layout system and should not generally be called otherwise, because the property
10908     * may be changed at any time by the layout.
10909     *
10910     * @param right The right of this view, in pixels.
10911     */
10912    public final void setRight(int right) {
10913        if (right != mRight) {
10914            final boolean matrixIsIdentity = hasIdentityMatrix();
10915            if (matrixIsIdentity) {
10916                if (mAttachInfo != null) {
10917                    int maxRight;
10918                    if (right < mRight) {
10919                        maxRight = mRight;
10920                    } else {
10921                        maxRight = right;
10922                    }
10923                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10924                }
10925            } else {
10926                // Double-invalidation is necessary to capture view's old and new areas
10927                invalidate(true);
10928            }
10929
10930            int oldWidth = mRight - mLeft;
10931            int height = mBottom - mTop;
10932
10933            mRight = right;
10934            mRenderNode.setRight(mRight);
10935
10936            sizeChange(mRight - mLeft, height, oldWidth, height);
10937
10938            if (!matrixIsIdentity) {
10939                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10940                invalidate(true);
10941            }
10942            mBackgroundSizeChanged = true;
10943            invalidateParentIfNeeded();
10944            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10945                // View was rejected last time it was drawn by its parent; this may have changed
10946                invalidateParentIfNeeded();
10947            }
10948        }
10949    }
10950
10951    /**
10952     * The visual x position of this view, in pixels. This is equivalent to the
10953     * {@link #setTranslationX(float) translationX} property plus the current
10954     * {@link #getLeft() left} property.
10955     *
10956     * @return The visual x position of this view, in pixels.
10957     */
10958    @ViewDebug.ExportedProperty(category = "drawing")
10959    public float getX() {
10960        return mLeft + getTranslationX();
10961    }
10962
10963    /**
10964     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10965     * {@link #setTranslationX(float) translationX} property to be the difference between
10966     * the x value passed in and the current {@link #getLeft() left} property.
10967     *
10968     * @param x The visual x position of this view, in pixels.
10969     */
10970    public void setX(float x) {
10971        setTranslationX(x - mLeft);
10972    }
10973
10974    /**
10975     * The visual y position of this view, in pixels. This is equivalent to the
10976     * {@link #setTranslationY(float) translationY} property plus the current
10977     * {@link #getTop() top} property.
10978     *
10979     * @return The visual y position of this view, in pixels.
10980     */
10981    @ViewDebug.ExportedProperty(category = "drawing")
10982    public float getY() {
10983        return mTop + getTranslationY();
10984    }
10985
10986    /**
10987     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10988     * {@link #setTranslationY(float) translationY} property to be the difference between
10989     * the y value passed in and the current {@link #getTop() top} property.
10990     *
10991     * @param y The visual y position of this view, in pixels.
10992     */
10993    public void setY(float y) {
10994        setTranslationY(y - mTop);
10995    }
10996
10997    /**
10998     * The visual z position of this view, in pixels. This is equivalent to the
10999     * {@link #setTranslationZ(float) translationZ} property plus the current
11000     * {@link #getElevation() elevation} property.
11001     *
11002     * @return The visual z position of this view, in pixels.
11003     */
11004    @ViewDebug.ExportedProperty(category = "drawing")
11005    public float getZ() {
11006        return getElevation() + getTranslationZ();
11007    }
11008
11009    /**
11010     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11011     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11012     * the x value passed in and the current {@link #getElevation() elevation} property.
11013     *
11014     * @param z The visual z position of this view, in pixels.
11015     */
11016    public void setZ(float z) {
11017        setTranslationZ(z - getElevation());
11018    }
11019
11020    /**
11021     * The base elevation of this view relative to its parent, in pixels.
11022     *
11023     * @return The base depth position of the view, in pixels.
11024     */
11025    @ViewDebug.ExportedProperty(category = "drawing")
11026    public float getElevation() {
11027        return mRenderNode.getElevation();
11028    }
11029
11030    /**
11031     * Sets the base elevation of this view, in pixels.
11032     *
11033     * @attr ref android.R.styleable#View_elevation
11034     */
11035    public void setElevation(float elevation) {
11036        if (elevation != getElevation()) {
11037            invalidateViewProperty(true, false);
11038            mRenderNode.setElevation(elevation);
11039            invalidateViewProperty(false, true);
11040
11041            invalidateParentIfNeededAndWasQuickRejected();
11042        }
11043    }
11044
11045    /**
11046     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11047     * This position is post-layout, in addition to wherever the object's
11048     * layout placed it.
11049     *
11050     * @return The horizontal position of this view relative to its left position, in pixels.
11051     */
11052    @ViewDebug.ExportedProperty(category = "drawing")
11053    public float getTranslationX() {
11054        return mRenderNode.getTranslationX();
11055    }
11056
11057    /**
11058     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11059     * This effectively positions the object post-layout, in addition to wherever the object's
11060     * layout placed it.
11061     *
11062     * @param translationX The horizontal position of this view relative to its left position,
11063     * in pixels.
11064     *
11065     * @attr ref android.R.styleable#View_translationX
11066     */
11067    public void setTranslationX(float translationX) {
11068        if (translationX != getTranslationX()) {
11069            invalidateViewProperty(true, false);
11070            mRenderNode.setTranslationX(translationX);
11071            invalidateViewProperty(false, true);
11072
11073            invalidateParentIfNeededAndWasQuickRejected();
11074            notifySubtreeAccessibilityStateChangedIfNeeded();
11075        }
11076    }
11077
11078    /**
11079     * The vertical location of this view relative to its {@link #getTop() top} position.
11080     * This position is post-layout, in addition to wherever the object's
11081     * layout placed it.
11082     *
11083     * @return The vertical position of this view relative to its top position,
11084     * in pixels.
11085     */
11086    @ViewDebug.ExportedProperty(category = "drawing")
11087    public float getTranslationY() {
11088        return mRenderNode.getTranslationY();
11089    }
11090
11091    /**
11092     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11093     * This effectively positions the object post-layout, in addition to wherever the object's
11094     * layout placed it.
11095     *
11096     * @param translationY The vertical position of this view relative to its top position,
11097     * in pixels.
11098     *
11099     * @attr ref android.R.styleable#View_translationY
11100     */
11101    public void setTranslationY(float translationY) {
11102        if (translationY != getTranslationY()) {
11103            invalidateViewProperty(true, false);
11104            mRenderNode.setTranslationY(translationY);
11105            invalidateViewProperty(false, true);
11106
11107            invalidateParentIfNeededAndWasQuickRejected();
11108        }
11109    }
11110
11111    /**
11112     * The depth location of this view relative to its {@link #getElevation() elevation}.
11113     *
11114     * @return The depth of this view relative to its elevation.
11115     */
11116    @ViewDebug.ExportedProperty(category = "drawing")
11117    public float getTranslationZ() {
11118        return mRenderNode.getTranslationZ();
11119    }
11120
11121    /**
11122     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11123     *
11124     * @attr ref android.R.styleable#View_translationZ
11125     */
11126    public void setTranslationZ(float translationZ) {
11127        if (translationZ != getTranslationZ()) {
11128            invalidateViewProperty(true, false);
11129            mRenderNode.setTranslationZ(translationZ);
11130            invalidateViewProperty(false, true);
11131
11132            invalidateParentIfNeededAndWasQuickRejected();
11133        }
11134    }
11135
11136    /** @hide */
11137    public void setAnimationMatrix(Matrix matrix) {
11138        invalidateViewProperty(true, false);
11139        mRenderNode.setAnimationMatrix(matrix);
11140        invalidateViewProperty(false, true);
11141
11142        invalidateParentIfNeededAndWasQuickRejected();
11143    }
11144
11145    /**
11146     * Returns the current StateListAnimator if exists.
11147     *
11148     * @return StateListAnimator or null if it does not exists
11149     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11150     */
11151    public StateListAnimator getStateListAnimator() {
11152        return mStateListAnimator;
11153    }
11154
11155    /**
11156     * Attaches the provided StateListAnimator to this View.
11157     * <p>
11158     * Any previously attached StateListAnimator will be detached.
11159     *
11160     * @param stateListAnimator The StateListAnimator to update the view
11161     * @see {@link android.animation.StateListAnimator}
11162     */
11163    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11164        if (mStateListAnimator == stateListAnimator) {
11165            return;
11166        }
11167        if (mStateListAnimator != null) {
11168            mStateListAnimator.setTarget(null);
11169        }
11170        mStateListAnimator = stateListAnimator;
11171        if (stateListAnimator != null) {
11172            stateListAnimator.setTarget(this);
11173            if (isAttachedToWindow()) {
11174                stateListAnimator.setState(getDrawableState());
11175            }
11176        }
11177    }
11178
11179    /**
11180     * Returns whether the Outline should be used to clip the contents of the View.
11181     * <p>
11182     * Note that this flag will only be respected if the View's Outline returns true from
11183     * {@link Outline#canClip()}.
11184     *
11185     * @see #setOutlineProvider(ViewOutlineProvider)
11186     * @see #setClipToOutline(boolean)
11187     */
11188    public final boolean getClipToOutline() {
11189        return mRenderNode.getClipToOutline();
11190    }
11191
11192    /**
11193     * Sets whether the View's Outline should be used to clip the contents of the View.
11194     * <p>
11195     * Only a single non-rectangular clip can be applied on a View at any time.
11196     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11197     * circular reveal} animation take priority over Outline clipping, and
11198     * child Outline clipping takes priority over Outline clipping done by a
11199     * parent.
11200     * <p>
11201     * Note that this flag will only be respected if the View's Outline returns true from
11202     * {@link Outline#canClip()}.
11203     *
11204     * @see #setOutlineProvider(ViewOutlineProvider)
11205     * @see #getClipToOutline()
11206     */
11207    public void setClipToOutline(boolean clipToOutline) {
11208        damageInParent();
11209        if (getClipToOutline() != clipToOutline) {
11210            mRenderNode.setClipToOutline(clipToOutline);
11211        }
11212    }
11213
11214    // correspond to the enum values of View_outlineProvider
11215    private static final int PROVIDER_BACKGROUND = 0;
11216    private static final int PROVIDER_NONE = 1;
11217    private static final int PROVIDER_BOUNDS = 2;
11218    private static final int PROVIDER_PADDED_BOUNDS = 3;
11219    private void setOutlineProviderFromAttribute(int providerInt) {
11220        switch (providerInt) {
11221            case PROVIDER_BACKGROUND:
11222                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11223                break;
11224            case PROVIDER_NONE:
11225                setOutlineProvider(null);
11226                break;
11227            case PROVIDER_BOUNDS:
11228                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11229                break;
11230            case PROVIDER_PADDED_BOUNDS:
11231                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11232                break;
11233        }
11234    }
11235
11236    /**
11237     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11238     * the shape of the shadow it casts, and enables outline clipping.
11239     * <p>
11240     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11241     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11242     * outline provider with this method allows this behavior to be overridden.
11243     * <p>
11244     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11245     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11246     * <p>
11247     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11248     *
11249     * @see #setClipToOutline(boolean)
11250     * @see #getClipToOutline()
11251     * @see #getOutlineProvider()
11252     */
11253    public void setOutlineProvider(ViewOutlineProvider provider) {
11254        mOutlineProvider = provider;
11255        invalidateOutline();
11256    }
11257
11258    /**
11259     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11260     * that defines the shape of the shadow it casts, and enables outline clipping.
11261     *
11262     * @see #setOutlineProvider(ViewOutlineProvider)
11263     */
11264    public ViewOutlineProvider getOutlineProvider() {
11265        return mOutlineProvider;
11266    }
11267
11268    /**
11269     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11270     *
11271     * @see #setOutlineProvider(ViewOutlineProvider)
11272     */
11273    public void invalidateOutline() {
11274        rebuildOutline();
11275
11276        notifySubtreeAccessibilityStateChangedIfNeeded();
11277        invalidateViewProperty(false, false);
11278    }
11279
11280    /**
11281     * Internal version of {@link #invalidateOutline()} which invalidates the
11282     * outline without invalidating the view itself. This is intended to be called from
11283     * within methods in the View class itself which are the result of the view being
11284     * invalidated already. For example, when we are drawing the background of a View,
11285     * we invalidate the outline in case it changed in the meantime, but we do not
11286     * need to invalidate the view because we're already drawing the background as part
11287     * of drawing the view in response to an earlier invalidation of the view.
11288     */
11289    private void rebuildOutline() {
11290        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11291        if (mAttachInfo == null) return;
11292
11293        if (mOutlineProvider == null) {
11294            // no provider, remove outline
11295            mRenderNode.setOutline(null);
11296        } else {
11297            final Outline outline = mAttachInfo.mTmpOutline;
11298            outline.setEmpty();
11299            outline.setAlpha(1.0f);
11300
11301            mOutlineProvider.getOutline(this, outline);
11302            mRenderNode.setOutline(outline);
11303        }
11304    }
11305
11306    /**
11307     * HierarchyViewer only
11308     *
11309     * @hide
11310     */
11311    @ViewDebug.ExportedProperty(category = "drawing")
11312    public boolean hasShadow() {
11313        return mRenderNode.hasShadow();
11314    }
11315
11316
11317    /** @hide */
11318    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11319        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11320        invalidateViewProperty(false, false);
11321    }
11322
11323    /**
11324     * Hit rectangle in parent's coordinates
11325     *
11326     * @param outRect The hit rectangle of the view.
11327     */
11328    public void getHitRect(Rect outRect) {
11329        if (hasIdentityMatrix() || mAttachInfo == null) {
11330            outRect.set(mLeft, mTop, mRight, mBottom);
11331        } else {
11332            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11333            tmpRect.set(0, 0, getWidth(), getHeight());
11334            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11335            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11336                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11337        }
11338    }
11339
11340    /**
11341     * Determines whether the given point, in local coordinates is inside the view.
11342     */
11343    /*package*/ final boolean pointInView(float localX, float localY) {
11344        return localX >= 0 && localX < (mRight - mLeft)
11345                && localY >= 0 && localY < (mBottom - mTop);
11346    }
11347
11348    /**
11349     * Utility method to determine whether the given point, in local coordinates,
11350     * is inside the view, where the area of the view is expanded by the slop factor.
11351     * This method is called while processing touch-move events to determine if the event
11352     * is still within the view.
11353     *
11354     * @hide
11355     */
11356    public boolean pointInView(float localX, float localY, float slop) {
11357        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11358                localY < ((mBottom - mTop) + slop);
11359    }
11360
11361    /**
11362     * When a view has focus and the user navigates away from it, the next view is searched for
11363     * starting from the rectangle filled in by this method.
11364     *
11365     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11366     * of the view.  However, if your view maintains some idea of internal selection,
11367     * such as a cursor, or a selected row or column, you should override this method and
11368     * fill in a more specific rectangle.
11369     *
11370     * @param r The rectangle to fill in, in this view's coordinates.
11371     */
11372    public void getFocusedRect(Rect r) {
11373        getDrawingRect(r);
11374    }
11375
11376    /**
11377     * If some part of this view is not clipped by any of its parents, then
11378     * return that area in r in global (root) coordinates. To convert r to local
11379     * coordinates (without taking possible View rotations into account), offset
11380     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11381     * If the view is completely clipped or translated out, return false.
11382     *
11383     * @param r If true is returned, r holds the global coordinates of the
11384     *        visible portion of this view.
11385     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11386     *        between this view and its root. globalOffet may be null.
11387     * @return true if r is non-empty (i.e. part of the view is visible at the
11388     *         root level.
11389     */
11390    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11391        int width = mRight - mLeft;
11392        int height = mBottom - mTop;
11393        if (width > 0 && height > 0) {
11394            r.set(0, 0, width, height);
11395            if (globalOffset != null) {
11396                globalOffset.set(-mScrollX, -mScrollY);
11397            }
11398            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11399        }
11400        return false;
11401    }
11402
11403    public final boolean getGlobalVisibleRect(Rect r) {
11404        return getGlobalVisibleRect(r, null);
11405    }
11406
11407    public final boolean getLocalVisibleRect(Rect r) {
11408        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11409        if (getGlobalVisibleRect(r, offset)) {
11410            r.offset(-offset.x, -offset.y); // make r local
11411            return true;
11412        }
11413        return false;
11414    }
11415
11416    /**
11417     * Offset this view's vertical location by the specified number of pixels.
11418     *
11419     * @param offset the number of pixels to offset the view by
11420     */
11421    public void offsetTopAndBottom(int offset) {
11422        if (offset != 0) {
11423            final boolean matrixIsIdentity = hasIdentityMatrix();
11424            if (matrixIsIdentity) {
11425                if (isHardwareAccelerated()) {
11426                    invalidateViewProperty(false, false);
11427                } else {
11428                    final ViewParent p = mParent;
11429                    if (p != null && mAttachInfo != null) {
11430                        final Rect r = mAttachInfo.mTmpInvalRect;
11431                        int minTop;
11432                        int maxBottom;
11433                        int yLoc;
11434                        if (offset < 0) {
11435                            minTop = mTop + offset;
11436                            maxBottom = mBottom;
11437                            yLoc = offset;
11438                        } else {
11439                            minTop = mTop;
11440                            maxBottom = mBottom + offset;
11441                            yLoc = 0;
11442                        }
11443                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11444                        p.invalidateChild(this, r);
11445                    }
11446                }
11447            } else {
11448                invalidateViewProperty(false, false);
11449            }
11450
11451            mTop += offset;
11452            mBottom += offset;
11453            mRenderNode.offsetTopAndBottom(offset);
11454            if (isHardwareAccelerated()) {
11455                invalidateViewProperty(false, false);
11456            } else {
11457                if (!matrixIsIdentity) {
11458                    invalidateViewProperty(false, true);
11459                }
11460                invalidateParentIfNeeded();
11461            }
11462            notifySubtreeAccessibilityStateChangedIfNeeded();
11463        }
11464    }
11465
11466    /**
11467     * Offset this view's horizontal location by the specified amount of pixels.
11468     *
11469     * @param offset the number of pixels to offset the view by
11470     */
11471    public void offsetLeftAndRight(int offset) {
11472        if (offset != 0) {
11473            final boolean matrixIsIdentity = hasIdentityMatrix();
11474            if (matrixIsIdentity) {
11475                if (isHardwareAccelerated()) {
11476                    invalidateViewProperty(false, false);
11477                } else {
11478                    final ViewParent p = mParent;
11479                    if (p != null && mAttachInfo != null) {
11480                        final Rect r = mAttachInfo.mTmpInvalRect;
11481                        int minLeft;
11482                        int maxRight;
11483                        if (offset < 0) {
11484                            minLeft = mLeft + offset;
11485                            maxRight = mRight;
11486                        } else {
11487                            minLeft = mLeft;
11488                            maxRight = mRight + offset;
11489                        }
11490                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11491                        p.invalidateChild(this, r);
11492                    }
11493                }
11494            } else {
11495                invalidateViewProperty(false, false);
11496            }
11497
11498            mLeft += offset;
11499            mRight += offset;
11500            mRenderNode.offsetLeftAndRight(offset);
11501            if (isHardwareAccelerated()) {
11502                invalidateViewProperty(false, false);
11503            } else {
11504                if (!matrixIsIdentity) {
11505                    invalidateViewProperty(false, true);
11506                }
11507                invalidateParentIfNeeded();
11508            }
11509            notifySubtreeAccessibilityStateChangedIfNeeded();
11510        }
11511    }
11512
11513    /**
11514     * Get the LayoutParams associated with this view. All views should have
11515     * layout parameters. These supply parameters to the <i>parent</i> of this
11516     * view specifying how it should be arranged. There are many subclasses of
11517     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11518     * of ViewGroup that are responsible for arranging their children.
11519     *
11520     * This method may return null if this View is not attached to a parent
11521     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11522     * was not invoked successfully. When a View is attached to a parent
11523     * ViewGroup, this method must not return null.
11524     *
11525     * @return The LayoutParams associated with this view, or null if no
11526     *         parameters have been set yet
11527     */
11528    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11529    public ViewGroup.LayoutParams getLayoutParams() {
11530        return mLayoutParams;
11531    }
11532
11533    /**
11534     * Set the layout parameters associated with this view. These supply
11535     * parameters to the <i>parent</i> of this view specifying how it should be
11536     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11537     * correspond to the different subclasses of ViewGroup that are responsible
11538     * for arranging their children.
11539     *
11540     * @param params The layout parameters for this view, cannot be null
11541     */
11542    public void setLayoutParams(ViewGroup.LayoutParams params) {
11543        if (params == null) {
11544            throw new NullPointerException("Layout parameters cannot be null");
11545        }
11546        mLayoutParams = params;
11547        resolveLayoutParams();
11548        if (mParent instanceof ViewGroup) {
11549            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11550        }
11551        requestLayout();
11552    }
11553
11554    /**
11555     * Resolve the layout parameters depending on the resolved layout direction
11556     *
11557     * @hide
11558     */
11559    public void resolveLayoutParams() {
11560        if (mLayoutParams != null) {
11561            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11562        }
11563    }
11564
11565    /**
11566     * Set the scrolled position of your view. This will cause a call to
11567     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11568     * invalidated.
11569     * @param x the x position to scroll to
11570     * @param y the y position to scroll to
11571     */
11572    public void scrollTo(int x, int y) {
11573        if (mScrollX != x || mScrollY != y) {
11574            int oldX = mScrollX;
11575            int oldY = mScrollY;
11576            mScrollX = x;
11577            mScrollY = y;
11578            invalidateParentCaches();
11579            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11580            if (!awakenScrollBars()) {
11581                postInvalidateOnAnimation();
11582            }
11583        }
11584    }
11585
11586    /**
11587     * Move the scrolled position of your view. This will cause a call to
11588     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11589     * invalidated.
11590     * @param x the amount of pixels to scroll by horizontally
11591     * @param y the amount of pixels to scroll by vertically
11592     */
11593    public void scrollBy(int x, int y) {
11594        scrollTo(mScrollX + x, mScrollY + y);
11595    }
11596
11597    /**
11598     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11599     * animation to fade the scrollbars out after a default delay. If a subclass
11600     * provides animated scrolling, the start delay should equal the duration
11601     * of the scrolling animation.</p>
11602     *
11603     * <p>The animation starts only if at least one of the scrollbars is
11604     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11605     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11606     * this method returns true, and false otherwise. If the animation is
11607     * started, this method calls {@link #invalidate()}; in that case the
11608     * caller should not call {@link #invalidate()}.</p>
11609     *
11610     * <p>This method should be invoked every time a subclass directly updates
11611     * the scroll parameters.</p>
11612     *
11613     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11614     * and {@link #scrollTo(int, int)}.</p>
11615     *
11616     * @return true if the animation is played, false otherwise
11617     *
11618     * @see #awakenScrollBars(int)
11619     * @see #scrollBy(int, int)
11620     * @see #scrollTo(int, int)
11621     * @see #isHorizontalScrollBarEnabled()
11622     * @see #isVerticalScrollBarEnabled()
11623     * @see #setHorizontalScrollBarEnabled(boolean)
11624     * @see #setVerticalScrollBarEnabled(boolean)
11625     */
11626    protected boolean awakenScrollBars() {
11627        return mScrollCache != null &&
11628                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11629    }
11630
11631    /**
11632     * Trigger the scrollbars to draw.
11633     * This method differs from awakenScrollBars() only in its default duration.
11634     * initialAwakenScrollBars() will show the scroll bars for longer than
11635     * usual to give the user more of a chance to notice them.
11636     *
11637     * @return true if the animation is played, false otherwise.
11638     */
11639    private boolean initialAwakenScrollBars() {
11640        return mScrollCache != null &&
11641                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11642    }
11643
11644    /**
11645     * <p>
11646     * Trigger the scrollbars to draw. When invoked this method starts an
11647     * animation to fade the scrollbars out after a fixed delay. If a subclass
11648     * provides animated scrolling, the start delay should equal the duration of
11649     * the scrolling animation.
11650     * </p>
11651     *
11652     * <p>
11653     * The animation starts only if at least one of the scrollbars is enabled,
11654     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11655     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11656     * this method returns true, and false otherwise. If the animation is
11657     * started, this method calls {@link #invalidate()}; in that case the caller
11658     * should not call {@link #invalidate()}.
11659     * </p>
11660     *
11661     * <p>
11662     * This method should be invoked everytime a subclass directly updates the
11663     * scroll parameters.
11664     * </p>
11665     *
11666     * @param startDelay the delay, in milliseconds, after which the animation
11667     *        should start; when the delay is 0, the animation starts
11668     *        immediately
11669     * @return true if the animation is played, false otherwise
11670     *
11671     * @see #scrollBy(int, int)
11672     * @see #scrollTo(int, int)
11673     * @see #isHorizontalScrollBarEnabled()
11674     * @see #isVerticalScrollBarEnabled()
11675     * @see #setHorizontalScrollBarEnabled(boolean)
11676     * @see #setVerticalScrollBarEnabled(boolean)
11677     */
11678    protected boolean awakenScrollBars(int startDelay) {
11679        return awakenScrollBars(startDelay, true);
11680    }
11681
11682    /**
11683     * <p>
11684     * Trigger the scrollbars to draw. When invoked this method starts an
11685     * animation to fade the scrollbars out after a fixed delay. If a subclass
11686     * provides animated scrolling, the start delay should equal the duration of
11687     * the scrolling animation.
11688     * </p>
11689     *
11690     * <p>
11691     * The animation starts only if at least one of the scrollbars is enabled,
11692     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11693     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11694     * this method returns true, and false otherwise. If the animation is
11695     * started, this method calls {@link #invalidate()} if the invalidate parameter
11696     * is set to true; in that case the caller
11697     * should not call {@link #invalidate()}.
11698     * </p>
11699     *
11700     * <p>
11701     * This method should be invoked everytime a subclass directly updates the
11702     * scroll parameters.
11703     * </p>
11704     *
11705     * @param startDelay the delay, in milliseconds, after which the animation
11706     *        should start; when the delay is 0, the animation starts
11707     *        immediately
11708     *
11709     * @param invalidate Wheter this method should call invalidate
11710     *
11711     * @return true if the animation is played, false otherwise
11712     *
11713     * @see #scrollBy(int, int)
11714     * @see #scrollTo(int, int)
11715     * @see #isHorizontalScrollBarEnabled()
11716     * @see #isVerticalScrollBarEnabled()
11717     * @see #setHorizontalScrollBarEnabled(boolean)
11718     * @see #setVerticalScrollBarEnabled(boolean)
11719     */
11720    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11721        final ScrollabilityCache scrollCache = mScrollCache;
11722
11723        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11724            return false;
11725        }
11726
11727        if (scrollCache.scrollBar == null) {
11728            scrollCache.scrollBar = new ScrollBarDrawable();
11729        }
11730
11731        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11732
11733            if (invalidate) {
11734                // Invalidate to show the scrollbars
11735                postInvalidateOnAnimation();
11736            }
11737
11738            if (scrollCache.state == ScrollabilityCache.OFF) {
11739                // FIXME: this is copied from WindowManagerService.
11740                // We should get this value from the system when it
11741                // is possible to do so.
11742                final int KEY_REPEAT_FIRST_DELAY = 750;
11743                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11744            }
11745
11746            // Tell mScrollCache when we should start fading. This may
11747            // extend the fade start time if one was already scheduled
11748            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11749            scrollCache.fadeStartTime = fadeStartTime;
11750            scrollCache.state = ScrollabilityCache.ON;
11751
11752            // Schedule our fader to run, unscheduling any old ones first
11753            if (mAttachInfo != null) {
11754                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11755                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11756            }
11757
11758            return true;
11759        }
11760
11761        return false;
11762    }
11763
11764    /**
11765     * Do not invalidate views which are not visible and which are not running an animation. They
11766     * will not get drawn and they should not set dirty flags as if they will be drawn
11767     */
11768    private boolean skipInvalidate() {
11769        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11770                (!(mParent instanceof ViewGroup) ||
11771                        !((ViewGroup) mParent).isViewTransitioning(this));
11772    }
11773
11774    /**
11775     * Mark the area defined by dirty as needing to be drawn. If the view is
11776     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11777     * point in the future.
11778     * <p>
11779     * This must be called from a UI thread. To call from a non-UI thread, call
11780     * {@link #postInvalidate()}.
11781     * <p>
11782     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11783     * {@code dirty}.
11784     *
11785     * @param dirty the rectangle representing the bounds of the dirty region
11786     */
11787    public void invalidate(Rect dirty) {
11788        final int scrollX = mScrollX;
11789        final int scrollY = mScrollY;
11790        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11791                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11792    }
11793
11794    /**
11795     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11796     * coordinates of the dirty rect are relative to the view. If the view is
11797     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11798     * point in the future.
11799     * <p>
11800     * This must be called from a UI thread. To call from a non-UI thread, call
11801     * {@link #postInvalidate()}.
11802     *
11803     * @param l the left position of the dirty region
11804     * @param t the top position of the dirty region
11805     * @param r the right position of the dirty region
11806     * @param b the bottom position of the dirty region
11807     */
11808    public void invalidate(int l, int t, int r, int b) {
11809        final int scrollX = mScrollX;
11810        final int scrollY = mScrollY;
11811        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11812    }
11813
11814    /**
11815     * Invalidate the whole view. If the view is visible,
11816     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11817     * the future.
11818     * <p>
11819     * This must be called from a UI thread. To call from a non-UI thread, call
11820     * {@link #postInvalidate()}.
11821     */
11822    public void invalidate() {
11823        invalidate(true);
11824    }
11825
11826    /**
11827     * This is where the invalidate() work actually happens. A full invalidate()
11828     * causes the drawing cache to be invalidated, but this function can be
11829     * called with invalidateCache set to false to skip that invalidation step
11830     * for cases that do not need it (for example, a component that remains at
11831     * the same dimensions with the same content).
11832     *
11833     * @param invalidateCache Whether the drawing cache for this view should be
11834     *            invalidated as well. This is usually true for a full
11835     *            invalidate, but may be set to false if the View's contents or
11836     *            dimensions have not changed.
11837     */
11838    void invalidate(boolean invalidateCache) {
11839        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11840    }
11841
11842    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11843            boolean fullInvalidate) {
11844        if (mGhostView != null) {
11845            mGhostView.invalidate(true);
11846            return;
11847        }
11848
11849        if (skipInvalidate()) {
11850            return;
11851        }
11852
11853        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11854                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11855                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11856                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11857            if (fullInvalidate) {
11858                mLastIsOpaque = isOpaque();
11859                mPrivateFlags &= ~PFLAG_DRAWN;
11860            }
11861
11862            mPrivateFlags |= PFLAG_DIRTY;
11863
11864            if (invalidateCache) {
11865                mPrivateFlags |= PFLAG_INVALIDATED;
11866                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11867            }
11868
11869            // Propagate the damage rectangle to the parent view.
11870            final AttachInfo ai = mAttachInfo;
11871            final ViewParent p = mParent;
11872            if (p != null && ai != null && l < r && t < b) {
11873                final Rect damage = ai.mTmpInvalRect;
11874                damage.set(l, t, r, b);
11875                p.invalidateChild(this, damage);
11876            }
11877
11878            // Damage the entire projection receiver, if necessary.
11879            if (mBackground != null && mBackground.isProjected()) {
11880                final View receiver = getProjectionReceiver();
11881                if (receiver != null) {
11882                    receiver.damageInParent();
11883                }
11884            }
11885
11886            // Damage the entire IsolatedZVolume receiving this view's shadow.
11887            if (isHardwareAccelerated() && getZ() != 0) {
11888                damageShadowReceiver();
11889            }
11890        }
11891    }
11892
11893    /**
11894     * @return this view's projection receiver, or {@code null} if none exists
11895     */
11896    private View getProjectionReceiver() {
11897        ViewParent p = getParent();
11898        while (p != null && p instanceof View) {
11899            final View v = (View) p;
11900            if (v.isProjectionReceiver()) {
11901                return v;
11902            }
11903            p = p.getParent();
11904        }
11905
11906        return null;
11907    }
11908
11909    /**
11910     * @return whether the view is a projection receiver
11911     */
11912    private boolean isProjectionReceiver() {
11913        return mBackground != null;
11914    }
11915
11916    /**
11917     * Damage area of the screen that can be covered by this View's shadow.
11918     *
11919     * This method will guarantee that any changes to shadows cast by a View
11920     * are damaged on the screen for future redraw.
11921     */
11922    private void damageShadowReceiver() {
11923        final AttachInfo ai = mAttachInfo;
11924        if (ai != null) {
11925            ViewParent p = getParent();
11926            if (p != null && p instanceof ViewGroup) {
11927                final ViewGroup vg = (ViewGroup) p;
11928                vg.damageInParent();
11929            }
11930        }
11931    }
11932
11933    /**
11934     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11935     * set any flags or handle all of the cases handled by the default invalidation methods.
11936     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11937     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11938     * walk up the hierarchy, transforming the dirty rect as necessary.
11939     *
11940     * The method also handles normal invalidation logic if display list properties are not
11941     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11942     * backup approach, to handle these cases used in the various property-setting methods.
11943     *
11944     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11945     * are not being used in this view
11946     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11947     * list properties are not being used in this view
11948     */
11949    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11950        if (!isHardwareAccelerated()
11951                || !mRenderNode.isValid()
11952                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11953            if (invalidateParent) {
11954                invalidateParentCaches();
11955            }
11956            if (forceRedraw) {
11957                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11958            }
11959            invalidate(false);
11960        } else {
11961            damageInParent();
11962        }
11963        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11964            damageShadowReceiver();
11965        }
11966    }
11967
11968    /**
11969     * Tells the parent view to damage this view's bounds.
11970     *
11971     * @hide
11972     */
11973    protected void damageInParent() {
11974        final AttachInfo ai = mAttachInfo;
11975        final ViewParent p = mParent;
11976        if (p != null && ai != null) {
11977            final Rect r = ai.mTmpInvalRect;
11978            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11979            if (mParent instanceof ViewGroup) {
11980                ((ViewGroup) mParent).damageChild(this, r);
11981            } else {
11982                mParent.invalidateChild(this, r);
11983            }
11984        }
11985    }
11986
11987    /**
11988     * Utility method to transform a given Rect by the current matrix of this view.
11989     */
11990    void transformRect(final Rect rect) {
11991        if (!getMatrix().isIdentity()) {
11992            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11993            boundingRect.set(rect);
11994            getMatrix().mapRect(boundingRect);
11995            rect.set((int) Math.floor(boundingRect.left),
11996                    (int) Math.floor(boundingRect.top),
11997                    (int) Math.ceil(boundingRect.right),
11998                    (int) Math.ceil(boundingRect.bottom));
11999        }
12000    }
12001
12002    /**
12003     * Used to indicate that the parent of this view should clear its caches. This functionality
12004     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12005     * which is necessary when various parent-managed properties of the view change, such as
12006     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12007     * clears the parent caches and does not causes an invalidate event.
12008     *
12009     * @hide
12010     */
12011    protected void invalidateParentCaches() {
12012        if (mParent instanceof View) {
12013            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12014        }
12015    }
12016
12017    /**
12018     * Used to indicate that the parent of this view should be invalidated. This functionality
12019     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12020     * which is necessary when various parent-managed properties of the view change, such as
12021     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12022     * an invalidation event to the parent.
12023     *
12024     * @hide
12025     */
12026    protected void invalidateParentIfNeeded() {
12027        if (isHardwareAccelerated() && mParent instanceof View) {
12028            ((View) mParent).invalidate(true);
12029        }
12030    }
12031
12032    /**
12033     * @hide
12034     */
12035    protected void invalidateParentIfNeededAndWasQuickRejected() {
12036        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12037            // View was rejected last time it was drawn by its parent; this may have changed
12038            invalidateParentIfNeeded();
12039        }
12040    }
12041
12042    /**
12043     * Indicates whether this View is opaque. An opaque View guarantees that it will
12044     * draw all the pixels overlapping its bounds using a fully opaque color.
12045     *
12046     * Subclasses of View should override this method whenever possible to indicate
12047     * whether an instance is opaque. Opaque Views are treated in a special way by
12048     * the View hierarchy, possibly allowing it to perform optimizations during
12049     * invalidate/draw passes.
12050     *
12051     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12052     */
12053    @ViewDebug.ExportedProperty(category = "drawing")
12054    public boolean isOpaque() {
12055        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12056                getFinalAlpha() >= 1.0f;
12057    }
12058
12059    /**
12060     * @hide
12061     */
12062    protected void computeOpaqueFlags() {
12063        // Opaque if:
12064        //   - Has a background
12065        //   - Background is opaque
12066        //   - Doesn't have scrollbars or scrollbars overlay
12067
12068        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12069            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12070        } else {
12071            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12072        }
12073
12074        final int flags = mViewFlags;
12075        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12076                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12077                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12078            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12079        } else {
12080            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12081        }
12082    }
12083
12084    /**
12085     * @hide
12086     */
12087    protected boolean hasOpaqueScrollbars() {
12088        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12089    }
12090
12091    /**
12092     * @return A handler associated with the thread running the View. This
12093     * handler can be used to pump events in the UI events queue.
12094     */
12095    public Handler getHandler() {
12096        final AttachInfo attachInfo = mAttachInfo;
12097        if (attachInfo != null) {
12098            return attachInfo.mHandler;
12099        }
12100        return null;
12101    }
12102
12103    /**
12104     * Gets the view root associated with the View.
12105     * @return The view root, or null if none.
12106     * @hide
12107     */
12108    public ViewRootImpl getViewRootImpl() {
12109        if (mAttachInfo != null) {
12110            return mAttachInfo.mViewRootImpl;
12111        }
12112        return null;
12113    }
12114
12115    /**
12116     * @hide
12117     */
12118    public HardwareRenderer getHardwareRenderer() {
12119        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12120    }
12121
12122    /**
12123     * <p>Causes the Runnable to be added to the message queue.
12124     * The runnable will be run on the user interface thread.</p>
12125     *
12126     * @param action The Runnable that will be executed.
12127     *
12128     * @return Returns true if the Runnable was successfully placed in to the
12129     *         message queue.  Returns false on failure, usually because the
12130     *         looper processing the message queue is exiting.
12131     *
12132     * @see #postDelayed
12133     * @see #removeCallbacks
12134     */
12135    public boolean post(Runnable action) {
12136        final AttachInfo attachInfo = mAttachInfo;
12137        if (attachInfo != null) {
12138            return attachInfo.mHandler.post(action);
12139        }
12140        // Assume that post will succeed later
12141        ViewRootImpl.getRunQueue().post(action);
12142        return true;
12143    }
12144
12145    /**
12146     * <p>Causes the Runnable to be added to the message queue, to be run
12147     * after the specified amount of time elapses.
12148     * The runnable will be run on the user interface thread.</p>
12149     *
12150     * @param action The Runnable that will be executed.
12151     * @param delayMillis The delay (in milliseconds) until the Runnable
12152     *        will be executed.
12153     *
12154     * @return true if the Runnable was successfully placed in to the
12155     *         message queue.  Returns false on failure, usually because the
12156     *         looper processing the message queue is exiting.  Note that a
12157     *         result of true does not mean the Runnable will be processed --
12158     *         if the looper is quit before the delivery time of the message
12159     *         occurs then the message will be dropped.
12160     *
12161     * @see #post
12162     * @see #removeCallbacks
12163     */
12164    public boolean postDelayed(Runnable action, long delayMillis) {
12165        final AttachInfo attachInfo = mAttachInfo;
12166        if (attachInfo != null) {
12167            return attachInfo.mHandler.postDelayed(action, delayMillis);
12168        }
12169        // Assume that post will succeed later
12170        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12171        return true;
12172    }
12173
12174    /**
12175     * <p>Causes the Runnable to execute on the next animation time step.
12176     * The runnable will be run on the user interface thread.</p>
12177     *
12178     * @param action The Runnable that will be executed.
12179     *
12180     * @see #postOnAnimationDelayed
12181     * @see #removeCallbacks
12182     */
12183    public void postOnAnimation(Runnable action) {
12184        final AttachInfo attachInfo = mAttachInfo;
12185        if (attachInfo != null) {
12186            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12187                    Choreographer.CALLBACK_ANIMATION, action, null);
12188        } else {
12189            // Assume that post will succeed later
12190            ViewRootImpl.getRunQueue().post(action);
12191        }
12192    }
12193
12194    /**
12195     * <p>Causes the Runnable to execute on the next animation time step,
12196     * after the specified amount of time elapses.
12197     * The runnable will be run on the user interface thread.</p>
12198     *
12199     * @param action The Runnable that will be executed.
12200     * @param delayMillis The delay (in milliseconds) until the Runnable
12201     *        will be executed.
12202     *
12203     * @see #postOnAnimation
12204     * @see #removeCallbacks
12205     */
12206    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12207        final AttachInfo attachInfo = mAttachInfo;
12208        if (attachInfo != null) {
12209            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12210                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12211        } else {
12212            // Assume that post will succeed later
12213            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12214        }
12215    }
12216
12217    /**
12218     * <p>Removes the specified Runnable from the message queue.</p>
12219     *
12220     * @param action The Runnable to remove from the message handling queue
12221     *
12222     * @return true if this view could ask the Handler to remove the Runnable,
12223     *         false otherwise. When the returned value is true, the Runnable
12224     *         may or may not have been actually removed from the message queue
12225     *         (for instance, if the Runnable was not in the queue already.)
12226     *
12227     * @see #post
12228     * @see #postDelayed
12229     * @see #postOnAnimation
12230     * @see #postOnAnimationDelayed
12231     */
12232    public boolean removeCallbacks(Runnable action) {
12233        if (action != null) {
12234            final AttachInfo attachInfo = mAttachInfo;
12235            if (attachInfo != null) {
12236                attachInfo.mHandler.removeCallbacks(action);
12237                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12238                        Choreographer.CALLBACK_ANIMATION, action, null);
12239            }
12240            // Assume that post will succeed later
12241            ViewRootImpl.getRunQueue().removeCallbacks(action);
12242        }
12243        return true;
12244    }
12245
12246    /**
12247     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12248     * Use this to invalidate the View from a non-UI thread.</p>
12249     *
12250     * <p>This method can be invoked from outside of the UI thread
12251     * only when this View is attached to a window.</p>
12252     *
12253     * @see #invalidate()
12254     * @see #postInvalidateDelayed(long)
12255     */
12256    public void postInvalidate() {
12257        postInvalidateDelayed(0);
12258    }
12259
12260    /**
12261     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12262     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12263     *
12264     * <p>This method can be invoked from outside of the UI thread
12265     * only when this View is attached to a window.</p>
12266     *
12267     * @param left The left coordinate of the rectangle to invalidate.
12268     * @param top The top coordinate of the rectangle to invalidate.
12269     * @param right The right coordinate of the rectangle to invalidate.
12270     * @param bottom The bottom coordinate of the rectangle to invalidate.
12271     *
12272     * @see #invalidate(int, int, int, int)
12273     * @see #invalidate(Rect)
12274     * @see #postInvalidateDelayed(long, int, int, int, int)
12275     */
12276    public void postInvalidate(int left, int top, int right, int bottom) {
12277        postInvalidateDelayed(0, left, top, right, bottom);
12278    }
12279
12280    /**
12281     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12282     * loop. Waits for the specified amount of time.</p>
12283     *
12284     * <p>This method can be invoked from outside of the UI thread
12285     * only when this View is attached to a window.</p>
12286     *
12287     * @param delayMilliseconds the duration in milliseconds to delay the
12288     *         invalidation by
12289     *
12290     * @see #invalidate()
12291     * @see #postInvalidate()
12292     */
12293    public void postInvalidateDelayed(long delayMilliseconds) {
12294        // We try only with the AttachInfo because there's no point in invalidating
12295        // if we are not attached to our window
12296        final AttachInfo attachInfo = mAttachInfo;
12297        if (attachInfo != null) {
12298            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12299        }
12300    }
12301
12302    /**
12303     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12304     * through the event loop. Waits for the specified amount of time.</p>
12305     *
12306     * <p>This method can be invoked from outside of the UI thread
12307     * only when this View is attached to a window.</p>
12308     *
12309     * @param delayMilliseconds the duration in milliseconds to delay the
12310     *         invalidation by
12311     * @param left The left coordinate of the rectangle to invalidate.
12312     * @param top The top coordinate of the rectangle to invalidate.
12313     * @param right The right coordinate of the rectangle to invalidate.
12314     * @param bottom The bottom coordinate of the rectangle to invalidate.
12315     *
12316     * @see #invalidate(int, int, int, int)
12317     * @see #invalidate(Rect)
12318     * @see #postInvalidate(int, int, int, int)
12319     */
12320    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12321            int right, int bottom) {
12322
12323        // We try only with the AttachInfo because there's no point in invalidating
12324        // if we are not attached to our window
12325        final AttachInfo attachInfo = mAttachInfo;
12326        if (attachInfo != null) {
12327            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12328            info.target = this;
12329            info.left = left;
12330            info.top = top;
12331            info.right = right;
12332            info.bottom = bottom;
12333
12334            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12335        }
12336    }
12337
12338    /**
12339     * <p>Cause an invalidate to happen on the next animation time step, typically the
12340     * next display frame.</p>
12341     *
12342     * <p>This method can be invoked from outside of the UI thread
12343     * only when this View is attached to a window.</p>
12344     *
12345     * @see #invalidate()
12346     */
12347    public void postInvalidateOnAnimation() {
12348        // We try only with the AttachInfo because there's no point in invalidating
12349        // if we are not attached to our window
12350        final AttachInfo attachInfo = mAttachInfo;
12351        if (attachInfo != null) {
12352            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12353        }
12354    }
12355
12356    /**
12357     * <p>Cause an invalidate of the specified area to happen on the next animation
12358     * time step, typically the next display frame.</p>
12359     *
12360     * <p>This method can be invoked from outside of the UI thread
12361     * only when this View is attached to a window.</p>
12362     *
12363     * @param left The left coordinate of the rectangle to invalidate.
12364     * @param top The top coordinate of the rectangle to invalidate.
12365     * @param right The right coordinate of the rectangle to invalidate.
12366     * @param bottom The bottom coordinate of the rectangle to invalidate.
12367     *
12368     * @see #invalidate(int, int, int, int)
12369     * @see #invalidate(Rect)
12370     */
12371    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12372        // We try only with the AttachInfo because there's no point in invalidating
12373        // if we are not attached to our window
12374        final AttachInfo attachInfo = mAttachInfo;
12375        if (attachInfo != null) {
12376            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12377            info.target = this;
12378            info.left = left;
12379            info.top = top;
12380            info.right = right;
12381            info.bottom = bottom;
12382
12383            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12384        }
12385    }
12386
12387    /**
12388     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12389     * This event is sent at most once every
12390     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12391     */
12392    private void postSendViewScrolledAccessibilityEventCallback() {
12393        if (mSendViewScrolledAccessibilityEvent == null) {
12394            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12395        }
12396        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12397            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12398            postDelayed(mSendViewScrolledAccessibilityEvent,
12399                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12400        }
12401    }
12402
12403    /**
12404     * Called by a parent to request that a child update its values for mScrollX
12405     * and mScrollY if necessary. This will typically be done if the child is
12406     * animating a scroll using a {@link android.widget.Scroller Scroller}
12407     * object.
12408     */
12409    public void computeScroll() {
12410    }
12411
12412    /**
12413     * <p>Indicate whether the horizontal edges are faded when the view is
12414     * scrolled horizontally.</p>
12415     *
12416     * @return true if the horizontal edges should are faded on scroll, false
12417     *         otherwise
12418     *
12419     * @see #setHorizontalFadingEdgeEnabled(boolean)
12420     *
12421     * @attr ref android.R.styleable#View_requiresFadingEdge
12422     */
12423    public boolean isHorizontalFadingEdgeEnabled() {
12424        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12425    }
12426
12427    /**
12428     * <p>Define whether the horizontal edges should be faded when this view
12429     * is scrolled horizontally.</p>
12430     *
12431     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12432     *                                    be faded when the view is scrolled
12433     *                                    horizontally
12434     *
12435     * @see #isHorizontalFadingEdgeEnabled()
12436     *
12437     * @attr ref android.R.styleable#View_requiresFadingEdge
12438     */
12439    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12440        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12441            if (horizontalFadingEdgeEnabled) {
12442                initScrollCache();
12443            }
12444
12445            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12446        }
12447    }
12448
12449    /**
12450     * <p>Indicate whether the vertical edges are faded when the view is
12451     * scrolled horizontally.</p>
12452     *
12453     * @return true if the vertical edges should are faded on scroll, false
12454     *         otherwise
12455     *
12456     * @see #setVerticalFadingEdgeEnabled(boolean)
12457     *
12458     * @attr ref android.R.styleable#View_requiresFadingEdge
12459     */
12460    public boolean isVerticalFadingEdgeEnabled() {
12461        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12462    }
12463
12464    /**
12465     * <p>Define whether the vertical edges should be faded when this view
12466     * is scrolled vertically.</p>
12467     *
12468     * @param verticalFadingEdgeEnabled true if the vertical edges should
12469     *                                  be faded when the view is scrolled
12470     *                                  vertically
12471     *
12472     * @see #isVerticalFadingEdgeEnabled()
12473     *
12474     * @attr ref android.R.styleable#View_requiresFadingEdge
12475     */
12476    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12477        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12478            if (verticalFadingEdgeEnabled) {
12479                initScrollCache();
12480            }
12481
12482            mViewFlags ^= FADING_EDGE_VERTICAL;
12483        }
12484    }
12485
12486    /**
12487     * Returns the strength, or intensity, of the top faded edge. The strength is
12488     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12489     * returns 0.0 or 1.0 but no value in between.
12490     *
12491     * Subclasses should override this method to provide a smoother fade transition
12492     * when scrolling occurs.
12493     *
12494     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12495     */
12496    protected float getTopFadingEdgeStrength() {
12497        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12498    }
12499
12500    /**
12501     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12502     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12503     * returns 0.0 or 1.0 but no value in between.
12504     *
12505     * Subclasses should override this method to provide a smoother fade transition
12506     * when scrolling occurs.
12507     *
12508     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12509     */
12510    protected float getBottomFadingEdgeStrength() {
12511        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12512                computeVerticalScrollRange() ? 1.0f : 0.0f;
12513    }
12514
12515    /**
12516     * Returns the strength, or intensity, of the left faded edge. The strength is
12517     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12518     * returns 0.0 or 1.0 but no value in between.
12519     *
12520     * Subclasses should override this method to provide a smoother fade transition
12521     * when scrolling occurs.
12522     *
12523     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12524     */
12525    protected float getLeftFadingEdgeStrength() {
12526        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12527    }
12528
12529    /**
12530     * Returns the strength, or intensity, of the right faded edge. The strength is
12531     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12532     * returns 0.0 or 1.0 but no value in between.
12533     *
12534     * Subclasses should override this method to provide a smoother fade transition
12535     * when scrolling occurs.
12536     *
12537     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12538     */
12539    protected float getRightFadingEdgeStrength() {
12540        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12541                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12542    }
12543
12544    /**
12545     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12546     * scrollbar is not drawn by default.</p>
12547     *
12548     * @return true if the horizontal scrollbar should be painted, false
12549     *         otherwise
12550     *
12551     * @see #setHorizontalScrollBarEnabled(boolean)
12552     */
12553    public boolean isHorizontalScrollBarEnabled() {
12554        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12555    }
12556
12557    /**
12558     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12559     * scrollbar is not drawn by default.</p>
12560     *
12561     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12562     *                                   be painted
12563     *
12564     * @see #isHorizontalScrollBarEnabled()
12565     */
12566    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12567        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12568            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12569            computeOpaqueFlags();
12570            resolvePadding();
12571        }
12572    }
12573
12574    /**
12575     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12576     * scrollbar is not drawn by default.</p>
12577     *
12578     * @return true if the vertical scrollbar should be painted, false
12579     *         otherwise
12580     *
12581     * @see #setVerticalScrollBarEnabled(boolean)
12582     */
12583    public boolean isVerticalScrollBarEnabled() {
12584        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12585    }
12586
12587    /**
12588     * <p>Define whether the vertical scrollbar should be drawn or not. The
12589     * scrollbar is not drawn by default.</p>
12590     *
12591     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12592     *                                 be painted
12593     *
12594     * @see #isVerticalScrollBarEnabled()
12595     */
12596    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12597        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12598            mViewFlags ^= SCROLLBARS_VERTICAL;
12599            computeOpaqueFlags();
12600            resolvePadding();
12601        }
12602    }
12603
12604    /**
12605     * @hide
12606     */
12607    protected void recomputePadding() {
12608        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12609    }
12610
12611    /**
12612     * Define whether scrollbars will fade when the view is not scrolling.
12613     *
12614     * @param fadeScrollbars wheter to enable fading
12615     *
12616     * @attr ref android.R.styleable#View_fadeScrollbars
12617     */
12618    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12619        initScrollCache();
12620        final ScrollabilityCache scrollabilityCache = mScrollCache;
12621        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12622        if (fadeScrollbars) {
12623            scrollabilityCache.state = ScrollabilityCache.OFF;
12624        } else {
12625            scrollabilityCache.state = ScrollabilityCache.ON;
12626        }
12627    }
12628
12629    /**
12630     *
12631     * Returns true if scrollbars will fade when this view is not scrolling
12632     *
12633     * @return true if scrollbar fading is enabled
12634     *
12635     * @attr ref android.R.styleable#View_fadeScrollbars
12636     */
12637    public boolean isScrollbarFadingEnabled() {
12638        return mScrollCache != null && mScrollCache.fadeScrollBars;
12639    }
12640
12641    /**
12642     *
12643     * Returns the delay before scrollbars fade.
12644     *
12645     * @return the delay before scrollbars fade
12646     *
12647     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12648     */
12649    public int getScrollBarDefaultDelayBeforeFade() {
12650        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12651                mScrollCache.scrollBarDefaultDelayBeforeFade;
12652    }
12653
12654    /**
12655     * Define the delay before scrollbars fade.
12656     *
12657     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12658     *
12659     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12660     */
12661    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12662        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12663    }
12664
12665    /**
12666     *
12667     * Returns the scrollbar fade duration.
12668     *
12669     * @return the scrollbar fade duration
12670     *
12671     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12672     */
12673    public int getScrollBarFadeDuration() {
12674        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12675                mScrollCache.scrollBarFadeDuration;
12676    }
12677
12678    /**
12679     * Define the scrollbar fade duration.
12680     *
12681     * @param scrollBarFadeDuration - the scrollbar fade duration
12682     *
12683     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12684     */
12685    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12686        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12687    }
12688
12689    /**
12690     *
12691     * Returns the scrollbar size.
12692     *
12693     * @return the scrollbar size
12694     *
12695     * @attr ref android.R.styleable#View_scrollbarSize
12696     */
12697    public int getScrollBarSize() {
12698        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12699                mScrollCache.scrollBarSize;
12700    }
12701
12702    /**
12703     * Define the scrollbar size.
12704     *
12705     * @param scrollBarSize - the scrollbar size
12706     *
12707     * @attr ref android.R.styleable#View_scrollbarSize
12708     */
12709    public void setScrollBarSize(int scrollBarSize) {
12710        getScrollCache().scrollBarSize = scrollBarSize;
12711    }
12712
12713    /**
12714     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12715     * inset. When inset, they add to the padding of the view. And the scrollbars
12716     * can be drawn inside the padding area or on the edge of the view. For example,
12717     * if a view has a background drawable and you want to draw the scrollbars
12718     * inside the padding specified by the drawable, you can use
12719     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12720     * appear at the edge of the view, ignoring the padding, then you can use
12721     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12722     * @param style the style of the scrollbars. Should be one of
12723     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12724     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12725     * @see #SCROLLBARS_INSIDE_OVERLAY
12726     * @see #SCROLLBARS_INSIDE_INSET
12727     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12728     * @see #SCROLLBARS_OUTSIDE_INSET
12729     *
12730     * @attr ref android.R.styleable#View_scrollbarStyle
12731     */
12732    public void setScrollBarStyle(@ScrollBarStyle int style) {
12733        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12734            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12735            computeOpaqueFlags();
12736            resolvePadding();
12737        }
12738    }
12739
12740    /**
12741     * <p>Returns the current scrollbar style.</p>
12742     * @return the current scrollbar style
12743     * @see #SCROLLBARS_INSIDE_OVERLAY
12744     * @see #SCROLLBARS_INSIDE_INSET
12745     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12746     * @see #SCROLLBARS_OUTSIDE_INSET
12747     *
12748     * @attr ref android.R.styleable#View_scrollbarStyle
12749     */
12750    @ViewDebug.ExportedProperty(mapping = {
12751            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12752            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12753            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12754            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12755    })
12756    @ScrollBarStyle
12757    public int getScrollBarStyle() {
12758        return mViewFlags & SCROLLBARS_STYLE_MASK;
12759    }
12760
12761    /**
12762     * <p>Compute the horizontal range that the horizontal scrollbar
12763     * represents.</p>
12764     *
12765     * <p>The range is expressed in arbitrary units that must be the same as the
12766     * units used by {@link #computeHorizontalScrollExtent()} and
12767     * {@link #computeHorizontalScrollOffset()}.</p>
12768     *
12769     * <p>The default range is the drawing width of this view.</p>
12770     *
12771     * @return the total horizontal range represented by the horizontal
12772     *         scrollbar
12773     *
12774     * @see #computeHorizontalScrollExtent()
12775     * @see #computeHorizontalScrollOffset()
12776     * @see android.widget.ScrollBarDrawable
12777     */
12778    protected int computeHorizontalScrollRange() {
12779        return getWidth();
12780    }
12781
12782    /**
12783     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12784     * within the horizontal range. This value is used to compute the position
12785     * of the thumb within the scrollbar's track.</p>
12786     *
12787     * <p>The range is expressed in arbitrary units that must be the same as the
12788     * units used by {@link #computeHorizontalScrollRange()} and
12789     * {@link #computeHorizontalScrollExtent()}.</p>
12790     *
12791     * <p>The default offset is the scroll offset of this view.</p>
12792     *
12793     * @return the horizontal offset of the scrollbar's thumb
12794     *
12795     * @see #computeHorizontalScrollRange()
12796     * @see #computeHorizontalScrollExtent()
12797     * @see android.widget.ScrollBarDrawable
12798     */
12799    protected int computeHorizontalScrollOffset() {
12800        return mScrollX;
12801    }
12802
12803    /**
12804     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12805     * within the horizontal range. This value is used to compute the length
12806     * of the thumb within the scrollbar's track.</p>
12807     *
12808     * <p>The range is expressed in arbitrary units that must be the same as the
12809     * units used by {@link #computeHorizontalScrollRange()} and
12810     * {@link #computeHorizontalScrollOffset()}.</p>
12811     *
12812     * <p>The default extent is the drawing width of this view.</p>
12813     *
12814     * @return the horizontal extent of the scrollbar's thumb
12815     *
12816     * @see #computeHorizontalScrollRange()
12817     * @see #computeHorizontalScrollOffset()
12818     * @see android.widget.ScrollBarDrawable
12819     */
12820    protected int computeHorizontalScrollExtent() {
12821        return getWidth();
12822    }
12823
12824    /**
12825     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12826     *
12827     * <p>The range is expressed in arbitrary units that must be the same as the
12828     * units used by {@link #computeVerticalScrollExtent()} and
12829     * {@link #computeVerticalScrollOffset()}.</p>
12830     *
12831     * @return the total vertical range represented by the vertical scrollbar
12832     *
12833     * <p>The default range is the drawing height of this view.</p>
12834     *
12835     * @see #computeVerticalScrollExtent()
12836     * @see #computeVerticalScrollOffset()
12837     * @see android.widget.ScrollBarDrawable
12838     */
12839    protected int computeVerticalScrollRange() {
12840        return getHeight();
12841    }
12842
12843    /**
12844     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12845     * within the horizontal range. This value is used to compute the position
12846     * of the thumb within the scrollbar's track.</p>
12847     *
12848     * <p>The range is expressed in arbitrary units that must be the same as the
12849     * units used by {@link #computeVerticalScrollRange()} and
12850     * {@link #computeVerticalScrollExtent()}.</p>
12851     *
12852     * <p>The default offset is the scroll offset of this view.</p>
12853     *
12854     * @return the vertical offset of the scrollbar's thumb
12855     *
12856     * @see #computeVerticalScrollRange()
12857     * @see #computeVerticalScrollExtent()
12858     * @see android.widget.ScrollBarDrawable
12859     */
12860    protected int computeVerticalScrollOffset() {
12861        return mScrollY;
12862    }
12863
12864    /**
12865     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12866     * within the vertical range. This value is used to compute the length
12867     * of the thumb within the scrollbar's track.</p>
12868     *
12869     * <p>The range is expressed in arbitrary units that must be the same as the
12870     * units used by {@link #computeVerticalScrollRange()} and
12871     * {@link #computeVerticalScrollOffset()}.</p>
12872     *
12873     * <p>The default extent is the drawing height of this view.</p>
12874     *
12875     * @return the vertical extent of the scrollbar's thumb
12876     *
12877     * @see #computeVerticalScrollRange()
12878     * @see #computeVerticalScrollOffset()
12879     * @see android.widget.ScrollBarDrawable
12880     */
12881    protected int computeVerticalScrollExtent() {
12882        return getHeight();
12883    }
12884
12885    /**
12886     * Check if this view can be scrolled horizontally in a certain direction.
12887     *
12888     * @param direction Negative to check scrolling left, positive to check scrolling right.
12889     * @return true if this view can be scrolled in the specified direction, false otherwise.
12890     */
12891    public boolean canScrollHorizontally(int direction) {
12892        final int offset = computeHorizontalScrollOffset();
12893        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12894        if (range == 0) return false;
12895        if (direction < 0) {
12896            return offset > 0;
12897        } else {
12898            return offset < range - 1;
12899        }
12900    }
12901
12902    /**
12903     * Check if this view can be scrolled vertically in a certain direction.
12904     *
12905     * @param direction Negative to check scrolling up, positive to check scrolling down.
12906     * @return true if this view can be scrolled in the specified direction, false otherwise.
12907     */
12908    public boolean canScrollVertically(int direction) {
12909        final int offset = computeVerticalScrollOffset();
12910        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12911        if (range == 0) return false;
12912        if (direction < 0) {
12913            return offset > 0;
12914        } else {
12915            return offset < range - 1;
12916        }
12917    }
12918
12919    /**
12920     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12921     * scrollbars are painted only if they have been awakened first.</p>
12922     *
12923     * @param canvas the canvas on which to draw the scrollbars
12924     *
12925     * @see #awakenScrollBars(int)
12926     */
12927    protected final void onDrawScrollBars(Canvas canvas) {
12928        // scrollbars are drawn only when the animation is running
12929        final ScrollabilityCache cache = mScrollCache;
12930        if (cache != null) {
12931
12932            int state = cache.state;
12933
12934            if (state == ScrollabilityCache.OFF) {
12935                return;
12936            }
12937
12938            boolean invalidate = false;
12939
12940            if (state == ScrollabilityCache.FADING) {
12941                // We're fading -- get our fade interpolation
12942                if (cache.interpolatorValues == null) {
12943                    cache.interpolatorValues = new float[1];
12944                }
12945
12946                float[] values = cache.interpolatorValues;
12947
12948                // Stops the animation if we're done
12949                if (cache.scrollBarInterpolator.timeToValues(values) ==
12950                        Interpolator.Result.FREEZE_END) {
12951                    cache.state = ScrollabilityCache.OFF;
12952                } else {
12953                    cache.scrollBar.setAlpha(Math.round(values[0]));
12954                }
12955
12956                // This will make the scroll bars inval themselves after
12957                // drawing. We only want this when we're fading so that
12958                // we prevent excessive redraws
12959                invalidate = true;
12960            } else {
12961                // We're just on -- but we may have been fading before so
12962                // reset alpha
12963                cache.scrollBar.setAlpha(255);
12964            }
12965
12966
12967            final int viewFlags = mViewFlags;
12968
12969            final boolean drawHorizontalScrollBar =
12970                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12971            final boolean drawVerticalScrollBar =
12972                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12973                && !isVerticalScrollBarHidden();
12974
12975            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12976                final int width = mRight - mLeft;
12977                final int height = mBottom - mTop;
12978
12979                final ScrollBarDrawable scrollBar = cache.scrollBar;
12980
12981                final int scrollX = mScrollX;
12982                final int scrollY = mScrollY;
12983                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12984
12985                int left;
12986                int top;
12987                int right;
12988                int bottom;
12989
12990                if (drawHorizontalScrollBar) {
12991                    int size = scrollBar.getSize(false);
12992                    if (size <= 0) {
12993                        size = cache.scrollBarSize;
12994                    }
12995
12996                    scrollBar.setParameters(computeHorizontalScrollRange(),
12997                                            computeHorizontalScrollOffset(),
12998                                            computeHorizontalScrollExtent(), false);
12999                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13000                            getVerticalScrollbarWidth() : 0;
13001                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13002                    left = scrollX + (mPaddingLeft & inside);
13003                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13004                    bottom = top + size;
13005                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13006                    if (invalidate) {
13007                        invalidate(left, top, right, bottom);
13008                    }
13009                }
13010
13011                if (drawVerticalScrollBar) {
13012                    int size = scrollBar.getSize(true);
13013                    if (size <= 0) {
13014                        size = cache.scrollBarSize;
13015                    }
13016
13017                    scrollBar.setParameters(computeVerticalScrollRange(),
13018                                            computeVerticalScrollOffset(),
13019                                            computeVerticalScrollExtent(), true);
13020                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13021                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13022                        verticalScrollbarPosition = isLayoutRtl() ?
13023                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13024                    }
13025                    switch (verticalScrollbarPosition) {
13026                        default:
13027                        case SCROLLBAR_POSITION_RIGHT:
13028                            left = scrollX + width - size - (mUserPaddingRight & inside);
13029                            break;
13030                        case SCROLLBAR_POSITION_LEFT:
13031                            left = scrollX + (mUserPaddingLeft & inside);
13032                            break;
13033                    }
13034                    top = scrollY + (mPaddingTop & inside);
13035                    right = left + size;
13036                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13037                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13038                    if (invalidate) {
13039                        invalidate(left, top, right, bottom);
13040                    }
13041                }
13042            }
13043        }
13044    }
13045
13046    /**
13047     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13048     * FastScroller is visible.
13049     * @return whether to temporarily hide the vertical scrollbar
13050     * @hide
13051     */
13052    protected boolean isVerticalScrollBarHidden() {
13053        return false;
13054    }
13055
13056    /**
13057     * <p>Draw the horizontal scrollbar if
13058     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13059     *
13060     * @param canvas the canvas on which to draw the scrollbar
13061     * @param scrollBar the scrollbar's drawable
13062     *
13063     * @see #isHorizontalScrollBarEnabled()
13064     * @see #computeHorizontalScrollRange()
13065     * @see #computeHorizontalScrollExtent()
13066     * @see #computeHorizontalScrollOffset()
13067     * @see android.widget.ScrollBarDrawable
13068     * @hide
13069     */
13070    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13071            int l, int t, int r, int b) {
13072        scrollBar.setBounds(l, t, r, b);
13073        scrollBar.draw(canvas);
13074    }
13075
13076    /**
13077     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13078     * returns true.</p>
13079     *
13080     * @param canvas the canvas on which to draw the scrollbar
13081     * @param scrollBar the scrollbar's drawable
13082     *
13083     * @see #isVerticalScrollBarEnabled()
13084     * @see #computeVerticalScrollRange()
13085     * @see #computeVerticalScrollExtent()
13086     * @see #computeVerticalScrollOffset()
13087     * @see android.widget.ScrollBarDrawable
13088     * @hide
13089     */
13090    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13091            int l, int t, int r, int b) {
13092        scrollBar.setBounds(l, t, r, b);
13093        scrollBar.draw(canvas);
13094    }
13095
13096    /**
13097     * Implement this to do your drawing.
13098     *
13099     * @param canvas the canvas on which the background will be drawn
13100     */
13101    protected void onDraw(Canvas canvas) {
13102    }
13103
13104    /*
13105     * Caller is responsible for calling requestLayout if necessary.
13106     * (This allows addViewInLayout to not request a new layout.)
13107     */
13108    void assignParent(ViewParent parent) {
13109        if (mParent == null) {
13110            mParent = parent;
13111        } else if (parent == null) {
13112            mParent = null;
13113        } else {
13114            throw new RuntimeException("view " + this + " being added, but"
13115                    + " it already has a parent");
13116        }
13117    }
13118
13119    /**
13120     * This is called when the view is attached to a window.  At this point it
13121     * has a Surface and will start drawing.  Note that this function is
13122     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13123     * however it may be called any time before the first onDraw -- including
13124     * before or after {@link #onMeasure(int, int)}.
13125     *
13126     * @see #onDetachedFromWindow()
13127     */
13128    protected void onAttachedToWindow() {
13129        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13130            mParent.requestTransparentRegion(this);
13131        }
13132
13133        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13134            initialAwakenScrollBars();
13135            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13136        }
13137
13138        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13139
13140        jumpDrawablesToCurrentState();
13141
13142        resetSubtreeAccessibilityStateChanged();
13143
13144        // rebuild, since Outline not maintained while View is detached
13145        rebuildOutline();
13146
13147        if (isFocused()) {
13148            InputMethodManager imm = InputMethodManager.peekInstance();
13149            imm.focusIn(this);
13150        }
13151    }
13152
13153    /**
13154     * Resolve all RTL related properties.
13155     *
13156     * @return true if resolution of RTL properties has been done
13157     *
13158     * @hide
13159     */
13160    public boolean resolveRtlPropertiesIfNeeded() {
13161        if (!needRtlPropertiesResolution()) return false;
13162
13163        // Order is important here: LayoutDirection MUST be resolved first
13164        if (!isLayoutDirectionResolved()) {
13165            resolveLayoutDirection();
13166            resolveLayoutParams();
13167        }
13168        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13169        if (!isTextDirectionResolved()) {
13170            resolveTextDirection();
13171        }
13172        if (!isTextAlignmentResolved()) {
13173            resolveTextAlignment();
13174        }
13175        // Should resolve Drawables before Padding because we need the layout direction of the
13176        // Drawable to correctly resolve Padding.
13177        if (!areDrawablesResolved()) {
13178            resolveDrawables();
13179        }
13180        if (!isPaddingResolved()) {
13181            resolvePadding();
13182        }
13183        onRtlPropertiesChanged(getLayoutDirection());
13184        return true;
13185    }
13186
13187    /**
13188     * Reset resolution of all RTL related properties.
13189     *
13190     * @hide
13191     */
13192    public void resetRtlProperties() {
13193        resetResolvedLayoutDirection();
13194        resetResolvedTextDirection();
13195        resetResolvedTextAlignment();
13196        resetResolvedPadding();
13197        resetResolvedDrawables();
13198    }
13199
13200    /**
13201     * @see #onScreenStateChanged(int)
13202     */
13203    void dispatchScreenStateChanged(int screenState) {
13204        onScreenStateChanged(screenState);
13205    }
13206
13207    /**
13208     * This method is called whenever the state of the screen this view is
13209     * attached to changes. A state change will usually occurs when the screen
13210     * turns on or off (whether it happens automatically or the user does it
13211     * manually.)
13212     *
13213     * @param screenState The new state of the screen. Can be either
13214     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13215     */
13216    public void onScreenStateChanged(int screenState) {
13217    }
13218
13219    /**
13220     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13221     */
13222    private boolean hasRtlSupport() {
13223        return mContext.getApplicationInfo().hasRtlSupport();
13224    }
13225
13226    /**
13227     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13228     * RTL not supported)
13229     */
13230    private boolean isRtlCompatibilityMode() {
13231        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13232        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13233    }
13234
13235    /**
13236     * @return true if RTL properties need resolution.
13237     *
13238     */
13239    private boolean needRtlPropertiesResolution() {
13240        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13241    }
13242
13243    /**
13244     * Called when any RTL property (layout direction or text direction or text alignment) has
13245     * been changed.
13246     *
13247     * Subclasses need to override this method to take care of cached information that depends on the
13248     * resolved layout direction, or to inform child views that inherit their layout direction.
13249     *
13250     * The default implementation does nothing.
13251     *
13252     * @param layoutDirection the direction of the layout
13253     *
13254     * @see #LAYOUT_DIRECTION_LTR
13255     * @see #LAYOUT_DIRECTION_RTL
13256     */
13257    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13258    }
13259
13260    /**
13261     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13262     * that the parent directionality can and will be resolved before its children.
13263     *
13264     * @return true if resolution has been done, false otherwise.
13265     *
13266     * @hide
13267     */
13268    public boolean resolveLayoutDirection() {
13269        // Clear any previous layout direction resolution
13270        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13271
13272        if (hasRtlSupport()) {
13273            // Set resolved depending on layout direction
13274            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13275                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13276                case LAYOUT_DIRECTION_INHERIT:
13277                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13278                    // later to get the correct resolved value
13279                    if (!canResolveLayoutDirection()) return false;
13280
13281                    // Parent has not yet resolved, LTR is still the default
13282                    try {
13283                        if (!mParent.isLayoutDirectionResolved()) return false;
13284
13285                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13286                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13287                        }
13288                    } catch (AbstractMethodError e) {
13289                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13290                                " does not fully implement ViewParent", e);
13291                    }
13292                    break;
13293                case LAYOUT_DIRECTION_RTL:
13294                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13295                    break;
13296                case LAYOUT_DIRECTION_LOCALE:
13297                    if((LAYOUT_DIRECTION_RTL ==
13298                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13299                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13300                    }
13301                    break;
13302                default:
13303                    // Nothing to do, LTR by default
13304            }
13305        }
13306
13307        // Set to resolved
13308        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13309        return true;
13310    }
13311
13312    /**
13313     * Check if layout direction resolution can be done.
13314     *
13315     * @return true if layout direction resolution can be done otherwise return false.
13316     */
13317    public boolean canResolveLayoutDirection() {
13318        switch (getRawLayoutDirection()) {
13319            case LAYOUT_DIRECTION_INHERIT:
13320                if (mParent != null) {
13321                    try {
13322                        return mParent.canResolveLayoutDirection();
13323                    } catch (AbstractMethodError e) {
13324                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13325                                " does not fully implement ViewParent", e);
13326                    }
13327                }
13328                return false;
13329
13330            default:
13331                return true;
13332        }
13333    }
13334
13335    /**
13336     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13337     * {@link #onMeasure(int, int)}.
13338     *
13339     * @hide
13340     */
13341    public void resetResolvedLayoutDirection() {
13342        // Reset the current resolved bits
13343        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13344    }
13345
13346    /**
13347     * @return true if the layout direction is inherited.
13348     *
13349     * @hide
13350     */
13351    public boolean isLayoutDirectionInherited() {
13352        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13353    }
13354
13355    /**
13356     * @return true if layout direction has been resolved.
13357     */
13358    public boolean isLayoutDirectionResolved() {
13359        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13360    }
13361
13362    /**
13363     * Return if padding has been resolved
13364     *
13365     * @hide
13366     */
13367    boolean isPaddingResolved() {
13368        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13369    }
13370
13371    /**
13372     * Resolves padding depending on layout direction, if applicable, and
13373     * recomputes internal padding values to adjust for scroll bars.
13374     *
13375     * @hide
13376     */
13377    public void resolvePadding() {
13378        final int resolvedLayoutDirection = getLayoutDirection();
13379
13380        if (!isRtlCompatibilityMode()) {
13381            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13382            // If start / end padding are defined, they will be resolved (hence overriding) to
13383            // left / right or right / left depending on the resolved layout direction.
13384            // If start / end padding are not defined, use the left / right ones.
13385            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13386                Rect padding = sThreadLocal.get();
13387                if (padding == null) {
13388                    padding = new Rect();
13389                    sThreadLocal.set(padding);
13390                }
13391                mBackground.getPadding(padding);
13392                if (!mLeftPaddingDefined) {
13393                    mUserPaddingLeftInitial = padding.left;
13394                }
13395                if (!mRightPaddingDefined) {
13396                    mUserPaddingRightInitial = padding.right;
13397                }
13398            }
13399            switch (resolvedLayoutDirection) {
13400                case LAYOUT_DIRECTION_RTL:
13401                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13402                        mUserPaddingRight = mUserPaddingStart;
13403                    } else {
13404                        mUserPaddingRight = mUserPaddingRightInitial;
13405                    }
13406                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13407                        mUserPaddingLeft = mUserPaddingEnd;
13408                    } else {
13409                        mUserPaddingLeft = mUserPaddingLeftInitial;
13410                    }
13411                    break;
13412                case LAYOUT_DIRECTION_LTR:
13413                default:
13414                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13415                        mUserPaddingLeft = mUserPaddingStart;
13416                    } else {
13417                        mUserPaddingLeft = mUserPaddingLeftInitial;
13418                    }
13419                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13420                        mUserPaddingRight = mUserPaddingEnd;
13421                    } else {
13422                        mUserPaddingRight = mUserPaddingRightInitial;
13423                    }
13424            }
13425
13426            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13427        }
13428
13429        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13430        onRtlPropertiesChanged(resolvedLayoutDirection);
13431
13432        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13433    }
13434
13435    /**
13436     * Reset the resolved layout direction.
13437     *
13438     * @hide
13439     */
13440    public void resetResolvedPadding() {
13441        resetResolvedPaddingInternal();
13442    }
13443
13444    /**
13445     * Used when we only want to reset *this* view's padding and not trigger overrides
13446     * in ViewGroup that reset children too.
13447     */
13448    void resetResolvedPaddingInternal() {
13449        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13450    }
13451
13452    /**
13453     * This is called when the view is detached from a window.  At this point it
13454     * no longer has a surface for drawing.
13455     *
13456     * @see #onAttachedToWindow()
13457     */
13458    protected void onDetachedFromWindow() {
13459    }
13460
13461    /**
13462     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13463     * after onDetachedFromWindow().
13464     *
13465     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13466     * The super method should be called at the end of the overriden method to ensure
13467     * subclasses are destroyed first
13468     *
13469     * @hide
13470     */
13471    protected void onDetachedFromWindowInternal() {
13472        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13473        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13474
13475        removeUnsetPressCallback();
13476        removeLongPressCallback();
13477        removePerformClickCallback();
13478        removeSendViewScrolledAccessibilityEventCallback();
13479        stopNestedScroll();
13480
13481        // Anything that started animating right before detach should already
13482        // be in its final state when re-attached.
13483        jumpDrawablesToCurrentState();
13484
13485        destroyDrawingCache();
13486
13487        cleanupDraw();
13488        mCurrentAnimation = null;
13489    }
13490
13491    private void cleanupDraw() {
13492        resetDisplayList();
13493        if (mAttachInfo != null) {
13494            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13495        }
13496    }
13497
13498    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13499    }
13500
13501    /**
13502     * @return The number of times this view has been attached to a window
13503     */
13504    protected int getWindowAttachCount() {
13505        return mWindowAttachCount;
13506    }
13507
13508    /**
13509     * Retrieve a unique token identifying the window this view is attached to.
13510     * @return Return the window's token for use in
13511     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13512     */
13513    public IBinder getWindowToken() {
13514        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13515    }
13516
13517    /**
13518     * Retrieve the {@link WindowId} for the window this view is
13519     * currently attached to.
13520     */
13521    public WindowId getWindowId() {
13522        if (mAttachInfo == null) {
13523            return null;
13524        }
13525        if (mAttachInfo.mWindowId == null) {
13526            try {
13527                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13528                        mAttachInfo.mWindowToken);
13529                mAttachInfo.mWindowId = new WindowId(
13530                        mAttachInfo.mIWindowId);
13531            } catch (RemoteException e) {
13532            }
13533        }
13534        return mAttachInfo.mWindowId;
13535    }
13536
13537    /**
13538     * Retrieve a unique token identifying the top-level "real" window of
13539     * the window that this view is attached to.  That is, this is like
13540     * {@link #getWindowToken}, except if the window this view in is a panel
13541     * window (attached to another containing window), then the token of
13542     * the containing window is returned instead.
13543     *
13544     * @return Returns the associated window token, either
13545     * {@link #getWindowToken()} or the containing window's token.
13546     */
13547    public IBinder getApplicationWindowToken() {
13548        AttachInfo ai = mAttachInfo;
13549        if (ai != null) {
13550            IBinder appWindowToken = ai.mPanelParentWindowToken;
13551            if (appWindowToken == null) {
13552                appWindowToken = ai.mWindowToken;
13553            }
13554            return appWindowToken;
13555        }
13556        return null;
13557    }
13558
13559    /**
13560     * Gets the logical display to which the view's window has been attached.
13561     *
13562     * @return The logical display, or null if the view is not currently attached to a window.
13563     */
13564    public Display getDisplay() {
13565        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13566    }
13567
13568    /**
13569     * Retrieve private session object this view hierarchy is using to
13570     * communicate with the window manager.
13571     * @return the session object to communicate with the window manager
13572     */
13573    /*package*/ IWindowSession getWindowSession() {
13574        return mAttachInfo != null ? mAttachInfo.mSession : null;
13575    }
13576
13577    /**
13578     * @param info the {@link android.view.View.AttachInfo} to associated with
13579     *        this view
13580     */
13581    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13582        //System.out.println("Attached! " + this);
13583        mAttachInfo = info;
13584        if (mOverlay != null) {
13585            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13586        }
13587        mWindowAttachCount++;
13588        // We will need to evaluate the drawable state at least once.
13589        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13590        if (mFloatingTreeObserver != null) {
13591            info.mTreeObserver.merge(mFloatingTreeObserver);
13592            mFloatingTreeObserver = null;
13593        }
13594        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13595            mAttachInfo.mScrollContainers.add(this);
13596            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13597        }
13598        performCollectViewAttributes(mAttachInfo, visibility);
13599        onAttachedToWindow();
13600
13601        ListenerInfo li = mListenerInfo;
13602        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13603                li != null ? li.mOnAttachStateChangeListeners : null;
13604        if (listeners != null && listeners.size() > 0) {
13605            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13606            // perform the dispatching. The iterator is a safe guard against listeners that
13607            // could mutate the list by calling the various add/remove methods. This prevents
13608            // the array from being modified while we iterate it.
13609            for (OnAttachStateChangeListener listener : listeners) {
13610                listener.onViewAttachedToWindow(this);
13611            }
13612        }
13613
13614        int vis = info.mWindowVisibility;
13615        if (vis != GONE) {
13616            onWindowVisibilityChanged(vis);
13617        }
13618        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13619            // If nobody has evaluated the drawable state yet, then do it now.
13620            refreshDrawableState();
13621        }
13622        needGlobalAttributesUpdate(false);
13623    }
13624
13625    void dispatchDetachedFromWindow() {
13626        AttachInfo info = mAttachInfo;
13627        if (info != null) {
13628            int vis = info.mWindowVisibility;
13629            if (vis != GONE) {
13630                onWindowVisibilityChanged(GONE);
13631            }
13632        }
13633
13634        onDetachedFromWindow();
13635        onDetachedFromWindowInternal();
13636
13637        ListenerInfo li = mListenerInfo;
13638        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13639                li != null ? li.mOnAttachStateChangeListeners : null;
13640        if (listeners != null && listeners.size() > 0) {
13641            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13642            // perform the dispatching. The iterator is a safe guard against listeners that
13643            // could mutate the list by calling the various add/remove methods. This prevents
13644            // the array from being modified while we iterate it.
13645            for (OnAttachStateChangeListener listener : listeners) {
13646                listener.onViewDetachedFromWindow(this);
13647            }
13648        }
13649
13650        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13651            mAttachInfo.mScrollContainers.remove(this);
13652            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13653        }
13654
13655        mAttachInfo = null;
13656        if (mOverlay != null) {
13657            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13658        }
13659    }
13660
13661    /**
13662     * Cancel any deferred high-level input events that were previously posted to the event queue.
13663     *
13664     * <p>Many views post high-level events such as click handlers to the event queue
13665     * to run deferred in order to preserve a desired user experience - clearing visible
13666     * pressed states before executing, etc. This method will abort any events of this nature
13667     * that are currently in flight.</p>
13668     *
13669     * <p>Custom views that generate their own high-level deferred input events should override
13670     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13671     *
13672     * <p>This will also cancel pending input events for any child views.</p>
13673     *
13674     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13675     * This will not impact newer events posted after this call that may occur as a result of
13676     * lower-level input events still waiting in the queue. If you are trying to prevent
13677     * double-submitted  events for the duration of some sort of asynchronous transaction
13678     * you should also take other steps to protect against unexpected double inputs e.g. calling
13679     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13680     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13681     */
13682    public final void cancelPendingInputEvents() {
13683        dispatchCancelPendingInputEvents();
13684    }
13685
13686    /**
13687     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13688     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13689     */
13690    void dispatchCancelPendingInputEvents() {
13691        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13692        onCancelPendingInputEvents();
13693        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13694            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13695                    " did not call through to super.onCancelPendingInputEvents()");
13696        }
13697    }
13698
13699    /**
13700     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13701     * a parent view.
13702     *
13703     * <p>This method is responsible for removing any pending high-level input events that were
13704     * posted to the event queue to run later. Custom view classes that post their own deferred
13705     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13706     * {@link android.os.Handler} should override this method, call
13707     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13708     * </p>
13709     */
13710    public void onCancelPendingInputEvents() {
13711        removePerformClickCallback();
13712        cancelLongPress();
13713        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13714    }
13715
13716    /**
13717     * Store this view hierarchy's frozen state into the given container.
13718     *
13719     * @param container The SparseArray in which to save the view's state.
13720     *
13721     * @see #restoreHierarchyState(android.util.SparseArray)
13722     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13723     * @see #onSaveInstanceState()
13724     */
13725    public void saveHierarchyState(SparseArray<Parcelable> container) {
13726        dispatchSaveInstanceState(container);
13727    }
13728
13729    /**
13730     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13731     * this view and its children. May be overridden to modify how freezing happens to a
13732     * view's children; for example, some views may want to not store state for their children.
13733     *
13734     * @param container The SparseArray in which to save the view's state.
13735     *
13736     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13737     * @see #saveHierarchyState(android.util.SparseArray)
13738     * @see #onSaveInstanceState()
13739     */
13740    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13741        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13742            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13743            Parcelable state = onSaveInstanceState();
13744            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13745                throw new IllegalStateException(
13746                        "Derived class did not call super.onSaveInstanceState()");
13747            }
13748            if (state != null) {
13749                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13750                // + ": " + state);
13751                container.put(mID, state);
13752            }
13753        }
13754    }
13755
13756    /**
13757     * Hook allowing a view to generate a representation of its internal state
13758     * that can later be used to create a new instance with that same state.
13759     * This state should only contain information that is not persistent or can
13760     * not be reconstructed later. For example, you will never store your
13761     * current position on screen because that will be computed again when a
13762     * new instance of the view is placed in its view hierarchy.
13763     * <p>
13764     * Some examples of things you may store here: the current cursor position
13765     * in a text view (but usually not the text itself since that is stored in a
13766     * content provider or other persistent storage), the currently selected
13767     * item in a list view.
13768     *
13769     * @return Returns a Parcelable object containing the view's current dynamic
13770     *         state, or null if there is nothing interesting to save. The
13771     *         default implementation returns null.
13772     * @see #onRestoreInstanceState(android.os.Parcelable)
13773     * @see #saveHierarchyState(android.util.SparseArray)
13774     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13775     * @see #setSaveEnabled(boolean)
13776     */
13777    protected Parcelable onSaveInstanceState() {
13778        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13779        return BaseSavedState.EMPTY_STATE;
13780    }
13781
13782    /**
13783     * Restore this view hierarchy's frozen state from the given container.
13784     *
13785     * @param container The SparseArray which holds previously frozen states.
13786     *
13787     * @see #saveHierarchyState(android.util.SparseArray)
13788     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13789     * @see #onRestoreInstanceState(android.os.Parcelable)
13790     */
13791    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13792        dispatchRestoreInstanceState(container);
13793    }
13794
13795    /**
13796     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13797     * state for this view and its children. May be overridden to modify how restoring
13798     * happens to a view's children; for example, some views may want to not store state
13799     * for their children.
13800     *
13801     * @param container The SparseArray which holds previously saved state.
13802     *
13803     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13804     * @see #restoreHierarchyState(android.util.SparseArray)
13805     * @see #onRestoreInstanceState(android.os.Parcelable)
13806     */
13807    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13808        if (mID != NO_ID) {
13809            Parcelable state = container.get(mID);
13810            if (state != null) {
13811                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13812                // + ": " + state);
13813                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13814                onRestoreInstanceState(state);
13815                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13816                    throw new IllegalStateException(
13817                            "Derived class did not call super.onRestoreInstanceState()");
13818                }
13819            }
13820        }
13821    }
13822
13823    /**
13824     * Hook allowing a view to re-apply a representation of its internal state that had previously
13825     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13826     * null state.
13827     *
13828     * @param state The frozen state that had previously been returned by
13829     *        {@link #onSaveInstanceState}.
13830     *
13831     * @see #onSaveInstanceState()
13832     * @see #restoreHierarchyState(android.util.SparseArray)
13833     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13834     */
13835    protected void onRestoreInstanceState(Parcelable state) {
13836        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13837        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13838            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13839                    + "received " + state.getClass().toString() + " instead. This usually happens "
13840                    + "when two views of different type have the same id in the same hierarchy. "
13841                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13842                    + "other views do not use the same id.");
13843        }
13844    }
13845
13846    /**
13847     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13848     *
13849     * @return the drawing start time in milliseconds
13850     */
13851    public long getDrawingTime() {
13852        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13853    }
13854
13855    /**
13856     * <p>Enables or disables the duplication of the parent's state into this view. When
13857     * duplication is enabled, this view gets its drawable state from its parent rather
13858     * than from its own internal properties.</p>
13859     *
13860     * <p>Note: in the current implementation, setting this property to true after the
13861     * view was added to a ViewGroup might have no effect at all. This property should
13862     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13863     *
13864     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13865     * property is enabled, an exception will be thrown.</p>
13866     *
13867     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13868     * parent, these states should not be affected by this method.</p>
13869     *
13870     * @param enabled True to enable duplication of the parent's drawable state, false
13871     *                to disable it.
13872     *
13873     * @see #getDrawableState()
13874     * @see #isDuplicateParentStateEnabled()
13875     */
13876    public void setDuplicateParentStateEnabled(boolean enabled) {
13877        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13878    }
13879
13880    /**
13881     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13882     *
13883     * @return True if this view's drawable state is duplicated from the parent,
13884     *         false otherwise
13885     *
13886     * @see #getDrawableState()
13887     * @see #setDuplicateParentStateEnabled(boolean)
13888     */
13889    public boolean isDuplicateParentStateEnabled() {
13890        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13891    }
13892
13893    /**
13894     * <p>Specifies the type of layer backing this view. The layer can be
13895     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13896     * {@link #LAYER_TYPE_HARDWARE}.</p>
13897     *
13898     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13899     * instance that controls how the layer is composed on screen. The following
13900     * properties of the paint are taken into account when composing the layer:</p>
13901     * <ul>
13902     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13903     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13904     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13905     * </ul>
13906     *
13907     * <p>If this view has an alpha value set to < 1.0 by calling
13908     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13909     * by this view's alpha value.</p>
13910     *
13911     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13912     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13913     * for more information on when and how to use layers.</p>
13914     *
13915     * @param layerType The type of layer to use with this view, must be one of
13916     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13917     *        {@link #LAYER_TYPE_HARDWARE}
13918     * @param paint The paint used to compose the layer. This argument is optional
13919     *        and can be null. It is ignored when the layer type is
13920     *        {@link #LAYER_TYPE_NONE}
13921     *
13922     * @see #getLayerType()
13923     * @see #LAYER_TYPE_NONE
13924     * @see #LAYER_TYPE_SOFTWARE
13925     * @see #LAYER_TYPE_HARDWARE
13926     * @see #setAlpha(float)
13927     *
13928     * @attr ref android.R.styleable#View_layerType
13929     */
13930    public void setLayerType(int layerType, Paint paint) {
13931        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13932            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13933                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13934        }
13935
13936        boolean typeChanged = mRenderNode.setLayerType(layerType);
13937
13938        if (!typeChanged) {
13939            setLayerPaint(paint);
13940            return;
13941        }
13942
13943        // Destroy any previous software drawing cache if needed
13944        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13945            destroyDrawingCache();
13946        }
13947
13948        mLayerType = layerType;
13949        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13950        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13951        mRenderNode.setLayerPaint(mLayerPaint);
13952
13953        // draw() behaves differently if we are on a layer, so we need to
13954        // invalidate() here
13955        invalidateParentCaches();
13956        invalidate(true);
13957    }
13958
13959    /**
13960     * Updates the {@link Paint} object used with the current layer (used only if the current
13961     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13962     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13963     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13964     * ensure that the view gets redrawn immediately.
13965     *
13966     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13967     * instance that controls how the layer is composed on screen. The following
13968     * properties of the paint are taken into account when composing the layer:</p>
13969     * <ul>
13970     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13971     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13972     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13973     * </ul>
13974     *
13975     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13976     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13977     *
13978     * @param paint The paint used to compose the layer. This argument is optional
13979     *        and can be null. It is ignored when the layer type is
13980     *        {@link #LAYER_TYPE_NONE}
13981     *
13982     * @see #setLayerType(int, android.graphics.Paint)
13983     */
13984    public void setLayerPaint(Paint paint) {
13985        int layerType = getLayerType();
13986        if (layerType != LAYER_TYPE_NONE) {
13987            mLayerPaint = paint == null ? new Paint() : paint;
13988            if (layerType == LAYER_TYPE_HARDWARE) {
13989                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13990                    invalidateViewProperty(false, false);
13991                }
13992            } else {
13993                invalidate();
13994            }
13995        }
13996    }
13997
13998    /**
13999     * Indicates whether this view has a static layer. A view with layer type
14000     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
14001     * dynamic.
14002     */
14003    boolean hasStaticLayer() {
14004        return true;
14005    }
14006
14007    /**
14008     * Indicates what type of layer is currently associated with this view. By default
14009     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14010     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14011     * for more information on the different types of layers.
14012     *
14013     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14014     *         {@link #LAYER_TYPE_HARDWARE}
14015     *
14016     * @see #setLayerType(int, android.graphics.Paint)
14017     * @see #buildLayer()
14018     * @see #LAYER_TYPE_NONE
14019     * @see #LAYER_TYPE_SOFTWARE
14020     * @see #LAYER_TYPE_HARDWARE
14021     */
14022    public int getLayerType() {
14023        return mLayerType;
14024    }
14025
14026    /**
14027     * Forces this view's layer to be created and this view to be rendered
14028     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14029     * invoking this method will have no effect.
14030     *
14031     * This method can for instance be used to render a view into its layer before
14032     * starting an animation. If this view is complex, rendering into the layer
14033     * before starting the animation will avoid skipping frames.
14034     *
14035     * @throws IllegalStateException If this view is not attached to a window
14036     *
14037     * @see #setLayerType(int, android.graphics.Paint)
14038     */
14039    public void buildLayer() {
14040        if (mLayerType == LAYER_TYPE_NONE) return;
14041
14042        final AttachInfo attachInfo = mAttachInfo;
14043        if (attachInfo == null) {
14044            throw new IllegalStateException("This view must be attached to a window first");
14045        }
14046
14047        if (getWidth() == 0 || getHeight() == 0) {
14048            return;
14049        }
14050
14051        switch (mLayerType) {
14052            case LAYER_TYPE_HARDWARE:
14053                updateDisplayListIfDirty();
14054                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14055                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14056                }
14057                break;
14058            case LAYER_TYPE_SOFTWARE:
14059                buildDrawingCache(true);
14060                break;
14061        }
14062    }
14063
14064    /**
14065     * If this View draws with a HardwareLayer, returns it.
14066     * Otherwise returns null
14067     *
14068     * TODO: Only TextureView uses this, can we eliminate it?
14069     */
14070    HardwareLayer getHardwareLayer() {
14071        return null;
14072    }
14073
14074    /**
14075     * Destroys all hardware rendering resources. This method is invoked
14076     * when the system needs to reclaim resources. Upon execution of this
14077     * method, you should free any OpenGL resources created by the view.
14078     *
14079     * Note: you <strong>must</strong> call
14080     * <code>super.destroyHardwareResources()</code> when overriding
14081     * this method.
14082     *
14083     * @hide
14084     */
14085    protected void destroyHardwareResources() {
14086        // Although the Layer will be destroyed by RenderNode, we want to release
14087        // the staging display list, which is also a signal to RenderNode that it's
14088        // safe to free its copy of the display list as it knows that we will
14089        // push an updated DisplayList if we try to draw again
14090        resetDisplayList();
14091    }
14092
14093    /**
14094     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14095     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14096     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14097     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14098     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14099     * null.</p>
14100     *
14101     * <p>Enabling the drawing cache is similar to
14102     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14103     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14104     * drawing cache has no effect on rendering because the system uses a different mechanism
14105     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14106     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14107     * for information on how to enable software and hardware layers.</p>
14108     *
14109     * <p>This API can be used to manually generate
14110     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14111     * {@link #getDrawingCache()}.</p>
14112     *
14113     * @param enabled true to enable the drawing cache, false otherwise
14114     *
14115     * @see #isDrawingCacheEnabled()
14116     * @see #getDrawingCache()
14117     * @see #buildDrawingCache()
14118     * @see #setLayerType(int, android.graphics.Paint)
14119     */
14120    public void setDrawingCacheEnabled(boolean enabled) {
14121        mCachingFailed = false;
14122        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14123    }
14124
14125    /**
14126     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14127     *
14128     * @return true if the drawing cache is enabled
14129     *
14130     * @see #setDrawingCacheEnabled(boolean)
14131     * @see #getDrawingCache()
14132     */
14133    @ViewDebug.ExportedProperty(category = "drawing")
14134    public boolean isDrawingCacheEnabled() {
14135        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14136    }
14137
14138    /**
14139     * Debugging utility which recursively outputs the dirty state of a view and its
14140     * descendants.
14141     *
14142     * @hide
14143     */
14144    @SuppressWarnings({"UnusedDeclaration"})
14145    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14146        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14147                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14148                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14149                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14150        if (clear) {
14151            mPrivateFlags &= clearMask;
14152        }
14153        if (this instanceof ViewGroup) {
14154            ViewGroup parent = (ViewGroup) this;
14155            final int count = parent.getChildCount();
14156            for (int i = 0; i < count; i++) {
14157                final View child = parent.getChildAt(i);
14158                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14159            }
14160        }
14161    }
14162
14163    /**
14164     * This method is used by ViewGroup to cause its children to restore or recreate their
14165     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14166     * to recreate its own display list, which would happen if it went through the normal
14167     * draw/dispatchDraw mechanisms.
14168     *
14169     * @hide
14170     */
14171    protected void dispatchGetDisplayList() {}
14172
14173    /**
14174     * A view that is not attached or hardware accelerated cannot create a display list.
14175     * This method checks these conditions and returns the appropriate result.
14176     *
14177     * @return true if view has the ability to create a display list, false otherwise.
14178     *
14179     * @hide
14180     */
14181    public boolean canHaveDisplayList() {
14182        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14183    }
14184
14185    private void updateDisplayListIfDirty() {
14186        final RenderNode renderNode = mRenderNode;
14187        if (!canHaveDisplayList()) {
14188            // can't populate RenderNode, don't try
14189            return;
14190        }
14191
14192        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14193                || !renderNode.isValid()
14194                || (mRecreateDisplayList)) {
14195            // Don't need to recreate the display list, just need to tell our
14196            // children to restore/recreate theirs
14197            if (renderNode.isValid()
14198                    && !mRecreateDisplayList) {
14199                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14200                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14201                dispatchGetDisplayList();
14202
14203                return; // no work needed
14204            }
14205
14206            // If we got here, we're recreating it. Mark it as such to ensure that
14207            // we copy in child display lists into ours in drawChild()
14208            mRecreateDisplayList = true;
14209
14210            int width = mRight - mLeft;
14211            int height = mBottom - mTop;
14212            int layerType = getLayerType();
14213
14214            final HardwareCanvas canvas = renderNode.start(width, height);
14215            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14216
14217            try {
14218                final HardwareLayer layer = getHardwareLayer();
14219                if (layer != null && layer.isValid()) {
14220                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14221                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14222                    buildDrawingCache(true);
14223                    Bitmap cache = getDrawingCache(true);
14224                    if (cache != null) {
14225                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14226                    }
14227                } else {
14228                    computeScroll();
14229
14230                    canvas.translate(-mScrollX, -mScrollY);
14231                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14232                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14233
14234                    // Fast path for layouts with no backgrounds
14235                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14236                        dispatchDraw(canvas);
14237                        if (mOverlay != null && !mOverlay.isEmpty()) {
14238                            mOverlay.getOverlayView().draw(canvas);
14239                        }
14240                    } else {
14241                        draw(canvas);
14242                    }
14243                }
14244            } finally {
14245                renderNode.end(canvas);
14246                setDisplayListProperties(renderNode);
14247            }
14248        } else {
14249            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14250            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14251        }
14252    }
14253
14254    /**
14255     * Returns a RenderNode with View draw content recorded, which can be
14256     * used to draw this view again without executing its draw method.
14257     *
14258     * @return A RenderNode ready to replay, or null if caching is not enabled.
14259     *
14260     * @hide
14261     */
14262    public RenderNode getDisplayList() {
14263        updateDisplayListIfDirty();
14264        return mRenderNode;
14265    }
14266
14267    private void resetDisplayList() {
14268        if (mRenderNode.isValid()) {
14269            mRenderNode.destroyDisplayListData();
14270        }
14271
14272        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14273            mBackgroundRenderNode.destroyDisplayListData();
14274        }
14275    }
14276
14277    /**
14278     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14279     *
14280     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14281     *
14282     * @see #getDrawingCache(boolean)
14283     */
14284    public Bitmap getDrawingCache() {
14285        return getDrawingCache(false);
14286    }
14287
14288    /**
14289     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14290     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14291     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14292     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14293     * request the drawing cache by calling this method and draw it on screen if the
14294     * returned bitmap is not null.</p>
14295     *
14296     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14297     * this method will create a bitmap of the same size as this view. Because this bitmap
14298     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14299     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14300     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14301     * size than the view. This implies that your application must be able to handle this
14302     * size.</p>
14303     *
14304     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14305     *        the current density of the screen when the application is in compatibility
14306     *        mode.
14307     *
14308     * @return A bitmap representing this view or null if cache is disabled.
14309     *
14310     * @see #setDrawingCacheEnabled(boolean)
14311     * @see #isDrawingCacheEnabled()
14312     * @see #buildDrawingCache(boolean)
14313     * @see #destroyDrawingCache()
14314     */
14315    public Bitmap getDrawingCache(boolean autoScale) {
14316        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14317            return null;
14318        }
14319        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14320            buildDrawingCache(autoScale);
14321        }
14322        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14323    }
14324
14325    /**
14326     * <p>Frees the resources used by the drawing cache. If you call
14327     * {@link #buildDrawingCache()} manually without calling
14328     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14329     * should cleanup the cache with this method afterwards.</p>
14330     *
14331     * @see #setDrawingCacheEnabled(boolean)
14332     * @see #buildDrawingCache()
14333     * @see #getDrawingCache()
14334     */
14335    public void destroyDrawingCache() {
14336        if (mDrawingCache != null) {
14337            mDrawingCache.recycle();
14338            mDrawingCache = null;
14339        }
14340        if (mUnscaledDrawingCache != null) {
14341            mUnscaledDrawingCache.recycle();
14342            mUnscaledDrawingCache = null;
14343        }
14344    }
14345
14346    /**
14347     * Setting a solid background color for the drawing cache's bitmaps will improve
14348     * performance and memory usage. Note, though that this should only be used if this
14349     * view will always be drawn on top of a solid color.
14350     *
14351     * @param color The background color to use for the drawing cache's bitmap
14352     *
14353     * @see #setDrawingCacheEnabled(boolean)
14354     * @see #buildDrawingCache()
14355     * @see #getDrawingCache()
14356     */
14357    public void setDrawingCacheBackgroundColor(int color) {
14358        if (color != mDrawingCacheBackgroundColor) {
14359            mDrawingCacheBackgroundColor = color;
14360            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14361        }
14362    }
14363
14364    /**
14365     * @see #setDrawingCacheBackgroundColor(int)
14366     *
14367     * @return The background color to used for the drawing cache's bitmap
14368     */
14369    public int getDrawingCacheBackgroundColor() {
14370        return mDrawingCacheBackgroundColor;
14371    }
14372
14373    /**
14374     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14375     *
14376     * @see #buildDrawingCache(boolean)
14377     */
14378    public void buildDrawingCache() {
14379        buildDrawingCache(false);
14380    }
14381
14382    /**
14383     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14384     *
14385     * <p>If you call {@link #buildDrawingCache()} manually without calling
14386     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14387     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14388     *
14389     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14390     * this method will create a bitmap of the same size as this view. Because this bitmap
14391     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14392     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14393     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14394     * size than the view. This implies that your application must be able to handle this
14395     * size.</p>
14396     *
14397     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14398     * you do not need the drawing cache bitmap, calling this method will increase memory
14399     * usage and cause the view to be rendered in software once, thus negatively impacting
14400     * performance.</p>
14401     *
14402     * @see #getDrawingCache()
14403     * @see #destroyDrawingCache()
14404     */
14405    public void buildDrawingCache(boolean autoScale) {
14406        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14407                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14408            mCachingFailed = false;
14409
14410            int width = mRight - mLeft;
14411            int height = mBottom - mTop;
14412
14413            final AttachInfo attachInfo = mAttachInfo;
14414            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14415
14416            if (autoScale && scalingRequired) {
14417                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14418                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14419            }
14420
14421            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14422            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14423            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14424
14425            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14426            final long drawingCacheSize =
14427                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14428            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14429                if (width > 0 && height > 0) {
14430                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14431                            + projectedBitmapSize + " bytes, only "
14432                            + drawingCacheSize + " available");
14433                }
14434                destroyDrawingCache();
14435                mCachingFailed = true;
14436                return;
14437            }
14438
14439            boolean clear = true;
14440            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14441
14442            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14443                Bitmap.Config quality;
14444                if (!opaque) {
14445                    // Never pick ARGB_4444 because it looks awful
14446                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14447                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14448                        case DRAWING_CACHE_QUALITY_AUTO:
14449                        case DRAWING_CACHE_QUALITY_LOW:
14450                        case DRAWING_CACHE_QUALITY_HIGH:
14451                        default:
14452                            quality = Bitmap.Config.ARGB_8888;
14453                            break;
14454                    }
14455                } else {
14456                    // Optimization for translucent windows
14457                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14458                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14459                }
14460
14461                // Try to cleanup memory
14462                if (bitmap != null) bitmap.recycle();
14463
14464                try {
14465                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14466                            width, height, quality);
14467                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14468                    if (autoScale) {
14469                        mDrawingCache = bitmap;
14470                    } else {
14471                        mUnscaledDrawingCache = bitmap;
14472                    }
14473                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14474                } catch (OutOfMemoryError e) {
14475                    // If there is not enough memory to create the bitmap cache, just
14476                    // ignore the issue as bitmap caches are not required to draw the
14477                    // view hierarchy
14478                    if (autoScale) {
14479                        mDrawingCache = null;
14480                    } else {
14481                        mUnscaledDrawingCache = null;
14482                    }
14483                    mCachingFailed = true;
14484                    return;
14485                }
14486
14487                clear = drawingCacheBackgroundColor != 0;
14488            }
14489
14490            Canvas canvas;
14491            if (attachInfo != null) {
14492                canvas = attachInfo.mCanvas;
14493                if (canvas == null) {
14494                    canvas = new Canvas();
14495                }
14496                canvas.setBitmap(bitmap);
14497                // Temporarily clobber the cached Canvas in case one of our children
14498                // is also using a drawing cache. Without this, the children would
14499                // steal the canvas by attaching their own bitmap to it and bad, bad
14500                // thing would happen (invisible views, corrupted drawings, etc.)
14501                attachInfo.mCanvas = null;
14502            } else {
14503                // This case should hopefully never or seldom happen
14504                canvas = new Canvas(bitmap);
14505            }
14506
14507            if (clear) {
14508                bitmap.eraseColor(drawingCacheBackgroundColor);
14509            }
14510
14511            computeScroll();
14512            final int restoreCount = canvas.save();
14513
14514            if (autoScale && scalingRequired) {
14515                final float scale = attachInfo.mApplicationScale;
14516                canvas.scale(scale, scale);
14517            }
14518
14519            canvas.translate(-mScrollX, -mScrollY);
14520
14521            mPrivateFlags |= PFLAG_DRAWN;
14522            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14523                    mLayerType != LAYER_TYPE_NONE) {
14524                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14525            }
14526
14527            // Fast path for layouts with no backgrounds
14528            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14529                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14530                dispatchDraw(canvas);
14531                if (mOverlay != null && !mOverlay.isEmpty()) {
14532                    mOverlay.getOverlayView().draw(canvas);
14533                }
14534            } else {
14535                draw(canvas);
14536            }
14537
14538            canvas.restoreToCount(restoreCount);
14539            canvas.setBitmap(null);
14540
14541            if (attachInfo != null) {
14542                // Restore the cached Canvas for our siblings
14543                attachInfo.mCanvas = canvas;
14544            }
14545        }
14546    }
14547
14548    /**
14549     * Create a snapshot of the view into a bitmap.  We should probably make
14550     * some form of this public, but should think about the API.
14551     */
14552    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14553        int width = mRight - mLeft;
14554        int height = mBottom - mTop;
14555
14556        final AttachInfo attachInfo = mAttachInfo;
14557        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14558        width = (int) ((width * scale) + 0.5f);
14559        height = (int) ((height * scale) + 0.5f);
14560
14561        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14562                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14563        if (bitmap == null) {
14564            throw new OutOfMemoryError();
14565        }
14566
14567        Resources resources = getResources();
14568        if (resources != null) {
14569            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14570        }
14571
14572        Canvas canvas;
14573        if (attachInfo != null) {
14574            canvas = attachInfo.mCanvas;
14575            if (canvas == null) {
14576                canvas = new Canvas();
14577            }
14578            canvas.setBitmap(bitmap);
14579            // Temporarily clobber the cached Canvas in case one of our children
14580            // is also using a drawing cache. Without this, the children would
14581            // steal the canvas by attaching their own bitmap to it and bad, bad
14582            // things would happen (invisible views, corrupted drawings, etc.)
14583            attachInfo.mCanvas = null;
14584        } else {
14585            // This case should hopefully never or seldom happen
14586            canvas = new Canvas(bitmap);
14587        }
14588
14589        if ((backgroundColor & 0xff000000) != 0) {
14590            bitmap.eraseColor(backgroundColor);
14591        }
14592
14593        computeScroll();
14594        final int restoreCount = canvas.save();
14595        canvas.scale(scale, scale);
14596        canvas.translate(-mScrollX, -mScrollY);
14597
14598        // Temporarily remove the dirty mask
14599        int flags = mPrivateFlags;
14600        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14601
14602        // Fast path for layouts with no backgrounds
14603        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14604            dispatchDraw(canvas);
14605            if (mOverlay != null && !mOverlay.isEmpty()) {
14606                mOverlay.getOverlayView().draw(canvas);
14607            }
14608        } else {
14609            draw(canvas);
14610        }
14611
14612        mPrivateFlags = flags;
14613
14614        canvas.restoreToCount(restoreCount);
14615        canvas.setBitmap(null);
14616
14617        if (attachInfo != null) {
14618            // Restore the cached Canvas for our siblings
14619            attachInfo.mCanvas = canvas;
14620        }
14621
14622        return bitmap;
14623    }
14624
14625    /**
14626     * Indicates whether this View is currently in edit mode. A View is usually
14627     * in edit mode when displayed within a developer tool. For instance, if
14628     * this View is being drawn by a visual user interface builder, this method
14629     * should return true.
14630     *
14631     * Subclasses should check the return value of this method to provide
14632     * different behaviors if their normal behavior might interfere with the
14633     * host environment. For instance: the class spawns a thread in its
14634     * constructor, the drawing code relies on device-specific features, etc.
14635     *
14636     * This method is usually checked in the drawing code of custom widgets.
14637     *
14638     * @return True if this View is in edit mode, false otherwise.
14639     */
14640    public boolean isInEditMode() {
14641        return false;
14642    }
14643
14644    /**
14645     * If the View draws content inside its padding and enables fading edges,
14646     * it needs to support padding offsets. Padding offsets are added to the
14647     * fading edges to extend the length of the fade so that it covers pixels
14648     * drawn inside the padding.
14649     *
14650     * Subclasses of this class should override this method if they need
14651     * to draw content inside the padding.
14652     *
14653     * @return True if padding offset must be applied, false otherwise.
14654     *
14655     * @see #getLeftPaddingOffset()
14656     * @see #getRightPaddingOffset()
14657     * @see #getTopPaddingOffset()
14658     * @see #getBottomPaddingOffset()
14659     *
14660     * @since CURRENT
14661     */
14662    protected boolean isPaddingOffsetRequired() {
14663        return false;
14664    }
14665
14666    /**
14667     * Amount by which to extend the left fading region. Called only when
14668     * {@link #isPaddingOffsetRequired()} returns true.
14669     *
14670     * @return The left padding offset in pixels.
14671     *
14672     * @see #isPaddingOffsetRequired()
14673     *
14674     * @since CURRENT
14675     */
14676    protected int getLeftPaddingOffset() {
14677        return 0;
14678    }
14679
14680    /**
14681     * Amount by which to extend the right fading region. Called only when
14682     * {@link #isPaddingOffsetRequired()} returns true.
14683     *
14684     * @return The right padding offset in pixels.
14685     *
14686     * @see #isPaddingOffsetRequired()
14687     *
14688     * @since CURRENT
14689     */
14690    protected int getRightPaddingOffset() {
14691        return 0;
14692    }
14693
14694    /**
14695     * Amount by which to extend the top fading region. Called only when
14696     * {@link #isPaddingOffsetRequired()} returns true.
14697     *
14698     * @return The top padding offset in pixels.
14699     *
14700     * @see #isPaddingOffsetRequired()
14701     *
14702     * @since CURRENT
14703     */
14704    protected int getTopPaddingOffset() {
14705        return 0;
14706    }
14707
14708    /**
14709     * Amount by which to extend the bottom fading region. Called only when
14710     * {@link #isPaddingOffsetRequired()} returns true.
14711     *
14712     * @return The bottom padding offset in pixels.
14713     *
14714     * @see #isPaddingOffsetRequired()
14715     *
14716     * @since CURRENT
14717     */
14718    protected int getBottomPaddingOffset() {
14719        return 0;
14720    }
14721
14722    /**
14723     * @hide
14724     * @param offsetRequired
14725     */
14726    protected int getFadeTop(boolean offsetRequired) {
14727        int top = mPaddingTop;
14728        if (offsetRequired) top += getTopPaddingOffset();
14729        return top;
14730    }
14731
14732    /**
14733     * @hide
14734     * @param offsetRequired
14735     */
14736    protected int getFadeHeight(boolean offsetRequired) {
14737        int padding = mPaddingTop;
14738        if (offsetRequired) padding += getTopPaddingOffset();
14739        return mBottom - mTop - mPaddingBottom - padding;
14740    }
14741
14742    /**
14743     * <p>Indicates whether this view is attached to a hardware accelerated
14744     * window or not.</p>
14745     *
14746     * <p>Even if this method returns true, it does not mean that every call
14747     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14748     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14749     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14750     * window is hardware accelerated,
14751     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14752     * return false, and this method will return true.</p>
14753     *
14754     * @return True if the view is attached to a window and the window is
14755     *         hardware accelerated; false in any other case.
14756     */
14757    @ViewDebug.ExportedProperty(category = "drawing")
14758    public boolean isHardwareAccelerated() {
14759        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14760    }
14761
14762    /**
14763     * Sets a rectangular area on this view to which the view will be clipped
14764     * when it is drawn. Setting the value to null will remove the clip bounds
14765     * and the view will draw normally, using its full bounds.
14766     *
14767     * @param clipBounds The rectangular area, in the local coordinates of
14768     * this view, to which future drawing operations will be clipped.
14769     */
14770    public void setClipBounds(Rect clipBounds) {
14771        if (clipBounds != null) {
14772            if (clipBounds.equals(mClipBounds)) {
14773                return;
14774            }
14775            if (mClipBounds == null) {
14776                invalidate();
14777                mClipBounds = new Rect(clipBounds);
14778            } else {
14779                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14780                        Math.min(mClipBounds.top, clipBounds.top),
14781                        Math.max(mClipBounds.right, clipBounds.right),
14782                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14783                mClipBounds.set(clipBounds);
14784            }
14785        } else {
14786            if (mClipBounds != null) {
14787                invalidate();
14788                mClipBounds = null;
14789            }
14790        }
14791        mRenderNode.setClipBounds(mClipBounds);
14792    }
14793
14794    /**
14795     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14796     *
14797     * @return A copy of the current clip bounds if clip bounds are set,
14798     * otherwise null.
14799     */
14800    public Rect getClipBounds() {
14801        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14802    }
14803
14804    /**
14805     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14806     * case of an active Animation being run on the view.
14807     */
14808    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14809            Animation a, boolean scalingRequired) {
14810        Transformation invalidationTransform;
14811        final int flags = parent.mGroupFlags;
14812        final boolean initialized = a.isInitialized();
14813        if (!initialized) {
14814            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14815            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14816            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14817            onAnimationStart();
14818        }
14819
14820        final Transformation t = parent.getChildTransformation();
14821        boolean more = a.getTransformation(drawingTime, t, 1f);
14822        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14823            if (parent.mInvalidationTransformation == null) {
14824                parent.mInvalidationTransformation = new Transformation();
14825            }
14826            invalidationTransform = parent.mInvalidationTransformation;
14827            a.getTransformation(drawingTime, invalidationTransform, 1f);
14828        } else {
14829            invalidationTransform = t;
14830        }
14831
14832        if (more) {
14833            if (!a.willChangeBounds()) {
14834                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14835                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14836                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14837                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14838                    // The child need to draw an animation, potentially offscreen, so
14839                    // make sure we do not cancel invalidate requests
14840                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14841                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14842                }
14843            } else {
14844                if (parent.mInvalidateRegion == null) {
14845                    parent.mInvalidateRegion = new RectF();
14846                }
14847                final RectF region = parent.mInvalidateRegion;
14848                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14849                        invalidationTransform);
14850
14851                // The child need to draw an animation, potentially offscreen, so
14852                // make sure we do not cancel invalidate requests
14853                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14854
14855                final int left = mLeft + (int) region.left;
14856                final int top = mTop + (int) region.top;
14857                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14858                        top + (int) (region.height() + .5f));
14859            }
14860        }
14861        return more;
14862    }
14863
14864    /**
14865     * This method is called by getDisplayList() when a display list is recorded for a View.
14866     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14867     */
14868    void setDisplayListProperties(RenderNode renderNode) {
14869        if (renderNode != null) {
14870            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14871            if (mParent instanceof ViewGroup) {
14872                renderNode.setClipToBounds(
14873                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14874            }
14875            float alpha = 1;
14876            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14877                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14878                ViewGroup parentVG = (ViewGroup) mParent;
14879                final Transformation t = parentVG.getChildTransformation();
14880                if (parentVG.getChildStaticTransformation(this, t)) {
14881                    final int transformType = t.getTransformationType();
14882                    if (transformType != Transformation.TYPE_IDENTITY) {
14883                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14884                            alpha = t.getAlpha();
14885                        }
14886                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14887                            renderNode.setStaticMatrix(t.getMatrix());
14888                        }
14889                    }
14890                }
14891            }
14892            if (mTransformationInfo != null) {
14893                alpha *= getFinalAlpha();
14894                if (alpha < 1) {
14895                    final int multipliedAlpha = (int) (255 * alpha);
14896                    if (onSetAlpha(multipliedAlpha)) {
14897                        alpha = 1;
14898                    }
14899                }
14900                renderNode.setAlpha(alpha);
14901            } else if (alpha < 1) {
14902                renderNode.setAlpha(alpha);
14903            }
14904        }
14905    }
14906
14907    /**
14908     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14909     * This draw() method is an implementation detail and is not intended to be overridden or
14910     * to be called from anywhere else other than ViewGroup.drawChild().
14911     */
14912    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14913        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14914        boolean more = false;
14915        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14916        final int flags = parent.mGroupFlags;
14917
14918        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14919            parent.getChildTransformation().clear();
14920            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14921        }
14922
14923        Transformation transformToApply = null;
14924        boolean concatMatrix = false;
14925
14926        boolean scalingRequired = false;
14927        boolean caching;
14928        int layerType = getLayerType();
14929
14930        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14931        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14932                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14933            caching = true;
14934            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14935            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14936        } else {
14937            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14938        }
14939
14940        final Animation a = getAnimation();
14941        if (a != null) {
14942            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14943            concatMatrix = a.willChangeTransformationMatrix();
14944            if (concatMatrix) {
14945                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14946            }
14947            transformToApply = parent.getChildTransformation();
14948        } else {
14949            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14950                // No longer animating: clear out old animation matrix
14951                mRenderNode.setAnimationMatrix(null);
14952                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14953            }
14954            if (!usingRenderNodeProperties &&
14955                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14956                final Transformation t = parent.getChildTransformation();
14957                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14958                if (hasTransform) {
14959                    final int transformType = t.getTransformationType();
14960                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14961                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14962                }
14963            }
14964        }
14965
14966        concatMatrix |= !childHasIdentityMatrix;
14967
14968        // Sets the flag as early as possible to allow draw() implementations
14969        // to call invalidate() successfully when doing animations
14970        mPrivateFlags |= PFLAG_DRAWN;
14971
14972        if (!concatMatrix &&
14973                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14974                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14975                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14976                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14977            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14978            return more;
14979        }
14980        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14981
14982        if (hardwareAccelerated) {
14983            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14984            // retain the flag's value temporarily in the mRecreateDisplayList flag
14985            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14986            mPrivateFlags &= ~PFLAG_INVALIDATED;
14987        }
14988
14989        RenderNode renderNode = null;
14990        Bitmap cache = null;
14991        boolean hasDisplayList = false;
14992        if (caching) {
14993            if (!hardwareAccelerated) {
14994                if (layerType != LAYER_TYPE_NONE) {
14995                    layerType = LAYER_TYPE_SOFTWARE;
14996                    buildDrawingCache(true);
14997                }
14998                cache = getDrawingCache(true);
14999            } else {
15000                switch (layerType) {
15001                    case LAYER_TYPE_SOFTWARE:
15002                        if (usingRenderNodeProperties) {
15003                            hasDisplayList = canHaveDisplayList();
15004                        } else {
15005                            buildDrawingCache(true);
15006                            cache = getDrawingCache(true);
15007                        }
15008                        break;
15009                    case LAYER_TYPE_HARDWARE:
15010                        if (usingRenderNodeProperties) {
15011                            hasDisplayList = canHaveDisplayList();
15012                        }
15013                        break;
15014                    case LAYER_TYPE_NONE:
15015                        // Delay getting the display list until animation-driven alpha values are
15016                        // set up and possibly passed on to the view
15017                        hasDisplayList = canHaveDisplayList();
15018                        break;
15019                }
15020            }
15021        }
15022        usingRenderNodeProperties &= hasDisplayList;
15023        if (usingRenderNodeProperties) {
15024            renderNode = getDisplayList();
15025            if (!renderNode.isValid()) {
15026                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15027                // to getDisplayList(), the display list will be marked invalid and we should not
15028                // try to use it again.
15029                renderNode = null;
15030                hasDisplayList = false;
15031                usingRenderNodeProperties = false;
15032            }
15033        }
15034
15035        int sx = 0;
15036        int sy = 0;
15037        if (!hasDisplayList) {
15038            computeScroll();
15039            sx = mScrollX;
15040            sy = mScrollY;
15041        }
15042
15043        final boolean hasNoCache = cache == null || hasDisplayList;
15044        final boolean offsetForScroll = cache == null && !hasDisplayList &&
15045                layerType != LAYER_TYPE_HARDWARE;
15046
15047        int restoreTo = -1;
15048        if (!usingRenderNodeProperties || transformToApply != null) {
15049            restoreTo = canvas.save();
15050        }
15051        if (offsetForScroll) {
15052            canvas.translate(mLeft - sx, mTop - sy);
15053        } else {
15054            if (!usingRenderNodeProperties) {
15055                canvas.translate(mLeft, mTop);
15056            }
15057            if (scalingRequired) {
15058                if (usingRenderNodeProperties) {
15059                    // TODO: Might not need this if we put everything inside the DL
15060                    restoreTo = canvas.save();
15061                }
15062                // mAttachInfo cannot be null, otherwise scalingRequired == false
15063                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15064                canvas.scale(scale, scale);
15065            }
15066        }
15067
15068        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
15069        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
15070                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15071            if (transformToApply != null || !childHasIdentityMatrix) {
15072                int transX = 0;
15073                int transY = 0;
15074
15075                if (offsetForScroll) {
15076                    transX = -sx;
15077                    transY = -sy;
15078                }
15079
15080                if (transformToApply != null) {
15081                    if (concatMatrix) {
15082                        if (usingRenderNodeProperties) {
15083                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15084                        } else {
15085                            // Undo the scroll translation, apply the transformation matrix,
15086                            // then redo the scroll translate to get the correct result.
15087                            canvas.translate(-transX, -transY);
15088                            canvas.concat(transformToApply.getMatrix());
15089                            canvas.translate(transX, transY);
15090                        }
15091                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15092                    }
15093
15094                    float transformAlpha = transformToApply.getAlpha();
15095                    if (transformAlpha < 1) {
15096                        alpha *= transformAlpha;
15097                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15098                    }
15099                }
15100
15101                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
15102                    canvas.translate(-transX, -transY);
15103                    canvas.concat(getMatrix());
15104                    canvas.translate(transX, transY);
15105                }
15106            }
15107
15108            // Deal with alpha if it is or used to be <1
15109            if (alpha < 1 ||
15110                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
15111                if (alpha < 1) {
15112                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15113                } else {
15114                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15115                }
15116                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15117                if (hasNoCache) {
15118                    final int multipliedAlpha = (int) (255 * alpha);
15119                    if (!onSetAlpha(multipliedAlpha)) {
15120                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15121                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
15122                                layerType != LAYER_TYPE_NONE) {
15123                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
15124                        }
15125                        if (usingRenderNodeProperties) {
15126                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15127                        } else  if (layerType == LAYER_TYPE_NONE) {
15128                            final int scrollX = hasDisplayList ? 0 : sx;
15129                            final int scrollY = hasDisplayList ? 0 : sy;
15130                            canvas.saveLayerAlpha(scrollX, scrollY,
15131                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
15132                                    multipliedAlpha, layerFlags);
15133                        }
15134                    } else {
15135                        // Alpha is handled by the child directly, clobber the layer's alpha
15136                        mPrivateFlags |= PFLAG_ALPHA_SET;
15137                    }
15138                }
15139            }
15140        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15141            onSetAlpha(255);
15142            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15143        }
15144
15145        if (!usingRenderNodeProperties) {
15146            // apply clips directly, since RenderNode won't do it for this draw
15147            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
15148                    && cache == null) {
15149                if (offsetForScroll) {
15150                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
15151                } else {
15152                    if (!scalingRequired || cache == null) {
15153                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
15154                    } else {
15155                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15156                    }
15157                }
15158            }
15159
15160            if (mClipBounds != null) {
15161                // clip bounds ignore scroll
15162                canvas.clipRect(mClipBounds);
15163            }
15164        }
15165
15166
15167
15168        if (!usingRenderNodeProperties && hasDisplayList) {
15169            renderNode = getDisplayList();
15170            if (!renderNode.isValid()) {
15171                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15172                // to getDisplayList(), the display list will be marked invalid and we should not
15173                // try to use it again.
15174                renderNode = null;
15175                hasDisplayList = false;
15176            }
15177        }
15178
15179        if (hasNoCache) {
15180            boolean layerRendered = false;
15181            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
15182                final HardwareLayer layer = getHardwareLayer();
15183                if (layer != null && layer.isValid()) {
15184                    int restoreAlpha = mLayerPaint.getAlpha();
15185                    mLayerPaint.setAlpha((int) (alpha * 255));
15186                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
15187                    mLayerPaint.setAlpha(restoreAlpha);
15188                    layerRendered = true;
15189                } else {
15190                    final int scrollX = hasDisplayList ? 0 : sx;
15191                    final int scrollY = hasDisplayList ? 0 : sy;
15192                    canvas.saveLayer(scrollX, scrollY,
15193                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
15194                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
15195                }
15196            }
15197
15198            if (!layerRendered) {
15199                if (!hasDisplayList) {
15200                    // Fast path for layouts with no backgrounds
15201                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15202                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15203                        dispatchDraw(canvas);
15204                    } else {
15205                        draw(canvas);
15206                    }
15207                } else {
15208                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15209                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
15210                }
15211            }
15212        } else if (cache != null) {
15213            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15214            Paint cachePaint;
15215            int restoreAlpha = 0;
15216
15217            if (layerType == LAYER_TYPE_NONE) {
15218                cachePaint = parent.mCachePaint;
15219                if (cachePaint == null) {
15220                    cachePaint = new Paint();
15221                    cachePaint.setDither(false);
15222                    parent.mCachePaint = cachePaint;
15223                }
15224            } else {
15225                cachePaint = mLayerPaint;
15226                restoreAlpha = mLayerPaint.getAlpha();
15227            }
15228            cachePaint.setAlpha((int) (alpha * 255));
15229            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15230            cachePaint.setAlpha(restoreAlpha);
15231        }
15232
15233        if (restoreTo >= 0) {
15234            canvas.restoreToCount(restoreTo);
15235        }
15236
15237        if (a != null && !more) {
15238            if (!hardwareAccelerated && !a.getFillAfter()) {
15239                onSetAlpha(255);
15240            }
15241            parent.finishAnimatingView(this, a);
15242        }
15243
15244        if (more && hardwareAccelerated) {
15245            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15246                // alpha animations should cause the child to recreate its display list
15247                invalidate(true);
15248            }
15249        }
15250
15251        mRecreateDisplayList = false;
15252
15253        return more;
15254    }
15255
15256    /**
15257     * Manually render this view (and all of its children) to the given Canvas.
15258     * The view must have already done a full layout before this function is
15259     * called.  When implementing a view, implement
15260     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15261     * If you do need to override this method, call the superclass version.
15262     *
15263     * @param canvas The Canvas to which the View is rendered.
15264     */
15265    public void draw(Canvas canvas) {
15266        final int privateFlags = mPrivateFlags;
15267        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15268                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15269        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15270
15271        /*
15272         * Draw traversal performs several drawing steps which must be executed
15273         * in the appropriate order:
15274         *
15275         *      1. Draw the background
15276         *      2. If necessary, save the canvas' layers to prepare for fading
15277         *      3. Draw view's content
15278         *      4. Draw children
15279         *      5. If necessary, draw the fading edges and restore layers
15280         *      6. Draw decorations (scrollbars for instance)
15281         */
15282
15283        // Step 1, draw the background, if needed
15284        int saveCount;
15285
15286        if (!dirtyOpaque) {
15287            drawBackground(canvas);
15288        }
15289
15290        // skip step 2 & 5 if possible (common case)
15291        final int viewFlags = mViewFlags;
15292        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15293        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15294        if (!verticalEdges && !horizontalEdges) {
15295            // Step 3, draw the content
15296            if (!dirtyOpaque) onDraw(canvas);
15297
15298            // Step 4, draw the children
15299            dispatchDraw(canvas);
15300
15301            // Step 6, draw decorations (scrollbars)
15302            onDrawScrollBars(canvas);
15303
15304            if (mOverlay != null && !mOverlay.isEmpty()) {
15305                mOverlay.getOverlayView().dispatchDraw(canvas);
15306            }
15307
15308            // we're done...
15309            return;
15310        }
15311
15312        /*
15313         * Here we do the full fledged routine...
15314         * (this is an uncommon case where speed matters less,
15315         * this is why we repeat some of the tests that have been
15316         * done above)
15317         */
15318
15319        boolean drawTop = false;
15320        boolean drawBottom = false;
15321        boolean drawLeft = false;
15322        boolean drawRight = false;
15323
15324        float topFadeStrength = 0.0f;
15325        float bottomFadeStrength = 0.0f;
15326        float leftFadeStrength = 0.0f;
15327        float rightFadeStrength = 0.0f;
15328
15329        // Step 2, save the canvas' layers
15330        int paddingLeft = mPaddingLeft;
15331
15332        final boolean offsetRequired = isPaddingOffsetRequired();
15333        if (offsetRequired) {
15334            paddingLeft += getLeftPaddingOffset();
15335        }
15336
15337        int left = mScrollX + paddingLeft;
15338        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15339        int top = mScrollY + getFadeTop(offsetRequired);
15340        int bottom = top + getFadeHeight(offsetRequired);
15341
15342        if (offsetRequired) {
15343            right += getRightPaddingOffset();
15344            bottom += getBottomPaddingOffset();
15345        }
15346
15347        final ScrollabilityCache scrollabilityCache = mScrollCache;
15348        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15349        int length = (int) fadeHeight;
15350
15351        // clip the fade length if top and bottom fades overlap
15352        // overlapping fades produce odd-looking artifacts
15353        if (verticalEdges && (top + length > bottom - length)) {
15354            length = (bottom - top) / 2;
15355        }
15356
15357        // also clip horizontal fades if necessary
15358        if (horizontalEdges && (left + length > right - length)) {
15359            length = (right - left) / 2;
15360        }
15361
15362        if (verticalEdges) {
15363            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15364            drawTop = topFadeStrength * fadeHeight > 1.0f;
15365            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15366            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15367        }
15368
15369        if (horizontalEdges) {
15370            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15371            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15372            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15373            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15374        }
15375
15376        saveCount = canvas.getSaveCount();
15377
15378        int solidColor = getSolidColor();
15379        if (solidColor == 0) {
15380            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15381
15382            if (drawTop) {
15383                canvas.saveLayer(left, top, right, top + length, null, flags);
15384            }
15385
15386            if (drawBottom) {
15387                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15388            }
15389
15390            if (drawLeft) {
15391                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15392            }
15393
15394            if (drawRight) {
15395                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15396            }
15397        } else {
15398            scrollabilityCache.setFadeColor(solidColor);
15399        }
15400
15401        // Step 3, draw the content
15402        if (!dirtyOpaque) onDraw(canvas);
15403
15404        // Step 4, draw the children
15405        dispatchDraw(canvas);
15406
15407        // Step 5, draw the fade effect and restore layers
15408        final Paint p = scrollabilityCache.paint;
15409        final Matrix matrix = scrollabilityCache.matrix;
15410        final Shader fade = scrollabilityCache.shader;
15411
15412        if (drawTop) {
15413            matrix.setScale(1, fadeHeight * topFadeStrength);
15414            matrix.postTranslate(left, top);
15415            fade.setLocalMatrix(matrix);
15416            p.setShader(fade);
15417            canvas.drawRect(left, top, right, top + length, p);
15418        }
15419
15420        if (drawBottom) {
15421            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15422            matrix.postRotate(180);
15423            matrix.postTranslate(left, bottom);
15424            fade.setLocalMatrix(matrix);
15425            p.setShader(fade);
15426            canvas.drawRect(left, bottom - length, right, bottom, p);
15427        }
15428
15429        if (drawLeft) {
15430            matrix.setScale(1, fadeHeight * leftFadeStrength);
15431            matrix.postRotate(-90);
15432            matrix.postTranslate(left, top);
15433            fade.setLocalMatrix(matrix);
15434            p.setShader(fade);
15435            canvas.drawRect(left, top, left + length, bottom, p);
15436        }
15437
15438        if (drawRight) {
15439            matrix.setScale(1, fadeHeight * rightFadeStrength);
15440            matrix.postRotate(90);
15441            matrix.postTranslate(right, top);
15442            fade.setLocalMatrix(matrix);
15443            p.setShader(fade);
15444            canvas.drawRect(right - length, top, right, bottom, p);
15445        }
15446
15447        canvas.restoreToCount(saveCount);
15448
15449        // Step 6, draw decorations (scrollbars)
15450        onDrawScrollBars(canvas);
15451
15452        if (mOverlay != null && !mOverlay.isEmpty()) {
15453            mOverlay.getOverlayView().dispatchDraw(canvas);
15454        }
15455    }
15456
15457    /**
15458     * Draws the background onto the specified canvas.
15459     *
15460     * @param canvas Canvas on which to draw the background
15461     */
15462    private void drawBackground(Canvas canvas) {
15463        final Drawable background = mBackground;
15464        if (background == null) {
15465            return;
15466        }
15467
15468        if (mBackgroundSizeChanged) {
15469            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15470            mBackgroundSizeChanged = false;
15471            rebuildOutline();
15472        }
15473
15474        // Attempt to use a display list if requested.
15475        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15476                && mAttachInfo.mHardwareRenderer != null) {
15477            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15478
15479            final RenderNode displayList = mBackgroundRenderNode;
15480            if (displayList != null && displayList.isValid()) {
15481                setBackgroundDisplayListProperties(displayList);
15482                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15483                return;
15484            }
15485        }
15486
15487        final int scrollX = mScrollX;
15488        final int scrollY = mScrollY;
15489        if ((scrollX | scrollY) == 0) {
15490            background.draw(canvas);
15491        } else {
15492            canvas.translate(scrollX, scrollY);
15493            background.draw(canvas);
15494            canvas.translate(-scrollX, -scrollY);
15495        }
15496    }
15497
15498    /**
15499     * Set up background drawable display list properties.
15500     *
15501     * @param displayList Valid display list for the background drawable
15502     */
15503    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15504        displayList.setTranslationX(mScrollX);
15505        displayList.setTranslationY(mScrollY);
15506    }
15507
15508    /**
15509     * Creates a new display list or updates the existing display list for the
15510     * specified Drawable.
15511     *
15512     * @param drawable Drawable for which to create a display list
15513     * @param renderNode Existing RenderNode, or {@code null}
15514     * @return A valid display list for the specified drawable
15515     */
15516    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15517        if (renderNode == null) {
15518            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15519        }
15520
15521        final Rect bounds = drawable.getBounds();
15522        final int width = bounds.width();
15523        final int height = bounds.height();
15524        final HardwareCanvas canvas = renderNode.start(width, height);
15525        try {
15526            drawable.draw(canvas);
15527        } finally {
15528            renderNode.end(canvas);
15529        }
15530
15531        // Set up drawable properties that are view-independent.
15532        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15533        renderNode.setProjectBackwards(drawable.isProjected());
15534        renderNode.setProjectionReceiver(true);
15535        renderNode.setClipToBounds(false);
15536        return renderNode;
15537    }
15538
15539    /**
15540     * Returns the overlay for this view, creating it if it does not yet exist.
15541     * Adding drawables to the overlay will cause them to be displayed whenever
15542     * the view itself is redrawn. Objects in the overlay should be actively
15543     * managed: remove them when they should not be displayed anymore. The
15544     * overlay will always have the same size as its host view.
15545     *
15546     * <p>Note: Overlays do not currently work correctly with {@link
15547     * SurfaceView} or {@link TextureView}; contents in overlays for these
15548     * types of views may not display correctly.</p>
15549     *
15550     * @return The ViewOverlay object for this view.
15551     * @see ViewOverlay
15552     */
15553    public ViewOverlay getOverlay() {
15554        if (mOverlay == null) {
15555            mOverlay = new ViewOverlay(mContext, this);
15556        }
15557        return mOverlay;
15558    }
15559
15560    /**
15561     * Override this if your view is known to always be drawn on top of a solid color background,
15562     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15563     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15564     * should be set to 0xFF.
15565     *
15566     * @see #setVerticalFadingEdgeEnabled(boolean)
15567     * @see #setHorizontalFadingEdgeEnabled(boolean)
15568     *
15569     * @return The known solid color background for this view, or 0 if the color may vary
15570     */
15571    @ViewDebug.ExportedProperty(category = "drawing")
15572    public int getSolidColor() {
15573        return 0;
15574    }
15575
15576    /**
15577     * Build a human readable string representation of the specified view flags.
15578     *
15579     * @param flags the view flags to convert to a string
15580     * @return a String representing the supplied flags
15581     */
15582    private static String printFlags(int flags) {
15583        String output = "";
15584        int numFlags = 0;
15585        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15586            output += "TAKES_FOCUS";
15587            numFlags++;
15588        }
15589
15590        switch (flags & VISIBILITY_MASK) {
15591        case INVISIBLE:
15592            if (numFlags > 0) {
15593                output += " ";
15594            }
15595            output += "INVISIBLE";
15596            // USELESS HERE numFlags++;
15597            break;
15598        case GONE:
15599            if (numFlags > 0) {
15600                output += " ";
15601            }
15602            output += "GONE";
15603            // USELESS HERE numFlags++;
15604            break;
15605        default:
15606            break;
15607        }
15608        return output;
15609    }
15610
15611    /**
15612     * Build a human readable string representation of the specified private
15613     * view flags.
15614     *
15615     * @param privateFlags the private view flags to convert to a string
15616     * @return a String representing the supplied flags
15617     */
15618    private static String printPrivateFlags(int privateFlags) {
15619        String output = "";
15620        int numFlags = 0;
15621
15622        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15623            output += "WANTS_FOCUS";
15624            numFlags++;
15625        }
15626
15627        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15628            if (numFlags > 0) {
15629                output += " ";
15630            }
15631            output += "FOCUSED";
15632            numFlags++;
15633        }
15634
15635        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15636            if (numFlags > 0) {
15637                output += " ";
15638            }
15639            output += "SELECTED";
15640            numFlags++;
15641        }
15642
15643        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15644            if (numFlags > 0) {
15645                output += " ";
15646            }
15647            output += "IS_ROOT_NAMESPACE";
15648            numFlags++;
15649        }
15650
15651        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15652            if (numFlags > 0) {
15653                output += " ";
15654            }
15655            output += "HAS_BOUNDS";
15656            numFlags++;
15657        }
15658
15659        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15660            if (numFlags > 0) {
15661                output += " ";
15662            }
15663            output += "DRAWN";
15664            // USELESS HERE numFlags++;
15665        }
15666        return output;
15667    }
15668
15669    /**
15670     * <p>Indicates whether or not this view's layout will be requested during
15671     * the next hierarchy layout pass.</p>
15672     *
15673     * @return true if the layout will be forced during next layout pass
15674     */
15675    public boolean isLayoutRequested() {
15676        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15677    }
15678
15679    /**
15680     * Return true if o is a ViewGroup that is laying out using optical bounds.
15681     * @hide
15682     */
15683    public static boolean isLayoutModeOptical(Object o) {
15684        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15685    }
15686
15687    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15688        Insets parentInsets = mParent instanceof View ?
15689                ((View) mParent).getOpticalInsets() : Insets.NONE;
15690        Insets childInsets = getOpticalInsets();
15691        return setFrame(
15692                left   + parentInsets.left - childInsets.left,
15693                top    + parentInsets.top  - childInsets.top,
15694                right  + parentInsets.left + childInsets.right,
15695                bottom + parentInsets.top  + childInsets.bottom);
15696    }
15697
15698    /**
15699     * Assign a size and position to a view and all of its
15700     * descendants
15701     *
15702     * <p>This is the second phase of the layout mechanism.
15703     * (The first is measuring). In this phase, each parent calls
15704     * layout on all of its children to position them.
15705     * This is typically done using the child measurements
15706     * that were stored in the measure pass().</p>
15707     *
15708     * <p>Derived classes should not override this method.
15709     * Derived classes with children should override
15710     * onLayout. In that method, they should
15711     * call layout on each of their children.</p>
15712     *
15713     * @param l Left position, relative to parent
15714     * @param t Top position, relative to parent
15715     * @param r Right position, relative to parent
15716     * @param b Bottom position, relative to parent
15717     */
15718    @SuppressWarnings({"unchecked"})
15719    public void layout(int l, int t, int r, int b) {
15720        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15721            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15722            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15723        }
15724
15725        int oldL = mLeft;
15726        int oldT = mTop;
15727        int oldB = mBottom;
15728        int oldR = mRight;
15729
15730        boolean changed = isLayoutModeOptical(mParent) ?
15731                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15732
15733        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15734            onLayout(changed, l, t, r, b);
15735            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15736
15737            ListenerInfo li = mListenerInfo;
15738            if (li != null && li.mOnLayoutChangeListeners != null) {
15739                ArrayList<OnLayoutChangeListener> listenersCopy =
15740                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15741                int numListeners = listenersCopy.size();
15742                for (int i = 0; i < numListeners; ++i) {
15743                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15744                }
15745            }
15746        }
15747
15748        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15749        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15750    }
15751
15752    /**
15753     * Called from layout when this view should
15754     * assign a size and position to each of its children.
15755     *
15756     * Derived classes with children should override
15757     * this method and call layout on each of
15758     * their children.
15759     * @param changed This is a new size or position for this view
15760     * @param left Left position, relative to parent
15761     * @param top Top position, relative to parent
15762     * @param right Right position, relative to parent
15763     * @param bottom Bottom position, relative to parent
15764     */
15765    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15766    }
15767
15768    /**
15769     * Assign a size and position to this view.
15770     *
15771     * This is called from layout.
15772     *
15773     * @param left Left position, relative to parent
15774     * @param top Top position, relative to parent
15775     * @param right Right position, relative to parent
15776     * @param bottom Bottom position, relative to parent
15777     * @return true if the new size and position are different than the
15778     *         previous ones
15779     * {@hide}
15780     */
15781    protected boolean setFrame(int left, int top, int right, int bottom) {
15782        boolean changed = false;
15783
15784        if (DBG) {
15785            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15786                    + right + "," + bottom + ")");
15787        }
15788
15789        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15790            changed = true;
15791
15792            // Remember our drawn bit
15793            int drawn = mPrivateFlags & PFLAG_DRAWN;
15794
15795            int oldWidth = mRight - mLeft;
15796            int oldHeight = mBottom - mTop;
15797            int newWidth = right - left;
15798            int newHeight = bottom - top;
15799            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15800
15801            // Invalidate our old position
15802            invalidate(sizeChanged);
15803
15804            mLeft = left;
15805            mTop = top;
15806            mRight = right;
15807            mBottom = bottom;
15808            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15809
15810            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15811
15812
15813            if (sizeChanged) {
15814                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15815            }
15816
15817            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
15818                // If we are visible, force the DRAWN bit to on so that
15819                // this invalidate will go through (at least to our parent).
15820                // This is because someone may have invalidated this view
15821                // before this call to setFrame came in, thereby clearing
15822                // the DRAWN bit.
15823                mPrivateFlags |= PFLAG_DRAWN;
15824                invalidate(sizeChanged);
15825                // parent display list may need to be recreated based on a change in the bounds
15826                // of any child
15827                invalidateParentCaches();
15828            }
15829
15830            // Reset drawn bit to original value (invalidate turns it off)
15831            mPrivateFlags |= drawn;
15832
15833            mBackgroundSizeChanged = true;
15834
15835            notifySubtreeAccessibilityStateChangedIfNeeded();
15836        }
15837        return changed;
15838    }
15839
15840    /**
15841     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
15842     * @hide
15843     */
15844    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
15845        setFrame(left, top, right, bottom);
15846    }
15847
15848    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15849        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15850        if (mOverlay != null) {
15851            mOverlay.getOverlayView().setRight(newWidth);
15852            mOverlay.getOverlayView().setBottom(newHeight);
15853        }
15854        rebuildOutline();
15855    }
15856
15857    /**
15858     * Finalize inflating a view from XML.  This is called as the last phase
15859     * of inflation, after all child views have been added.
15860     *
15861     * <p>Even if the subclass overrides onFinishInflate, they should always be
15862     * sure to call the super method, so that we get called.
15863     */
15864    protected void onFinishInflate() {
15865    }
15866
15867    /**
15868     * Returns the resources associated with this view.
15869     *
15870     * @return Resources object.
15871     */
15872    public Resources getResources() {
15873        return mResources;
15874    }
15875
15876    /**
15877     * Invalidates the specified Drawable.
15878     *
15879     * @param drawable the drawable to invalidate
15880     */
15881    @Override
15882    public void invalidateDrawable(@NonNull Drawable drawable) {
15883        if (verifyDrawable(drawable)) {
15884            final Rect dirty = drawable.getDirtyBounds();
15885            final int scrollX = mScrollX;
15886            final int scrollY = mScrollY;
15887
15888            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15889                    dirty.right + scrollX, dirty.bottom + scrollY);
15890            rebuildOutline();
15891        }
15892    }
15893
15894    /**
15895     * Schedules an action on a drawable to occur at a specified time.
15896     *
15897     * @param who the recipient of the action
15898     * @param what the action to run on the drawable
15899     * @param when the time at which the action must occur. Uses the
15900     *        {@link SystemClock#uptimeMillis} timebase.
15901     */
15902    @Override
15903    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15904        if (verifyDrawable(who) && what != null) {
15905            final long delay = when - SystemClock.uptimeMillis();
15906            if (mAttachInfo != null) {
15907                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15908                        Choreographer.CALLBACK_ANIMATION, what, who,
15909                        Choreographer.subtractFrameDelay(delay));
15910            } else {
15911                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15912            }
15913        }
15914    }
15915
15916    /**
15917     * Cancels a scheduled action on a drawable.
15918     *
15919     * @param who the recipient of the action
15920     * @param what the action to cancel
15921     */
15922    @Override
15923    public void unscheduleDrawable(Drawable who, Runnable what) {
15924        if (verifyDrawable(who) && what != null) {
15925            if (mAttachInfo != null) {
15926                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15927                        Choreographer.CALLBACK_ANIMATION, what, who);
15928            }
15929            ViewRootImpl.getRunQueue().removeCallbacks(what);
15930        }
15931    }
15932
15933    /**
15934     * Unschedule any events associated with the given Drawable.  This can be
15935     * used when selecting a new Drawable into a view, so that the previous
15936     * one is completely unscheduled.
15937     *
15938     * @param who The Drawable to unschedule.
15939     *
15940     * @see #drawableStateChanged
15941     */
15942    public void unscheduleDrawable(Drawable who) {
15943        if (mAttachInfo != null && who != null) {
15944            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15945                    Choreographer.CALLBACK_ANIMATION, null, who);
15946        }
15947    }
15948
15949    /**
15950     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15951     * that the View directionality can and will be resolved before its Drawables.
15952     *
15953     * Will call {@link View#onResolveDrawables} when resolution is done.
15954     *
15955     * @hide
15956     */
15957    protected void resolveDrawables() {
15958        // Drawables resolution may need to happen before resolving the layout direction (which is
15959        // done only during the measure() call).
15960        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15961        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15962        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15963        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15964        // direction to be resolved as its resolved value will be the same as its raw value.
15965        if (!isLayoutDirectionResolved() &&
15966                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15967            return;
15968        }
15969
15970        final int layoutDirection = isLayoutDirectionResolved() ?
15971                getLayoutDirection() : getRawLayoutDirection();
15972
15973        if (mBackground != null) {
15974            mBackground.setLayoutDirection(layoutDirection);
15975        }
15976        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15977        onResolveDrawables(layoutDirection);
15978    }
15979
15980    boolean areDrawablesResolved() {
15981        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15982    }
15983
15984    /**
15985     * Called when layout direction has been resolved.
15986     *
15987     * The default implementation does nothing.
15988     *
15989     * @param layoutDirection The resolved layout direction.
15990     *
15991     * @see #LAYOUT_DIRECTION_LTR
15992     * @see #LAYOUT_DIRECTION_RTL
15993     *
15994     * @hide
15995     */
15996    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15997    }
15998
15999    /**
16000     * @hide
16001     */
16002    protected void resetResolvedDrawables() {
16003        resetResolvedDrawablesInternal();
16004    }
16005
16006    void resetResolvedDrawablesInternal() {
16007        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16008    }
16009
16010    /**
16011     * If your view subclass is displaying its own Drawable objects, it should
16012     * override this function and return true for any Drawable it is
16013     * displaying.  This allows animations for those drawables to be
16014     * scheduled.
16015     *
16016     * <p>Be sure to call through to the super class when overriding this
16017     * function.
16018     *
16019     * @param who The Drawable to verify.  Return true if it is one you are
16020     *            displaying, else return the result of calling through to the
16021     *            super class.
16022     *
16023     * @return boolean If true than the Drawable is being displayed in the
16024     *         view; else false and it is not allowed to animate.
16025     *
16026     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16027     * @see #drawableStateChanged()
16028     */
16029    protected boolean verifyDrawable(Drawable who) {
16030        return who == mBackground;
16031    }
16032
16033    /**
16034     * This function is called whenever the state of the view changes in such
16035     * a way that it impacts the state of drawables being shown.
16036     * <p>
16037     * If the View has a StateListAnimator, it will also be called to run necessary state
16038     * change animations.
16039     * <p>
16040     * Be sure to call through to the superclass when overriding this function.
16041     *
16042     * @see Drawable#setState(int[])
16043     */
16044    protected void drawableStateChanged() {
16045        final Drawable d = mBackground;
16046        if (d != null && d.isStateful()) {
16047            d.setState(getDrawableState());
16048        }
16049
16050        if (mStateListAnimator != null) {
16051            mStateListAnimator.setState(getDrawableState());
16052        }
16053    }
16054
16055    /**
16056     * This function is called whenever the view hotspot changes and needs to
16057     * be propagated to drawables managed by the view.
16058     * <p>
16059     * Be sure to call through to the superclass when overriding this function.
16060     *
16061     * @param x hotspot x coordinate
16062     * @param y hotspot y coordinate
16063     */
16064    public void drawableHotspotChanged(float x, float y) {
16065        if (mBackground != null) {
16066            mBackground.setHotspot(x, y);
16067        }
16068    }
16069
16070    /**
16071     * Call this to force a view to update its drawable state. This will cause
16072     * drawableStateChanged to be called on this view. Views that are interested
16073     * in the new state should call getDrawableState.
16074     *
16075     * @see #drawableStateChanged
16076     * @see #getDrawableState
16077     */
16078    public void refreshDrawableState() {
16079        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16080        drawableStateChanged();
16081
16082        ViewParent parent = mParent;
16083        if (parent != null) {
16084            parent.childDrawableStateChanged(this);
16085        }
16086    }
16087
16088    /**
16089     * Return an array of resource IDs of the drawable states representing the
16090     * current state of the view.
16091     *
16092     * @return The current drawable state
16093     *
16094     * @see Drawable#setState(int[])
16095     * @see #drawableStateChanged()
16096     * @see #onCreateDrawableState(int)
16097     */
16098    public final int[] getDrawableState() {
16099        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16100            return mDrawableState;
16101        } else {
16102            mDrawableState = onCreateDrawableState(0);
16103            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16104            return mDrawableState;
16105        }
16106    }
16107
16108    /**
16109     * Generate the new {@link android.graphics.drawable.Drawable} state for
16110     * this view. This is called by the view
16111     * system when the cached Drawable state is determined to be invalid.  To
16112     * retrieve the current state, you should use {@link #getDrawableState}.
16113     *
16114     * @param extraSpace if non-zero, this is the number of extra entries you
16115     * would like in the returned array in which you can place your own
16116     * states.
16117     *
16118     * @return Returns an array holding the current {@link Drawable} state of
16119     * the view.
16120     *
16121     * @see #mergeDrawableStates(int[], int[])
16122     */
16123    protected int[] onCreateDrawableState(int extraSpace) {
16124        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16125                mParent instanceof View) {
16126            return ((View) mParent).onCreateDrawableState(extraSpace);
16127        }
16128
16129        int[] drawableState;
16130
16131        int privateFlags = mPrivateFlags;
16132
16133        int viewStateIndex = 0;
16134        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
16135        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
16136        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
16137        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
16138        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
16139        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
16140        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16141                HardwareRenderer.isAvailable()) {
16142            // This is set if HW acceleration is requested, even if the current
16143            // process doesn't allow it.  This is just to allow app preview
16144            // windows to better match their app.
16145            viewStateIndex |= VIEW_STATE_ACCELERATED;
16146        }
16147        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
16148
16149        final int privateFlags2 = mPrivateFlags2;
16150        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
16151        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
16152
16153        drawableState = VIEW_STATE_SETS[viewStateIndex];
16154
16155        //noinspection ConstantIfStatement
16156        if (false) {
16157            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16158            Log.i("View", toString()
16159                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16160                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16161                    + " fo=" + hasFocus()
16162                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16163                    + " wf=" + hasWindowFocus()
16164                    + ": " + Arrays.toString(drawableState));
16165        }
16166
16167        if (extraSpace == 0) {
16168            return drawableState;
16169        }
16170
16171        final int[] fullState;
16172        if (drawableState != null) {
16173            fullState = new int[drawableState.length + extraSpace];
16174            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16175        } else {
16176            fullState = new int[extraSpace];
16177        }
16178
16179        return fullState;
16180    }
16181
16182    /**
16183     * Merge your own state values in <var>additionalState</var> into the base
16184     * state values <var>baseState</var> that were returned by
16185     * {@link #onCreateDrawableState(int)}.
16186     *
16187     * @param baseState The base state values returned by
16188     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16189     * own additional state values.
16190     *
16191     * @param additionalState The additional state values you would like
16192     * added to <var>baseState</var>; this array is not modified.
16193     *
16194     * @return As a convenience, the <var>baseState</var> array you originally
16195     * passed into the function is returned.
16196     *
16197     * @see #onCreateDrawableState(int)
16198     */
16199    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16200        final int N = baseState.length;
16201        int i = N - 1;
16202        while (i >= 0 && baseState[i] == 0) {
16203            i--;
16204        }
16205        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16206        return baseState;
16207    }
16208
16209    /**
16210     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16211     * on all Drawable objects associated with this view.
16212     * <p>
16213     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16214     * attached to this view.
16215     */
16216    public void jumpDrawablesToCurrentState() {
16217        if (mBackground != null) {
16218            mBackground.jumpToCurrentState();
16219        }
16220        if (mStateListAnimator != null) {
16221            mStateListAnimator.jumpToCurrentState();
16222        }
16223    }
16224
16225    /**
16226     * Sets the background color for this view.
16227     * @param color the color of the background
16228     */
16229    @RemotableViewMethod
16230    public void setBackgroundColor(int color) {
16231        if (mBackground instanceof ColorDrawable) {
16232            ((ColorDrawable) mBackground.mutate()).setColor(color);
16233            computeOpaqueFlags();
16234            mBackgroundResource = 0;
16235        } else {
16236            setBackground(new ColorDrawable(color));
16237        }
16238    }
16239
16240    /**
16241     * Set the background to a given resource. The resource should refer to
16242     * a Drawable object or 0 to remove the background.
16243     * @param resid The identifier of the resource.
16244     *
16245     * @attr ref android.R.styleable#View_background
16246     */
16247    @RemotableViewMethod
16248    public void setBackgroundResource(int resid) {
16249        if (resid != 0 && resid == mBackgroundResource) {
16250            return;
16251        }
16252
16253        Drawable d = null;
16254        if (resid != 0) {
16255            d = mContext.getDrawable(resid);
16256        }
16257        setBackground(d);
16258
16259        mBackgroundResource = resid;
16260    }
16261
16262    /**
16263     * Set the background to a given Drawable, or remove the background. If the
16264     * background has padding, this View's padding is set to the background's
16265     * padding. However, when a background is removed, this View's padding isn't
16266     * touched. If setting the padding is desired, please use
16267     * {@link #setPadding(int, int, int, int)}.
16268     *
16269     * @param background The Drawable to use as the background, or null to remove the
16270     *        background
16271     */
16272    public void setBackground(Drawable background) {
16273        //noinspection deprecation
16274        setBackgroundDrawable(background);
16275    }
16276
16277    /**
16278     * @deprecated use {@link #setBackground(Drawable)} instead
16279     */
16280    @Deprecated
16281    public void setBackgroundDrawable(Drawable background) {
16282        computeOpaqueFlags();
16283
16284        if (background == mBackground) {
16285            return;
16286        }
16287
16288        boolean requestLayout = false;
16289
16290        mBackgroundResource = 0;
16291
16292        /*
16293         * Regardless of whether we're setting a new background or not, we want
16294         * to clear the previous drawable.
16295         */
16296        if (mBackground != null) {
16297            mBackground.setCallback(null);
16298            unscheduleDrawable(mBackground);
16299        }
16300
16301        if (background != null) {
16302            Rect padding = sThreadLocal.get();
16303            if (padding == null) {
16304                padding = new Rect();
16305                sThreadLocal.set(padding);
16306            }
16307            resetResolvedDrawablesInternal();
16308            background.setLayoutDirection(getLayoutDirection());
16309            if (background.getPadding(padding)) {
16310                resetResolvedPaddingInternal();
16311                switch (background.getLayoutDirection()) {
16312                    case LAYOUT_DIRECTION_RTL:
16313                        mUserPaddingLeftInitial = padding.right;
16314                        mUserPaddingRightInitial = padding.left;
16315                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16316                        break;
16317                    case LAYOUT_DIRECTION_LTR:
16318                    default:
16319                        mUserPaddingLeftInitial = padding.left;
16320                        mUserPaddingRightInitial = padding.right;
16321                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16322                }
16323                mLeftPaddingDefined = false;
16324                mRightPaddingDefined = false;
16325            }
16326
16327            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16328            // if it has a different minimum size, we should layout again
16329            if (mBackground == null
16330                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16331                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16332                requestLayout = true;
16333            }
16334
16335            background.setCallback(this);
16336            if (background.isStateful()) {
16337                background.setState(getDrawableState());
16338            }
16339            background.setVisible(getVisibility() == VISIBLE, false);
16340            mBackground = background;
16341
16342            applyBackgroundTint();
16343
16344            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16345                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16346                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16347                requestLayout = true;
16348            }
16349        } else {
16350            /* Remove the background */
16351            mBackground = null;
16352
16353            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16354                /*
16355                 * This view ONLY drew the background before and we're removing
16356                 * the background, so now it won't draw anything
16357                 * (hence we SKIP_DRAW)
16358                 */
16359                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16360                mPrivateFlags |= PFLAG_SKIP_DRAW;
16361            }
16362
16363            /*
16364             * When the background is set, we try to apply its padding to this
16365             * View. When the background is removed, we don't touch this View's
16366             * padding. This is noted in the Javadocs. Hence, we don't need to
16367             * requestLayout(), the invalidate() below is sufficient.
16368             */
16369
16370            // The old background's minimum size could have affected this
16371            // View's layout, so let's requestLayout
16372            requestLayout = true;
16373        }
16374
16375        computeOpaqueFlags();
16376
16377        if (requestLayout) {
16378            requestLayout();
16379        }
16380
16381        mBackgroundSizeChanged = true;
16382        invalidate(true);
16383    }
16384
16385    /**
16386     * Gets the background drawable
16387     *
16388     * @return The drawable used as the background for this view, if any.
16389     *
16390     * @see #setBackground(Drawable)
16391     *
16392     * @attr ref android.R.styleable#View_background
16393     */
16394    public Drawable getBackground() {
16395        return mBackground;
16396    }
16397
16398    /**
16399     * Applies a tint to the background drawable. Does not modify the current tint
16400     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16401     * <p>
16402     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16403     * mutate the drawable and apply the specified tint and tint mode using
16404     * {@link Drawable#setTintList(ColorStateList)}.
16405     *
16406     * @param tint the tint to apply, may be {@code null} to clear tint
16407     *
16408     * @attr ref android.R.styleable#View_backgroundTint
16409     * @see #getBackgroundTintList()
16410     * @see Drawable#setTintList(ColorStateList)
16411     */
16412    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16413        if (mBackgroundTint == null) {
16414            mBackgroundTint = new TintInfo();
16415        }
16416        mBackgroundTint.mTintList = tint;
16417        mBackgroundTint.mHasTintList = true;
16418
16419        applyBackgroundTint();
16420    }
16421
16422    /**
16423     * Return the tint applied to the background drawable, if specified.
16424     *
16425     * @return the tint applied to the background drawable
16426     * @attr ref android.R.styleable#View_backgroundTint
16427     * @see #setBackgroundTintList(ColorStateList)
16428     */
16429    @Nullable
16430    public ColorStateList getBackgroundTintList() {
16431        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16432    }
16433
16434    /**
16435     * Specifies the blending mode used to apply the tint specified by
16436     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16437     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16438     *
16439     * @param tintMode the blending mode used to apply the tint, may be
16440     *                 {@code null} to clear tint
16441     * @attr ref android.R.styleable#View_backgroundTintMode
16442     * @see #getBackgroundTintMode()
16443     * @see Drawable#setTintMode(PorterDuff.Mode)
16444     */
16445    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16446        if (mBackgroundTint == null) {
16447            mBackgroundTint = new TintInfo();
16448        }
16449        mBackgroundTint.mTintMode = tintMode;
16450        mBackgroundTint.mHasTintMode = true;
16451
16452        applyBackgroundTint();
16453    }
16454
16455    /**
16456     * Return the blending mode used to apply the tint to the background
16457     * drawable, if specified.
16458     *
16459     * @return the blending mode used to apply the tint to the background
16460     *         drawable
16461     * @attr ref android.R.styleable#View_backgroundTintMode
16462     * @see #setBackgroundTintMode(PorterDuff.Mode)
16463     */
16464    @Nullable
16465    public PorterDuff.Mode getBackgroundTintMode() {
16466        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16467    }
16468
16469    private void applyBackgroundTint() {
16470        if (mBackground != null && mBackgroundTint != null) {
16471            final TintInfo tintInfo = mBackgroundTint;
16472            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16473                mBackground = mBackground.mutate();
16474
16475                if (tintInfo.mHasTintList) {
16476                    mBackground.setTintList(tintInfo.mTintList);
16477                }
16478
16479                if (tintInfo.mHasTintMode) {
16480                    mBackground.setTintMode(tintInfo.mTintMode);
16481                }
16482
16483                // The drawable (or one of its children) may not have been
16484                // stateful before applying the tint, so let's try again.
16485                if (mBackground.isStateful()) {
16486                    mBackground.setState(getDrawableState());
16487                }
16488            }
16489        }
16490    }
16491
16492    /**
16493     * Sets the padding. The view may add on the space required to display
16494     * the scrollbars, depending on the style and visibility of the scrollbars.
16495     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16496     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16497     * from the values set in this call.
16498     *
16499     * @attr ref android.R.styleable#View_padding
16500     * @attr ref android.R.styleable#View_paddingBottom
16501     * @attr ref android.R.styleable#View_paddingLeft
16502     * @attr ref android.R.styleable#View_paddingRight
16503     * @attr ref android.R.styleable#View_paddingTop
16504     * @param left the left padding in pixels
16505     * @param top the top padding in pixels
16506     * @param right the right padding in pixels
16507     * @param bottom the bottom padding in pixels
16508     */
16509    public void setPadding(int left, int top, int right, int bottom) {
16510        resetResolvedPaddingInternal();
16511
16512        mUserPaddingStart = UNDEFINED_PADDING;
16513        mUserPaddingEnd = UNDEFINED_PADDING;
16514
16515        mUserPaddingLeftInitial = left;
16516        mUserPaddingRightInitial = right;
16517
16518        mLeftPaddingDefined = true;
16519        mRightPaddingDefined = true;
16520
16521        internalSetPadding(left, top, right, bottom);
16522    }
16523
16524    /**
16525     * @hide
16526     */
16527    protected void internalSetPadding(int left, int top, int right, int bottom) {
16528        mUserPaddingLeft = left;
16529        mUserPaddingRight = right;
16530        mUserPaddingBottom = bottom;
16531
16532        final int viewFlags = mViewFlags;
16533        boolean changed = false;
16534
16535        // Common case is there are no scroll bars.
16536        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16537            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16538                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16539                        ? 0 : getVerticalScrollbarWidth();
16540                switch (mVerticalScrollbarPosition) {
16541                    case SCROLLBAR_POSITION_DEFAULT:
16542                        if (isLayoutRtl()) {
16543                            left += offset;
16544                        } else {
16545                            right += offset;
16546                        }
16547                        break;
16548                    case SCROLLBAR_POSITION_RIGHT:
16549                        right += offset;
16550                        break;
16551                    case SCROLLBAR_POSITION_LEFT:
16552                        left += offset;
16553                        break;
16554                }
16555            }
16556            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16557                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16558                        ? 0 : getHorizontalScrollbarHeight();
16559            }
16560        }
16561
16562        if (mPaddingLeft != left) {
16563            changed = true;
16564            mPaddingLeft = left;
16565        }
16566        if (mPaddingTop != top) {
16567            changed = true;
16568            mPaddingTop = top;
16569        }
16570        if (mPaddingRight != right) {
16571            changed = true;
16572            mPaddingRight = right;
16573        }
16574        if (mPaddingBottom != bottom) {
16575            changed = true;
16576            mPaddingBottom = bottom;
16577        }
16578
16579        if (changed) {
16580            requestLayout();
16581        }
16582    }
16583
16584    /**
16585     * Sets the relative padding. The view may add on the space required to display
16586     * the scrollbars, depending on the style and visibility of the scrollbars.
16587     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16588     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16589     * from the values set in this call.
16590     *
16591     * @attr ref android.R.styleable#View_padding
16592     * @attr ref android.R.styleable#View_paddingBottom
16593     * @attr ref android.R.styleable#View_paddingStart
16594     * @attr ref android.R.styleable#View_paddingEnd
16595     * @attr ref android.R.styleable#View_paddingTop
16596     * @param start the start padding in pixels
16597     * @param top the top padding in pixels
16598     * @param end the end padding in pixels
16599     * @param bottom the bottom padding in pixels
16600     */
16601    public void setPaddingRelative(int start, int top, int end, int bottom) {
16602        resetResolvedPaddingInternal();
16603
16604        mUserPaddingStart = start;
16605        mUserPaddingEnd = end;
16606        mLeftPaddingDefined = true;
16607        mRightPaddingDefined = true;
16608
16609        switch(getLayoutDirection()) {
16610            case LAYOUT_DIRECTION_RTL:
16611                mUserPaddingLeftInitial = end;
16612                mUserPaddingRightInitial = start;
16613                internalSetPadding(end, top, start, bottom);
16614                break;
16615            case LAYOUT_DIRECTION_LTR:
16616            default:
16617                mUserPaddingLeftInitial = start;
16618                mUserPaddingRightInitial = end;
16619                internalSetPadding(start, top, end, bottom);
16620        }
16621    }
16622
16623    /**
16624     * Returns the top padding of this view.
16625     *
16626     * @return the top padding in pixels
16627     */
16628    public int getPaddingTop() {
16629        return mPaddingTop;
16630    }
16631
16632    /**
16633     * Returns the bottom padding of this view. If there are inset and enabled
16634     * scrollbars, this value may include the space required to display the
16635     * scrollbars as well.
16636     *
16637     * @return the bottom padding in pixels
16638     */
16639    public int getPaddingBottom() {
16640        return mPaddingBottom;
16641    }
16642
16643    /**
16644     * Returns the left padding of this view. If there are inset and enabled
16645     * scrollbars, this value may include the space required to display the
16646     * scrollbars as well.
16647     *
16648     * @return the left padding in pixels
16649     */
16650    public int getPaddingLeft() {
16651        if (!isPaddingResolved()) {
16652            resolvePadding();
16653        }
16654        return mPaddingLeft;
16655    }
16656
16657    /**
16658     * Returns the start padding of this view depending on its resolved layout direction.
16659     * If there are inset and enabled scrollbars, this value may include the space
16660     * required to display the scrollbars as well.
16661     *
16662     * @return the start padding in pixels
16663     */
16664    public int getPaddingStart() {
16665        if (!isPaddingResolved()) {
16666            resolvePadding();
16667        }
16668        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16669                mPaddingRight : mPaddingLeft;
16670    }
16671
16672    /**
16673     * Returns the right padding of this view. If there are inset and enabled
16674     * scrollbars, this value may include the space required to display the
16675     * scrollbars as well.
16676     *
16677     * @return the right padding in pixels
16678     */
16679    public int getPaddingRight() {
16680        if (!isPaddingResolved()) {
16681            resolvePadding();
16682        }
16683        return mPaddingRight;
16684    }
16685
16686    /**
16687     * Returns the end padding of this view depending on its resolved layout direction.
16688     * If there are inset and enabled scrollbars, this value may include the space
16689     * required to display the scrollbars as well.
16690     *
16691     * @return the end padding in pixels
16692     */
16693    public int getPaddingEnd() {
16694        if (!isPaddingResolved()) {
16695            resolvePadding();
16696        }
16697        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16698                mPaddingLeft : mPaddingRight;
16699    }
16700
16701    /**
16702     * Return if the padding as been set thru relative values
16703     * {@link #setPaddingRelative(int, int, int, int)} or thru
16704     * @attr ref android.R.styleable#View_paddingStart or
16705     * @attr ref android.R.styleable#View_paddingEnd
16706     *
16707     * @return true if the padding is relative or false if it is not.
16708     */
16709    public boolean isPaddingRelative() {
16710        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16711    }
16712
16713    Insets computeOpticalInsets() {
16714        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16715    }
16716
16717    /**
16718     * @hide
16719     */
16720    public void resetPaddingToInitialValues() {
16721        if (isRtlCompatibilityMode()) {
16722            mPaddingLeft = mUserPaddingLeftInitial;
16723            mPaddingRight = mUserPaddingRightInitial;
16724            return;
16725        }
16726        if (isLayoutRtl()) {
16727            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16728            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16729        } else {
16730            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16731            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16732        }
16733    }
16734
16735    /**
16736     * @hide
16737     */
16738    public Insets getOpticalInsets() {
16739        if (mLayoutInsets == null) {
16740            mLayoutInsets = computeOpticalInsets();
16741        }
16742        return mLayoutInsets;
16743    }
16744
16745    /**
16746     * Set this view's optical insets.
16747     *
16748     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16749     * property. Views that compute their own optical insets should call it as part of measurement.
16750     * This method does not request layout. If you are setting optical insets outside of
16751     * measure/layout itself you will want to call requestLayout() yourself.
16752     * </p>
16753     * @hide
16754     */
16755    public void setOpticalInsets(Insets insets) {
16756        mLayoutInsets = insets;
16757    }
16758
16759    /**
16760     * Changes the selection state of this view. A view can be selected or not.
16761     * Note that selection is not the same as focus. Views are typically
16762     * selected in the context of an AdapterView like ListView or GridView;
16763     * the selected view is the view that is highlighted.
16764     *
16765     * @param selected true if the view must be selected, false otherwise
16766     */
16767    public void setSelected(boolean selected) {
16768        //noinspection DoubleNegation
16769        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16770            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16771            if (!selected) resetPressedState();
16772            invalidate(true);
16773            refreshDrawableState();
16774            dispatchSetSelected(selected);
16775            if (selected) {
16776                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
16777            } else {
16778                notifyViewAccessibilityStateChangedIfNeeded(
16779                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16780            }
16781        }
16782    }
16783
16784    /**
16785     * Dispatch setSelected to all of this View's children.
16786     *
16787     * @see #setSelected(boolean)
16788     *
16789     * @param selected The new selected state
16790     */
16791    protected void dispatchSetSelected(boolean selected) {
16792    }
16793
16794    /**
16795     * Indicates the selection state of this view.
16796     *
16797     * @return true if the view is selected, false otherwise
16798     */
16799    @ViewDebug.ExportedProperty
16800    public boolean isSelected() {
16801        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16802    }
16803
16804    /**
16805     * Changes the activated state of this view. A view can be activated or not.
16806     * Note that activation is not the same as selection.  Selection is
16807     * a transient property, representing the view (hierarchy) the user is
16808     * currently interacting with.  Activation is a longer-term state that the
16809     * user can move views in and out of.  For example, in a list view with
16810     * single or multiple selection enabled, the views in the current selection
16811     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16812     * here.)  The activated state is propagated down to children of the view it
16813     * is set on.
16814     *
16815     * @param activated true if the view must be activated, false otherwise
16816     */
16817    public void setActivated(boolean activated) {
16818        //noinspection DoubleNegation
16819        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16820            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16821            invalidate(true);
16822            refreshDrawableState();
16823            dispatchSetActivated(activated);
16824        }
16825    }
16826
16827    /**
16828     * Dispatch setActivated to all of this View's children.
16829     *
16830     * @see #setActivated(boolean)
16831     *
16832     * @param activated The new activated state
16833     */
16834    protected void dispatchSetActivated(boolean activated) {
16835    }
16836
16837    /**
16838     * Indicates the activation state of this view.
16839     *
16840     * @return true if the view is activated, false otherwise
16841     */
16842    @ViewDebug.ExportedProperty
16843    public boolean isActivated() {
16844        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16845    }
16846
16847    /**
16848     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16849     * observer can be used to get notifications when global events, like
16850     * layout, happen.
16851     *
16852     * The returned ViewTreeObserver observer is not guaranteed to remain
16853     * valid for the lifetime of this View. If the caller of this method keeps
16854     * a long-lived reference to ViewTreeObserver, it should always check for
16855     * the return value of {@link ViewTreeObserver#isAlive()}.
16856     *
16857     * @return The ViewTreeObserver for this view's hierarchy.
16858     */
16859    public ViewTreeObserver getViewTreeObserver() {
16860        if (mAttachInfo != null) {
16861            return mAttachInfo.mTreeObserver;
16862        }
16863        if (mFloatingTreeObserver == null) {
16864            mFloatingTreeObserver = new ViewTreeObserver();
16865        }
16866        return mFloatingTreeObserver;
16867    }
16868
16869    /**
16870     * <p>Finds the topmost view in the current view hierarchy.</p>
16871     *
16872     * @return the topmost view containing this view
16873     */
16874    public View getRootView() {
16875        if (mAttachInfo != null) {
16876            final View v = mAttachInfo.mRootView;
16877            if (v != null) {
16878                return v;
16879            }
16880        }
16881
16882        View parent = this;
16883
16884        while (parent.mParent != null && parent.mParent instanceof View) {
16885            parent = (View) parent.mParent;
16886        }
16887
16888        return parent;
16889    }
16890
16891    /**
16892     * Transforms a motion event from view-local coordinates to on-screen
16893     * coordinates.
16894     *
16895     * @param ev the view-local motion event
16896     * @return false if the transformation could not be applied
16897     * @hide
16898     */
16899    public boolean toGlobalMotionEvent(MotionEvent ev) {
16900        final AttachInfo info = mAttachInfo;
16901        if (info == null) {
16902            return false;
16903        }
16904
16905        final Matrix m = info.mTmpMatrix;
16906        m.set(Matrix.IDENTITY_MATRIX);
16907        transformMatrixToGlobal(m);
16908        ev.transform(m);
16909        return true;
16910    }
16911
16912    /**
16913     * Transforms a motion event from on-screen coordinates to view-local
16914     * coordinates.
16915     *
16916     * @param ev the on-screen motion event
16917     * @return false if the transformation could not be applied
16918     * @hide
16919     */
16920    public boolean toLocalMotionEvent(MotionEvent ev) {
16921        final AttachInfo info = mAttachInfo;
16922        if (info == null) {
16923            return false;
16924        }
16925
16926        final Matrix m = info.mTmpMatrix;
16927        m.set(Matrix.IDENTITY_MATRIX);
16928        transformMatrixToLocal(m);
16929        ev.transform(m);
16930        return true;
16931    }
16932
16933    /**
16934     * Modifies the input matrix such that it maps view-local coordinates to
16935     * on-screen coordinates.
16936     *
16937     * @param m input matrix to modify
16938     * @hide
16939     */
16940    public void transformMatrixToGlobal(Matrix m) {
16941        final ViewParent parent = mParent;
16942        if (parent instanceof View) {
16943            final View vp = (View) parent;
16944            vp.transformMatrixToGlobal(m);
16945            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16946        } else if (parent instanceof ViewRootImpl) {
16947            final ViewRootImpl vr = (ViewRootImpl) parent;
16948            vr.transformMatrixToGlobal(m);
16949            m.preTranslate(0, -vr.mCurScrollY);
16950        }
16951
16952        m.preTranslate(mLeft, mTop);
16953
16954        if (!hasIdentityMatrix()) {
16955            m.preConcat(getMatrix());
16956        }
16957    }
16958
16959    /**
16960     * Modifies the input matrix such that it maps on-screen coordinates to
16961     * view-local coordinates.
16962     *
16963     * @param m input matrix to modify
16964     * @hide
16965     */
16966    public void transformMatrixToLocal(Matrix m) {
16967        final ViewParent parent = mParent;
16968        if (parent instanceof View) {
16969            final View vp = (View) parent;
16970            vp.transformMatrixToLocal(m);
16971            m.postTranslate(vp.mScrollX, vp.mScrollY);
16972        } else if (parent instanceof ViewRootImpl) {
16973            final ViewRootImpl vr = (ViewRootImpl) parent;
16974            vr.transformMatrixToLocal(m);
16975            m.postTranslate(0, vr.mCurScrollY);
16976        }
16977
16978        m.postTranslate(-mLeft, -mTop);
16979
16980        if (!hasIdentityMatrix()) {
16981            m.postConcat(getInverseMatrix());
16982        }
16983    }
16984
16985    /**
16986     * @hide
16987     */
16988    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16989            @ViewDebug.IntToString(from = 0, to = "x"),
16990            @ViewDebug.IntToString(from = 1, to = "y")
16991    })
16992    public int[] getLocationOnScreen() {
16993        int[] location = new int[2];
16994        getLocationOnScreen(location);
16995        return location;
16996    }
16997
16998    /**
16999     * <p>Computes the coordinates of this view on the screen. The argument
17000     * must be an array of two integers. After the method returns, the array
17001     * contains the x and y location in that order.</p>
17002     *
17003     * @param location an array of two integers in which to hold the coordinates
17004     */
17005    public void getLocationOnScreen(int[] location) {
17006        getLocationInWindow(location);
17007
17008        final AttachInfo info = mAttachInfo;
17009        if (info != null) {
17010            location[0] += info.mWindowLeft;
17011            location[1] += info.mWindowTop;
17012        }
17013    }
17014
17015    /**
17016     * <p>Computes the coordinates of this view in its window. The argument
17017     * must be an array of two integers. After the method returns, the array
17018     * contains the x and y location in that order.</p>
17019     *
17020     * @param location an array of two integers in which to hold the coordinates
17021     */
17022    public void getLocationInWindow(int[] location) {
17023        if (location == null || location.length < 2) {
17024            throw new IllegalArgumentException("location must be an array of two integers");
17025        }
17026
17027        if (mAttachInfo == null) {
17028            // When the view is not attached to a window, this method does not make sense
17029            location[0] = location[1] = 0;
17030            return;
17031        }
17032
17033        float[] position = mAttachInfo.mTmpTransformLocation;
17034        position[0] = position[1] = 0.0f;
17035
17036        if (!hasIdentityMatrix()) {
17037            getMatrix().mapPoints(position);
17038        }
17039
17040        position[0] += mLeft;
17041        position[1] += mTop;
17042
17043        ViewParent viewParent = mParent;
17044        while (viewParent instanceof View) {
17045            final View view = (View) viewParent;
17046
17047            position[0] -= view.mScrollX;
17048            position[1] -= view.mScrollY;
17049
17050            if (!view.hasIdentityMatrix()) {
17051                view.getMatrix().mapPoints(position);
17052            }
17053
17054            position[0] += view.mLeft;
17055            position[1] += view.mTop;
17056
17057            viewParent = view.mParent;
17058         }
17059
17060        if (viewParent instanceof ViewRootImpl) {
17061            // *cough*
17062            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17063            position[1] -= vr.mCurScrollY;
17064        }
17065
17066        location[0] = (int) (position[0] + 0.5f);
17067        location[1] = (int) (position[1] + 0.5f);
17068    }
17069
17070    /**
17071     * {@hide}
17072     * @param id the id of the view to be found
17073     * @return the view of the specified id, null if cannot be found
17074     */
17075    protected View findViewTraversal(int id) {
17076        if (id == mID) {
17077            return this;
17078        }
17079        return null;
17080    }
17081
17082    /**
17083     * {@hide}
17084     * @param tag the tag of the view to be found
17085     * @return the view of specified tag, null if cannot be found
17086     */
17087    protected View findViewWithTagTraversal(Object tag) {
17088        if (tag != null && tag.equals(mTag)) {
17089            return this;
17090        }
17091        return null;
17092    }
17093
17094    /**
17095     * {@hide}
17096     * @param predicate The predicate to evaluate.
17097     * @param childToSkip If not null, ignores this child during the recursive traversal.
17098     * @return The first view that matches the predicate or null.
17099     */
17100    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17101        if (predicate.apply(this)) {
17102            return this;
17103        }
17104        return null;
17105    }
17106
17107    /**
17108     * Look for a child view with the given id.  If this view has the given
17109     * id, return this view.
17110     *
17111     * @param id The id to search for.
17112     * @return The view that has the given id in the hierarchy or null
17113     */
17114    public final View findViewById(int id) {
17115        if (id < 0) {
17116            return null;
17117        }
17118        return findViewTraversal(id);
17119    }
17120
17121    /**
17122     * Finds a view by its unuque and stable accessibility id.
17123     *
17124     * @param accessibilityId The searched accessibility id.
17125     * @return The found view.
17126     */
17127    final View findViewByAccessibilityId(int accessibilityId) {
17128        if (accessibilityId < 0) {
17129            return null;
17130        }
17131        return findViewByAccessibilityIdTraversal(accessibilityId);
17132    }
17133
17134    /**
17135     * Performs the traversal to find a view by its unuque and stable accessibility id.
17136     *
17137     * <strong>Note:</strong>This method does not stop at the root namespace
17138     * boundary since the user can touch the screen at an arbitrary location
17139     * potentially crossing the root namespace bounday which will send an
17140     * accessibility event to accessibility services and they should be able
17141     * to obtain the event source. Also accessibility ids are guaranteed to be
17142     * unique in the window.
17143     *
17144     * @param accessibilityId The accessibility id.
17145     * @return The found view.
17146     *
17147     * @hide
17148     */
17149    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17150        if (getAccessibilityViewId() == accessibilityId) {
17151            return this;
17152        }
17153        return null;
17154    }
17155
17156    /**
17157     * Look for a child view with the given tag.  If this view has the given
17158     * tag, return this view.
17159     *
17160     * @param tag The tag to search for, using "tag.equals(getTag())".
17161     * @return The View that has the given tag in the hierarchy or null
17162     */
17163    public final View findViewWithTag(Object tag) {
17164        if (tag == null) {
17165            return null;
17166        }
17167        return findViewWithTagTraversal(tag);
17168    }
17169
17170    /**
17171     * {@hide}
17172     * Look for a child view that matches the specified predicate.
17173     * If this view matches the predicate, return this view.
17174     *
17175     * @param predicate The predicate to evaluate.
17176     * @return The first view that matches the predicate or null.
17177     */
17178    public final View findViewByPredicate(Predicate<View> predicate) {
17179        return findViewByPredicateTraversal(predicate, null);
17180    }
17181
17182    /**
17183     * {@hide}
17184     * Look for a child view that matches the specified predicate,
17185     * starting with the specified view and its descendents and then
17186     * recusively searching the ancestors and siblings of that view
17187     * until this view is reached.
17188     *
17189     * This method is useful in cases where the predicate does not match
17190     * a single unique view (perhaps multiple views use the same id)
17191     * and we are trying to find the view that is "closest" in scope to the
17192     * starting view.
17193     *
17194     * @param start The view to start from.
17195     * @param predicate The predicate to evaluate.
17196     * @return The first view that matches the predicate or null.
17197     */
17198    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17199        View childToSkip = null;
17200        for (;;) {
17201            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17202            if (view != null || start == this) {
17203                return view;
17204            }
17205
17206            ViewParent parent = start.getParent();
17207            if (parent == null || !(parent instanceof View)) {
17208                return null;
17209            }
17210
17211            childToSkip = start;
17212            start = (View) parent;
17213        }
17214    }
17215
17216    /**
17217     * Sets the identifier for this view. The identifier does not have to be
17218     * unique in this view's hierarchy. The identifier should be a positive
17219     * number.
17220     *
17221     * @see #NO_ID
17222     * @see #getId()
17223     * @see #findViewById(int)
17224     *
17225     * @param id a number used to identify the view
17226     *
17227     * @attr ref android.R.styleable#View_id
17228     */
17229    public void setId(int id) {
17230        mID = id;
17231        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17232            mID = generateViewId();
17233        }
17234    }
17235
17236    /**
17237     * {@hide}
17238     *
17239     * @param isRoot true if the view belongs to the root namespace, false
17240     *        otherwise
17241     */
17242    public void setIsRootNamespace(boolean isRoot) {
17243        if (isRoot) {
17244            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17245        } else {
17246            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17247        }
17248    }
17249
17250    /**
17251     * {@hide}
17252     *
17253     * @return true if the view belongs to the root namespace, false otherwise
17254     */
17255    public boolean isRootNamespace() {
17256        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17257    }
17258
17259    /**
17260     * Returns this view's identifier.
17261     *
17262     * @return a positive integer used to identify the view or {@link #NO_ID}
17263     *         if the view has no ID
17264     *
17265     * @see #setId(int)
17266     * @see #findViewById(int)
17267     * @attr ref android.R.styleable#View_id
17268     */
17269    @ViewDebug.CapturedViewProperty
17270    public int getId() {
17271        return mID;
17272    }
17273
17274    /**
17275     * Returns this view's tag.
17276     *
17277     * @return the Object stored in this view as a tag, or {@code null} if not
17278     *         set
17279     *
17280     * @see #setTag(Object)
17281     * @see #getTag(int)
17282     */
17283    @ViewDebug.ExportedProperty
17284    public Object getTag() {
17285        return mTag;
17286    }
17287
17288    /**
17289     * Sets the tag associated with this view. A tag can be used to mark
17290     * a view in its hierarchy and does not have to be unique within the
17291     * hierarchy. Tags can also be used to store data within a view without
17292     * resorting to another data structure.
17293     *
17294     * @param tag an Object to tag the view with
17295     *
17296     * @see #getTag()
17297     * @see #setTag(int, Object)
17298     */
17299    public void setTag(final Object tag) {
17300        mTag = tag;
17301    }
17302
17303    /**
17304     * Returns the tag associated with this view and the specified key.
17305     *
17306     * @param key The key identifying the tag
17307     *
17308     * @return the Object stored in this view as a tag, or {@code null} if not
17309     *         set
17310     *
17311     * @see #setTag(int, Object)
17312     * @see #getTag()
17313     */
17314    public Object getTag(int key) {
17315        if (mKeyedTags != null) return mKeyedTags.get(key);
17316        return null;
17317    }
17318
17319    /**
17320     * Sets a tag associated with this view and a key. A tag can be used
17321     * to mark a view in its hierarchy and does not have to be unique within
17322     * the hierarchy. Tags can also be used to store data within a view
17323     * without resorting to another data structure.
17324     *
17325     * The specified key should be an id declared in the resources of the
17326     * application to ensure it is unique (see the <a
17327     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17328     * Keys identified as belonging to
17329     * the Android framework or not associated with any package will cause
17330     * an {@link IllegalArgumentException} to be thrown.
17331     *
17332     * @param key The key identifying the tag
17333     * @param tag An Object to tag the view with
17334     *
17335     * @throws IllegalArgumentException If they specified key is not valid
17336     *
17337     * @see #setTag(Object)
17338     * @see #getTag(int)
17339     */
17340    public void setTag(int key, final Object tag) {
17341        // If the package id is 0x00 or 0x01, it's either an undefined package
17342        // or a framework id
17343        if ((key >>> 24) < 2) {
17344            throw new IllegalArgumentException("The key must be an application-specific "
17345                    + "resource id.");
17346        }
17347
17348        setKeyedTag(key, tag);
17349    }
17350
17351    /**
17352     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
17353     * framework id.
17354     *
17355     * @hide
17356     */
17357    public void setTagInternal(int key, Object tag) {
17358        if ((key >>> 24) != 0x1) {
17359            throw new IllegalArgumentException("The key must be a framework-specific "
17360                    + "resource id.");
17361        }
17362
17363        setKeyedTag(key, tag);
17364    }
17365
17366    private void setKeyedTag(int key, Object tag) {
17367        if (mKeyedTags == null) {
17368            mKeyedTags = new SparseArray<Object>(2);
17369        }
17370
17371        mKeyedTags.put(key, tag);
17372    }
17373
17374    /**
17375     * Prints information about this view in the log output, with the tag
17376     * {@link #VIEW_LOG_TAG}.
17377     *
17378     * @hide
17379     */
17380    public void debug() {
17381        debug(0);
17382    }
17383
17384    /**
17385     * Prints information about this view in the log output, with the tag
17386     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17387     * indentation defined by the <code>depth</code>.
17388     *
17389     * @param depth the indentation level
17390     *
17391     * @hide
17392     */
17393    protected void debug(int depth) {
17394        String output = debugIndent(depth - 1);
17395
17396        output += "+ " + this;
17397        int id = getId();
17398        if (id != -1) {
17399            output += " (id=" + id + ")";
17400        }
17401        Object tag = getTag();
17402        if (tag != null) {
17403            output += " (tag=" + tag + ")";
17404        }
17405        Log.d(VIEW_LOG_TAG, output);
17406
17407        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17408            output = debugIndent(depth) + " FOCUSED";
17409            Log.d(VIEW_LOG_TAG, output);
17410        }
17411
17412        output = debugIndent(depth);
17413        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17414                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17415                + "} ";
17416        Log.d(VIEW_LOG_TAG, output);
17417
17418        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17419                || mPaddingBottom != 0) {
17420            output = debugIndent(depth);
17421            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17422                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17423            Log.d(VIEW_LOG_TAG, output);
17424        }
17425
17426        output = debugIndent(depth);
17427        output += "mMeasureWidth=" + mMeasuredWidth +
17428                " mMeasureHeight=" + mMeasuredHeight;
17429        Log.d(VIEW_LOG_TAG, output);
17430
17431        output = debugIndent(depth);
17432        if (mLayoutParams == null) {
17433            output += "BAD! no layout params";
17434        } else {
17435            output = mLayoutParams.debug(output);
17436        }
17437        Log.d(VIEW_LOG_TAG, output);
17438
17439        output = debugIndent(depth);
17440        output += "flags={";
17441        output += View.printFlags(mViewFlags);
17442        output += "}";
17443        Log.d(VIEW_LOG_TAG, output);
17444
17445        output = debugIndent(depth);
17446        output += "privateFlags={";
17447        output += View.printPrivateFlags(mPrivateFlags);
17448        output += "}";
17449        Log.d(VIEW_LOG_TAG, output);
17450    }
17451
17452    /**
17453     * Creates a string of whitespaces used for indentation.
17454     *
17455     * @param depth the indentation level
17456     * @return a String containing (depth * 2 + 3) * 2 white spaces
17457     *
17458     * @hide
17459     */
17460    protected static String debugIndent(int depth) {
17461        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17462        for (int i = 0; i < (depth * 2) + 3; i++) {
17463            spaces.append(' ').append(' ');
17464        }
17465        return spaces.toString();
17466    }
17467
17468    /**
17469     * <p>Return the offset of the widget's text baseline from the widget's top
17470     * boundary. If this widget does not support baseline alignment, this
17471     * method returns -1. </p>
17472     *
17473     * @return the offset of the baseline within the widget's bounds or -1
17474     *         if baseline alignment is not supported
17475     */
17476    @ViewDebug.ExportedProperty(category = "layout")
17477    public int getBaseline() {
17478        return -1;
17479    }
17480
17481    /**
17482     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17483     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17484     * a layout pass.
17485     *
17486     * @return whether the view hierarchy is currently undergoing a layout pass
17487     */
17488    public boolean isInLayout() {
17489        ViewRootImpl viewRoot = getViewRootImpl();
17490        return (viewRoot != null && viewRoot.isInLayout());
17491    }
17492
17493    /**
17494     * Call this when something has changed which has invalidated the
17495     * layout of this view. This will schedule a layout pass of the view
17496     * tree. This should not be called while the view hierarchy is currently in a layout
17497     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17498     * end of the current layout pass (and then layout will run again) or after the current
17499     * frame is drawn and the next layout occurs.
17500     *
17501     * <p>Subclasses which override this method should call the superclass method to
17502     * handle possible request-during-layout errors correctly.</p>
17503     */
17504    public void requestLayout() {
17505        if (mMeasureCache != null) mMeasureCache.clear();
17506
17507        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17508            // Only trigger request-during-layout logic if this is the view requesting it,
17509            // not the views in its parent hierarchy
17510            ViewRootImpl viewRoot = getViewRootImpl();
17511            if (viewRoot != null && viewRoot.isInLayout()) {
17512                if (!viewRoot.requestLayoutDuringLayout(this)) {
17513                    return;
17514                }
17515            }
17516            mAttachInfo.mViewRequestingLayout = this;
17517        }
17518
17519        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17520        mPrivateFlags |= PFLAG_INVALIDATED;
17521
17522        if (mParent != null && !mParent.isLayoutRequested()) {
17523            mParent.requestLayout();
17524        }
17525        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17526            mAttachInfo.mViewRequestingLayout = null;
17527        }
17528    }
17529
17530    /**
17531     * Forces this view to be laid out during the next layout pass.
17532     * This method does not call requestLayout() or forceLayout()
17533     * on the parent.
17534     */
17535    public void forceLayout() {
17536        if (mMeasureCache != null) mMeasureCache.clear();
17537
17538        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17539        mPrivateFlags |= PFLAG_INVALIDATED;
17540    }
17541
17542    /**
17543     * <p>
17544     * This is called to find out how big a view should be. The parent
17545     * supplies constraint information in the width and height parameters.
17546     * </p>
17547     *
17548     * <p>
17549     * The actual measurement work of a view is performed in
17550     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17551     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17552     * </p>
17553     *
17554     *
17555     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17556     *        parent
17557     * @param heightMeasureSpec Vertical space requirements as imposed by the
17558     *        parent
17559     *
17560     * @see #onMeasure(int, int)
17561     */
17562    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17563        boolean optical = isLayoutModeOptical(this);
17564        if (optical != isLayoutModeOptical(mParent)) {
17565            Insets insets = getOpticalInsets();
17566            int oWidth  = insets.left + insets.right;
17567            int oHeight = insets.top  + insets.bottom;
17568            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17569            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17570        }
17571
17572        // Suppress sign extension for the low bytes
17573        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17574        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17575
17576        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17577        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
17578                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
17579        final boolean matchingSize = isExactly &&
17580                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
17581                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
17582        if (forceLayout || !matchingSize &&
17583                (widthMeasureSpec != mOldWidthMeasureSpec ||
17584                        heightMeasureSpec != mOldHeightMeasureSpec)) {
17585
17586            // first clears the measured dimension flag
17587            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17588
17589            resolveRtlPropertiesIfNeeded();
17590
17591            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
17592            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17593                // measure ourselves, this should set the measured dimension flag back
17594                onMeasure(widthMeasureSpec, heightMeasureSpec);
17595                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17596            } else {
17597                long value = mMeasureCache.valueAt(cacheIndex);
17598                // Casting a long to int drops the high 32 bits, no mask needed
17599                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17600                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17601            }
17602
17603            // flag not set, setMeasuredDimension() was not invoked, we raise
17604            // an exception to warn the developer
17605            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17606                throw new IllegalStateException("onMeasure() did not set the"
17607                        + " measured dimension by calling"
17608                        + " setMeasuredDimension()");
17609            }
17610
17611            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17612        }
17613
17614        mOldWidthMeasureSpec = widthMeasureSpec;
17615        mOldHeightMeasureSpec = heightMeasureSpec;
17616
17617        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17618                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17619    }
17620
17621    /**
17622     * <p>
17623     * Measure the view and its content to determine the measured width and the
17624     * measured height. This method is invoked by {@link #measure(int, int)} and
17625     * should be overriden by subclasses to provide accurate and efficient
17626     * measurement of their contents.
17627     * </p>
17628     *
17629     * <p>
17630     * <strong>CONTRACT:</strong> When overriding this method, you
17631     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17632     * measured width and height of this view. Failure to do so will trigger an
17633     * <code>IllegalStateException</code>, thrown by
17634     * {@link #measure(int, int)}. Calling the superclass'
17635     * {@link #onMeasure(int, int)} is a valid use.
17636     * </p>
17637     *
17638     * <p>
17639     * The base class implementation of measure defaults to the background size,
17640     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17641     * override {@link #onMeasure(int, int)} to provide better measurements of
17642     * their content.
17643     * </p>
17644     *
17645     * <p>
17646     * If this method is overridden, it is the subclass's responsibility to make
17647     * sure the measured height and width are at least the view's minimum height
17648     * and width ({@link #getSuggestedMinimumHeight()} and
17649     * {@link #getSuggestedMinimumWidth()}).
17650     * </p>
17651     *
17652     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17653     *                         The requirements are encoded with
17654     *                         {@link android.view.View.MeasureSpec}.
17655     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17656     *                         The requirements are encoded with
17657     *                         {@link android.view.View.MeasureSpec}.
17658     *
17659     * @see #getMeasuredWidth()
17660     * @see #getMeasuredHeight()
17661     * @see #setMeasuredDimension(int, int)
17662     * @see #getSuggestedMinimumHeight()
17663     * @see #getSuggestedMinimumWidth()
17664     * @see android.view.View.MeasureSpec#getMode(int)
17665     * @see android.view.View.MeasureSpec#getSize(int)
17666     */
17667    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17668        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17669                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17670    }
17671
17672    /**
17673     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17674     * measured width and measured height. Failing to do so will trigger an
17675     * exception at measurement time.</p>
17676     *
17677     * @param measuredWidth The measured width of this view.  May be a complex
17678     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17679     * {@link #MEASURED_STATE_TOO_SMALL}.
17680     * @param measuredHeight The measured height of this view.  May be a complex
17681     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17682     * {@link #MEASURED_STATE_TOO_SMALL}.
17683     */
17684    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17685        boolean optical = isLayoutModeOptical(this);
17686        if (optical != isLayoutModeOptical(mParent)) {
17687            Insets insets = getOpticalInsets();
17688            int opticalWidth  = insets.left + insets.right;
17689            int opticalHeight = insets.top  + insets.bottom;
17690
17691            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17692            measuredHeight += optical ? opticalHeight : -opticalHeight;
17693        }
17694        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17695    }
17696
17697    /**
17698     * Sets the measured dimension without extra processing for things like optical bounds.
17699     * Useful for reapplying consistent values that have already been cooked with adjustments
17700     * for optical bounds, etc. such as those from the measurement cache.
17701     *
17702     * @param measuredWidth The measured width of this view.  May be a complex
17703     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17704     * {@link #MEASURED_STATE_TOO_SMALL}.
17705     * @param measuredHeight The measured height of this view.  May be a complex
17706     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17707     * {@link #MEASURED_STATE_TOO_SMALL}.
17708     */
17709    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17710        mMeasuredWidth = measuredWidth;
17711        mMeasuredHeight = measuredHeight;
17712
17713        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17714    }
17715
17716    /**
17717     * Merge two states as returned by {@link #getMeasuredState()}.
17718     * @param curState The current state as returned from a view or the result
17719     * of combining multiple views.
17720     * @param newState The new view state to combine.
17721     * @return Returns a new integer reflecting the combination of the two
17722     * states.
17723     */
17724    public static int combineMeasuredStates(int curState, int newState) {
17725        return curState | newState;
17726    }
17727
17728    /**
17729     * Version of {@link #resolveSizeAndState(int, int, int)}
17730     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17731     */
17732    public static int resolveSize(int size, int measureSpec) {
17733        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17734    }
17735
17736    /**
17737     * Utility to reconcile a desired size and state, with constraints imposed
17738     * by a MeasureSpec.  Will take the desired size, unless a different size
17739     * is imposed by the constraints.  The returned value is a compound integer,
17740     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17741     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17742     * size is smaller than the size the view wants to be.
17743     *
17744     * @param size How big the view wants to be
17745     * @param measureSpec Constraints imposed by the parent
17746     * @return Size information bit mask as defined by
17747     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17748     */
17749    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17750        int result = size;
17751        int specMode = MeasureSpec.getMode(measureSpec);
17752        int specSize =  MeasureSpec.getSize(measureSpec);
17753        switch (specMode) {
17754        case MeasureSpec.UNSPECIFIED:
17755            result = size;
17756            break;
17757        case MeasureSpec.AT_MOST:
17758            if (specSize < size) {
17759                result = specSize | MEASURED_STATE_TOO_SMALL;
17760            } else {
17761                result = size;
17762            }
17763            break;
17764        case MeasureSpec.EXACTLY:
17765            result = specSize;
17766            break;
17767        }
17768        return result | (childMeasuredState&MEASURED_STATE_MASK);
17769    }
17770
17771    /**
17772     * Utility to return a default size. Uses the supplied size if the
17773     * MeasureSpec imposed no constraints. Will get larger if allowed
17774     * by the MeasureSpec.
17775     *
17776     * @param size Default size for this view
17777     * @param measureSpec Constraints imposed by the parent
17778     * @return The size this view should be.
17779     */
17780    public static int getDefaultSize(int size, int measureSpec) {
17781        int result = size;
17782        int specMode = MeasureSpec.getMode(measureSpec);
17783        int specSize = MeasureSpec.getSize(measureSpec);
17784
17785        switch (specMode) {
17786        case MeasureSpec.UNSPECIFIED:
17787            result = size;
17788            break;
17789        case MeasureSpec.AT_MOST:
17790        case MeasureSpec.EXACTLY:
17791            result = specSize;
17792            break;
17793        }
17794        return result;
17795    }
17796
17797    /**
17798     * Returns the suggested minimum height that the view should use. This
17799     * returns the maximum of the view's minimum height
17800     * and the background's minimum height
17801     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17802     * <p>
17803     * When being used in {@link #onMeasure(int, int)}, the caller should still
17804     * ensure the returned height is within the requirements of the parent.
17805     *
17806     * @return The suggested minimum height of the view.
17807     */
17808    protected int getSuggestedMinimumHeight() {
17809        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17810
17811    }
17812
17813    /**
17814     * Returns the suggested minimum width that the view should use. This
17815     * returns the maximum of the view's minimum width)
17816     * and the background's minimum width
17817     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17818     * <p>
17819     * When being used in {@link #onMeasure(int, int)}, the caller should still
17820     * ensure the returned width is within the requirements of the parent.
17821     *
17822     * @return The suggested minimum width of the view.
17823     */
17824    protected int getSuggestedMinimumWidth() {
17825        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17826    }
17827
17828    /**
17829     * Returns the minimum height of the view.
17830     *
17831     * @return the minimum height the view will try to be.
17832     *
17833     * @see #setMinimumHeight(int)
17834     *
17835     * @attr ref android.R.styleable#View_minHeight
17836     */
17837    public int getMinimumHeight() {
17838        return mMinHeight;
17839    }
17840
17841    /**
17842     * Sets the minimum height of the view. It is not guaranteed the view will
17843     * be able to achieve this minimum height (for example, if its parent layout
17844     * constrains it with less available height).
17845     *
17846     * @param minHeight The minimum height the view will try to be.
17847     *
17848     * @see #getMinimumHeight()
17849     *
17850     * @attr ref android.R.styleable#View_minHeight
17851     */
17852    public void setMinimumHeight(int minHeight) {
17853        mMinHeight = minHeight;
17854        requestLayout();
17855    }
17856
17857    /**
17858     * Returns the minimum width of the view.
17859     *
17860     * @return the minimum width the view will try to be.
17861     *
17862     * @see #setMinimumWidth(int)
17863     *
17864     * @attr ref android.R.styleable#View_minWidth
17865     */
17866    public int getMinimumWidth() {
17867        return mMinWidth;
17868    }
17869
17870    /**
17871     * Sets the minimum width of the view. It is not guaranteed the view will
17872     * be able to achieve this minimum width (for example, if its parent layout
17873     * constrains it with less available width).
17874     *
17875     * @param minWidth The minimum width the view will try to be.
17876     *
17877     * @see #getMinimumWidth()
17878     *
17879     * @attr ref android.R.styleable#View_minWidth
17880     */
17881    public void setMinimumWidth(int minWidth) {
17882        mMinWidth = minWidth;
17883        requestLayout();
17884
17885    }
17886
17887    /**
17888     * Get the animation currently associated with this view.
17889     *
17890     * @return The animation that is currently playing or
17891     *         scheduled to play for this view.
17892     */
17893    public Animation getAnimation() {
17894        return mCurrentAnimation;
17895    }
17896
17897    /**
17898     * Start the specified animation now.
17899     *
17900     * @param animation the animation to start now
17901     */
17902    public void startAnimation(Animation animation) {
17903        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17904        setAnimation(animation);
17905        invalidateParentCaches();
17906        invalidate(true);
17907    }
17908
17909    /**
17910     * Cancels any animations for this view.
17911     */
17912    public void clearAnimation() {
17913        if (mCurrentAnimation != null) {
17914            mCurrentAnimation.detach();
17915        }
17916        mCurrentAnimation = null;
17917        invalidateParentIfNeeded();
17918    }
17919
17920    /**
17921     * Sets the next animation to play for this view.
17922     * If you want the animation to play immediately, use
17923     * {@link #startAnimation(android.view.animation.Animation)} instead.
17924     * This method provides allows fine-grained
17925     * control over the start time and invalidation, but you
17926     * must make sure that 1) the animation has a start time set, and
17927     * 2) the view's parent (which controls animations on its children)
17928     * will be invalidated when the animation is supposed to
17929     * start.
17930     *
17931     * @param animation The next animation, or null.
17932     */
17933    public void setAnimation(Animation animation) {
17934        mCurrentAnimation = animation;
17935
17936        if (animation != null) {
17937            // If the screen is off assume the animation start time is now instead of
17938            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17939            // would cause the animation to start when the screen turns back on
17940            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17941                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17942                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17943            }
17944            animation.reset();
17945        }
17946    }
17947
17948    /**
17949     * Invoked by a parent ViewGroup to notify the start of the animation
17950     * currently associated with this view. If you override this method,
17951     * always call super.onAnimationStart();
17952     *
17953     * @see #setAnimation(android.view.animation.Animation)
17954     * @see #getAnimation()
17955     */
17956    protected void onAnimationStart() {
17957        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17958    }
17959
17960    /**
17961     * Invoked by a parent ViewGroup to notify the end of the animation
17962     * currently associated with this view. If you override this method,
17963     * always call super.onAnimationEnd();
17964     *
17965     * @see #setAnimation(android.view.animation.Animation)
17966     * @see #getAnimation()
17967     */
17968    protected void onAnimationEnd() {
17969        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17970    }
17971
17972    /**
17973     * Invoked if there is a Transform that involves alpha. Subclass that can
17974     * draw themselves with the specified alpha should return true, and then
17975     * respect that alpha when their onDraw() is called. If this returns false
17976     * then the view may be redirected to draw into an offscreen buffer to
17977     * fulfill the request, which will look fine, but may be slower than if the
17978     * subclass handles it internally. The default implementation returns false.
17979     *
17980     * @param alpha The alpha (0..255) to apply to the view's drawing
17981     * @return true if the view can draw with the specified alpha.
17982     */
17983    protected boolean onSetAlpha(int alpha) {
17984        return false;
17985    }
17986
17987    /**
17988     * This is used by the RootView to perform an optimization when
17989     * the view hierarchy contains one or several SurfaceView.
17990     * SurfaceView is always considered transparent, but its children are not,
17991     * therefore all View objects remove themselves from the global transparent
17992     * region (passed as a parameter to this function).
17993     *
17994     * @param region The transparent region for this ViewAncestor (window).
17995     *
17996     * @return Returns true if the effective visibility of the view at this
17997     * point is opaque, regardless of the transparent region; returns false
17998     * if it is possible for underlying windows to be seen behind the view.
17999     *
18000     * {@hide}
18001     */
18002    public boolean gatherTransparentRegion(Region region) {
18003        final AttachInfo attachInfo = mAttachInfo;
18004        if (region != null && attachInfo != null) {
18005            final int pflags = mPrivateFlags;
18006            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18007                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18008                // remove it from the transparent region.
18009                final int[] location = attachInfo.mTransparentLocation;
18010                getLocationInWindow(location);
18011                region.op(location[0], location[1], location[0] + mRight - mLeft,
18012                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18013            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18014                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18015                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18016                // exists, so we remove the background drawable's non-transparent
18017                // parts from this transparent region.
18018                applyDrawableToTransparentRegion(mBackground, region);
18019            }
18020        }
18021        return true;
18022    }
18023
18024    /**
18025     * Play a sound effect for this view.
18026     *
18027     * <p>The framework will play sound effects for some built in actions, such as
18028     * clicking, but you may wish to play these effects in your widget,
18029     * for instance, for internal navigation.
18030     *
18031     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18032     * {@link #isSoundEffectsEnabled()} is true.
18033     *
18034     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18035     */
18036    public void playSoundEffect(int soundConstant) {
18037        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18038            return;
18039        }
18040        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18041    }
18042
18043    /**
18044     * BZZZTT!!1!
18045     *
18046     * <p>Provide haptic feedback to the user for this view.
18047     *
18048     * <p>The framework will provide haptic feedback for some built in actions,
18049     * such as long presses, but you may wish to provide feedback for your
18050     * own widget.
18051     *
18052     * <p>The feedback will only be performed if
18053     * {@link #isHapticFeedbackEnabled()} is true.
18054     *
18055     * @param feedbackConstant One of the constants defined in
18056     * {@link HapticFeedbackConstants}
18057     */
18058    public boolean performHapticFeedback(int feedbackConstant) {
18059        return performHapticFeedback(feedbackConstant, 0);
18060    }
18061
18062    /**
18063     * BZZZTT!!1!
18064     *
18065     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18066     *
18067     * @param feedbackConstant One of the constants defined in
18068     * {@link HapticFeedbackConstants}
18069     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18070     */
18071    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18072        if (mAttachInfo == null) {
18073            return false;
18074        }
18075        //noinspection SimplifiableIfStatement
18076        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18077                && !isHapticFeedbackEnabled()) {
18078            return false;
18079        }
18080        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18081                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18082    }
18083
18084    /**
18085     * Request that the visibility of the status bar or other screen/window
18086     * decorations be changed.
18087     *
18088     * <p>This method is used to put the over device UI into temporary modes
18089     * where the user's attention is focused more on the application content,
18090     * by dimming or hiding surrounding system affordances.  This is typically
18091     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18092     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18093     * to be placed behind the action bar (and with these flags other system
18094     * affordances) so that smooth transitions between hiding and showing them
18095     * can be done.
18096     *
18097     * <p>Two representative examples of the use of system UI visibility is
18098     * implementing a content browsing application (like a magazine reader)
18099     * and a video playing application.
18100     *
18101     * <p>The first code shows a typical implementation of a View in a content
18102     * browsing application.  In this implementation, the application goes
18103     * into a content-oriented mode by hiding the status bar and action bar,
18104     * and putting the navigation elements into lights out mode.  The user can
18105     * then interact with content while in this mode.  Such an application should
18106     * provide an easy way for the user to toggle out of the mode (such as to
18107     * check information in the status bar or access notifications).  In the
18108     * implementation here, this is done simply by tapping on the content.
18109     *
18110     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18111     *      content}
18112     *
18113     * <p>This second code sample shows a typical implementation of a View
18114     * in a video playing application.  In this situation, while the video is
18115     * playing the application would like to go into a complete full-screen mode,
18116     * to use as much of the display as possible for the video.  When in this state
18117     * the user can not interact with the application; the system intercepts
18118     * touching on the screen to pop the UI out of full screen mode.  See
18119     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18120     *
18121     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18122     *      content}
18123     *
18124     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18125     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18126     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18127     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18128     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18129     */
18130    public void setSystemUiVisibility(int visibility) {
18131        if (visibility != mSystemUiVisibility) {
18132            mSystemUiVisibility = visibility;
18133            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18134                mParent.recomputeViewAttributes(this);
18135            }
18136        }
18137    }
18138
18139    /**
18140     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18141     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18142     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18143     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18144     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18145     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18146     */
18147    public int getSystemUiVisibility() {
18148        return mSystemUiVisibility;
18149    }
18150
18151    /**
18152     * Returns the current system UI visibility that is currently set for
18153     * the entire window.  This is the combination of the
18154     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18155     * views in the window.
18156     */
18157    public int getWindowSystemUiVisibility() {
18158        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18159    }
18160
18161    /**
18162     * Override to find out when the window's requested system UI visibility
18163     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18164     * This is different from the callbacks received through
18165     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18166     * in that this is only telling you about the local request of the window,
18167     * not the actual values applied by the system.
18168     */
18169    public void onWindowSystemUiVisibilityChanged(int visible) {
18170    }
18171
18172    /**
18173     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18174     * the view hierarchy.
18175     */
18176    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18177        onWindowSystemUiVisibilityChanged(visible);
18178    }
18179
18180    /**
18181     * Set a listener to receive callbacks when the visibility of the system bar changes.
18182     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18183     */
18184    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18185        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18186        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18187            mParent.recomputeViewAttributes(this);
18188        }
18189    }
18190
18191    /**
18192     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18193     * the view hierarchy.
18194     */
18195    public void dispatchSystemUiVisibilityChanged(int visibility) {
18196        ListenerInfo li = mListenerInfo;
18197        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18198            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18199                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18200        }
18201    }
18202
18203    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18204        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18205        if (val != mSystemUiVisibility) {
18206            setSystemUiVisibility(val);
18207            return true;
18208        }
18209        return false;
18210    }
18211
18212    /** @hide */
18213    public void setDisabledSystemUiVisibility(int flags) {
18214        if (mAttachInfo != null) {
18215            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18216                mAttachInfo.mDisabledSystemUiVisibility = flags;
18217                if (mParent != null) {
18218                    mParent.recomputeViewAttributes(this);
18219                }
18220            }
18221        }
18222    }
18223
18224    /**
18225     * Creates an image that the system displays during the drag and drop
18226     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18227     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18228     * appearance as the given View. The default also positions the center of the drag shadow
18229     * directly under the touch point. If no View is provided (the constructor with no parameters
18230     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18231     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
18232     * default is an invisible drag shadow.
18233     * <p>
18234     * You are not required to use the View you provide to the constructor as the basis of the
18235     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18236     * anything you want as the drag shadow.
18237     * </p>
18238     * <p>
18239     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18240     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18241     *  size and position of the drag shadow. It uses this data to construct a
18242     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18243     *  so that your application can draw the shadow image in the Canvas.
18244     * </p>
18245     *
18246     * <div class="special reference">
18247     * <h3>Developer Guides</h3>
18248     * <p>For a guide to implementing drag and drop features, read the
18249     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18250     * </div>
18251     */
18252    public static class DragShadowBuilder {
18253        private final WeakReference<View> mView;
18254
18255        /**
18256         * Constructs a shadow image builder based on a View. By default, the resulting drag
18257         * shadow will have the same appearance and dimensions as the View, with the touch point
18258         * over the center of the View.
18259         * @param view A View. Any View in scope can be used.
18260         */
18261        public DragShadowBuilder(View view) {
18262            mView = new WeakReference<View>(view);
18263        }
18264
18265        /**
18266         * Construct a shadow builder object with no associated View.  This
18267         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18268         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18269         * to supply the drag shadow's dimensions and appearance without
18270         * reference to any View object. If they are not overridden, then the result is an
18271         * invisible drag shadow.
18272         */
18273        public DragShadowBuilder() {
18274            mView = new WeakReference<View>(null);
18275        }
18276
18277        /**
18278         * Returns the View object that had been passed to the
18279         * {@link #View.DragShadowBuilder(View)}
18280         * constructor.  If that View parameter was {@code null} or if the
18281         * {@link #View.DragShadowBuilder()}
18282         * constructor was used to instantiate the builder object, this method will return
18283         * null.
18284         *
18285         * @return The View object associate with this builder object.
18286         */
18287        @SuppressWarnings({"JavadocReference"})
18288        final public View getView() {
18289            return mView.get();
18290        }
18291
18292        /**
18293         * Provides the metrics for the shadow image. These include the dimensions of
18294         * the shadow image, and the point within that shadow that should
18295         * be centered under the touch location while dragging.
18296         * <p>
18297         * The default implementation sets the dimensions of the shadow to be the
18298         * same as the dimensions of the View itself and centers the shadow under
18299         * the touch point.
18300         * </p>
18301         *
18302         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18303         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18304         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18305         * image.
18306         *
18307         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18308         * shadow image that should be underneath the touch point during the drag and drop
18309         * operation. Your application must set {@link android.graphics.Point#x} to the
18310         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18311         */
18312        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18313            final View view = mView.get();
18314            if (view != null) {
18315                shadowSize.set(view.getWidth(), view.getHeight());
18316                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18317            } else {
18318                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18319            }
18320        }
18321
18322        /**
18323         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18324         * based on the dimensions it received from the
18325         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18326         *
18327         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18328         */
18329        public void onDrawShadow(Canvas canvas) {
18330            final View view = mView.get();
18331            if (view != null) {
18332                view.draw(canvas);
18333            } else {
18334                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
18335            }
18336        }
18337    }
18338
18339    /**
18340     * Starts a drag and drop operation. When your application calls this method, it passes a
18341     * {@link android.view.View.DragShadowBuilder} object to the system. The
18342     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
18343     * to get metrics for the drag shadow, and then calls the object's
18344     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
18345     * <p>
18346     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
18347     *  drag events to all the View objects in your application that are currently visible. It does
18348     *  this either by calling the View object's drag listener (an implementation of
18349     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
18350     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
18351     *  Both are passed a {@link android.view.DragEvent} object that has a
18352     *  {@link android.view.DragEvent#getAction()} value of
18353     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
18354     * </p>
18355     * <p>
18356     * Your application can invoke startDrag() on any attached View object. The View object does not
18357     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
18358     * be related to the View the user selected for dragging.
18359     * </p>
18360     * @param data A {@link android.content.ClipData} object pointing to the data to be
18361     * transferred by the drag and drop operation.
18362     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
18363     * drag shadow.
18364     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
18365     * drop operation. This Object is put into every DragEvent object sent by the system during the
18366     * current drag.
18367     * <p>
18368     * myLocalState is a lightweight mechanism for the sending information from the dragged View
18369     * to the target Views. For example, it can contain flags that differentiate between a
18370     * a copy operation and a move operation.
18371     * </p>
18372     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
18373     * so the parameter should be set to 0.
18374     * @return {@code true} if the method completes successfully, or
18375     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
18376     * do a drag, and so no drag operation is in progress.
18377     */
18378    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
18379            Object myLocalState, int flags) {
18380        if (ViewDebug.DEBUG_DRAG) {
18381            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
18382        }
18383        boolean okay = false;
18384
18385        Point shadowSize = new Point();
18386        Point shadowTouchPoint = new Point();
18387        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18388
18389        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18390                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18391            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18392        }
18393
18394        if (ViewDebug.DEBUG_DRAG) {
18395            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18396                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18397        }
18398        Surface surface = new Surface();
18399        try {
18400            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18401                    flags, shadowSize.x, shadowSize.y, surface);
18402            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18403                    + " surface=" + surface);
18404            if (token != null) {
18405                Canvas canvas = surface.lockCanvas(null);
18406                try {
18407                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18408                    shadowBuilder.onDrawShadow(canvas);
18409                } finally {
18410                    surface.unlockCanvasAndPost(canvas);
18411                }
18412
18413                final ViewRootImpl root = getViewRootImpl();
18414
18415                // Cache the local state object for delivery with DragEvents
18416                root.setLocalDragState(myLocalState);
18417
18418                // repurpose 'shadowSize' for the last touch point
18419                root.getLastTouchPoint(shadowSize);
18420
18421                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18422                        shadowSize.x, shadowSize.y,
18423                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18424                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18425
18426                // Off and running!  Release our local surface instance; the drag
18427                // shadow surface is now managed by the system process.
18428                surface.release();
18429            }
18430        } catch (Exception e) {
18431            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18432            surface.destroy();
18433        }
18434
18435        return okay;
18436    }
18437
18438    /**
18439     * Handles drag events sent by the system following a call to
18440     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18441     *<p>
18442     * When the system calls this method, it passes a
18443     * {@link android.view.DragEvent} object. A call to
18444     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18445     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18446     * operation.
18447     * @param event The {@link android.view.DragEvent} sent by the system.
18448     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18449     * in DragEvent, indicating the type of drag event represented by this object.
18450     * @return {@code true} if the method was successful, otherwise {@code false}.
18451     * <p>
18452     *  The method should return {@code true} in response to an action type of
18453     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18454     *  operation.
18455     * </p>
18456     * <p>
18457     *  The method should also return {@code true} in response to an action type of
18458     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18459     *  {@code false} if it didn't.
18460     * </p>
18461     */
18462    public boolean onDragEvent(DragEvent event) {
18463        return false;
18464    }
18465
18466    /**
18467     * Detects if this View is enabled and has a drag event listener.
18468     * If both are true, then it calls the drag event listener with the
18469     * {@link android.view.DragEvent} it received. If the drag event listener returns
18470     * {@code true}, then dispatchDragEvent() returns {@code true}.
18471     * <p>
18472     * For all other cases, the method calls the
18473     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18474     * method and returns its result.
18475     * </p>
18476     * <p>
18477     * This ensures that a drag event is always consumed, even if the View does not have a drag
18478     * event listener. However, if the View has a listener and the listener returns true, then
18479     * onDragEvent() is not called.
18480     * </p>
18481     */
18482    public boolean dispatchDragEvent(DragEvent event) {
18483        ListenerInfo li = mListenerInfo;
18484        //noinspection SimplifiableIfStatement
18485        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18486                && li.mOnDragListener.onDrag(this, event)) {
18487            return true;
18488        }
18489        return onDragEvent(event);
18490    }
18491
18492    boolean canAcceptDrag() {
18493        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18494    }
18495
18496    /**
18497     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18498     * it is ever exposed at all.
18499     * @hide
18500     */
18501    public void onCloseSystemDialogs(String reason) {
18502    }
18503
18504    /**
18505     * Given a Drawable whose bounds have been set to draw into this view,
18506     * update a Region being computed for
18507     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18508     * that any non-transparent parts of the Drawable are removed from the
18509     * given transparent region.
18510     *
18511     * @param dr The Drawable whose transparency is to be applied to the region.
18512     * @param region A Region holding the current transparency information,
18513     * where any parts of the region that are set are considered to be
18514     * transparent.  On return, this region will be modified to have the
18515     * transparency information reduced by the corresponding parts of the
18516     * Drawable that are not transparent.
18517     * {@hide}
18518     */
18519    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18520        if (DBG) {
18521            Log.i("View", "Getting transparent region for: " + this);
18522        }
18523        final Region r = dr.getTransparentRegion();
18524        final Rect db = dr.getBounds();
18525        final AttachInfo attachInfo = mAttachInfo;
18526        if (r != null && attachInfo != null) {
18527            final int w = getRight()-getLeft();
18528            final int h = getBottom()-getTop();
18529            if (db.left > 0) {
18530                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18531                r.op(0, 0, db.left, h, Region.Op.UNION);
18532            }
18533            if (db.right < w) {
18534                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18535                r.op(db.right, 0, w, h, Region.Op.UNION);
18536            }
18537            if (db.top > 0) {
18538                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18539                r.op(0, 0, w, db.top, Region.Op.UNION);
18540            }
18541            if (db.bottom < h) {
18542                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18543                r.op(0, db.bottom, w, h, Region.Op.UNION);
18544            }
18545            final int[] location = attachInfo.mTransparentLocation;
18546            getLocationInWindow(location);
18547            r.translate(location[0], location[1]);
18548            region.op(r, Region.Op.INTERSECT);
18549        } else {
18550            region.op(db, Region.Op.DIFFERENCE);
18551        }
18552    }
18553
18554    private void checkForLongClick(int delayOffset) {
18555        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18556            mHasPerformedLongPress = false;
18557
18558            if (mPendingCheckForLongPress == null) {
18559                mPendingCheckForLongPress = new CheckForLongPress();
18560            }
18561            mPendingCheckForLongPress.rememberWindowAttachCount();
18562            postDelayed(mPendingCheckForLongPress,
18563                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18564        }
18565    }
18566
18567    /**
18568     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18569     * LayoutInflater} class, which provides a full range of options for view inflation.
18570     *
18571     * @param context The Context object for your activity or application.
18572     * @param resource The resource ID to inflate
18573     * @param root A view group that will be the parent.  Used to properly inflate the
18574     * layout_* parameters.
18575     * @see LayoutInflater
18576     */
18577    public static View inflate(Context context, int resource, ViewGroup root) {
18578        LayoutInflater factory = LayoutInflater.from(context);
18579        return factory.inflate(resource, root);
18580    }
18581
18582    /**
18583     * Scroll the view with standard behavior for scrolling beyond the normal
18584     * content boundaries. Views that call this method should override
18585     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18586     * results of an over-scroll operation.
18587     *
18588     * Views can use this method to handle any touch or fling-based scrolling.
18589     *
18590     * @param deltaX Change in X in pixels
18591     * @param deltaY Change in Y in pixels
18592     * @param scrollX Current X scroll value in pixels before applying deltaX
18593     * @param scrollY Current Y scroll value in pixels before applying deltaY
18594     * @param scrollRangeX Maximum content scroll range along the X axis
18595     * @param scrollRangeY Maximum content scroll range along the Y axis
18596     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18597     *          along the X axis.
18598     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18599     *          along the Y axis.
18600     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18601     * @return true if scrolling was clamped to an over-scroll boundary along either
18602     *          axis, false otherwise.
18603     */
18604    @SuppressWarnings({"UnusedParameters"})
18605    protected boolean overScrollBy(int deltaX, int deltaY,
18606            int scrollX, int scrollY,
18607            int scrollRangeX, int scrollRangeY,
18608            int maxOverScrollX, int maxOverScrollY,
18609            boolean isTouchEvent) {
18610        final int overScrollMode = mOverScrollMode;
18611        final boolean canScrollHorizontal =
18612                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18613        final boolean canScrollVertical =
18614                computeVerticalScrollRange() > computeVerticalScrollExtent();
18615        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18616                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18617        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18618                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18619
18620        int newScrollX = scrollX + deltaX;
18621        if (!overScrollHorizontal) {
18622            maxOverScrollX = 0;
18623        }
18624
18625        int newScrollY = scrollY + deltaY;
18626        if (!overScrollVertical) {
18627            maxOverScrollY = 0;
18628        }
18629
18630        // Clamp values if at the limits and record
18631        final int left = -maxOverScrollX;
18632        final int right = maxOverScrollX + scrollRangeX;
18633        final int top = -maxOverScrollY;
18634        final int bottom = maxOverScrollY + scrollRangeY;
18635
18636        boolean clampedX = false;
18637        if (newScrollX > right) {
18638            newScrollX = right;
18639            clampedX = true;
18640        } else if (newScrollX < left) {
18641            newScrollX = left;
18642            clampedX = true;
18643        }
18644
18645        boolean clampedY = false;
18646        if (newScrollY > bottom) {
18647            newScrollY = bottom;
18648            clampedY = true;
18649        } else if (newScrollY < top) {
18650            newScrollY = top;
18651            clampedY = true;
18652        }
18653
18654        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18655
18656        return clampedX || clampedY;
18657    }
18658
18659    /**
18660     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18661     * respond to the results of an over-scroll operation.
18662     *
18663     * @param scrollX New X scroll value in pixels
18664     * @param scrollY New Y scroll value in pixels
18665     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18666     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18667     */
18668    protected void onOverScrolled(int scrollX, int scrollY,
18669            boolean clampedX, boolean clampedY) {
18670        // Intentionally empty.
18671    }
18672
18673    /**
18674     * Returns the over-scroll mode for this view. The result will be
18675     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18676     * (allow over-scrolling only if the view content is larger than the container),
18677     * or {@link #OVER_SCROLL_NEVER}.
18678     *
18679     * @return This view's over-scroll mode.
18680     */
18681    public int getOverScrollMode() {
18682        return mOverScrollMode;
18683    }
18684
18685    /**
18686     * Set the over-scroll mode for this view. Valid over-scroll modes are
18687     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18688     * (allow over-scrolling only if the view content is larger than the container),
18689     * or {@link #OVER_SCROLL_NEVER}.
18690     *
18691     * Setting the over-scroll mode of a view will have an effect only if the
18692     * view is capable of scrolling.
18693     *
18694     * @param overScrollMode The new over-scroll mode for this view.
18695     */
18696    public void setOverScrollMode(int overScrollMode) {
18697        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18698                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18699                overScrollMode != OVER_SCROLL_NEVER) {
18700            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18701        }
18702        mOverScrollMode = overScrollMode;
18703    }
18704
18705    /**
18706     * Enable or disable nested scrolling for this view.
18707     *
18708     * <p>If this property is set to true the view will be permitted to initiate nested
18709     * scrolling operations with a compatible parent view in the current hierarchy. If this
18710     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18711     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18712     * the nested scroll.</p>
18713     *
18714     * @param enabled true to enable nested scrolling, false to disable
18715     *
18716     * @see #isNestedScrollingEnabled()
18717     */
18718    public void setNestedScrollingEnabled(boolean enabled) {
18719        if (enabled) {
18720            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18721        } else {
18722            stopNestedScroll();
18723            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18724        }
18725    }
18726
18727    /**
18728     * Returns true if nested scrolling is enabled for this view.
18729     *
18730     * <p>If nested scrolling is enabled and this View class implementation supports it,
18731     * this view will act as a nested scrolling child view when applicable, forwarding data
18732     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18733     * parent.</p>
18734     *
18735     * @return true if nested scrolling is enabled
18736     *
18737     * @see #setNestedScrollingEnabled(boolean)
18738     */
18739    public boolean isNestedScrollingEnabled() {
18740        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18741                PFLAG3_NESTED_SCROLLING_ENABLED;
18742    }
18743
18744    /**
18745     * Begin a nestable scroll operation along the given axes.
18746     *
18747     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18748     *
18749     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18750     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18751     * In the case of touch scrolling the nested scroll will be terminated automatically in
18752     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18753     * In the event of programmatic scrolling the caller must explicitly call
18754     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18755     *
18756     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18757     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18758     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18759     *
18760     * <p>At each incremental step of the scroll the caller should invoke
18761     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18762     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18763     * parent at least partially consumed the scroll and the caller should adjust the amount it
18764     * scrolls by.</p>
18765     *
18766     * <p>After applying the remainder of the scroll delta the caller should invoke
18767     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18768     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18769     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18770     * </p>
18771     *
18772     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18773     *             {@link #SCROLL_AXIS_VERTICAL}.
18774     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18775     *         the current gesture.
18776     *
18777     * @see #stopNestedScroll()
18778     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18779     * @see #dispatchNestedScroll(int, int, int, int, int[])
18780     */
18781    public boolean startNestedScroll(int axes) {
18782        if (hasNestedScrollingParent()) {
18783            // Already in progress
18784            return true;
18785        }
18786        if (isNestedScrollingEnabled()) {
18787            ViewParent p = getParent();
18788            View child = this;
18789            while (p != null) {
18790                try {
18791                    if (p.onStartNestedScroll(child, this, axes)) {
18792                        mNestedScrollingParent = p;
18793                        p.onNestedScrollAccepted(child, this, axes);
18794                        return true;
18795                    }
18796                } catch (AbstractMethodError e) {
18797                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18798                            "method onStartNestedScroll", e);
18799                    // Allow the search upward to continue
18800                }
18801                if (p instanceof View) {
18802                    child = (View) p;
18803                }
18804                p = p.getParent();
18805            }
18806        }
18807        return false;
18808    }
18809
18810    /**
18811     * Stop a nested scroll in progress.
18812     *
18813     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18814     *
18815     * @see #startNestedScroll(int)
18816     */
18817    public void stopNestedScroll() {
18818        if (mNestedScrollingParent != null) {
18819            mNestedScrollingParent.onStopNestedScroll(this);
18820            mNestedScrollingParent = null;
18821        }
18822    }
18823
18824    /**
18825     * Returns true if this view has a nested scrolling parent.
18826     *
18827     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18828     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18829     *
18830     * @return whether this view has a nested scrolling parent
18831     */
18832    public boolean hasNestedScrollingParent() {
18833        return mNestedScrollingParent != null;
18834    }
18835
18836    /**
18837     * Dispatch one step of a nested scroll in progress.
18838     *
18839     * <p>Implementations of views that support nested scrolling should call this to report
18840     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18841     * is not currently in progress or nested scrolling is not
18842     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18843     *
18844     * <p>Compatible View implementations should also call
18845     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18846     * consuming a component of the scroll event themselves.</p>
18847     *
18848     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18849     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18850     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18851     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18852     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18853     *                       in local view coordinates of this view from before this operation
18854     *                       to after it completes. View implementations may use this to adjust
18855     *                       expected input coordinate tracking.
18856     * @return true if the event was dispatched, false if it could not be dispatched.
18857     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18858     */
18859    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18860            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18861        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18862            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18863                int startX = 0;
18864                int startY = 0;
18865                if (offsetInWindow != null) {
18866                    getLocationInWindow(offsetInWindow);
18867                    startX = offsetInWindow[0];
18868                    startY = offsetInWindow[1];
18869                }
18870
18871                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18872                        dxUnconsumed, dyUnconsumed);
18873
18874                if (offsetInWindow != null) {
18875                    getLocationInWindow(offsetInWindow);
18876                    offsetInWindow[0] -= startX;
18877                    offsetInWindow[1] -= startY;
18878                }
18879                return true;
18880            } else if (offsetInWindow != null) {
18881                // No motion, no dispatch. Keep offsetInWindow up to date.
18882                offsetInWindow[0] = 0;
18883                offsetInWindow[1] = 0;
18884            }
18885        }
18886        return false;
18887    }
18888
18889    /**
18890     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18891     *
18892     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18893     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18894     * scrolling operation to consume some or all of the scroll operation before the child view
18895     * consumes it.</p>
18896     *
18897     * @param dx Horizontal scroll distance in pixels
18898     * @param dy Vertical scroll distance in pixels
18899     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18900     *                 and consumed[1] the consumed dy.
18901     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18902     *                       in local view coordinates of this view from before this operation
18903     *                       to after it completes. View implementations may use this to adjust
18904     *                       expected input coordinate tracking.
18905     * @return true if the parent consumed some or all of the scroll delta
18906     * @see #dispatchNestedScroll(int, int, int, int, int[])
18907     */
18908    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18909        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18910            if (dx != 0 || dy != 0) {
18911                int startX = 0;
18912                int startY = 0;
18913                if (offsetInWindow != null) {
18914                    getLocationInWindow(offsetInWindow);
18915                    startX = offsetInWindow[0];
18916                    startY = offsetInWindow[1];
18917                }
18918
18919                if (consumed == null) {
18920                    if (mTempNestedScrollConsumed == null) {
18921                        mTempNestedScrollConsumed = new int[2];
18922                    }
18923                    consumed = mTempNestedScrollConsumed;
18924                }
18925                consumed[0] = 0;
18926                consumed[1] = 0;
18927                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18928
18929                if (offsetInWindow != null) {
18930                    getLocationInWindow(offsetInWindow);
18931                    offsetInWindow[0] -= startX;
18932                    offsetInWindow[1] -= startY;
18933                }
18934                return consumed[0] != 0 || consumed[1] != 0;
18935            } else if (offsetInWindow != null) {
18936                offsetInWindow[0] = 0;
18937                offsetInWindow[1] = 0;
18938            }
18939        }
18940        return false;
18941    }
18942
18943    /**
18944     * Dispatch a fling to a nested scrolling parent.
18945     *
18946     * <p>This method should be used to indicate that a nested scrolling child has detected
18947     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18948     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18949     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18950     * along a scrollable axis.</p>
18951     *
18952     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18953     * its own content, it can use this method to delegate the fling to its nested scrolling
18954     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18955     *
18956     * @param velocityX Horizontal fling velocity in pixels per second
18957     * @param velocityY Vertical fling velocity in pixels per second
18958     * @param consumed true if the child consumed the fling, false otherwise
18959     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18960     */
18961    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18962        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18963            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18964        }
18965        return false;
18966    }
18967
18968    /**
18969     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18970     *
18971     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18972     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18973     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18974     * before the child view consumes it. If this method returns <code>true</code>, a nested
18975     * parent view consumed the fling and this view should not scroll as a result.</p>
18976     *
18977     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18978     * the fling at a time. If a parent view consumed the fling this method will return false.
18979     * Custom view implementations should account for this in two ways:</p>
18980     *
18981     * <ul>
18982     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18983     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18984     *     position regardless.</li>
18985     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18986     *     even to settle back to a valid idle position.</li>
18987     * </ul>
18988     *
18989     * <p>Views should also not offer fling velocities to nested parent views along an axis
18990     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18991     * should not offer a horizontal fling velocity to its parents since scrolling along that
18992     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18993     *
18994     * @param velocityX Horizontal fling velocity in pixels per second
18995     * @param velocityY Vertical fling velocity in pixels per second
18996     * @return true if a nested scrolling parent consumed the fling
18997     */
18998    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18999        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19000            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19001        }
19002        return false;
19003    }
19004
19005    /**
19006     * Gets a scale factor that determines the distance the view should scroll
19007     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19008     * @return The vertical scroll scale factor.
19009     * @hide
19010     */
19011    protected float getVerticalScrollFactor() {
19012        if (mVerticalScrollFactor == 0) {
19013            TypedValue outValue = new TypedValue();
19014            if (!mContext.getTheme().resolveAttribute(
19015                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19016                throw new IllegalStateException(
19017                        "Expected theme to define listPreferredItemHeight.");
19018            }
19019            mVerticalScrollFactor = outValue.getDimension(
19020                    mContext.getResources().getDisplayMetrics());
19021        }
19022        return mVerticalScrollFactor;
19023    }
19024
19025    /**
19026     * Gets a scale factor that determines the distance the view should scroll
19027     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19028     * @return The horizontal scroll scale factor.
19029     * @hide
19030     */
19031    protected float getHorizontalScrollFactor() {
19032        // TODO: Should use something else.
19033        return getVerticalScrollFactor();
19034    }
19035
19036    /**
19037     * Return the value specifying the text direction or policy that was set with
19038     * {@link #setTextDirection(int)}.
19039     *
19040     * @return the defined text direction. It can be one of:
19041     *
19042     * {@link #TEXT_DIRECTION_INHERIT},
19043     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19044     * {@link #TEXT_DIRECTION_ANY_RTL},
19045     * {@link #TEXT_DIRECTION_LTR},
19046     * {@link #TEXT_DIRECTION_RTL},
19047     * {@link #TEXT_DIRECTION_LOCALE}
19048     *
19049     * @attr ref android.R.styleable#View_textDirection
19050     *
19051     * @hide
19052     */
19053    @ViewDebug.ExportedProperty(category = "text", mapping = {
19054            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19055            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19056            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19057            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19058            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19059            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19060    })
19061    public int getRawTextDirection() {
19062        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19063    }
19064
19065    /**
19066     * Set the text direction.
19067     *
19068     * @param textDirection the direction to set. Should be one of:
19069     *
19070     * {@link #TEXT_DIRECTION_INHERIT},
19071     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19072     * {@link #TEXT_DIRECTION_ANY_RTL},
19073     * {@link #TEXT_DIRECTION_LTR},
19074     * {@link #TEXT_DIRECTION_RTL},
19075     * {@link #TEXT_DIRECTION_LOCALE}
19076     *
19077     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19078     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19079     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19080     *
19081     * @attr ref android.R.styleable#View_textDirection
19082     */
19083    public void setTextDirection(int textDirection) {
19084        if (getRawTextDirection() != textDirection) {
19085            // Reset the current text direction and the resolved one
19086            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19087            resetResolvedTextDirection();
19088            // Set the new text direction
19089            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19090            // Do resolution
19091            resolveTextDirection();
19092            // Notify change
19093            onRtlPropertiesChanged(getLayoutDirection());
19094            // Refresh
19095            requestLayout();
19096            invalidate(true);
19097        }
19098    }
19099
19100    /**
19101     * Return the resolved text direction.
19102     *
19103     * @return the resolved text direction. Returns one of:
19104     *
19105     * {@link #TEXT_DIRECTION_FIRST_STRONG}
19106     * {@link #TEXT_DIRECTION_ANY_RTL},
19107     * {@link #TEXT_DIRECTION_LTR},
19108     * {@link #TEXT_DIRECTION_RTL},
19109     * {@link #TEXT_DIRECTION_LOCALE}
19110     *
19111     * @attr ref android.R.styleable#View_textDirection
19112     */
19113    @ViewDebug.ExportedProperty(category = "text", mapping = {
19114            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19115            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19116            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19117            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19118            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19119            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
19120    })
19121    public int getTextDirection() {
19122        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19123    }
19124
19125    /**
19126     * Resolve the text direction.
19127     *
19128     * @return true if resolution has been done, false otherwise.
19129     *
19130     * @hide
19131     */
19132    public boolean resolveTextDirection() {
19133        // Reset any previous text direction resolution
19134        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19135
19136        if (hasRtlSupport()) {
19137            // Set resolved text direction flag depending on text direction flag
19138            final int textDirection = getRawTextDirection();
19139            switch(textDirection) {
19140                case TEXT_DIRECTION_INHERIT:
19141                    if (!canResolveTextDirection()) {
19142                        // We cannot do the resolution if there is no parent, so use the default one
19143                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19144                        // Resolution will need to happen again later
19145                        return false;
19146                    }
19147
19148                    // Parent has not yet resolved, so we still return the default
19149                    try {
19150                        if (!mParent.isTextDirectionResolved()) {
19151                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19152                            // Resolution will need to happen again later
19153                            return false;
19154                        }
19155                    } catch (AbstractMethodError e) {
19156                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19157                                " does not fully implement ViewParent", e);
19158                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19159                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19160                        return true;
19161                    }
19162
19163                    // Set current resolved direction to the same value as the parent's one
19164                    int parentResolvedDirection;
19165                    try {
19166                        parentResolvedDirection = mParent.getTextDirection();
19167                    } catch (AbstractMethodError e) {
19168                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19169                                " does not fully implement ViewParent", e);
19170                        parentResolvedDirection = TEXT_DIRECTION_LTR;
19171                    }
19172                    switch (parentResolvedDirection) {
19173                        case TEXT_DIRECTION_FIRST_STRONG:
19174                        case TEXT_DIRECTION_ANY_RTL:
19175                        case TEXT_DIRECTION_LTR:
19176                        case TEXT_DIRECTION_RTL:
19177                        case TEXT_DIRECTION_LOCALE:
19178                            mPrivateFlags2 |=
19179                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19180                            break;
19181                        default:
19182                            // Default resolved direction is "first strong" heuristic
19183                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19184                    }
19185                    break;
19186                case TEXT_DIRECTION_FIRST_STRONG:
19187                case TEXT_DIRECTION_ANY_RTL:
19188                case TEXT_DIRECTION_LTR:
19189                case TEXT_DIRECTION_RTL:
19190                case TEXT_DIRECTION_LOCALE:
19191                    // Resolved direction is the same as text direction
19192                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19193                    break;
19194                default:
19195                    // Default resolved direction is "first strong" heuristic
19196                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19197            }
19198        } else {
19199            // Default resolved direction is "first strong" heuristic
19200            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19201        }
19202
19203        // Set to resolved
19204        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19205        return true;
19206    }
19207
19208    /**
19209     * Check if text direction resolution can be done.
19210     *
19211     * @return true if text direction resolution can be done otherwise return false.
19212     */
19213    public boolean canResolveTextDirection() {
19214        switch (getRawTextDirection()) {
19215            case TEXT_DIRECTION_INHERIT:
19216                if (mParent != null) {
19217                    try {
19218                        return mParent.canResolveTextDirection();
19219                    } catch (AbstractMethodError e) {
19220                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19221                                " does not fully implement ViewParent", e);
19222                    }
19223                }
19224                return false;
19225
19226            default:
19227                return true;
19228        }
19229    }
19230
19231    /**
19232     * Reset resolved text direction. Text direction will be resolved during a call to
19233     * {@link #onMeasure(int, int)}.
19234     *
19235     * @hide
19236     */
19237    public void resetResolvedTextDirection() {
19238        // Reset any previous text direction resolution
19239        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19240        // Set to default value
19241        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19242    }
19243
19244    /**
19245     * @return true if text direction is inherited.
19246     *
19247     * @hide
19248     */
19249    public boolean isTextDirectionInherited() {
19250        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19251    }
19252
19253    /**
19254     * @return true if text direction is resolved.
19255     */
19256    public boolean isTextDirectionResolved() {
19257        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19258    }
19259
19260    /**
19261     * Return the value specifying the text alignment or policy that was set with
19262     * {@link #setTextAlignment(int)}.
19263     *
19264     * @return the defined text alignment. It can be one of:
19265     *
19266     * {@link #TEXT_ALIGNMENT_INHERIT},
19267     * {@link #TEXT_ALIGNMENT_GRAVITY},
19268     * {@link #TEXT_ALIGNMENT_CENTER},
19269     * {@link #TEXT_ALIGNMENT_TEXT_START},
19270     * {@link #TEXT_ALIGNMENT_TEXT_END},
19271     * {@link #TEXT_ALIGNMENT_VIEW_START},
19272     * {@link #TEXT_ALIGNMENT_VIEW_END}
19273     *
19274     * @attr ref android.R.styleable#View_textAlignment
19275     *
19276     * @hide
19277     */
19278    @ViewDebug.ExportedProperty(category = "text", mapping = {
19279            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19280            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19281            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19282            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19283            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19284            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19285            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19286    })
19287    @TextAlignment
19288    public int getRawTextAlignment() {
19289        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19290    }
19291
19292    /**
19293     * Set the text alignment.
19294     *
19295     * @param textAlignment The text alignment to set. Should be one of
19296     *
19297     * {@link #TEXT_ALIGNMENT_INHERIT},
19298     * {@link #TEXT_ALIGNMENT_GRAVITY},
19299     * {@link #TEXT_ALIGNMENT_CENTER},
19300     * {@link #TEXT_ALIGNMENT_TEXT_START},
19301     * {@link #TEXT_ALIGNMENT_TEXT_END},
19302     * {@link #TEXT_ALIGNMENT_VIEW_START},
19303     * {@link #TEXT_ALIGNMENT_VIEW_END}
19304     *
19305     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19306     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19307     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19308     *
19309     * @attr ref android.R.styleable#View_textAlignment
19310     */
19311    public void setTextAlignment(@TextAlignment int textAlignment) {
19312        if (textAlignment != getRawTextAlignment()) {
19313            // Reset the current and resolved text alignment
19314            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19315            resetResolvedTextAlignment();
19316            // Set the new text alignment
19317            mPrivateFlags2 |=
19318                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
19319            // Do resolution
19320            resolveTextAlignment();
19321            // Notify change
19322            onRtlPropertiesChanged(getLayoutDirection());
19323            // Refresh
19324            requestLayout();
19325            invalidate(true);
19326        }
19327    }
19328
19329    /**
19330     * Return the resolved text alignment.
19331     *
19332     * @return the resolved text alignment. Returns one of:
19333     *
19334     * {@link #TEXT_ALIGNMENT_GRAVITY},
19335     * {@link #TEXT_ALIGNMENT_CENTER},
19336     * {@link #TEXT_ALIGNMENT_TEXT_START},
19337     * {@link #TEXT_ALIGNMENT_TEXT_END},
19338     * {@link #TEXT_ALIGNMENT_VIEW_START},
19339     * {@link #TEXT_ALIGNMENT_VIEW_END}
19340     *
19341     * @attr ref android.R.styleable#View_textAlignment
19342     */
19343    @ViewDebug.ExportedProperty(category = "text", mapping = {
19344            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19345            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19346            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19347            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19348            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19349            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19350            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19351    })
19352    @TextAlignment
19353    public int getTextAlignment() {
19354        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
19355                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
19356    }
19357
19358    /**
19359     * Resolve the text alignment.
19360     *
19361     * @return true if resolution has been done, false otherwise.
19362     *
19363     * @hide
19364     */
19365    public boolean resolveTextAlignment() {
19366        // Reset any previous text alignment resolution
19367        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19368
19369        if (hasRtlSupport()) {
19370            // Set resolved text alignment flag depending on text alignment flag
19371            final int textAlignment = getRawTextAlignment();
19372            switch (textAlignment) {
19373                case TEXT_ALIGNMENT_INHERIT:
19374                    // Check if we can resolve the text alignment
19375                    if (!canResolveTextAlignment()) {
19376                        // We cannot do the resolution if there is no parent so use the default
19377                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19378                        // Resolution will need to happen again later
19379                        return false;
19380                    }
19381
19382                    // Parent has not yet resolved, so we still return the default
19383                    try {
19384                        if (!mParent.isTextAlignmentResolved()) {
19385                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19386                            // Resolution will need to happen again later
19387                            return false;
19388                        }
19389                    } catch (AbstractMethodError e) {
19390                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19391                                " does not fully implement ViewParent", e);
19392                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
19393                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19394                        return true;
19395                    }
19396
19397                    int parentResolvedTextAlignment;
19398                    try {
19399                        parentResolvedTextAlignment = mParent.getTextAlignment();
19400                    } catch (AbstractMethodError e) {
19401                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19402                                " does not fully implement ViewParent", e);
19403                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
19404                    }
19405                    switch (parentResolvedTextAlignment) {
19406                        case TEXT_ALIGNMENT_GRAVITY:
19407                        case TEXT_ALIGNMENT_TEXT_START:
19408                        case TEXT_ALIGNMENT_TEXT_END:
19409                        case TEXT_ALIGNMENT_CENTER:
19410                        case TEXT_ALIGNMENT_VIEW_START:
19411                        case TEXT_ALIGNMENT_VIEW_END:
19412                            // Resolved text alignment is the same as the parent resolved
19413                            // text alignment
19414                            mPrivateFlags2 |=
19415                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19416                            break;
19417                        default:
19418                            // Use default resolved text alignment
19419                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19420                    }
19421                    break;
19422                case TEXT_ALIGNMENT_GRAVITY:
19423                case TEXT_ALIGNMENT_TEXT_START:
19424                case TEXT_ALIGNMENT_TEXT_END:
19425                case TEXT_ALIGNMENT_CENTER:
19426                case TEXT_ALIGNMENT_VIEW_START:
19427                case TEXT_ALIGNMENT_VIEW_END:
19428                    // Resolved text alignment is the same as text alignment
19429                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19430                    break;
19431                default:
19432                    // Use default resolved text alignment
19433                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19434            }
19435        } else {
19436            // Use default resolved text alignment
19437            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19438        }
19439
19440        // Set the resolved
19441        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19442        return true;
19443    }
19444
19445    /**
19446     * Check if text alignment resolution can be done.
19447     *
19448     * @return true if text alignment resolution can be done otherwise return false.
19449     */
19450    public boolean canResolveTextAlignment() {
19451        switch (getRawTextAlignment()) {
19452            case TEXT_DIRECTION_INHERIT:
19453                if (mParent != null) {
19454                    try {
19455                        return mParent.canResolveTextAlignment();
19456                    } catch (AbstractMethodError e) {
19457                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19458                                " does not fully implement ViewParent", e);
19459                    }
19460                }
19461                return false;
19462
19463            default:
19464                return true;
19465        }
19466    }
19467
19468    /**
19469     * Reset resolved text alignment. Text alignment will be resolved during a call to
19470     * {@link #onMeasure(int, int)}.
19471     *
19472     * @hide
19473     */
19474    public void resetResolvedTextAlignment() {
19475        // Reset any previous text alignment resolution
19476        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19477        // Set to default
19478        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19479    }
19480
19481    /**
19482     * @return true if text alignment is inherited.
19483     *
19484     * @hide
19485     */
19486    public boolean isTextAlignmentInherited() {
19487        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
19488    }
19489
19490    /**
19491     * @return true if text alignment is resolved.
19492     */
19493    public boolean isTextAlignmentResolved() {
19494        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19495    }
19496
19497    /**
19498     * Generate a value suitable for use in {@link #setId(int)}.
19499     * This value will not collide with ID values generated at build time by aapt for R.id.
19500     *
19501     * @return a generated ID value
19502     */
19503    public static int generateViewId() {
19504        for (;;) {
19505            final int result = sNextGeneratedId.get();
19506            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
19507            int newValue = result + 1;
19508            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
19509            if (sNextGeneratedId.compareAndSet(result, newValue)) {
19510                return result;
19511            }
19512        }
19513    }
19514
19515    /**
19516     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
19517     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
19518     *                           a normal View or a ViewGroup with
19519     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
19520     * @hide
19521     */
19522    public void captureTransitioningViews(List<View> transitioningViews) {
19523        if (getVisibility() == View.VISIBLE) {
19524            transitioningViews.add(this);
19525        }
19526    }
19527
19528    /**
19529     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19530     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19531     * @hide
19532     */
19533    public void findNamedViews(Map<String, View> namedElements) {
19534        if (getVisibility() == VISIBLE || mGhostView != null) {
19535            String transitionName = getTransitionName();
19536            if (transitionName != null) {
19537                namedElements.put(transitionName, this);
19538            }
19539        }
19540    }
19541
19542    //
19543    // Properties
19544    //
19545    /**
19546     * A Property wrapper around the <code>alpha</code> functionality handled by the
19547     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19548     */
19549    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19550        @Override
19551        public void setValue(View object, float value) {
19552            object.setAlpha(value);
19553        }
19554
19555        @Override
19556        public Float get(View object) {
19557            return object.getAlpha();
19558        }
19559    };
19560
19561    /**
19562     * A Property wrapper around the <code>translationX</code> functionality handled by the
19563     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19564     */
19565    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19566        @Override
19567        public void setValue(View object, float value) {
19568            object.setTranslationX(value);
19569        }
19570
19571                @Override
19572        public Float get(View object) {
19573            return object.getTranslationX();
19574        }
19575    };
19576
19577    /**
19578     * A Property wrapper around the <code>translationY</code> functionality handled by the
19579     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19580     */
19581    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19582        @Override
19583        public void setValue(View object, float value) {
19584            object.setTranslationY(value);
19585        }
19586
19587        @Override
19588        public Float get(View object) {
19589            return object.getTranslationY();
19590        }
19591    };
19592
19593    /**
19594     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19595     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19596     */
19597    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19598        @Override
19599        public void setValue(View object, float value) {
19600            object.setTranslationZ(value);
19601        }
19602
19603        @Override
19604        public Float get(View object) {
19605            return object.getTranslationZ();
19606        }
19607    };
19608
19609    /**
19610     * A Property wrapper around the <code>x</code> functionality handled by the
19611     * {@link View#setX(float)} and {@link View#getX()} methods.
19612     */
19613    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19614        @Override
19615        public void setValue(View object, float value) {
19616            object.setX(value);
19617        }
19618
19619        @Override
19620        public Float get(View object) {
19621            return object.getX();
19622        }
19623    };
19624
19625    /**
19626     * A Property wrapper around the <code>y</code> functionality handled by the
19627     * {@link View#setY(float)} and {@link View#getY()} methods.
19628     */
19629    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19630        @Override
19631        public void setValue(View object, float value) {
19632            object.setY(value);
19633        }
19634
19635        @Override
19636        public Float get(View object) {
19637            return object.getY();
19638        }
19639    };
19640
19641    /**
19642     * A Property wrapper around the <code>z</code> functionality handled by the
19643     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19644     */
19645    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19646        @Override
19647        public void setValue(View object, float value) {
19648            object.setZ(value);
19649        }
19650
19651        @Override
19652        public Float get(View object) {
19653            return object.getZ();
19654        }
19655    };
19656
19657    /**
19658     * A Property wrapper around the <code>rotation</code> functionality handled by the
19659     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19660     */
19661    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19662        @Override
19663        public void setValue(View object, float value) {
19664            object.setRotation(value);
19665        }
19666
19667        @Override
19668        public Float get(View object) {
19669            return object.getRotation();
19670        }
19671    };
19672
19673    /**
19674     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19675     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19676     */
19677    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19678        @Override
19679        public void setValue(View object, float value) {
19680            object.setRotationX(value);
19681        }
19682
19683        @Override
19684        public Float get(View object) {
19685            return object.getRotationX();
19686        }
19687    };
19688
19689    /**
19690     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19691     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19692     */
19693    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19694        @Override
19695        public void setValue(View object, float value) {
19696            object.setRotationY(value);
19697        }
19698
19699        @Override
19700        public Float get(View object) {
19701            return object.getRotationY();
19702        }
19703    };
19704
19705    /**
19706     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19707     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19708     */
19709    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19710        @Override
19711        public void setValue(View object, float value) {
19712            object.setScaleX(value);
19713        }
19714
19715        @Override
19716        public Float get(View object) {
19717            return object.getScaleX();
19718        }
19719    };
19720
19721    /**
19722     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19723     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19724     */
19725    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19726        @Override
19727        public void setValue(View object, float value) {
19728            object.setScaleY(value);
19729        }
19730
19731        @Override
19732        public Float get(View object) {
19733            return object.getScaleY();
19734        }
19735    };
19736
19737    /**
19738     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19739     * Each MeasureSpec represents a requirement for either the width or the height.
19740     * A MeasureSpec is comprised of a size and a mode. There are three possible
19741     * modes:
19742     * <dl>
19743     * <dt>UNSPECIFIED</dt>
19744     * <dd>
19745     * The parent has not imposed any constraint on the child. It can be whatever size
19746     * it wants.
19747     * </dd>
19748     *
19749     * <dt>EXACTLY</dt>
19750     * <dd>
19751     * The parent has determined an exact size for the child. The child is going to be
19752     * given those bounds regardless of how big it wants to be.
19753     * </dd>
19754     *
19755     * <dt>AT_MOST</dt>
19756     * <dd>
19757     * The child can be as large as it wants up to the specified size.
19758     * </dd>
19759     * </dl>
19760     *
19761     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19762     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19763     */
19764    public static class MeasureSpec {
19765        private static final int MODE_SHIFT = 30;
19766        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19767
19768        /**
19769         * Measure specification mode: The parent has not imposed any constraint
19770         * on the child. It can be whatever size it wants.
19771         */
19772        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19773
19774        /**
19775         * Measure specification mode: The parent has determined an exact size
19776         * for the child. The child is going to be given those bounds regardless
19777         * of how big it wants to be.
19778         */
19779        public static final int EXACTLY     = 1 << MODE_SHIFT;
19780
19781        /**
19782         * Measure specification mode: The child can be as large as it wants up
19783         * to the specified size.
19784         */
19785        public static final int AT_MOST     = 2 << MODE_SHIFT;
19786
19787        /**
19788         * Creates a measure specification based on the supplied size and mode.
19789         *
19790         * The mode must always be one of the following:
19791         * <ul>
19792         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19793         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19794         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19795         * </ul>
19796         *
19797         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19798         * implementation was such that the order of arguments did not matter
19799         * and overflow in either value could impact the resulting MeasureSpec.
19800         * {@link android.widget.RelativeLayout} was affected by this bug.
19801         * Apps targeting API levels greater than 17 will get the fixed, more strict
19802         * behavior.</p>
19803         *
19804         * @param size the size of the measure specification
19805         * @param mode the mode of the measure specification
19806         * @return the measure specification based on size and mode
19807         */
19808        public static int makeMeasureSpec(int size, int mode) {
19809            if (sUseBrokenMakeMeasureSpec) {
19810                return size + mode;
19811            } else {
19812                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19813            }
19814        }
19815
19816        /**
19817         * Extracts the mode from the supplied measure specification.
19818         *
19819         * @param measureSpec the measure specification to extract the mode from
19820         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19821         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19822         *         {@link android.view.View.MeasureSpec#EXACTLY}
19823         */
19824        public static int getMode(int measureSpec) {
19825            return (measureSpec & MODE_MASK);
19826        }
19827
19828        /**
19829         * Extracts the size from the supplied measure specification.
19830         *
19831         * @param measureSpec the measure specification to extract the size from
19832         * @return the size in pixels defined in the supplied measure specification
19833         */
19834        public static int getSize(int measureSpec) {
19835            return (measureSpec & ~MODE_MASK);
19836        }
19837
19838        static int adjust(int measureSpec, int delta) {
19839            final int mode = getMode(measureSpec);
19840            if (mode == UNSPECIFIED) {
19841                // No need to adjust size for UNSPECIFIED mode.
19842                return makeMeasureSpec(0, UNSPECIFIED);
19843            }
19844            int size = getSize(measureSpec) + delta;
19845            if (size < 0) {
19846                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19847                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19848                size = 0;
19849            }
19850            return makeMeasureSpec(size, mode);
19851        }
19852
19853        /**
19854         * Returns a String representation of the specified measure
19855         * specification.
19856         *
19857         * @param measureSpec the measure specification to convert to a String
19858         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19859         */
19860        public static String toString(int measureSpec) {
19861            int mode = getMode(measureSpec);
19862            int size = getSize(measureSpec);
19863
19864            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19865
19866            if (mode == UNSPECIFIED)
19867                sb.append("UNSPECIFIED ");
19868            else if (mode == EXACTLY)
19869                sb.append("EXACTLY ");
19870            else if (mode == AT_MOST)
19871                sb.append("AT_MOST ");
19872            else
19873                sb.append(mode).append(" ");
19874
19875            sb.append(size);
19876            return sb.toString();
19877        }
19878    }
19879
19880    private final class CheckForLongPress implements Runnable {
19881        private int mOriginalWindowAttachCount;
19882
19883        @Override
19884        public void run() {
19885            if (isPressed() && (mParent != null)
19886                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19887                if (performLongClick()) {
19888                    mHasPerformedLongPress = true;
19889                }
19890            }
19891        }
19892
19893        public void rememberWindowAttachCount() {
19894            mOriginalWindowAttachCount = mWindowAttachCount;
19895        }
19896    }
19897
19898    private final class CheckForTap implements Runnable {
19899        public float x;
19900        public float y;
19901
19902        @Override
19903        public void run() {
19904            mPrivateFlags &= ~PFLAG_PREPRESSED;
19905            setPressed(true, x, y);
19906            checkForLongClick(ViewConfiguration.getTapTimeout());
19907        }
19908    }
19909
19910    private final class PerformClick implements Runnable {
19911        @Override
19912        public void run() {
19913            performClick();
19914        }
19915    }
19916
19917    /** @hide */
19918    public void hackTurnOffWindowResizeAnim(boolean off) {
19919        mAttachInfo.mTurnOffWindowResizeAnim = off;
19920    }
19921
19922    /**
19923     * This method returns a ViewPropertyAnimator object, which can be used to animate
19924     * specific properties on this View.
19925     *
19926     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19927     */
19928    public ViewPropertyAnimator animate() {
19929        if (mAnimator == null) {
19930            mAnimator = new ViewPropertyAnimator(this);
19931        }
19932        return mAnimator;
19933    }
19934
19935    /**
19936     * Sets the name of the View to be used to identify Views in Transitions.
19937     * Names should be unique in the View hierarchy.
19938     *
19939     * @param transitionName The name of the View to uniquely identify it for Transitions.
19940     */
19941    public final void setTransitionName(String transitionName) {
19942        mTransitionName = transitionName;
19943    }
19944
19945    /**
19946     * Returns the name of the View to be used to identify Views in Transitions.
19947     * Names should be unique in the View hierarchy.
19948     *
19949     * <p>This returns null if the View has not been given a name.</p>
19950     *
19951     * @return The name used of the View to be used to identify Views in Transitions or null
19952     * if no name has been given.
19953     */
19954    @ViewDebug.ExportedProperty
19955    public String getTransitionName() {
19956        return mTransitionName;
19957    }
19958
19959    /**
19960     * Interface definition for a callback to be invoked when a hardware key event is
19961     * dispatched to this view. The callback will be invoked before the key event is
19962     * given to the view. This is only useful for hardware keyboards; a software input
19963     * method has no obligation to trigger this listener.
19964     */
19965    public interface OnKeyListener {
19966        /**
19967         * Called when a hardware key is dispatched to a view. This allows listeners to
19968         * get a chance to respond before the target view.
19969         * <p>Key presses in software keyboards will generally NOT trigger this method,
19970         * although some may elect to do so in some situations. Do not assume a
19971         * software input method has to be key-based; even if it is, it may use key presses
19972         * in a different way than you expect, so there is no way to reliably catch soft
19973         * input key presses.
19974         *
19975         * @param v The view the key has been dispatched to.
19976         * @param keyCode The code for the physical key that was pressed
19977         * @param event The KeyEvent object containing full information about
19978         *        the event.
19979         * @return True if the listener has consumed the event, false otherwise.
19980         */
19981        boolean onKey(View v, int keyCode, KeyEvent event);
19982    }
19983
19984    /**
19985     * Interface definition for a callback to be invoked when a touch event is
19986     * dispatched to this view. The callback will be invoked before the touch
19987     * event is given to the view.
19988     */
19989    public interface OnTouchListener {
19990        /**
19991         * Called when a touch event is dispatched to a view. This allows listeners to
19992         * get a chance to respond before the target view.
19993         *
19994         * @param v The view the touch event has been dispatched to.
19995         * @param event The MotionEvent object containing full information about
19996         *        the event.
19997         * @return True if the listener has consumed the event, false otherwise.
19998         */
19999        boolean onTouch(View v, MotionEvent event);
20000    }
20001
20002    /**
20003     * Interface definition for a callback to be invoked when a hover event is
20004     * dispatched to this view. The callback will be invoked before the hover
20005     * event is given to the view.
20006     */
20007    public interface OnHoverListener {
20008        /**
20009         * Called when a hover event is dispatched to a view. This allows listeners to
20010         * get a chance to respond before the target view.
20011         *
20012         * @param v The view the hover event has been dispatched to.
20013         * @param event The MotionEvent object containing full information about
20014         *        the event.
20015         * @return True if the listener has consumed the event, false otherwise.
20016         */
20017        boolean onHover(View v, MotionEvent event);
20018    }
20019
20020    /**
20021     * Interface definition for a callback to be invoked when a generic motion event is
20022     * dispatched to this view. The callback will be invoked before the generic motion
20023     * event is given to the view.
20024     */
20025    public interface OnGenericMotionListener {
20026        /**
20027         * Called when a generic motion event is dispatched to a view. This allows listeners to
20028         * get a chance to respond before the target view.
20029         *
20030         * @param v The view the generic motion event has been dispatched to.
20031         * @param event The MotionEvent object containing full information about
20032         *        the event.
20033         * @return True if the listener has consumed the event, false otherwise.
20034         */
20035        boolean onGenericMotion(View v, MotionEvent event);
20036    }
20037
20038    /**
20039     * Interface definition for a callback to be invoked when a view has been clicked and held.
20040     */
20041    public interface OnLongClickListener {
20042        /**
20043         * Called when a view has been clicked and held.
20044         *
20045         * @param v The view that was clicked and held.
20046         *
20047         * @return true if the callback consumed the long click, false otherwise.
20048         */
20049        boolean onLongClick(View v);
20050    }
20051
20052    /**
20053     * Interface definition for a callback to be invoked when a drag is being dispatched
20054     * to this view.  The callback will be invoked before the hosting view's own
20055     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20056     * onDrag(event) behavior, it should return 'false' from this callback.
20057     *
20058     * <div class="special reference">
20059     * <h3>Developer Guides</h3>
20060     * <p>For a guide to implementing drag and drop features, read the
20061     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20062     * </div>
20063     */
20064    public interface OnDragListener {
20065        /**
20066         * Called when a drag event is dispatched to a view. This allows listeners
20067         * to get a chance to override base View behavior.
20068         *
20069         * @param v The View that received the drag event.
20070         * @param event The {@link android.view.DragEvent} object for the drag event.
20071         * @return {@code true} if the drag event was handled successfully, or {@code false}
20072         * if the drag event was not handled. Note that {@code false} will trigger the View
20073         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20074         */
20075        boolean onDrag(View v, DragEvent event);
20076    }
20077
20078    /**
20079     * Interface definition for a callback to be invoked when the focus state of
20080     * a view changed.
20081     */
20082    public interface OnFocusChangeListener {
20083        /**
20084         * Called when the focus state of a view has changed.
20085         *
20086         * @param v The view whose state has changed.
20087         * @param hasFocus The new focus state of v.
20088         */
20089        void onFocusChange(View v, boolean hasFocus);
20090    }
20091
20092    /**
20093     * Interface definition for a callback to be invoked when a view is clicked.
20094     */
20095    public interface OnClickListener {
20096        /**
20097         * Called when a view has been clicked.
20098         *
20099         * @param v The view that was clicked.
20100         */
20101        void onClick(View v);
20102    }
20103
20104    /**
20105     * Interface definition for a callback to be invoked when the context menu
20106     * for this view is being built.
20107     */
20108    public interface OnCreateContextMenuListener {
20109        /**
20110         * Called when the context menu for this view is being built. It is not
20111         * safe to hold onto the menu after this method returns.
20112         *
20113         * @param menu The context menu that is being built
20114         * @param v The view for which the context menu is being built
20115         * @param menuInfo Extra information about the item for which the
20116         *            context menu should be shown. This information will vary
20117         *            depending on the class of v.
20118         */
20119        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20120    }
20121
20122    /**
20123     * Interface definition for a callback to be invoked when the status bar changes
20124     * visibility.  This reports <strong>global</strong> changes to the system UI
20125     * state, not what the application is requesting.
20126     *
20127     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20128     */
20129    public interface OnSystemUiVisibilityChangeListener {
20130        /**
20131         * Called when the status bar changes visibility because of a call to
20132         * {@link View#setSystemUiVisibility(int)}.
20133         *
20134         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20135         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20136         * This tells you the <strong>global</strong> state of these UI visibility
20137         * flags, not what your app is currently applying.
20138         */
20139        public void onSystemUiVisibilityChange(int visibility);
20140    }
20141
20142    /**
20143     * Interface definition for a callback to be invoked when this view is attached
20144     * or detached from its window.
20145     */
20146    public interface OnAttachStateChangeListener {
20147        /**
20148         * Called when the view is attached to a window.
20149         * @param v The view that was attached
20150         */
20151        public void onViewAttachedToWindow(View v);
20152        /**
20153         * Called when the view is detached from a window.
20154         * @param v The view that was detached
20155         */
20156        public void onViewDetachedFromWindow(View v);
20157    }
20158
20159    /**
20160     * Listener for applying window insets on a view in a custom way.
20161     *
20162     * <p>Apps may choose to implement this interface if they want to apply custom policy
20163     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
20164     * is set, its
20165     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
20166     * method will be called instead of the View's own
20167     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
20168     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
20169     * the View's normal behavior as part of its own.</p>
20170     */
20171    public interface OnApplyWindowInsetsListener {
20172        /**
20173         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
20174         * on a View, this listener method will be called instead of the view's own
20175         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
20176         *
20177         * @param v The view applying window insets
20178         * @param insets The insets to apply
20179         * @return The insets supplied, minus any insets that were consumed
20180         */
20181        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
20182    }
20183
20184    private final class UnsetPressedState implements Runnable {
20185        @Override
20186        public void run() {
20187            setPressed(false);
20188        }
20189    }
20190
20191    /**
20192     * Base class for derived classes that want to save and restore their own
20193     * state in {@link android.view.View#onSaveInstanceState()}.
20194     */
20195    public static class BaseSavedState extends AbsSavedState {
20196        /**
20197         * Constructor used when reading from a parcel. Reads the state of the superclass.
20198         *
20199         * @param source
20200         */
20201        public BaseSavedState(Parcel source) {
20202            super(source);
20203        }
20204
20205        /**
20206         * Constructor called by derived classes when creating their SavedState objects
20207         *
20208         * @param superState The state of the superclass of this view
20209         */
20210        public BaseSavedState(Parcelable superState) {
20211            super(superState);
20212        }
20213
20214        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20215                new Parcelable.Creator<BaseSavedState>() {
20216            public BaseSavedState createFromParcel(Parcel in) {
20217                return new BaseSavedState(in);
20218            }
20219
20220            public BaseSavedState[] newArray(int size) {
20221                return new BaseSavedState[size];
20222            }
20223        };
20224    }
20225
20226    /**
20227     * A set of information given to a view when it is attached to its parent
20228     * window.
20229     */
20230    final static class AttachInfo {
20231        interface Callbacks {
20232            void playSoundEffect(int effectId);
20233            boolean performHapticFeedback(int effectId, boolean always);
20234        }
20235
20236        /**
20237         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20238         * to a Handler. This class contains the target (View) to invalidate and
20239         * the coordinates of the dirty rectangle.
20240         *
20241         * For performance purposes, this class also implements a pool of up to
20242         * POOL_LIMIT objects that get reused. This reduces memory allocations
20243         * whenever possible.
20244         */
20245        static class InvalidateInfo {
20246            private static final int POOL_LIMIT = 10;
20247
20248            private static final SynchronizedPool<InvalidateInfo> sPool =
20249                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20250
20251            View target;
20252
20253            int left;
20254            int top;
20255            int right;
20256            int bottom;
20257
20258            public static InvalidateInfo obtain() {
20259                InvalidateInfo instance = sPool.acquire();
20260                return (instance != null) ? instance : new InvalidateInfo();
20261            }
20262
20263            public void recycle() {
20264                target = null;
20265                sPool.release(this);
20266            }
20267        }
20268
20269        final IWindowSession mSession;
20270
20271        final IWindow mWindow;
20272
20273        final IBinder mWindowToken;
20274
20275        final Display mDisplay;
20276
20277        final Callbacks mRootCallbacks;
20278
20279        IWindowId mIWindowId;
20280        WindowId mWindowId;
20281
20282        /**
20283         * The top view of the hierarchy.
20284         */
20285        View mRootView;
20286
20287        IBinder mPanelParentWindowToken;
20288
20289        boolean mHardwareAccelerated;
20290        boolean mHardwareAccelerationRequested;
20291        HardwareRenderer mHardwareRenderer;
20292        List<RenderNode> mPendingAnimatingRenderNodes;
20293
20294        /**
20295         * The state of the display to which the window is attached, as reported
20296         * by {@link Display#getState()}.  Note that the display state constants
20297         * declared by {@link Display} do not exactly line up with the screen state
20298         * constants declared by {@link View} (there are more display states than
20299         * screen states).
20300         */
20301        int mDisplayState = Display.STATE_UNKNOWN;
20302
20303        /**
20304         * Scale factor used by the compatibility mode
20305         */
20306        float mApplicationScale;
20307
20308        /**
20309         * Indicates whether the application is in compatibility mode
20310         */
20311        boolean mScalingRequired;
20312
20313        /**
20314         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
20315         */
20316        boolean mTurnOffWindowResizeAnim;
20317
20318        /**
20319         * Left position of this view's window
20320         */
20321        int mWindowLeft;
20322
20323        /**
20324         * Top position of this view's window
20325         */
20326        int mWindowTop;
20327
20328        /**
20329         * Indicates whether views need to use 32-bit drawing caches
20330         */
20331        boolean mUse32BitDrawingCache;
20332
20333        /**
20334         * For windows that are full-screen but using insets to layout inside
20335         * of the screen areas, these are the current insets to appear inside
20336         * the overscan area of the display.
20337         */
20338        final Rect mOverscanInsets = new Rect();
20339
20340        /**
20341         * For windows that are full-screen but using insets to layout inside
20342         * of the screen decorations, these are the current insets for the
20343         * content of the window.
20344         */
20345        final Rect mContentInsets = new Rect();
20346
20347        /**
20348         * For windows that are full-screen but using insets to layout inside
20349         * of the screen decorations, these are the current insets for the
20350         * actual visible parts of the window.
20351         */
20352        final Rect mVisibleInsets = new Rect();
20353
20354        /**
20355         * For windows that are full-screen but using insets to layout inside
20356         * of the screen decorations, these are the current insets for the
20357         * stable system windows.
20358         */
20359        final Rect mStableInsets = new Rect();
20360
20361        /**
20362         * The internal insets given by this window.  This value is
20363         * supplied by the client (through
20364         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
20365         * be given to the window manager when changed to be used in laying
20366         * out windows behind it.
20367         */
20368        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
20369                = new ViewTreeObserver.InternalInsetsInfo();
20370
20371        /**
20372         * Set to true when mGivenInternalInsets is non-empty.
20373         */
20374        boolean mHasNonEmptyGivenInternalInsets;
20375
20376        /**
20377         * All views in the window's hierarchy that serve as scroll containers,
20378         * used to determine if the window can be resized or must be panned
20379         * to adjust for a soft input area.
20380         */
20381        final ArrayList<View> mScrollContainers = new ArrayList<View>();
20382
20383        final KeyEvent.DispatcherState mKeyDispatchState
20384                = new KeyEvent.DispatcherState();
20385
20386        /**
20387         * Indicates whether the view's window currently has the focus.
20388         */
20389        boolean mHasWindowFocus;
20390
20391        /**
20392         * The current visibility of the window.
20393         */
20394        int mWindowVisibility;
20395
20396        /**
20397         * Indicates the time at which drawing started to occur.
20398         */
20399        long mDrawingTime;
20400
20401        /**
20402         * Indicates whether or not ignoring the DIRTY_MASK flags.
20403         */
20404        boolean mIgnoreDirtyState;
20405
20406        /**
20407         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
20408         * to avoid clearing that flag prematurely.
20409         */
20410        boolean mSetIgnoreDirtyState = false;
20411
20412        /**
20413         * Indicates whether the view's window is currently in touch mode.
20414         */
20415        boolean mInTouchMode;
20416
20417        /**
20418         * Indicates whether the view has requested unbuffered input dispatching for the current
20419         * event stream.
20420         */
20421        boolean mUnbufferedDispatchRequested;
20422
20423        /**
20424         * Indicates that ViewAncestor should trigger a global layout change
20425         * the next time it performs a traversal
20426         */
20427        boolean mRecomputeGlobalAttributes;
20428
20429        /**
20430         * Always report new attributes at next traversal.
20431         */
20432        boolean mForceReportNewAttributes;
20433
20434        /**
20435         * Set during a traveral if any views want to keep the screen on.
20436         */
20437        boolean mKeepScreenOn;
20438
20439        /**
20440         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
20441         */
20442        int mSystemUiVisibility;
20443
20444        /**
20445         * Hack to force certain system UI visibility flags to be cleared.
20446         */
20447        int mDisabledSystemUiVisibility;
20448
20449        /**
20450         * Last global system UI visibility reported by the window manager.
20451         */
20452        int mGlobalSystemUiVisibility;
20453
20454        /**
20455         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
20456         * attached.
20457         */
20458        boolean mHasSystemUiListeners;
20459
20460        /**
20461         * Set if the window has requested to extend into the overscan region
20462         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
20463         */
20464        boolean mOverscanRequested;
20465
20466        /**
20467         * Set if the visibility of any views has changed.
20468         */
20469        boolean mViewVisibilityChanged;
20470
20471        /**
20472         * Set to true if a view has been scrolled.
20473         */
20474        boolean mViewScrollChanged;
20475
20476        /**
20477         * Set to true if high contrast mode enabled
20478         */
20479        boolean mHighContrastText;
20480
20481        /**
20482         * Global to the view hierarchy used as a temporary for dealing with
20483         * x/y points in the transparent region computations.
20484         */
20485        final int[] mTransparentLocation = new int[2];
20486
20487        /**
20488         * Global to the view hierarchy used as a temporary for dealing with
20489         * x/y points in the ViewGroup.invalidateChild implementation.
20490         */
20491        final int[] mInvalidateChildLocation = new int[2];
20492
20493        /**
20494         * Global to the view hierarchy used as a temporary for dealng with
20495         * computing absolute on-screen location.
20496         */
20497        final int[] mTmpLocation = new int[2];
20498
20499        /**
20500         * Global to the view hierarchy used as a temporary for dealing with
20501         * x/y location when view is transformed.
20502         */
20503        final float[] mTmpTransformLocation = new float[2];
20504
20505        /**
20506         * The view tree observer used to dispatch global events like
20507         * layout, pre-draw, touch mode change, etc.
20508         */
20509        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
20510
20511        /**
20512         * A Canvas used by the view hierarchy to perform bitmap caching.
20513         */
20514        Canvas mCanvas;
20515
20516        /**
20517         * The view root impl.
20518         */
20519        final ViewRootImpl mViewRootImpl;
20520
20521        /**
20522         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
20523         * handler can be used to pump events in the UI events queue.
20524         */
20525        final Handler mHandler;
20526
20527        /**
20528         * Temporary for use in computing invalidate rectangles while
20529         * calling up the hierarchy.
20530         */
20531        final Rect mTmpInvalRect = new Rect();
20532
20533        /**
20534         * Temporary for use in computing hit areas with transformed views
20535         */
20536        final RectF mTmpTransformRect = new RectF();
20537
20538        /**
20539         * Temporary for use in computing hit areas with transformed views
20540         */
20541        final RectF mTmpTransformRect1 = new RectF();
20542
20543        /**
20544         * Temporary list of rectanges.
20545         */
20546        final List<RectF> mTmpRectList = new ArrayList<>();
20547
20548        /**
20549         * Temporary for use in transforming invalidation rect
20550         */
20551        final Matrix mTmpMatrix = new Matrix();
20552
20553        /**
20554         * Temporary for use in transforming invalidation rect
20555         */
20556        final Transformation mTmpTransformation = new Transformation();
20557
20558        /**
20559         * Temporary for use in querying outlines from OutlineProviders
20560         */
20561        final Outline mTmpOutline = new Outline();
20562
20563        /**
20564         * Temporary list for use in collecting focusable descendents of a view.
20565         */
20566        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20567
20568        /**
20569         * The id of the window for accessibility purposes.
20570         */
20571        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20572
20573        /**
20574         * Flags related to accessibility processing.
20575         *
20576         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20577         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20578         */
20579        int mAccessibilityFetchFlags;
20580
20581        /**
20582         * The drawable for highlighting accessibility focus.
20583         */
20584        Drawable mAccessibilityFocusDrawable;
20585
20586        /**
20587         * Show where the margins, bounds and layout bounds are for each view.
20588         */
20589        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20590
20591        /**
20592         * Point used to compute visible regions.
20593         */
20594        final Point mPoint = new Point();
20595
20596        /**
20597         * Used to track which View originated a requestLayout() call, used when
20598         * requestLayout() is called during layout.
20599         */
20600        View mViewRequestingLayout;
20601
20602        /**
20603         * Creates a new set of attachment information with the specified
20604         * events handler and thread.
20605         *
20606         * @param handler the events handler the view must use
20607         */
20608        AttachInfo(IWindowSession session, IWindow window, Display display,
20609                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20610            mSession = session;
20611            mWindow = window;
20612            mWindowToken = window.asBinder();
20613            mDisplay = display;
20614            mViewRootImpl = viewRootImpl;
20615            mHandler = handler;
20616            mRootCallbacks = effectPlayer;
20617        }
20618    }
20619
20620    /**
20621     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20622     * is supported. This avoids keeping too many unused fields in most
20623     * instances of View.</p>
20624     */
20625    private static class ScrollabilityCache implements Runnable {
20626
20627        /**
20628         * Scrollbars are not visible
20629         */
20630        public static final int OFF = 0;
20631
20632        /**
20633         * Scrollbars are visible
20634         */
20635        public static final int ON = 1;
20636
20637        /**
20638         * Scrollbars are fading away
20639         */
20640        public static final int FADING = 2;
20641
20642        public boolean fadeScrollBars;
20643
20644        public int fadingEdgeLength;
20645        public int scrollBarDefaultDelayBeforeFade;
20646        public int scrollBarFadeDuration;
20647
20648        public int scrollBarSize;
20649        public ScrollBarDrawable scrollBar;
20650        public float[] interpolatorValues;
20651        public View host;
20652
20653        public final Paint paint;
20654        public final Matrix matrix;
20655        public Shader shader;
20656
20657        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20658
20659        private static final float[] OPAQUE = { 255 };
20660        private static final float[] TRANSPARENT = { 0.0f };
20661
20662        /**
20663         * When fading should start. This time moves into the future every time
20664         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20665         */
20666        public long fadeStartTime;
20667
20668
20669        /**
20670         * The current state of the scrollbars: ON, OFF, or FADING
20671         */
20672        public int state = OFF;
20673
20674        private int mLastColor;
20675
20676        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20677            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20678            scrollBarSize = configuration.getScaledScrollBarSize();
20679            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20680            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20681
20682            paint = new Paint();
20683            matrix = new Matrix();
20684            // use use a height of 1, and then wack the matrix each time we
20685            // actually use it.
20686            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20687            paint.setShader(shader);
20688            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20689
20690            this.host = host;
20691        }
20692
20693        public void setFadeColor(int color) {
20694            if (color != mLastColor) {
20695                mLastColor = color;
20696
20697                if (color != 0) {
20698                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20699                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20700                    paint.setShader(shader);
20701                    // Restore the default transfer mode (src_over)
20702                    paint.setXfermode(null);
20703                } else {
20704                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20705                    paint.setShader(shader);
20706                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20707                }
20708            }
20709        }
20710
20711        public void run() {
20712            long now = AnimationUtils.currentAnimationTimeMillis();
20713            if (now >= fadeStartTime) {
20714
20715                // the animation fades the scrollbars out by changing
20716                // the opacity (alpha) from fully opaque to fully
20717                // transparent
20718                int nextFrame = (int) now;
20719                int framesCount = 0;
20720
20721                Interpolator interpolator = scrollBarInterpolator;
20722
20723                // Start opaque
20724                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20725
20726                // End transparent
20727                nextFrame += scrollBarFadeDuration;
20728                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20729
20730                state = FADING;
20731
20732                // Kick off the fade animation
20733                host.invalidate(true);
20734            }
20735        }
20736    }
20737
20738    /**
20739     * Resuable callback for sending
20740     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20741     */
20742    private class SendViewScrolledAccessibilityEvent implements Runnable {
20743        public volatile boolean mIsPending;
20744
20745        public void run() {
20746            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20747            mIsPending = false;
20748        }
20749    }
20750
20751    /**
20752     * <p>
20753     * This class represents a delegate that can be registered in a {@link View}
20754     * to enhance accessibility support via composition rather via inheritance.
20755     * It is specifically targeted to widget developers that extend basic View
20756     * classes i.e. classes in package android.view, that would like their
20757     * applications to be backwards compatible.
20758     * </p>
20759     * <div class="special reference">
20760     * <h3>Developer Guides</h3>
20761     * <p>For more information about making applications accessible, read the
20762     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20763     * developer guide.</p>
20764     * </div>
20765     * <p>
20766     * A scenario in which a developer would like to use an accessibility delegate
20767     * is overriding a method introduced in a later API version then the minimal API
20768     * version supported by the application. For example, the method
20769     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20770     * in API version 4 when the accessibility APIs were first introduced. If a
20771     * developer would like his application to run on API version 4 devices (assuming
20772     * all other APIs used by the application are version 4 or lower) and take advantage
20773     * of this method, instead of overriding the method which would break the application's
20774     * backwards compatibility, he can override the corresponding method in this
20775     * delegate and register the delegate in the target View if the API version of
20776     * the system is high enough i.e. the API version is same or higher to the API
20777     * version that introduced
20778     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20779     * </p>
20780     * <p>
20781     * Here is an example implementation:
20782     * </p>
20783     * <code><pre><p>
20784     * if (Build.VERSION.SDK_INT >= 14) {
20785     *     // If the API version is equal of higher than the version in
20786     *     // which onInitializeAccessibilityNodeInfo was introduced we
20787     *     // register a delegate with a customized implementation.
20788     *     View view = findViewById(R.id.view_id);
20789     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20790     *         public void onInitializeAccessibilityNodeInfo(View host,
20791     *                 AccessibilityNodeInfo info) {
20792     *             // Let the default implementation populate the info.
20793     *             super.onInitializeAccessibilityNodeInfo(host, info);
20794     *             // Set some other information.
20795     *             info.setEnabled(host.isEnabled());
20796     *         }
20797     *     });
20798     * }
20799     * </code></pre></p>
20800     * <p>
20801     * This delegate contains methods that correspond to the accessibility methods
20802     * in View. If a delegate has been specified the implementation in View hands
20803     * off handling to the corresponding method in this delegate. The default
20804     * implementation the delegate methods behaves exactly as the corresponding
20805     * method in View for the case of no accessibility delegate been set. Hence,
20806     * to customize the behavior of a View method, clients can override only the
20807     * corresponding delegate method without altering the behavior of the rest
20808     * accessibility related methods of the host view.
20809     * </p>
20810     */
20811    public static class AccessibilityDelegate {
20812
20813        /**
20814         * Sends an accessibility event of the given type. If accessibility is not
20815         * enabled this method has no effect.
20816         * <p>
20817         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20818         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20819         * been set.
20820         * </p>
20821         *
20822         * @param host The View hosting the delegate.
20823         * @param eventType The type of the event to send.
20824         *
20825         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20826         */
20827        public void sendAccessibilityEvent(View host, int eventType) {
20828            host.sendAccessibilityEventInternal(eventType);
20829        }
20830
20831        /**
20832         * Performs the specified accessibility action on the view. For
20833         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20834         * <p>
20835         * The default implementation behaves as
20836         * {@link View#performAccessibilityAction(int, Bundle)
20837         *  View#performAccessibilityAction(int, Bundle)} for the case of
20838         *  no accessibility delegate been set.
20839         * </p>
20840         *
20841         * @param action The action to perform.
20842         * @return Whether the action was performed.
20843         *
20844         * @see View#performAccessibilityAction(int, Bundle)
20845         *      View#performAccessibilityAction(int, Bundle)
20846         */
20847        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20848            return host.performAccessibilityActionInternal(action, args);
20849        }
20850
20851        /**
20852         * Sends an accessibility event. This method behaves exactly as
20853         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20854         * empty {@link AccessibilityEvent} and does not perform a check whether
20855         * accessibility is enabled.
20856         * <p>
20857         * The default implementation behaves as
20858         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20859         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20860         * the case of no accessibility delegate been set.
20861         * </p>
20862         *
20863         * @param host The View hosting the delegate.
20864         * @param event The event to send.
20865         *
20866         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20867         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20868         */
20869        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20870            host.sendAccessibilityEventUncheckedInternal(event);
20871        }
20872
20873        /**
20874         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20875         * to its children for adding their text content to the event.
20876         * <p>
20877         * The default implementation behaves as
20878         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20879         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20880         * the case of no accessibility delegate been set.
20881         * </p>
20882         *
20883         * @param host The View hosting the delegate.
20884         * @param event The event.
20885         * @return True if the event population was completed.
20886         *
20887         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20888         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20889         */
20890        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20891            return host.dispatchPopulateAccessibilityEventInternal(event);
20892        }
20893
20894        /**
20895         * Gives a chance to the host View to populate the accessibility event with its
20896         * text content.
20897         * <p>
20898         * The default implementation behaves as
20899         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20900         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20901         * the case of no accessibility delegate been set.
20902         * </p>
20903         *
20904         * @param host The View hosting the delegate.
20905         * @param event The accessibility event which to populate.
20906         *
20907         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20908         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20909         */
20910        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20911            host.onPopulateAccessibilityEventInternal(event);
20912        }
20913
20914        /**
20915         * Initializes an {@link AccessibilityEvent} with information about the
20916         * the host View which is the event source.
20917         * <p>
20918         * The default implementation behaves as
20919         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20920         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20921         * the case of no accessibility delegate been set.
20922         * </p>
20923         *
20924         * @param host The View hosting the delegate.
20925         * @param event The event to initialize.
20926         *
20927         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20928         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20929         */
20930        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20931            host.onInitializeAccessibilityEventInternal(event);
20932        }
20933
20934        /**
20935         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20936         * <p>
20937         * The default implementation behaves as
20938         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20939         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20940         * the case of no accessibility delegate been set.
20941         * </p>
20942         *
20943         * @param host The View hosting the delegate.
20944         * @param info The instance to initialize.
20945         *
20946         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20947         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20948         */
20949        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20950            host.onInitializeAccessibilityNodeInfoInternal(info);
20951        }
20952
20953        /**
20954         * Called when a child of the host View has requested sending an
20955         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20956         * to augment the event.
20957         * <p>
20958         * The default implementation behaves as
20959         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20960         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20961         * the case of no accessibility delegate been set.
20962         * </p>
20963         *
20964         * @param host The View hosting the delegate.
20965         * @param child The child which requests sending the event.
20966         * @param event The event to be sent.
20967         * @return True if the event should be sent
20968         *
20969         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20970         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20971         */
20972        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20973                AccessibilityEvent event) {
20974            return host.onRequestSendAccessibilityEventInternal(child, event);
20975        }
20976
20977        /**
20978         * Gets the provider for managing a virtual view hierarchy rooted at this View
20979         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20980         * that explore the window content.
20981         * <p>
20982         * The default implementation behaves as
20983         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20984         * the case of no accessibility delegate been set.
20985         * </p>
20986         *
20987         * @return The provider.
20988         *
20989         * @see AccessibilityNodeProvider
20990         */
20991        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20992            return null;
20993        }
20994
20995        /**
20996         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20997         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20998         * This method is responsible for obtaining an accessibility node info from a
20999         * pool of reusable instances and calling
21000         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21001         * view to initialize the former.
21002         * <p>
21003         * <strong>Note:</strong> The client is responsible for recycling the obtained
21004         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21005         * creation.
21006         * </p>
21007         * <p>
21008         * The default implementation behaves as
21009         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21010         * the case of no accessibility delegate been set.
21011         * </p>
21012         * @return A populated {@link AccessibilityNodeInfo}.
21013         *
21014         * @see AccessibilityNodeInfo
21015         *
21016         * @hide
21017         */
21018        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21019            return host.createAccessibilityNodeInfoInternal();
21020        }
21021    }
21022
21023    private class MatchIdPredicate implements Predicate<View> {
21024        public int mId;
21025
21026        @Override
21027        public boolean apply(View view) {
21028            return (view.mID == mId);
21029        }
21030    }
21031
21032    private class MatchLabelForPredicate implements Predicate<View> {
21033        private int mLabeledId;
21034
21035        @Override
21036        public boolean apply(View view) {
21037            return (view.mLabelForId == mLabeledId);
21038        }
21039    }
21040
21041    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21042        private int mChangeTypes = 0;
21043        private boolean mPosted;
21044        private boolean mPostedWithDelay;
21045        private long mLastEventTimeMillis;
21046
21047        @Override
21048        public void run() {
21049            mPosted = false;
21050            mPostedWithDelay = false;
21051            mLastEventTimeMillis = SystemClock.uptimeMillis();
21052            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21053                final AccessibilityEvent event = AccessibilityEvent.obtain();
21054                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21055                event.setContentChangeTypes(mChangeTypes);
21056                sendAccessibilityEventUnchecked(event);
21057            }
21058            mChangeTypes = 0;
21059        }
21060
21061        public void runOrPost(int changeType) {
21062            mChangeTypes |= changeType;
21063
21064            // If this is a live region or the child of a live region, collect
21065            // all events from this frame and send them on the next frame.
21066            if (inLiveRegion()) {
21067                // If we're already posted with a delay, remove that.
21068                if (mPostedWithDelay) {
21069                    removeCallbacks(this);
21070                    mPostedWithDelay = false;
21071                }
21072                // Only post if we're not already posted.
21073                if (!mPosted) {
21074                    post(this);
21075                    mPosted = true;
21076                }
21077                return;
21078            }
21079
21080            if (mPosted) {
21081                return;
21082            }
21083
21084            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21085            final long minEventIntevalMillis =
21086                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21087            if (timeSinceLastMillis >= minEventIntevalMillis) {
21088                removeCallbacks(this);
21089                run();
21090            } else {
21091                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21092                mPostedWithDelay = true;
21093            }
21094        }
21095    }
21096
21097    private boolean inLiveRegion() {
21098        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21099            return true;
21100        }
21101
21102        ViewParent parent = getParent();
21103        while (parent instanceof View) {
21104            if (((View) parent).getAccessibilityLiveRegion()
21105                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21106                return true;
21107            }
21108            parent = parent.getParent();
21109        }
21110
21111        return false;
21112    }
21113
21114    /**
21115     * Dump all private flags in readable format, useful for documentation and
21116     * sanity checking.
21117     */
21118    private static void dumpFlags() {
21119        final HashMap<String, String> found = Maps.newHashMap();
21120        try {
21121            for (Field field : View.class.getDeclaredFields()) {
21122                final int modifiers = field.getModifiers();
21123                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21124                    if (field.getType().equals(int.class)) {
21125                        final int value = field.getInt(null);
21126                        dumpFlag(found, field.getName(), value);
21127                    } else if (field.getType().equals(int[].class)) {
21128                        final int[] values = (int[]) field.get(null);
21129                        for (int i = 0; i < values.length; i++) {
21130                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21131                        }
21132                    }
21133                }
21134            }
21135        } catch (IllegalAccessException e) {
21136            throw new RuntimeException(e);
21137        }
21138
21139        final ArrayList<String> keys = Lists.newArrayList();
21140        keys.addAll(found.keySet());
21141        Collections.sort(keys);
21142        for (String key : keys) {
21143            Log.d(VIEW_LOG_TAG, found.get(key));
21144        }
21145    }
21146
21147    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
21148        // Sort flags by prefix, then by bits, always keeping unique keys
21149        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
21150        final int prefix = name.indexOf('_');
21151        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
21152        final String output = bits + " " + name;
21153        found.put(key, output);
21154    }
21155}
21156